2017-02-23 424 views
1

我必須在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 

所以我的問題是,是我在哪裏可以從這裏走,因爲數字不正確加起來和字母的值不正確,所以基本上我該如何正確計算

+1

什麼是你的問題? – aberger

+0

我編輯過它 –

回答

2

我真的不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"))) 
+0

好像你會一直想調用'sum_digits'直到總和<10。一個while循環也許? –

+0

好的,如果你想sum_digits,直到總和<10那麼: '而數字<10: number = sum_digits(number)' – user4624500

+0

我建議你更新你的答案來做到這一點。無論如何,我反正是因爲你完美地說明了這個想法,因爲我沒有看到有人長時間使用'sum_'而不是'sum'。這實際上是正確的做法。 –

0

這工作考慮你總是拆你的號碼的位數水平,我讓你把它包在功能和修改詞典添加其他的字母

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)