【发布时间】:2021-09-14 17:08:30
【问题描述】:
我正在尝试在我的 Python 程序中使用 RECURSION 计算一串数字中的所有偶数和奇数,但它一直向我显示此错误:“TypeError:并非所有参数在字符串格式化期间都转换...”请,可以有人帮帮我吗?
我在 JS 中尝试过,效果很好……但在 python 上却不行。我觉得我做错了什么。
下面是我的代码:
def count_even_odd_recursive(string):
def helper(helper_input):
odd = 0
even = 0
if len(helper_input) == 0:
return
if helper_input[0] % 2 == 0:
even += 1
elif helper_input[0] % 2 != 0:
odd += 1
helper(helper_input[1::])
if even > odd:
return f'There are more even numbers ({even}) that odd.'
else:
return f'There are more odd numbers ({odd}) that even.'
helper(string)
print(count_even_odd_recursive("0987650"))
【问题讨论】:
-
通常,
string由characters组成,而不是numbers。您究竟是如何将string转换为collection of numbers的? -
您需要将
helper_input[0]转换为int。尝试将int(helper_input[0]) % 2 == 0作为if语句的条件(以及对elif条件的否定)。 -
最重要的是,
count_even_odd_recursive不返回任何内容,因此printing其结果(您的最后一条语句)应始终打印None。 -
@zr0gravity7 我将它转换为 int,它给了我 None 作为输出。
-
返回助手(字符串)
标签: python python-3.x recursion