我有以下代码:
import math
print "Hey, lets solve Task 4 :)"
number1 = input ("How many digits do you want to look at? ")
number2 = input ("What would you like the digits to add up to? ")
final = []
if number1 == 1:
cow = range(1,10)
elif number1 == 2:
cow = range(10,100)
elif number1 == 3:
cow = range(001,1000)
elif number1 == 4:
cow = range(1000,10000)
elif number1 == 5:
cow = range(10000,100000)
elif number1 == 6:
cow = range(100000,1000000)
elif number1 == 7:
cow = range(1000000,10000000)
elif number1 == 8:
cow = range(10000000,100000000)
elif number1 == 9:
cow = range(100000000,1000000000)
elif number1 == 10:
cow = range(1000000000,10000000000)
number3 = cow[-1] + 1
number10 = number3
number8 = number3 - 1
if number1 == 1:
test = range(1,number10)
elif number1 == 2:
test = range(00,number10)
elif number1 == 3:
test = range(000,number10)
elif number1 == 4:
test = range(0000,number10)
elif number1 == 5:
test = range(00000,number10)
elif number1 == 6:
test = range(000000,number10)
elif number1 == 7:
test = range(0000000,number10)
elif number1 == 8:
test = range(00000000,number10)
elif number1 == 9:
test = range(000000000,number10)
elif number1 == 10:
test = range(0000000000,number10)
if number1 == 1:
number7 = number8
elif number1 == 2:
number7 = number8 + 1
elif number1 == 3:
number7 = number8 + 1
elif number1 == 4:
number7 = number8 + 1
elif number1 == 5:
number7 = number8 + 1
elif number1 == 6:
number7 = number8 + 1
elif number1 == 7:
number7 = number8 + 1
elif number1 == 8:
number7 = number8 + 1
elif number1 == 9:
number7 = number8 + 1
elif number1 == 10:
number7 = number8 + 1
n = 0
while n < number7:
a = test[n]
a = str(a)
print a
number4 = sum(int(x) for x in a)
if number4 == number2:
final.append(number4)
n = n + 1
print len(final)
基本上,这段代码计算出有多少位数字包含整数,这些整数加起来等于某些数字。当它运行时,它会询问您想要多少位数(例如 4)以及您希望它们相加的数字。例如,您可以选择 4 和 18,它会计算从 1000 到 9999 的数字中有多少整数加起来为 18(例如 4545)。
问题是,最后一个问题问有多少个 10 位数字加起来是 39。使用这个代码,我的电脑会花很多时间,因为它必须从 1 一直数到最大的 10 位数字。当我尝试它时,它使我的电脑崩溃了!
有没有办法加快循环?
谢谢!