使用来自输入的字符串的递归计数

时间:2017-02-01 02:54:59

标签: python string recursion counting

我试图创建一个游戏,其中得分取决于字母的价值。我仍然难以保持计数,同时仍然会递归到字符串的下一个字母。我真的卡住了&希望你能帮忙!

def net_zero():
    guess_prompt = input('Guess a string: ')
    win_display = 'Congratulations you win'
    low_vowels = "aeiou" # +1
    low_constants = "bcdfghjklmnpqrstvwxyz" # -1
    up_vowels = "AEIOU" # +2
    up_constants = "BCDFGHJKLMNPQRSTVWXYZ" # -2
    ten_digits = "0123456789" # +3
    #else -3

    count = 0
    if len(guess_prompt) == 0:
        return count
    elif guess_prompt[0] in low_vowels:
        return (count + 1) + guess_prompt[1:]
    elif guess_prompt[0] in low_constants:
        return (count - 1) + guess_prompt[1:]
    elif guess_prompt[0] in up_vowels:
        return (count + 2) + guess_prompt[1:]
    elif guess_prompt[0] in up_constants:
        return (count - 2) + guess_prompt[1:]
    elif guess_prompt[0] in ten_digits:
        return (count + 3) + guess_prompt[1:] 
    else: return (count - 3) + guess_prompt[1:]

2 个答案:

答案 0 :(得分:3)

我想你想做以下

count = 0

if len(guess_prompt) == 0:
        return count
for letter in guess_prompt:
    if letter in low_vowels:
        count +=1
    if letter in low_constants:
        count -=1
    ...

return count

答案 1 :(得分:0)

我觉得你可以使用dict而不是使用字符串内容进行查找。它将改善查找时间。

guess_prompt = "aaB4??BBBBB"
value = {}
for char in "aeiou":
  value[char] = 1

for char in "bcdfghjklmnpqrstvwxyz":
  value[char] = -1

for char in "AEIOU":
  value[char] = 2

for char in "BCDFGHJKLMNPQRSTVWXYZ":
  value[char] = -2

for char in "0123456789":
  value[char] = 3

count = 0
for char in guess_prompt:
  count = count + value.get(char, -3) #default value -3

print(count) ## PRINTS -13 ##