简体   繁体   中英

While loops with multiple condtions. Python

I'm writing a function that, given a random int, will return the next int that is both a prime number and a palindrome. ie getint(13) will return 101. One of the conditions of this function is that recursion is not allowed.

Where am i going wrong here?

def golf(number):
    x = number +1
    for i in range(2, x):
        while str(x) != str(x)[::-1] and  x % i == 0:
            x += 1
    return x

Your for loop will only go as far as x 's initial value: the range(2,x) is computed only once, right after x = number + 1 . So increasing x inside the loop doesn't make a difference. Consider using a while loop, something like:

i = 2
while i <= x:
    ...
    i += 1

And you should probably first check is x is a palindrome (a "cheap" operation) and then, if it is, check weather it is prime (an "expensive" operation), not try do it all in a couple of nested loops that make little sense.

Divide the problem into smaller pieces. It will be easier for you to understand what's going on:

def golf(number):
    x = number + 1
    while True:
        if is_palindrome(x) and is_prime(x):
            return x
        x += 1

Now all you have to do is implement is_palindrome(x) and is_prime(x) :

import math

def is_prime(x):
    for i in xrange(2, math.ceil(math.sqrt(x))+1):
        if x % i == 0:
            return False
    return True

def is_palindrome(x):
    x = str(x)
    return x == x[::-1]

Side note : the math.ceil(math.sqrt(x))+1 might be an overkill (perhaps int(...)+1 is enough) if math.sqrt works correctly for squares (ie does not depend on floating point calculations so math.sqrt(a*a)==a is always true). Well in worst case the loop will do one more iteration then necessary. Better safe then sorry.

In your code:

def golf(number):
    x = number +1
    for i in range(2, x):
        while str(x) != str(x)[::-1] and  x % i == 0:
            x += 1
    return x

The program execution will not satisfy the while loop half of the time since any even number will not be divisible by any odd number and vice-versa . Also in a single iteration of the for loop, x will be incremented every time the while loop is satisfied.

You need to separate the prime checking and palindrome checking. The approach given by freakish is the simplest.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM