Python:Euler项目145

2024-04-26 18:51:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我今天的问题是,对于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);

Tags: thetoreturnifisdefitreg
3条回答

您可以使用内置函数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)

输出:

^{pr2}$

帮助关于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.

当您的范围是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

然而,似乎更容易做的是检查每个数字是否为偶数:

^{pr2}$

使其更加简单,并且只检查单个数字而不是子字符串。在

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

相关问题 更多 >