Lecture Notes on 13 Feb 2017
Active Reading: Type code as you read.
Read Chapter 6: Sections 6.1 - 6.6
Write the code from the following listings and run them:
* Listing 6.1: TestMax.py
* Listing 6.2: PrintGradeFunction.py
* Listing 6.3: ReturnGradeFunction.py
* Listing 6.4: Increment.py
Challenge Problem:
Imagine you are standing in front of a long hall way that has 500 doors. Each
door is numbered starting from 1 and ending at 500. All the doors are closed.
There are also 500 persons numbered from 1 to 500. The first person comes and
opens all the doors. The second person starts at door number 2 and visits all
the even doors and closes them.
The third person starts at door number 3 and visits all the doors that are
multiples of 3. If the door is open he closes it. If a door is closed he
opens it. The fourth person starts at door number 4 and visits all the doors
that are multiples of 4 and he closes open doors and opens closed doors.
After all 500 people have gone through the hallway, how many doors are still
open?
# sum the digits of a number
def sum_digits (n):
sum_num = 0
while (n > 0):
sum_num += (n % 10)
n = n // 10
return sum_num
# sum the proper divisors of a number
def sum_divisors (n):
sum_div = 0
limit = n // 2
div = 1
while (div <= limit):
if (n % div == 0):
sum_div += div
div += 1
return sum_div
# reverse a number
def rev_num (n):
rev_n = 0
while (n > 0):
rev_n = rev_n * 10 + (n % 10)
n = n // 10
return rev_n
# determines if a number is palindromic
def is_palindromic (n):
return n == rev_num(n)
# determine if a number is prime
def is_prime (n):
if (n == 1):
return False
limit = int (n ** 0.5) + 1
divisor = 2
while (divisor < limit):
if (n % divisor == 0):
return False
divisor += 1
return True
def main():
# prompt the user to enter a number
num = int (input ("Enter a number: "))
# print the sum of the digits
print (sum_digits(num))
# print sum of the proper divisors
print (sum_divisors (num))
# print the reverse of a number
print (rev_num (num))
# print all perfect numbers less than 10000
n = 1
while (n <= 10000):
if (n == sum_divisors (n)):
print (n)
n += 1
main()