使用while循环生成数学序列?
我被要求做以下事情:
使用一个循环,你需要写一个程序,生成下面这个数学序列:
1 * 9 + 2 = 11(你需要计算这个数字)
12 * 9 + 3 = 111
123 * 9 + 4 = 1111
然后你的程序要一直运行,直到结果只包含“1”。你可以把数字当作字符串来构建,然后在计算之前把它转换成整数。计算完后,再把结果转换回字符串,看看它是否全是“1”。
示例输出:
1 * 9 + 2 = 11
12 * 9 + 3 = 111
123 * 9 + 4 = 1111
1234 * 9 + 5 = 11111
这是我的代码:
def main():
Current = 1
Next = 2
Addition = 2
output = funcCalculation(Current, Addition)
while (verifyAllOnes(output) == True):
print(output)
#string concat to get new current number
Current = int(str(Current) + str(Next))
Addition += 1
Next += 1
output = funcCalculation(Current, Next)
def funcCalculation(a,b):
return (a * 9 + b)
def verifyAllOnes(val):
Num_str = str(val)
for ch in Num_str:
if(str(ch)!= "1"):
return False
return True
main()
问题是公式没有和每行的“1”的序列一起打印出来。我哪里出错了?
2 个回答
测试全是1的情况
首先,这里有一种简单的方法来检查一个值是否全是1:
def only_ones(n):
n_str = str(n)
return set(n_str) == set(['1'])
你可以用一些更“数学”的方式来做这个检查,但我不确定这样做会不会更快。不过,如果你对其他进制(比如不是10进制)感兴趣,这种方法会更容易推广。
def only_ones(n):
return (n % 10 == 1) and (n == 1 or only_ones2(n / 10))
关于如何生成特定的递归关系的不确定性...
至于实际解决这个问题,实际上不太清楚这个序列应该是什么。
接下来是什么呢?
123456
1234567
12345678
123456789
?
是1234567890吗?还是12345678910?或者1234567900?如果不回答这个问题,就无法以任何通用的方式解决这个问题(除非这些111..的序列在你遇到这个问题之前就结束了)。
我将采用一个数学上比较吸引人的假设,那就是我们讨论的值是之前所有11111...值的总和(注意,12 = 11 + 1,123 = 111 + 11 + 1,1234 = 1111 + 111 + 11 + 1,等等)。
一个解决方案
在这种情况下,你可以这样做:
def sequence_gen():
a = 1
b = 1
i = 2
while only_ones(b):
yield b
b = a*9 + i
a += b
i += 1
注意,我把这个放在一个生成器里,这样可以更方便地只获取你实际想要的结果数量。这个序列可能是无限的,所以单独运行这个while代码可能会花费一些时间;-)
s = sequence_gen()
s.next() #=> 1
s.next() #=> 11
生成器给你提供了很多灵活性。例如,你可以使用itertools.islice
函数来获取序列的前10个值:
import itertools as it
s = sequence_gen()
xs = [x for x in it.islice(s, 10)]
print xs
伪代码:
a = 1
b = 2
result = a * 9 + b
while string representation of result contains only 1s:
a = concat a with the old value of b, as a number
b = b + 1
result = a * 9 + b
这个可以直接转换成Python代码。