python文字游戏 生成数字菜单_python自学日记5——文字游戏
學習python時記錄自己或觀察別人從錯誤到正確的思路遠比只看正確答案效果好——傅查理
1.判斷單詞中是否有字母“e"
寫一個函數has_no_e,當給定的單詞不包含字母‘e'時,返回True
剛開始我寫的是這樣的:
def has_no_e(word):
for letter in word:
if letter=='e':
return False
return True
has_no_e('tdy')
但是總是跟預想的結果不一樣,單詞有‘e'時也返回True,所以添加一個print想看看情況:
def has_no_e(word):
for letter in word:
if letter=='e':
print(letter)
return False
return True
has_no_e('hello')
但是也沒效果,print貌似也沒生效,這時有點懷疑打印問題了
def has_no_e(word):
for letter in word:
print(letter)
has_no_e('hello')
但是這個打印時沒有問題了,所以想把判斷條件單獨拿出來試一下:
word='hello'
for letter in word:
if letter=='e':
return False
else:
return True
File "", line 4
return False
^
SyntaxError: 'return' outside function
這個報了一個語法錯誤,上網查了下,原因是return在函數之外沒有任何意義,后面想把return改成break,但是break在多層循環中只能打斷一層,無法跳出循環,既然拆出來沒解決,只能從最初的代碼找原因,后面發現return True在循環里了,放到循環外應該就可以了,然后試了下
def has_no_e(word):
for letter in word:
if letter=='e'or letter=='E':
return False
return True
has_no_e('tdy')
返回正常,這樣就可以了,后面有補充了對'E'的篩查。
2.讀入words.txt,打印出不含'e'的單詞,并計算這種單詞在整個單詞表中的百分比
words.txt可在http://thinkpython.com/code/w...,然后計算打印單詞數量和單詞總數,再求百分比,先計算打印單詞數量如下
def has_no_e(word):
for letter in word:
if letter=='e'or letter=='E':
return False
print(word)
return True
fin=open('words.txt')
count=0
sum=0
for line in fin:
word=line.strip()
has_no_e(word)
count+=1
sum+=1
print(count)
單詞打印倒是對的,但是sum和count是一樣的,這時我想的是先求一下單詞總數是多少,看看哪個出錯了
fin=open('words.txt')
count=0
for line in fin:
count+=1
print(count)
發現結果和上面是一樣,那么上面得出的是單詞總數,說明自己對循環不夠熟悉,以為前面加了個條件就是計算條件的數量了。但是加了個函數不知道怎么統計函數里的單詞數量,所以想著不用函數,如下
fin=open('words.txt')
sum=0
count=0
for line in fin:
for letter in word:
if letter=='e':
continue
print(word)
count+=1
sum+=1
print(sum)
print(count)
但是打印出來全是最后一個字母,數字統計的也有問題,后面想這個邏輯還是對的,把判斷加到原來代碼的函數上試試;
def has_no_e(word):
for letter in word:
if letter=='e'or letter=='E':
return False
return True
fin=open('words.txt')
sum=0
count=0
for line in fin:
word=line.strip()
if has_no_e(word): #返回True時才走下面的邏輯,這樣統計的就不是全部的單詞了
print(word)
count+=1
sum+=1
print(count)
print(sum)
print(count/sum)
這樣結果是對的了,但是得出的是小數,需要把小數轉換為百分比
a=count/sum
b='%.2f%%'%(a*100)#將小數轉換為百分比且保留兩位小數
print(b)
3.編寫一個函數is_abecedarian,如果單詞中的字母是按照字母表順序排列的(兩個重復也OK),則返回True
看到這個讓我想起在前面做過一個字符串比較的題,題目中說字符串也是可以通過運算符比較大小的,大寫字母小于小寫字母,同類字母按照字母表排序前面的小于后面的,然后根據這個寫出如下代碼:
def is_abecedarian(word):
for i in range(0,len(word)-1): #此處注意是len(word)-1,因為下面有word[i+1],如果不減一后面會造成下標超出范圍的情況
if word[i]>word[i+1]:
return False
return True
is_abecedarian('Aabbcee')
根據這個函數和前面寫過的代碼可計算出words.txt單詞表中符合此規則的單詞總數
fin=open('words.txt')
count=0
sum=0
for line in fin:
word=line.strip()
if is_abecedarian(word):
print(word)
count+=1
sum+=1
print(count)
print(sum)
a=count/sum
b='%.2f%%'%(a*100)
print(b)
在113809個單詞中符合的有596個,占比0.52%。
看了答案后有三種方法如下:
#for循環法,不過與我的略有不同
def is_abecedarian1(word):
previous=word[0]
for c in word:
if c
return False
previous=c
return True
#遞歸方法
def is_abecedarian2(word):
if len(word)<=1:
return True
if word[0]>word[1]:
return False
return is_abecedarian2(word[1:])
is_abecedarian2('aello')
#while循環
def is_abecedarian3(word):
i=0
while i
if word[i+1]
return False
i+=1
return True
is_abecedarian3('aello')
調試建議:
在所有包含'e'的單詞中,你應當測試以'e'開始的單詞,也應當測試以其結尾的單詞,以及其在單詞中部的情況。應當測試長單詞、短單詞及非常短的單詞,比如空字符串。空字符串是特殊情形的一個例子,特殊情況往往不那么明顯,但又常常隱藏著錯誤。
注意:你可能發現一種類型的錯誤(不應該包含但被卻被包含的單詞),但對另一種情況(應當包含但沒包含的單詞)則不能發現。
程序測試可以用來顯示bug的存在,但無法顯示它們的缺席。
今天學到一個新的解決問題的方法:問題識別
解決問題的一種方式,把問題表述為已經解決的某個問題的特例。
4.練習:汽車里程表共6位,初始情況,后四位是回文,行使一公里后后五位是回文,再過一公里,中間四位是回文,再過一公里,6位數是回文,求初始值,通過[::-1]來測試一個單詞是不是回文
剛開始按照字符串切片和對題目的條件設置得出如下代碼:
def is_palindrome(word):
if word==word[::-1]:
return True
return False
def chushizhi():
for mile in range(1000000):
if len(str(mile))!=6:
return False
if is_palindrome(str(mile)[2:]) and is_palindrome(str(mile+1)[1:]) and is_palindrome(str(mile+2)[1:5]) and is_palindrome(str(mile+3)):
print(mile)
return False
chushizhi()
這個返回是False,因為知道肯定有結果,所以知道這肯定有問題,但是這個以后要注意,以后如果不知道預期結果,那么就檢查不出bug來了。第一想法就是先減少判斷條件看看情況,如下代碼:
def is_palindrome(word):
if word==word[::-1]:
return True
return False
def chushizhi():
for mile in range(1000000):
if len(str(mile))!=6:
return False #因為return后都不執行,所以后面的代碼由于這個return變得無效了
if is_palindrome(str(mile)[2:]):#減少這里的判斷條件
print(mile)
return False
chushizhi()
結果還是和上面一樣,再仔細看上面判斷條件發現,如果mile從0到1000000,那么前面遇到一個字符長度不等于6時直接返回False,所以是因為前面的判斷條件后的return導致后面的代碼無法執行導致的,所以改成下面的代碼:
def is_palindrome(word):
if word==word[::-1]:
return True
return False
def chushizhi():
for mile in range(1000000):
if len(str(mile))==6 and is_palindrome(str(mile)[2:]) and is_palindrome(str(mile+1)[1:]) and is_palindrome(str(mile+2)[1:5]) and is_palindrome(str(mile+3)):
print(mile)
chushizhi()
返回結果198888和199999,測試了下是對的。但是總有個疑問,汽車里程剛開始不是從100000開始的,而是從000000開始的,那么從000000到100000之間是否有符合這個的呢,先看了下答案怎么寫的;
def has_palindrome(i, start, len):
"""Returns True if the integer i, when written as a string,
contains a palindrome with length (len), starting at index (start).
"""
s = str(i)[start:start+len]
return s[::-1] == s
def check(i):
"""Checks whether the integer (i) has the properties described
in the puzzler.
"""
return (has_palindrome(i, 2, 4) and
has_palindrome(i+1, 1, 5) and
has_palindrome(i+2, 1, 4) and
has_palindrome(i+3, 0, 6))
def check_all():
"""Enumerates the six-digit numbers and prints any that satisfy the
requirements of the puzzler"""
i = 100000
while i <= 999996:
if check(i):
print(i)
i = i + 1
check_all()
結果和我的一樣,而且從代碼看來答案代碼也沒有考慮十萬以前的數字。
我決定自己寫一下,將上面代碼改成下面的樣子:
def is_palindrome(word):
if word==word[::-1]:
return True
return False
def chushizhi():
for mile in range(1000000):
a=len(str(mile))
if a<6 and is_palindrome(str(mile).zfill(6)) and is_palindrome(str(mile+1).zfill(6)) and is_palindrome(str(mile+2).zfill(6)) and is_palindrome(str(mile+3).zfill(6)):
print(mile)
elif len(str(mile))==6 and is_palindrome(str(mile)[2:]) and is_palindrome(str(mile+1)[1:]) and is_palindrome(str(mile+2)[1:5]) and is_palindrome(str(mile+3)):
print(mile)
chushizhi()
加了一個判斷,當小于6位數時,通過字符串方法zfill,在前面用0補齊,不過得出的結果還是一樣的,但是感覺這樣會更嚴謹一些。
5.#練習:我和母親年齡的兩位數互為倒數,至今已經發生過6次,它可能總共發生8次,我現在多大
提示:可能會發現字符串方法zfill有用
根據這個提示說明我年齡小于10的時候也有互為倒數的情況發生,需要做個分析,互為倒數用到一個前面寫過的函數is_reverse,然后判斷條件是年齡互為倒數且我的年齡小于母親的年齡,得出如下代碼:
def is_reverse(word1,word2):
if len(word1)!=len(word2):
return False
i=0
j=len(word2)-1
while j>=0:
if word1[i]!=word2[j]:
return False
i=i+1
j=j-1
return True
def age_me():
for mo_age in range(10,100):
for age in range(100):
if len(str(age))<2 and is_reverse(str(age).zfill(2),str(mo_age)) and age
print(age,mo_age,mo_age-age)
if is_reverse(str(age),str(mo_age)) and age
print(age,mo_age,mo_age-age)
return a
age_me()
得出了很多個符合條件的數字對,但是這個無法直觀看出哪個符合,所以需要計算二者差值,差值數量為8的數值對的第六組是現在的年齡:
def is_reverse(word1,word2):
if len(word1)!=len(word2):
return False
i=0
j=len(word2)-1
while j>=0:
if word1[i]!=word2[j]:
return False
i=i+1
j=j-1
return True
def all_list(arr): #統計列表中每個元素出現的次數
result={}
for i in set(arr):
result[i]=arr.count(i)
return result
def age_me():
a=[]
for mo_age in range(10,100):
for age in range(100):
if len(str(age))<2 and is_reverse(str(age).zfill(2),str(mo_age)) and age
print(age,mo_age,mo_age-age)
a.append(mo_age-age)
if is_reverse(str(age),str(mo_age)) and age
print(age,mo_age,mo_age-age)
a.append(mo_age-age)
return all_list(a)
age_me()
然后得出了差值為18時共出現了8次,從上開始數第六次是57和75,所以我現在年齡時57歲。
下面是答案的代碼:
def str_fill(i, len):
"""return the integer (i) written as a string with at least
(len) digits"""
return str(i).zfill(len)
def are_reversed(i, j):
""" return True if the integers i and j, written as strings,
are the reverse of each other"""
return str_fill(i,2) == str_fill(j,2)[::-1]
def num_instances(diff, flag=False):
"""returns the number of times the mother and daughter have
pallindromic ages in their lives, given the difference in age.
If flag==True, prints the details."""
daughter = 0
count = 0
while True:
mother = daughter + diff
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():
"""enumerate the possible differences in age between mother
and daughter, and for each difference, count 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('daughter mother')
num_instances(18, True)
總結
以上是生活随笔為你收集整理的python文字游戏 生成数字菜单_python自学日记5——文字游戏的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: html5+css3第一次作业_“台风爷
- 下一篇: python成员运算符包括_Python