2023年7月26日发(作者:)
Thinkpython(第⼆版)习题代码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 timetime_now = ()minutes = time_now // 60hours = minutes // 60days = hours // 24hour = hours % 24minutes = minutes % 60sec = time_now % 60 #秒 secondsprint('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('Non') else: print('Yesn')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 Falseans = 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 Falseans = is_power(9, 3)print(ans)# 1是任何数的乘⽅,a**n表⽰a的n次⽅,a为底数,注意底数不能为06-5:def gcd(a, b): if b == 0: return a return gcd(b, a%b)print(gcd(12, 15))7-1:import mathdef mysqrt(a, x): while True: y = (x + a/x) / 2 if abs(y-x) < 0.000001: break x = y return xdef test_square_root(a, x): my_ans = mysqrt(a, x) math_ans = (a) diff = abs(my_ans - math_ans) print(a, my_ans, math_ans, diff)print('a mysqrt(a) (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 mathdef 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 mathdef estimate_pi(): cnt = 2*(2) / 9801 k = 0 tie = 0 while True: item = ial(4*k) * (1103+26390*k) / (ial(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('_ans ==',)estimate_pi()
8-2:'''count(str,beg,end)返回str在string中出现的次数,如果beg或者end指定则返回指定范围内str出现的次数'''word = 'banana'cnt = ('a')
print(cnt)8-3:def is_palindrome(word): new_word = word[::-1] if new_word == word: return True else: return Falseprint(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 Falsesum = 0num = 0fin = open(r'D:')## 我使⽤的是本章第⼀节给出的单词列表for line in fin: word = () sum = sum + 1 if is_abecedarian(word): num += 1 print(word)ratio = num / sum * 100print('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 Falsedef check_all(): num = 100000 while num < 999996: if check(num): print(num) num += 1check_all()9-9:'''每隔⼗⼀年会出现⼀次,⼀共出现8次,就是:20 31 42 53 64 75 86 9702 13 24 35 46 57 68 79现在的年纪就是57岁,代码就不写了,假定⼀下母⼦之间的年龄差距,暴⼒遍历就好了''''''zfill()⽅法: Python zfill() ⽅法返回指定长度的字符串,原字符串右对齐,前⾯填充0。zfill()⽅法语法:(width) width -- 指定字符串的长度。原字符串右对齐,前⾯填充0。'''##⽰例:str = "this is string example wow"print (" : ",(40))print (" : ",(50))##输出结果: : this is string example : 000000this is string example wow10-1:def nested_sum(t): ans = 0 for x in t: ans += sum(x) return anst = [[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_tt = [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): () () return t1 == t2t1 = ['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_() for i in range(len(t) - 1): if new_t[i] == new_t[i+1]: return True return Falset = ['a', 'b', 'c']print(has_duplicates(t))t = ['a', 'b', 'a']print(has_duplicates(t))10-8:import randomdef has_duplicates(t):##查看是否有同⼀天过⽣⽇的同学 new_t = list(t) new_() for i in range(len(t) - 1): if new_t[i] == new_t[i+1]: return True return Falsedef random_birthday(n):##随机⽣成23个同学的⽣⽇,并储存为⼀个list t = [] for i in range(n): birthday = t(1, 365) (birthday) return tdef 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 countnum_students = 23num_simulations = 1000count = 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 timedef fuc_1(): fin = open(r'D:') t = [] for line in fin: word = () (word) return tdef fuc_2(): fin = open(r'D:') t = [] for line in fin: word = () t = t + [word] return tstart_time = ()t = fuc_1()elapsed_time = () - start_timeprint (len(t))print (t[:10])print(elapsed_time)start_time = ()t = fuc_2()elapsed_time = () - start_timeprint(len(t))print(t[:10])print(elapsed_time)10-10:import bisectdef make_word_list(): word_list = [] fin = open(r'D:') for line in fin: word = () word_(word) return word_listdef 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 = _left(word_list, word) ##在list中查找word的位置,并返回下标 if i == len(word_list): return False return word_list[i] == wordword_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:') for line in fin: word = () word_(word) return word_listdef 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])
发布者:admin,转转请注明出处:http://www.yc00.com/xiaochengxu/1690307625a329888.html
评论列表(0条)