8-4 + 8-5
def divisor(num):
result = []
for i in range(1, num/2+1):
if num % i == 0:
result.append(i)
result.append(num)
return result
def isprime(num):
if divisor(num) == [1, num]:
return True
else:
return False
8-6
def divfactor(num):
testprime = (i for i in divisor(num) if isprime(i))
result = []
for i in testprime:
while True:
if num % i == 0:
result.append(i)
num /= i
else:
break
return result
8-7
def isperfect(num):
a = divisor(num)
a.remove(num)
if sum(a) == num:
return 1
else:
return 0
8-8
def factoria(num):
s = 1
for i in range(1,num+1):
s *= i
return s
print factoria(int(raw_input("num: ")))
8-9
def fib(num):
if num <= 2:
return 1
else:
return fib(num-1) + fib(num-2)
memo = {2: 1, 1: 1}
def fastfib(num, memo):
if num <= 2:
return memo[num]
else:
if num not in memo:
memo[num] = fib(memo[num-1]) + fib(memo[num-2])
return memo[num]
第二种方法速度较第一种快,第一种在数值较大时会很慢。
8-11
def nametrack():
num = int(raw_input('Enter total number of names(a digit): '))
result = []
times = 1
# input the name
for i in range(num):
prompt = 'Enter a name(Last name, First name)' + str(i) + ': '
name = raw_input(prompt)
if ', ' not in name:
print '\n>>Wrong format... should be Last, First.'
print '>>You have done this', times, 'tine(s) already. Fixing input...'
times += 1
# handle the name
name = name.split(' ')
name[0], name[1] = name[1], name[0]
else:
name = name.split(', ')
result.append(name)
# sort the name
lookup = {alist[0]: alist[1] for alist in result}
ziplist = zip(*result)
sortedlist = sorted(ziplist[0])
print '\nThe sorted list (by last name) is:'
for i in sortedlist:
print i + ', ' + lookup[i]
nametrack()
8-12
# -*- coding: utf-8 -*-
def printnumber():
print '-' * 15
start = int(raw_input(u' 输入起始值: '))
stop = int(raw_input(u' 输入结束值: '))
num = len(bin(stop)) - 2
# 打印表格
if stop < 33 or start > 137:
print '{0:7}{1:{4}}{2:7}{3:7}'.format('DEC', 'BIN', 'OCT', 'HEX', num+5)
print '-' * 31
for i in range(start, stop+1):
print '{0:<7}{0:>0{2}b}{1:5}{0:<2o}{1:5}{0:<7x}'.format(i, '', num)
else:
print '{0:7}{1:{5}}{2:7}{3:7}{4:6}'.format('DEC', 'BIN', 'OCT', 'HEX', 'ASCII', num+5)
print '-' * 37
for i in range(start, stop+1):
print '{0:<7}{0:>0{2}b}{1:5}{0:<2o}{1:5}{0:<7x}{0:<6c}'.format(i, '', num)
printnumber()