我想解决一个使用递归的问题,如果我使用'if'语句,这个问题会非常冗长。我正在查看n有多少次CONST = 50。我想返回50在n中出现的次数。我知道这很简单,但我想用递归来实现这一点,这并不是直截了当的。条件是这样的:在Python中使用递归
0 < n == 50 -> 1 instance
50 < n <= 100 -> 2 instance
100 < n <= 150 -> 3 instance
150 < n <= 200 -> 4 instance
200 < n <= 250 -> 5 instance
...
...
...
下面是我开始的,但我卡住了:提前提供任何帮助
def num_of_times(n)
""" (int) => int
when n is entered count 1 for every 50 found. If any number is over 50, yet does not
equal another 50 (e.g. n = 60; 60 - 50 = 10; 50 -> 1; 10 -> 1) will call for a count, which would be a count of 2 in this case.
>>>num_of_times(60)
2
>>>num_of_times(200)
4
"""
count = 0
if n > 0 and n == 50:
count += 1
elif n > 50:
""" Here is where my thinking is going to sleep"""
...
...
...
感谢。
为什么不使用整数除法之间和,之间= 2等,然后 ? '1 +((n-1)/ 50)' – sfstewman 2013-04-08 17:27:25
或'math.ceil(n/50.0)'。 – 2013-04-08 17:29:33