在Python中幸运数字挑战
我必须在python中创建一个幸运数字程序,但我不断遇到很多错误。 如果你不知道一个幸运的名字是个什么数字,它基本上是在每个字母都有一个值,你添加值toether您的名字和第二名称,以便例如 李四在Python中幸运数字挑战
165 465 1+6+5 = 12 4+6+5 = 15 15 + 12 = 27 2+7 = 8 then 8 = has diplomatic skills
以下是我迄今所做的:
#this will go all the way to z charDict = { 'A' : 1, 'B' : 2, 'C' : 3, 'D' : 4} # example names - while loop will go here firstName = 'AAB' lastName = 'DCDD' # split the strings into a list of chars firstNameChars = list(firstName) lastNameChars = list(lastName) # sum up values firstNameSum = 0 lastNameSum = 0 for chr in firstNameChars: firstNameSum += charDict[chr] for chr in lastNameChars: lastNameSum += charDict[chr] # cast sums to strings. In this example, this would be '2024' combinedNames = str(firstNameSum) + str(lastNameSum) # split the string into a list of chars combinedNameDigits = list(combinedNames) # sum them up finalSum = 0 for dgt in combinedNames: finalSum += int(dgt) # print the lucky number print finalSum
所以我的问题是,是我在哪里可以从这里走,因为数字不正确加起来和字母的值不正确,所以基本上我该如何正确计算
我真的不undersand如何:李四给165 465,以及如何:AAB DCDD给2024 然而,标准的方式转换成以数字字母和总结了一些数字如下:
def letters_to_numbers(name):
sum_ = 0
for letter in name:
sum_ += ord(letter.upper())-64 #ord("A")=65 minus 64 -> 1
return sum_
def sum_digits(number):
sum_ = 0
while number:
sum_ += number%10
number //=10
return sum_
sum_digits(
sum_digits(letters_to_numbers("john"))
+sum_digits(letters_to_numbers("doe")))
好像你会一直想调用'sum_digits'直到总和
好的,如果你想sum_digits,直到总和 user4624500
我建议你更新你的答案来做到这一点。无论如何,我反正是因为你完美地说明了这个想法,因为我没有看到有人长时间使用'sum_'而不是'sum'。这实际上是正确的做法。 –
这工作考虑你总是拆你的号码的位数水平,我让你把它包在功能和修改词典添加其他的字母
first = 'aaa'
last = 'bbb'
name = first + last
dicti = {'a':1, 'b':2, '1':1, '2':2 , '3':3 , '4':4 , '5':5 , '6':6 ,
'7':7 , '8':8 , '9':9 , '0':0}
while len(name) >1:
sum = 0
for letter in name:
sum = sum + dicti[letter]
name = str(sum)
final_sum = int(name)
什么是你的问题? – aberger
我编辑过它 –