3-2:
def do_twice(f, s1):
f(s1)
f(s1)
def print_spam(s2):
print(s2)
def print_twice(s3):
print(s3)
print(s3)
def do_four(f1,f2,s4):
f1(f2,s4)
f1(f2,s4)
do_twice(print_twice, 'aaa')
do_four(do_twice, print_spam, 'spam')
3-3.1:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def push1():
print('+ - - - -', end = ' ') # 默认情况下print会自动换行,可以在结尾打印一个空格改变这一行为
def push2():
print('| ', end = ' ')
def do_twice(f):
f()
f()
def do_four(f):
f()
f()
f()
f()
def row1():
do_twice(push1)
print('+')
def row2():
do_twice(push2)
print('|')
row1()
do_four(row2)
row1()
do_four(row2)
row1()
3-3.2:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def push1():
print('+ - - - -', end = ' ') # 默认情况下print会自动换行,可以在结尾打印一个空格改变这一行为
def push2():
print('| ', end = ' ')
def do_twice(f):
f()
f()
def do_four(f):
f()
f()
f()
f()
def row1():
do_four(push1)
print('+')
def row2():
do_four(push2)
print('|')
row1()
do_four(row2)
row1()
do_four(row2)
row1()
do_four(row2)
row1()
do_four(row2)
row1()
5-1:
import time
time_now = time.time()
minutes = time_now // 60
hours = minutes // 60
days = hours // 24
hour = hours % 24
minutes = minutes % 60
sec = time_now % 60 #秒 seconds
print('time_now =',time_now)
print('days =',days,'\n' ,'hours =',hours,'\n','minutes =',minutes,'\n','sec =',sec)
5-2:
def check_fermat(a, b, c, n): #5-2-1的函数
a = a ** n
b = b ** n
c = c ** n
if a + b == c and n > 2:
print('Oh,my gad! fermat is wrong!')
else:
print('No, it not true')
def input_user(): #5-2-2的函数
a = input('Please enter the value of a: \n')
b = input('Please enter the value of b: \n')
c = input('Please enter the value of c: \n')
n = input('Please enter the value of n: \n')
check_fermat(int(a), int(b), int(c), int(n))
input_user()
5-3:
def is_triangle(a, b, c): #5-3-1
if a>=b+c or b>=a+c or c>=a+b:
print('No\n')
else:
print('Yes\n')
def input_user(): #5-3-2
a = input('Please enter the value of a: \n')
b = input('Please enter the value of b: \n')
c = input('Please enter the value of c: \n')
is_triangle(int(a), int(b), int(c))
input_user()
6-2:
def ack(m,n):
if m == 0:
return n+1
elif m>0 and n==0:
return ack(m-1, 1)
elif m>0 and n>0:
return ack(m-1, ack(m, n-1))
print(ack(3, 4))
##对于很大的数字m和n,递归调用的层数过多,系统分配的栈空间溢出,从而出现错误提示
6-3:
def is_palindrome(word):
lenth = len(word)
if lenth == 0 or lenth == 1:
return True
if word[0] == word[-1]:
return is_palindrome(word[1:-1])
return False
ans = is_palindrome('asa')
print(ans)
6-4:
def is_power(a, b):
if a == 1:
return True
if a == 0:
return False
if a%b==0:
return is_power(a/b, b)
return False
ans = is_power(9, 3)
print(ans)
# 1是任何数的乘方,a**n表示a的n次方,a为底数,注意底数不能为0
6-5:
def gcd(a, b):
if b == 0:
return a
return gcd(b, a%b)
print(gcd(12, 15))
7-1:
import math
def mysqrt(a, x):
while True:
y = (x + a/x) / 2
if abs(y-x) < 0.000000000000000001:
break
x = y
return x
def test_square_root(a, x):
my_ans = mysqrt(a, x)
math_ans = math.sqrt(a)
diff = abs(my_ans - math_ans)
print(a, my_ans, math_ans, diff)
print('a mysqrt(a) math.sqrt(a) diff')
print('- --------- ------------ ----')
test_square_root(1, 1)
test_square_root(2, 2)
test_square_root(3, 2)
test_square_root(4, 2)
test_square_root(5, 2)
test_square_root(6, 2)
test_square_root(7, 2)
test_square_root(8, 2)
test_square_root(9 ,2)
7-2:
import math
def eval_loop():
ans = ''
while True:
print('Please enter your words:\n')
word = input()
if word == 'done':
return ans
break
ans = eval(word)
print(ans)
print(eval_loop())
7-3:
import math
def estimate_pi():
cnt = 2*math.sqrt(2) / 9801
k = 0
tie = 0
while True:
item = math.factorial(4*k) * (1103+26390*k) / (math.factorial(k) ** 4) / (396 ** (4*k))
tie = tie + item
k = k + 1
if item < 1e-15:
break
pi = 1 / (tie*cnt)
print('my_ans ==',pi)
print('math.pi_ans ==',math.pi)
estimate_pi()
8-2:
'''
count(str,beg,end)返回str在string中出现的次数,如果beg或者end指定则返回指定范围内str出现的次数
'''
word = 'banana'
cnt = word.count('a')
print(cnt)
8-3:
def is_palindrome(word):
new_word = word[::-1]
if new_word == word:
return True
else:
return False
print(is_palindrome('asa'))
9-7:
def is_abecedarian(word):
if len(word) < 6:
return False
one = 0
tow = 2
three = 4
while three < len(word)-1:
if word[one] == word[one+1] and word[tow] == word[tow+1] and word[three] == word[three+1]:
return True
one += 1
tow += 1
three += 1
return False
sum = 0
num = 0
fin = open(r'D:\python\words.txt')## 我使用的是本章第一节给出的单词列表
for line in fin:
word = line.strip()
sum = sum + 1
if is_abecedarian(word):
num += 1
print(word)
ratio = num / sum * 100
print('sum =',sum)
print('num =',num)
print('The ratio of words without e to total words is:',ratio,'%' )
9-8:
def palindrome(num, start, lenth):
s = str(num)[start:start+lenth]
return s == s[::-1]
def check(num):
if palindrome(num,2,4) and palindrome(num+1,1,5) and palindrome(num+2,1,4) and palindrome(num+3,0,6):
return True
return False
def check_all():
num = 100000
while num < 999996:
if check(num):
print(num)
num += 1
check_all()
9-9:
'''
每隔十一年会出现一次,一共出现8次,就是:
20 31 42 53 64 75 86 97
02 13 24 35 46 57 68 79
现在的年纪就是57岁,代码就不写了,假定一下母子之间的年龄差距,暴力遍历就好了
'''
'''
zfill()方法: Python zfill() 方法返回指定长度的字符串,原字符串右对齐,前面填充0。
zfill()方法语法:str.zfill(width) width -- 指定字符串的长度。原字符串右对齐,前面填充0。
'''
##示例:
str = "this is string example from runoob....wow!!!"
print ("str.zfill : ",str.zfill(40))
print ("str.zfill : ",str.zfill(50))
##输出结果:
str.zfill : this is string example from runoob....wow!!!
str.zfill : 000000this is string example from runoob....wow!!!
10-1:
def nested_sum(t):
ans = 0
for x in t:
ans += sum(x)
return ans
t = [[1,2], [3], [4,5,6]]
print(nested_sum(t))
10-2:
def cumsum(t):
ans = 0
ans_t = []
for x in t:
ans += x
ans_t = ans_t + [ans]
return ans_t
t = [1, 2, 3]
print(cumsum(t))
10-3:
def middle(t): ##新建一个列表
return t[1:-1]
t = [1, 2, 3, 4]
print(middle(t))
10-4:
def chop(t):##修改一个list,切片的操作会新建一个list
del t[0]
del t[-1]
t = [1, 2, 3, 4]
chop(t)
print(t)
10-5:
def is_sorted(t):
return t == sorted(t)
'''
Python list内置sort()方法用来排序,也可以用python内置的全局sorted()方法来对可迭代的序列排序生成新的序列。
sort不会产生一个新的list,仅仅是用于这个list对象的方法,而sorted是函数,返回一个新的list
'''
t = [1, 2, 2]
print(is_sorted(t))
t= ['b', 'a']
print(is_sorted(t))
10-6:
def is_anagram(t1, t2):
t1.sort()
t2.sort()
return t1 == t2
t1 = ['a', 'c', 'b', 'd']
t2 = ['b', 'd', 'c', 'a']
print(is_anagram(t1, t2))
t1 = ['a', 'b' ,'b']
t2 = ['b', 'b', 'a']
print(is_anagram(t1, t2))
t1 = ['a', 'b', 'c']
t2 = ['a', 'b', 'd']
print(is_anagram(t1, t2))
10-7:
def has_duplicates(t):
new_t = list(t)
new_t.sort()
for i in range(len(t) - 1):
if new_t[i] == new_t[i+1]:
return True
return False
t = ['a', 'b', 'c']
print(has_duplicates(t))
t = ['a', 'b', 'a']
print(has_duplicates(t))
10-8:
import random
def has_duplicates(t):##查看是否有同一天过生日的同学
new_t = list(t)
new_t.sort()
for i in range(len(t) - 1):
if new_t[i] == new_t[i+1]:
return True
return False
def random_birthday(n):##随机生成23个同学的生日,并储存为一个list
t = []
for i in range(n):
birthday = random.randint(1, 365)
t.append(birthday)
return t
def count_match(num_students, num_simulations):##计算23个同学在1000次试验中,有多少次至少有一对同学同一天过生日的
count = 0
for i in range(num_simulations):
t = random_birthday(num_students)
if has_duplicates(t):
count += 1
return count
num_students = 23
num_simulations = 1000
count = count_match(num_students, num_simulations)
print('After %d simulations' % num_simulations)
print('with %d students' % num_students)
print('there were %d simulations with at least one match' % count)
print('The probability of matching success is ',count / num_simulations)
10-9:
import time
def fuc_1():
fin = open(r'D:\python\words.txt')
t = []
for line in fin:
word = line.strip()
t.append(word)
return t
def fuc_2():
fin = open(r'D:\python\words.txt')
t = []
for line in fin:
word = line.strip()
t = t + [word]
return t
start_time = time.time()
t = fuc_1()
elapsed_time = time.time() - start_time
print (len(t))
print (t[:10])
print(elapsed_time)
start_time = time.time()
t = fuc_2()
elapsed_time = time.time() - start_time
print(len(t))
print(t[:10])
print(elapsed_time)
10-10:
import bisect
def make_word_list():
word_list = []
fin = open(r'D:\python\words.txt')
for line in fin:
word = line.strip()
word_list.append(word)
return word_list
def in_bisect(word_list, word):
if len(word_list) == 0:
return False
i = len(word_list) // 2
if word_list[i] == word:
return True
if word_list[i] > word:
return in_bisect(word_list[:i], word)
else:
return in_bisect(word_list[i+1:], word)
def in_bisect_cheat(word_list,word):
i = bisect.bisect_left(word_list, word) ##在list中查找word的位置,并返回下标
if i == len(word_list):
return False
return word_list[i] == word
word_list = make_word_list()
for word in ['as', 'to', 'for', 'be', 'so', 'zoo','aaaaa']:
print(word,'in list',in_bisect(word_list, word))
print('\n')
for word in ['as', 'to', 'for', 'be', 'so', 'zoo','aaaaa']:
print(word,'in list',in_bisect_cheat(word_list, word))
10-11:
def make_word_list():
word_list = []
fin = open(r'D:\python\words.txt')
for line in fin:
word = line.strip()
word_list.append(word)
return word_list
def in_bisect(word_list, word):
if len(word_list) == 0:
return False
i = len(word_list) // 2
if word_list[i] == word:
return True
if word_list[i] > word:
return in_bisect(word_list[:i], word)
else:
return in_bisect(word_list[i+1:], word)
def reverse_pair(word_list,word):
rev_word = word[::-1]
return in_bisect(word_list, rev_word)
word_list = make_word_list()
for word in word_list:
if reverse_pair(word_list, word):
print(word, word[::-1])