今天我的问题是,如果我正在走向欧拉145的正确道路,如果它有点高效。我大部分都失望了,只是我的一个Defs给了我麻烦int(str(麻木)[: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);
答案 0 :(得分:1)
您可以使用内置函数all()
并使用一组来跟踪已经解决的数字;例如,如果你已经解决了36
,那么就没有理由解决63
:
seen = set()
def allEvenDigits(numb): # This is the issue one
return all( int(n)%2 == 0 for n in str(numb))
for i in range(1, 1000): # its 1000 to save a few minutes
revNumb = reversed(i);
total = revNumb+i;
if i not in seen and revNumb not in seen:
if (allEvenDigits(total)):
print(i, "+" , revNumb, "=",total);
seen.add(i)
seen.add(revNumb)
<强>输出:强>
(1, '+', 1, '=', 2)
(2, '+', 2, '=', 4)
(3, '+', 3, '=', 6)
(4, '+', 4, '=', 8)
(11, '+', 11, '=', 22)
(13, '+', 31, '=', 44)
(15, '+', 51, '=', 66)
(17, '+', 71, '=', 88)
(22, '+', 22, '=', 44)
(24, '+', 42, '=', 66)
(26, '+', 62, '=', 88)
(33, '+', 33, '=', 66)
(35, '+', 53, '=', 88)
(44, '+', 44, '=', 88)
...
all
上的帮助:
>>> all?
Type: builtin_function_or_method
String Form:<built-in function all>
Namespace: Python builtin
Docstring:
all(iterable) -> bool
Return True if bool(x) is True for all values x in the iterable.
If the iterable is empty, return True.
答案 1 :(得分:0)
当您的范围为range(0, len(str(numb)))
时,您将以空字符串开头。你可以用以下方法解决它:
def allEvenDigits(numb): # This is the issue one
hasEvenNumb = False;
for i in range(1, 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);
>>> allEvenDigits(52)
False
然而,似乎更容易做的是检查每个数字是否均匀:
def allEvenDigits(numb):
hasEvenNumb = True
for char in str(numb):
if int(char) % 2 == 0:
hasEvenNumb = False
break
return hasEvenNumb
allEvenDigits(52)
使它更直接一点,只检查单个数字而不是子字符串。
答案 2 :(得分:0)
def sumrevers(x):
summation = x + int(str(x)[::-1])
if summation % 2 != 0: return summation
def checknum(x):
if not (str(x)[-1] == "0") or (str(x)[0] == "0"):
if type(sumrevers(x)) == int:
num = str(sumrevers(x))
checklis = [k for k in str(num)]
if all(int(i) % 2 != 0 for i in checklis): return True
cnt = 0
for i in xrange(1, 1000000001):
if checknum(i):
cnt += 1
print cnt