幂和算法

2024-10-04 01:35:48 发布

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

我正在研究下面的问题,第二部分。然而,当我在python中实现它时,它失败了,“RecursionError:maximum recursion depth exceeded”。 enter image description here

这是我的算法:

import math
def sumofpowers2(x):
    count = 1
    if math.isclose(x ** count,0,rel_tol=0.001):
        return 0
    count += 1
    return 1 + x * sumofpowers2(x)

print(sumofpowers2(0.8))

已编辑。你知道吗


Tags: import算法returnifdefcountmathrel
2条回答

首先,请学习基本调试:在依赖值之前添加一个简单的print来跟踪值:

def sumofpowers2(x):
    count = 1
    print(x, count, x**count)
    if math.isclose(x ** count,0,rel_tol=0.001):
        ...

输出:

(0.8, 1, 0.8)
(0.8, 1, 0.8)
(0.8, 1, 0.8)
...

这就指出了关键问题:每次进入例程时,都将count重置为1。简单的解决方法是将初始化提升到循环之外:

count = 1

def sumofpowers2(x):
    global count
    print(x, count, x**count)
    if math.isclose(x ** count,0,rel_tol=0.001):

输出:

0.8 1 0.8
0.8 2 0.6400000000000001
0.8 3 0.5120000000000001
0.8 4 0.4096000000000001
0.8 5 0.3276800000000001
0.8 6 0.2621440000000001
0.8 7 0.20971520000000007
0.8 8 0.1677721600000001
0.8 9 0.13421772800000006
0.8 10 0.10737418240000006
0.8 11 0.08589934592000005
0.8 12 0.06871947673600004
0.8 13 0.054975581388800036
0.8 14 0.043980465111040035
0.8 15 0.03518437208883203
0.8 16 0.028147497671065624
0.8 17 0.022517998136852502
0.8 18 0.018014398509482003
0.8 19 0.014411518807585602
0.8 20 0.011529215046068483
0.8 21 0.009223372036854787
0.8 22 0.00737869762948383
0.8 23 0.005902958103587064
0.8 24 0.004722366482869652
0.8 25 0.0037778931862957215
0.8 26 0.0030223145490365774
0.8 27 0.002417851639229262
0.8 28 0.0019342813113834097
0.8 29 0.0015474250491067279
0.8 30 0.0012379400392853823
0.8 31 0.0009903520314283058
4.993810299803575

更好的是,将count作为一个添加到函数中的参数:

def sumofpowers2(x, count):
    print(x, count, x**count)
    if math.isclose(x ** count,0,rel_tol=0.001):
        return 0
    return 1 + x * sumofpowers2(x, count+1)

并不是说你的级联算法不是你期望的值。你知道吗

简而言之,sumofpowers2(x)使用相同的参数调用自身,导致无限递归(除非if条件从一开始就是真的,否则它永远不会是真的)。你知道吗

每次sumofpowers2()调用自身时,都会创建一个名为count的新变量并将其设置为1。要使这段代码正常工作,您需要找出一种方法来跨调用携带count的值。你知道吗

相关问题 更多 >