确定何时停止可能的无限迭代?

问题描述 投票:0回答:1

作为初学者,我遇到的一个常见问题是何时停止迭代。例如,如果我要编写一个函数来确定整数是否为happy(通过蛮力),我什么时候停止?另一个例子,涉及到Mandelbrot set之类的东西,我怎么知道停止迭代并坚定地说数字发散或收敛?它是否取决于您正在处理的问题,或者是否有一种方法可以执行此类操作?

iteration
1个回答
0
投票

Brute-force方法,您必须找到基本情况才能像递归一样终止程序。对于快乐素数,基本情况是在迭代中找到循环。

代码

# sum of square of digit of n 
def numSquareSum(n): 
    squareSum = 0 
    while(n): 
        squareSum += (n % 10) * (n % 10) 
        n = int(n / 10) 
    return squareSum


#method return true if n is Happy Number 
def isHappyNumber(n): 
    li = [] 
    while (1):
        n = numSquareSum(n) 
        if (n == 1): 
            return True 
        if (n in li): 
            return False 
        li.append(n) 
# Main Code 
n = 7; 
if (isHappyNumber(n)): 
    print(n , "is a Happy number")
else: 
    print(n , "is not a Happy number") 

希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.