先做了第8,9,10章的,最近再赶论文,实在没时间了,泪目
8-2
print(word.count('a'))
def countt(word):
count = 0
for i in word:
if i=='a':
count+=1
return count
print(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_word
print(rotate_word('cheer', 7))
print(rotate_word('IBM', -1))
9-1
#输出大于20个字母的单词
fin=open('D:\words.txt')
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=string.count(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 False
return True
fin = open('words.txt')
count = 0
num_of_words = 113809
for line in fin:
word = line.strip()
if has_no_e(word) == True:
count += 1
print(word)
print(count / num_of_words * 100, '%')
9-3
#编写一个函数,接受一个单词和一个禁止使用的字符的字符串,如果单词中不包含禁止的字符串则返回True
def avoids(word,long_word):
if word in long_word.strip():
return False
else:
return True
print(avoids('fuck','don not say hello fuck'))
fin = open('words.txt')
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 False
return True
print(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 False
return True
fin = open('words.txt')
count = 0
for 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 False
previous_letter = letter # 更新letter
return True
fin = open('words.txt')
count = 0
for line in fin:
word = line.strip()
if is_abecedarian(word) == True:
print(word)
count += 1
print(count)
9-7
#判断是否包含三个连续的双字符
def searched_word(word):
count = 0
index = 0
while index < len(word) - 1:
if word[index] == word[index + 1]:
count += 1
if count == 3:
return True
index += 2
else:
count = 0
index += 1
fin = open('words.txt')
count = 0
for 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 += 1
if is_palindrome(str(number)[1:]):
number += 1
if is_palindrome(str(number)[1:5]):
number += 1
if is_palindrome(str(number)):
return True
return False
for 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: int
n: int length
returns: string
"""
return str(i).zfill(n)
def are_reversed(i, j):
"""Checks if i and j are the reverse of each other.
@考虑了单数的情况
i: int
j: int
returns: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 have
palindromic ages in their lives, given the difference in age.
diff: int difference in ages
flag: bool, if True, prints the details
"""
daughter = 0
count = 0
while 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 + 1
if flag:
print(daughter, mother)
if mother > 120:
break
daughter = daughter + 1
return count
def check_diffs():
"""Finds age differences that satisfy the problem.
Enumerates the possible differences in age between mother
and daughter, and for each difference, counts the number of times
over their lives they will have ages that are the reverse of
each other.
"""
diff = 10
while diff < 70:
n = num_instances(diff)
if n > 0:
print(diff, n)
diff = diff + 1
print('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=0
for i in t:
for z in i:
count+=z
return count
print(nested_sum(t))
def nested_sum2(t):
count=0
for i in t:
count+=sum(i)
return count
print(nested_sum2(t))
10-2
def cumsum(li):
result = []
total = 0
for elem in li:
total += elem
result.append(total)
return result
t = [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 True
previous_elem = elem
return False
t = [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 dates
def has_matches(dates):
dates.sort()
for i in range(len(dates) - 1):
if dates[i] == dates[i + 1]:
return True
return False
def chances(num_of_simulations, pupils):
matches = 0
for i in range(num_of_simulations):
dates = date_generator(pupils)
if has_matches(dates):
matches += 1
print("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 wordlist
print(get_wordlist('words.txt'))
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 random
random.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 using append.
returns: list of strings
"""
word_list = []
fin = open('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:
# search the first half
return in_bisect(word_list[:i], word)
else:
# search the second half
return 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 False
return word_list[i] == word
if __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 False
return word_list[i] == word
def 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_pairs
li = word_list("words.txt")
print(reverse_pair(li))
10-12
import bisect
def 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 False
return word_list[i] == word
def 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_words
def 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("words.txt")
print(interlock(li))
print()
# Answer2:
print(three_way_interlock(li))