【发布时间】:2015-12-17 17:36:59
【问题描述】:
我想创建一个程序,通过根据单词在单词中的第一个位置添加赋予单词的字母的值来计算单词的“值”(作为练习,我是 Python 新手)。
IE。 "foo" 将返回 5(如 'f' = 1,'o' = 2),"bar" 将返回 6(如 'b' = 1,'a' = 2,'r' = 3)。
到目前为止,这是我的代码:
# -*- coding: utf-8 -*-
def ppn(word):
word = list(word)
cipher = dict()
i = 1
e = 0
for letter in word:
if letter not in cipher:
cipher[letter] = i
e += i
i += 1
else:
e += cipher[letter]
return ''.join(word) + ": " + str(e)
if __name__ == "__main__":
print ppn(str(raw_input()))
它运行良好,但是对于包含 'ł'、'ą' 等字符的单词,它不会返回正确的值(我猜这是因为它首先将这些字母转换为 Unicode 代码)。有没有办法绕过它,让解释器把所有个字母当作单个字母处理?
【问题讨论】:
标签: python python-2.7