How to change for-loop iterator variable in the loop in Python?

后端 未结 5 1518
旧巷少年郎
旧巷少年郎 2021-01-22 05:02

I want to know if is it possible to change the value of the iterator in its for-loop?

For example I want to write a program to calculate prime factor of a number in the

5条回答
  •  迷失自我
    2021-01-22 05:19

    The standard way of dealing with this is to completely exhaust the divisions by i in the body of the for loop itself:

    def primeFactors(number):
        for i in range(2,number+1):
            while number % i == 0:
                print(i, end=',')
                number /= i
    

    It's slightly more efficient to do the division and remainder in one step:

    def primeFactors(number):
        for i in range(2, number+1):
            while True:
                q, r = divmod(number, i)
                if r != 0:
                    break
                print(i, end=',')
                number = q
    

提交回复
热议问题