我今天的问题是,对于Euler 145,我是否走在正确的道路上,它是否有点效率。我已经完成了大部分,只有一个def在int(str(numb)[:I])%2==0进行偶数检查时出现问题。我的代码在下面。10号线是问题点
def reversed(reg): # to flip the number around
fliped = str(reg)[::-1];
return(int(fliped)); # Return it as a int.
def allEvenDigits(numb): # This is the issue one
hasEvenNumb = False;
for i in range(0, len(str(numb))):
if int(str(numb)[:i])%2 == 0: # if int of the string numb's char at i is even
hasEvenNumb = True; ## return that it is true
break; # why go on if we found a even.
return(hasEvenNumb);
for i in range(1, 1000): # its 1000 to save a few minutes
revNumb = reversed(i);
total = revNumb+i;
if(allEvenDigits(total)):
print(i, "+" , revNumb, "=",Total);
您可以使用内置函数
all()
,并使用一个集合来跟踪已经求解的数字;例如,如果您已经求解了36
,那么就没有理由求解63
:输出:
^{pr2}$帮助关于
all
:当您的范围是
range(0, len(str(numb)))
时,您从一个空字符串开始。你可以用以下方法解决:然而,似乎更容易做的是检查每个数字是否为偶数:
^{pr2}$使其更加简单,并且只检查单个数字而不是子字符串。在
相关问题 更多 >
编程相关推荐