所以我正在研究Project Euler 145,上面写着:
Some positive integers n have the property that the sum
[ n + reverse(n) ]
consists entirely of odd (decimal) digits. For instance,36 + 63 = 99
and409 + 904 = 1313
. We will call such numbers reversible; so 36, 63, 409, and 904 are reversible. Leading zeroes are not allowed in either n or reverse(n).There are 120 reversible numbers below one-thousand.
How many reversible numbers are there below one-billion (10**9)?
我正在尝试以下代码(而不是使用10^9,而是使用10来检查结果(应该是零)是否正在发生:
def check(x):
y = int(str(x)[::-1]) #x backwards
#add the rev number to the original number (convert them to a list)
xy = list(str(x+y))
#a list of even digits.
evens = ['0', '2', '4', '6', '8']
#check if the number has any digits using intersection method.
intersect = set(xy).intersection(set(evens))
if not intersect:
#if there was no intersection the digits must be all odd.
return True
return False
def firstCheck(x):
if (int(str(x)[:1])+(x%10))%2 == 0:
#See if first number and last number of x make an even number.
return False
return True
def solve():
L = range(1, 10) #Make a list of 10
for x in L:
if firstCheck(x) == False:
#This quickly gets rid of some elements, not all, but some.
L.remove(x)
for x in L:
if check(x) == False:
#This should get rid of all the elements.
L.remove(x)
#what is remaining should be the number of "reversible" numbers.
#So return the length of the list.
return len(L)
print solve()
它分为两个部分:在solve
方法中有一个firstCheck
和{
我看到两个问题。在
首先,您(两次)修改要迭代的列表:
这将导致意想不到的和难以预测的行为。迭代列表的副本或使用列表理解进行简单筛选:
^{pr2}$等等
第二,您没有检查以消除任何前导零,所以check(10)在应该为False时为True。修复这些问题后,您的代码似乎可以正常工作:
[我刚刚添加了一个参数来选择范围。]
Java解决方案,需要3分钟
相关问题 更多 >
编程相关推荐