如何制作程序来计算每个单词的值
我试图让程序计算每个单词的值,如果a是1,b是2,c是3,依此类推。我已经完成了大部分代码,但它不起作用。任何人都可以给我一些建议吗?我最近才开始学习python,那么你能尽可能详细吗?谢谢。如何制作程序来计算每个单词的值
__author__ = "Anthony Chen"
__copyright__ = "Copyright (C) 2017 Anthony Chen"
__license__ = "Public Domain"
__version__ = "1.0"
output = ('None')
worth = {'a':1,
'b':2,
'c':3,
'd':4,
'e':5,
'f':6,
'g':7,
'h':8,
'i':9,
'j':10,
'k':11,
'l':12,
'm':13,
'n':14,
'o':16,
'q':17,
'r':18,
's':19,
't':20,
'u':21,
'v':22,
'w':23,
'x':24,
'y':25,
'z':26,
}
def findworth():
for char in wordlist:
if char in wordlist:
output = (worth[char])
wordlist.replace(output)
elif worth[char] == False:
output = (None)
while True:
output = (None)
wordlist = []
word = input(str("Find out how many cents your word is worth. Please enter your word:"))
word = word.lower()
wordlist = list(word)
wordlist = findworth()
output = sum(wordlist)
print("Your word's value is:")
print (output)
print('.')
这是什么节目,当我运行它:
**Find out how many cents your word is worth. Please enter your word:Bananas
Traceback (most recent call last):
File "C:/Anthony/School/__CentsWord/WordWorth.py", line 49, in <module>
wordlist = findworth()
File "C:/Anthony/School/__CentsWord/WordWorth.py", line 39, in findworth
wordlist.replace(output)
AttributeError: 'list' object has no attribute 'replace'**
根据您的解决方案(它不是海事组织非常好,将提供一个更好的)
def findworth():
for i,char in enumerate(wordlist):
if char in worth:
output = (worth[char])
wordlist[i] = (output)
else:
output = (None)
while True:
output = (None)
wordlist = []
word = input(str("Find out how many cents your word is worth. Please enter your word:"))
word = word.lower()
wordlist = list(word)
findworth()
output = sum(wordlist)
print("Your word's value is:")
print (output)
print('.')
一通过减少冗余更好的解决方案
while True:
word = input(str("Find out how many cents your word is worth. Please enter your word:"))
word = word.lower()
output = 0 # set initial value
for char in word: # iterate string for each character
if char in worth: # check if its a valid char
output += worth[char] # same as output = output + worth[char]
print("Your word's value is:")
print (output)
print('.')
Python的字符串已经是迭代的,所以你不必把它做成一个列表:)
'output = sum(word.lower()如果char值在char中,值为[char]','sum()'理解将'for'循环减少为一行,节省足够的空间来添加停止条件:'如果不输出: 中断' – f5r5e5d
对于避免了更先进的技术解决方案:
worth = {
'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7,
'h':8, 'i':9, 'j':10, 'k':11, 'l':12, 'm':13, 'n':14,
'o':15, 'q':17, 'r':18, 's':19, 't':20, 'u':21,
'v':22, 'w':23, 'x':24, 'y':25, 'z':26}
def findworth(word):
total = 0
for char in word:
if char in worth:
total += worth[char]
return total
print("Find out how many cents your word is worth.")
while True:
word = input("Please enter your word: ").lower()
print("Your word's value is:", findworth(word))
给你输出如下:
Find out how many cents your word is worth.
Please enter your word: abc
Your word's value is: 6
Please enter your word: hello
Your word's value is: 53
注:worth
目前缺少p
,使o
不正确的值,这也许应该是:
worth = {
'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7,
'h':8, 'i':9, 'j':10, 'k':11, 'l':12, 'm':13, 'n':14,
'o':15, 'p':16, 'q':17, 'r':18, 's':19, 't':20, 'u':21,
'v':22, 'w':23, 'x':24, 'y':25, 'z':26}
是你好不是52的分数? –
通常情况是,但是OP给出'o'为'16'而不是'15'。 –
他们发现了,他们忘了'p' –
我的第一个评论是用来产生worth
的方法是很长篇大论,因此容易出错,事实上,看来你已经忘了'p'
,而是使用'o':16
。您可以代替生成你使用字典理解实在值得的名单:
worth = {chr(x+96):x for x in range(1,27)}
这是通过遍历数字1..26,并转换n + 96
一个字符(使用ASCII表中看到,97 'a'
, 98 'b'
等等,这个人物,然后作为关键值
接下来,我们可以生成单词中的每个字符值的列表:
word = "hello"
scores = [worth[c] for c in word]
这将会给我们scores == [8, 5, 12, 12, 5]
。
最后,你可以调用sum
函数中添加了所有的值的列表:
sum(scores)
返回52
。
你可以把这个连成一个函数来获取:
def get_word_score(word):
worth = {chr(x+96):x for x in range(1,27)}
scores = [worth[c] for c in word]
return sum(scores)
或者这可以在1号线进行搭配:
sum([ord(c)-96 for c in word])
ord
做的chr
相反,它返回的ASCII给出的字符的值。
作为使用词'hello'
的sum([ord(c)-96 for c in word])
的演练。第一步是让每个字符转换为列表:减去96
>>> [ord(c) for c in 'hello']
[104, 101, 108, 108, 111]
下一页每个ASCII值转换为字母的位置是::
>>> [c for c in 'hello']
['h', 'e', 'l', 'l', 'o']
接下来的每个字符转换为字符的ASCII值
>>> [ord(c)-96 for c in 'hello']
[8, 5, 12, 12, 15]
最后总和:
>>> sum([ord(c)-96 for c in 'hello'])
52
然后
你的代码的功能是:
while True:
word = input("Find out how many cents your word is worth. Please enter your word:").lower()
output = sum([ord(c)-96 for c in word])
print("Your word's value is:", output, ".")
我知道。我只是不知道如何解决它。 –
python'list'没有'replace'函数,在遍历它时修改列表也是一种冒险的做法。这可能会导致各种问题。此外,你的主循环期望你的'findworth'函数返回一个数字列表,目前它不会。所以你可以在'findworth'函数开头定义一个空列表,然后在迭代列表中追加每个字符的值。 – Eric
只是为了好玩,试试'print(sum(ord(c) - 96 for c in“hello”))''。仅适用于小写a-z。 –