开发者

resetting the parameters of a for loop from inside the loop in Python3

I am working through the project euler problems in Python 3 as a fun way to learn the language, and my solution to problem number three I feel is a little funky. The problem is to find the largest prime factor of 600851475143, and I solved it in a pretty sprawling way as follows:

#!/usr/local/bin/python3
# encoding: utf-8
# what is the largest prime factor of whatever the user types


def main():
    original = int(input("Input a number: "))
    if original == isPrime(original):
        print(original, "is prime")
    else:
        print(factor(original), "is the largest prime factor of", original)

def factor(number):
    nummy=2
    for num in range(nummy, number):
        if (number%num==0 and isPrime(num)==num):
            biggest=int(num)
            number=int(number/biggest)
            nummy = int(biggest+2)
            print("so far,",biggest, "is the biggest prime factor...")
            if number < biggest:
                break
    return big开发者_C百科gest      

def isPrime(value):
    for num in range(2, int(value**0.5)+1):
        if value%num==0:
            return int(value/num)
    return value


if __name__ == "__main__": main()

as you can see, in my "factor" function, I tried to update the upper limit of the range in my for loop, but it didn't really work like I was expecting so I had to add the if number < biggest block to get the whole thing to run in a reasonable amount of time.

Is there a way to update the parameters of a for loop from inside the loop?

I appreciate any insight on this.


range(nummy, number) is evaluated before you enter the for loop so it is not possible in your case.

Generally it is possible in python(though not always), but it is a bad idea. It is better to check for changed conditions and break out of the loop as you did.


I don't think that will run in reasonable time.

I'll point out a few things, without giving out solutions:

You don't need to try and divide X with every number up to X to know it's prime. If it's not divisible by 2, it won't be divisible by 4 either; if not by 3, less so by 9. You can also stop earlier than (X-1) -- after all, X won't be divisible by a prime larger than... what?

Well, I had 3 more items, but they all derive from the above. Hope it helps you!


As S. Lott said, you will want to use a while loop, but you would want to assign the ceiling of the range to a variable since you want it to be mutable.

Also, I am not sure why you are doing:

biggest=int(num)
number=int(number/biggest)
nummy = int(biggest+2)

num would already be an int (otherwise, you would not be able to do the mathematical operations to do prior to that point). Integer division could also be done as:

number = number // biggest
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜