think python 课后题实现

阅读: 评论:0

think python 课后题实现

think python 课后题实现

先做了第8,9,10章的,最近再赶论文,实在没时间了,泪目
8-2

unt('a'))def countt(word):count = 0for i in word:if i=='a':count+=1return countprint(countt('bananaa'))

8-3

#一个字符串的切片可以接受指定步长的第三个索引,步长为2意味着中间间隔1,步长为3,意味着隔2个字符
fruit='banana'
print(fruit[0:5:2])
#bnn
print(fruit[::-1])
#直接输出ananab 倒叙#判断是否为回文词语
def is_huiweici(word):return word==word[::-1]print(is_huiweici('is'))
#false

8-5

#实现凯撒密码移动固定位置
#利用自带的函数 ord 可以读取字母位置
def rotate_word(word,s):newword=[]for i in word:newword.append(chr(ord(i)+s))return str(newword)print(rotate_word('ibm',-1))def rotate_word(word, shift):"""Uses Ceasar cypher to encrypt given word using given shift."""rotated_word = ''for letter in word:rotated_word += chr(ord(letter) + shift)return rotated_wordprint(rotate_word('cheer', 7))
print(rotate_word('IBM', -1))

9-1

#输出大于20个字母的单词
fin=open('D:')
for line in fin:word=line.strip() #分词if len(word)>20:print(word)

9-2

#统计出现没有e的单词
#统计单词的总数
#区别一下strip()  spilt()#strip 默认为空格
str='000000this is an example00000'
print(str.strip('0'))
#this is an example
#splict()
#str.split(str="", num&#unt(str)). 参数前面是分割参数,后面是分割次数
str = "Line1-abcdef nLine2-abc nLine4-abcd"
print (str.split( ))
print (str.split(' ', 1 ))
#['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
#['Line1-abcdef', 'nLine2-abc nLine4-abcd']def has_no_e(word):for letter in word:if letter == 'e':return Falsereturn Truefin = open(&#')
count = 0
num_of_words = 113809for line in fin:word = line.strip()if has_no_e(word) == True:count += 1print(word)print(count / num_of_words * 100, '%')

9-3

#编写一个函数,接受一个单词和一个禁止使用的字符的字符串,如果单词中不包含禁止的字符串则返回True
def avoids(word,long_word):if word in long_word.strip():return Falseelse:return True
print(avoids('fuck','don not say hello fuck'))
fin = open(&#')
count = 0
forbidden_letters = input("Type forbidden letters: ")
for line in fin:word = line.strip()if avoids(word, forbidden_letters) == True:count += 1
print(count)

9-4

def uses_only(word, letters):for letter in word:if letter not in letters:return Falsereturn Trueprint(uses_only('good','a b c d e f g'))

9-5

##统计包含AEIOU所有元音字符的单词
def uses_all(word, letters):required = letters.split() #for letter in required:if letter not in word:return Falsereturn Truefin = open(&#')
count = 0for line in fin:word = line.strip()if uses_all(word, 'a e i o u y') == True:print(word)count += 1
print(count)# How many words are there that use all the vowels aeiou?
# 598# How about aeiouy?
# 42

9-6

#单词按照字母顺序排序
def is_abecedarian(word):previous_letter = word[0]for letter in word:if ord(letter) <ord(previous_letter):return Falseprevious_letter = letter # 更新letterreturn Truefin = open(&#')
count = 0for line in fin:word = line.strip()if is_abecedarian(word) == True:print(word)count += 1
print(count)

9-7

#判断是否包含三个连续的双字符def searched_word(word):count = 0index = 0while index < len(word) - 1:if word[index] == word[index + 1]:count += 1if count == 3:return Trueindex += 2else:count = 0index += 1fin = open(&#')
count = 0for line in fin:word = line.strip()if searched_word(word) == True:print(word)count += 1
print(count)

9-8

def is_palindrome(word):return word == word[::-1]def searched_number(number):if is_palindrome(str(number)[2:]):number += 1if is_palindrome(str(number)[1:]):number += 1if is_palindrome(str(number)[1:5]):number += 1if is_palindrome(str(number)):return Truereturn Falsefor num in range(100000, 1000000):if searched_number(num):print(num)

9-9


def str_fill(i, n):"""Returns i as a string with at least n digits.i: intn: int lengthreturns: string"""return str(i).zfill(n)def are_reversed(i, j):"""Checks if i and j are the reverse of each other.@考虑了单数的情况i: intj: intreturns:bool"""return str_fill(i, 2) == str_fill(j, 2)[::-1]def num_instances(diff, flag=False):"""Counts the number of palindromic ages.Returns the number of times the mother and daughter havepalindromic ages in their lives, given the difference in age.diff: int difference in agesflag: bool, if True, prints the details"""daughter = 0count = 0while True:mother = daughter + diff# assuming that mother and daughter don't have the same birthday,# they have two chances per year to have palindromic ages.if are_reversed(daughter, mother) or are_reversed(daughter, mother + 1):count = count + 1if flag:print(daughter, mother)if mother > 120:breakdaughter = daughter + 1return countdef check_diffs():"""Finds age differences that satisfy the problem.Enumerates the possible differences in age between motherand daughter, and for each difference, counts the number of timesover their lives they will have ages that are the reverse ofeach other."""diff = 10while diff < 70:n = num_instances(diff)if n > 0:print(diff, n)diff = diff + 1print('diff  #instances')
check_diffs()print()
print('daughter  mother')
num_instances(18, True)

10-1

#求列表里面的和
t=[[1,2],[3],[4,5,6]]
def nested_sum(t):count=0for i in t:for z in i:count+=zreturn countprint(nested_sum(t))def nested_sum2(t):count=0for i in t:count+=sum(i)return count
print(nested_sum2(t))

10-2

def cumsum(li):result = []total = 0for elem in li:total += elemresult.append(total)return resultt = [1, 2, 3]
print(cumsum(t))

10-3

#退出首尾的元素,提取中间的list
#用del实现
oldlist=[1,2,3,4,5,6,7]
del(oldlist[len(oldlist)-1])
del(oldlist[0])
print(oldlist)
##用切片实现  切片用中括号 ,内容是掐头去尾
print(oldlist[0:len(oldlist)])def middle(li):return li[1:-1]lis = middle(oldlist)print(lis)

10-5

#写一个is_sorted的函数,判断是否按顺序来的
def is_sorted(a):return a==sorted(a)
print(is_sorted([1,2,3,6,1]))

10-6

#判断重排一个单词中字母的顺序,得到另外一个单词,那么称这两个单词为变位词
def is_anagram(text1, text2):return sorted(text1) == sorted(text2)

10-7

#判断列表的元素是否有相等的,排除空列表和单列表
def has_duplicates(li):if len(li) == 0:return "List is empty."   #加上return 直接就跳出了elif len(li) == 1:return "List contains only one element."previous_elem = li[0]for elem in sorted(li):if previous_elem == elem:return Trueprevious_elem = elemreturn Falset = [4, 7, 2, 7, 3, 8, 9]
print(has_duplicates(t))
print(has_duplicates(['b', 'd', 'a', 't']))
print(has_duplicates([]))
print(has_duplicates(['']))
print(has_duplicates([5, 7, 9, 2, 4, 1, 8, ]))

10-8

#23个学生,相同生日的概率
#使用random
from random import randint
def date_generator(pupils):dates = []for student in range(pupils):dates.append(randint(1, 366))return datesdef has_matches(dates):dates.sort()for i in range(len(dates) - 1):if dates[i] == dates[i + 1]:return Truereturn False
def chances(num_of_simulations, pupils):matches = 0for i in range(num_of_simulations):dates = date_generator(pupils)if has_matches(dates):matches += 1print("There are {} classes having students with the same birthday date".format(matches))print("in {} simulations.".format(num_of_simulations))chances(1000, 23)
print(date_generator(23))

10-9

#读取word,txt。每个单词一个元素放到列表里面
def get_wordlist(lujing):with open(lujing) as fin:wordlist=[]for line in fin:words=line.strip()wordlist.append(words)return wordlistprint(get_wordlist(&#'))

10-10

#编写一个查找函数,看看元素在列表的哪个位置
#先学习一下python的二分查找的模块 bisect
##待深究
##
##
##
import bisect
import random
print('New pos contents')
print('-----------------')
newlist = []for i in range(1, 15):r = random.randint(1, 100)position = bisect.bisect(newlist, r)bisect.insort(newlist, r)print('%3d %3d' % (r, position), newlist)
import bisect
import randomrandom.seed(1)
print('New pos contents')
print('-----------------')
l = []for i in range(1, 15):r = random.randint(1, 100)position = bisect.bisect_left(l, r)bisect.insort_left(l, r)print('%3d %3d' % (r, position), l)import bisect
def make_word_list():"""Reads lines from a file and builds a list urns: list of strings"""word_list = []fin = open(&#')for line in fin:word = line.strip()word_list.append(word)return word_listdef in_bisect(word_list, word):if len(word_list) == 0:return Falsei = len(word_list) // 2if word_list[i] == word:return Trueif word_list[i] > word:# search the first halfreturn in_bisect(word_list[:i], word)else:# search the second halfreturn in_bisect(word_list[i + 1:], word)def in_bisect_cheat(word_list, word):i = bisect.bisect_left(word_list, word)if i == len(word_list):return Falsereturn word_list[i] == wordif __name__ == '__main__':word_list = make_word_list()for word in ['aa', 'alien', 'allen', 'zymurgy']:print(word, 'in list', in_bisect(word_list, word))for word in ['aa', 'alien', 'allen', 'zymurgy']:print(word, 'in list', in_bisect_cheat(word_list, word))

10-11

#查找翻转单词
import bisect
def word_list(file):fin = open(file)li = []for line in fin:word = line.strip()li.append(word)return li#获得了一个word_list
def in_bisect_cheat(word_list, word):i = bisect.bisect_left(word_list, word) #返回x的左侧位置if i == len(word_list):return Falsereturn word_list[i] == worddef reverse_pair(li):list_of_pairs = []for word in li:if in_bisect_cheat(li, word[::-1]): #单词翻转后,查找是否在LI上pair = (word, word[::-1])list_of_pairs.append(pair)return list_of_pairsli = word_list(&#")
print(reverse_pair(li))

10-12

import bisectdef word_list(file):fin = open(file)li = []for line in fin:word = line.strip()li.append(word)return li
def in_bisect_cheat(word_list, word):i = bisect.bisect_left(word_list, word)if i == len(word_list):return Falsereturn word_list[i] == worddef interlock(word_list):interlocking_words = []for word in word_list:if in_bisect_cheat(word_list, word[::2]) and in_bisect_cheat(word_list, word[1::2]):interlockers = (word[::2], word[1::2], word)interlocking_words.append(interlockers)return interlocking_wordsdef three_way_interlock(word_list):interlocking_words = []for word in word_list:if in_bisect_cheat(word_list, word[::3]) and in_bisect_cheat(word_list, word[1::3]) and in_bisect_cheat(word_list, word[2::3]):interlockers = (word[::3], word[1::3], word[2::3], word)interlocking_words.append(interlockers)return interlocking_words# Answer1:
li = word_list(&#")
print(interlock(li))
print()# Answer2:
print(three_way_interlock(li))

本文发布于:2024-02-05 04:03:15,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170723633562900.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:课后   python
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23