处理一个非常常见的问题,以确定单词是否是初学者(所有字母按字母顺序排列).我可以用"Think Python"中的几种方式做一个单词; 但是,希望能够遍历一个单词列表,确定哪些是初学者并计算那些是初学者.
def start():
lines= []
words= []
for line in open('word_test1.txt'):
lines.append(line.strip())
numlines=len(lines)
count = 0
for word in lines[:]:
i = 0
while i < len(word)-1:
if word[i+1] < word[i]:
return
i = i+1
print (word)
count= count + 1
print (count)
start()
Run Code Online (Sandbox Code Playgroud)
我认为我的问题在于"while i"循环中的"return".在我正在使用的列表中,至少有三个初学者的话.上面的代码读取前两个(它们是第一个条目),打印它们,计算它们但是在下面的非初始化单词中断出循环并结束程序.
我是编程的新手,这花了我几个小时的时间.
我正试图用Python解决生日悖论.我很接近,但最后一块让我感到茫然.我正在使用随机生成给定范围和要创建的项目数的数字列表.这样可行.
然后我检查列表(上面生成的)是否有重复.这样可行.
然后我尝试生成给定(n)列表.这是我遇到麻烦的地方.它生成一个列表然后返回"NoneType"不可迭代.令我困惑的是,列表已生成,但Python并未将其视为列表.
这是代码:
def make_bd(n, r):
"""Generates (r) numbers of birthdays in a range (n)."""
import random
t = [random.randrange(n) for i in range(r)]
print (t)
def has_dupe(test):
"""Here I test to see if I can detect a duplicate birthday.
This is based on problem #4."""
d = []
count = 0
for number in test:
if number in d:
count = count + 1
d.append(number)
if count >= 1:
return True
return False
def dupebd(n,r,t):
count_dupe = 0 …
Run Code Online (Sandbox Code Playgroud)