[英]My code is producing a logic error with recursion and I don't know how to fix it
def k_comp(n):
n_new = 0
if n == 0:
n_new = 2
if n == 1:
n_new == 1
if n > 1:
n_new = (k_comp(n-1) + k_comp(n-2))**2
return n_new
def Kseq(start, stop, step):
""" (int,int,int) -> list of integers
Kseq(0,6,1)--->
[2, 1, 9, 100, 11881, 143544361]
Kseq(2,6,2)---->
[9, 11881]
"""
final_list = []
append_this = 0
for i in range (start,stop,step):
append_this = k_comp(i)
final_list.append(append_this)
return final_list
print(Kseq(0,6,1))
Instead of the expected output it prints: [2, 0, 4, 16, 144, 16384] 而不是预期的输出,它打印:[2,0,4,16,144,16384]
The code is supposed to do this: Input: This function is passed start (>= 0), stop (>start), and step (>= 1) values that define a sequence of numbers. 该代码应该执行以下操作:输入:此函数传递定义数字序列的开始(> = 0),停止(> start)和步进(> = 1)值。 Output: This function returns a list of the corresponding K sequence. 输出:此函数返回相应K序列的列表。 The k sequence is k(n) = (k(n-1) + k(n-2))^2 第k个序列为k(n)=(k(n-1)+ k(n-2))^ 2
You have mixed up assignment and equality in k_comp 您在k_comp中混合了分配和相等性
You have: 你有:
if n == 1:
n_new == 1
You should have: 你应该有:
if n == 1:
n_new = 1
Single '=' means assign the value on the right to the variable on the left. 单个“ =”表示将右侧的值分配给左侧的变量。
Double '==' means is the left value and the right value equal. 双'=='表示左值和右值相等。 In this case it will be going no it isn't equal therefore False. 在这种情况下,它将不存在,因此不相等,因此为False。 False is a valid python statement; False是有效的python语句; it just won't be doing what you expect. 只是不会做您期望的事情。
Your issue is with your second if
condition in k_comp()
, ==
is an equality test: 您的问题是您的第二个if
条件是否在k_comp()
, ==
是一个相等测试:
if n == 1:
n_new == 1
This leaves n_new = 0
, so I assume you meant: 这使n_new = 0
,所以我假设你的意思是:
if n == 1:
n_new = 1
After making the change: 进行更改后:
In []:
Kseq(0, 6, 1)
Out[]:
[2, 1, 9, 100, 11881, 143544361]
Note: This is going to be very inefficient because it calculates k_comp(k)
multiple times, you can just construct the sequence of k
, eg: 注意:这将非常低效,因为它将多次计算k_comp(k)
,您只需构造k
的序列即可,例如:
def k_seq():
k = [2, 1]
for _ in range(2, n):
k.append((k[-1] + k[-2])**2)
return k
def Kseq(start, stop, step):
return k_seq(stop)[start::step]
In []
Kseq(0, 6, 1)
Out[]:
[2, 1, 9, 100, 11881, 143544361]
In []:
Kseq(2, 6, 2)
Out[]:
[9, 11881]
Difference in timing: 时间差异:
In []:
%timeit Kseq_recursive(0, 10, 1)
Out[]:
75.8 µs ± 1.28 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In []:
%timeit Kseq_sequence(0, 10, 1)
Out[]:
4.39 µs ± 77.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Or as a generator 或作为发电机
import itertools as it
def k_gen():
kprime, k = 2, 1
yield from (kprime, k)
while True:
kprime, k = k, (kprime + k)**2
yield k
def Kseq(start, stop, step):
return list(it.islice(k_gen(), start, stop, step))
In []:
Kseq(0, 6, 1)
Out[]:
[2, 1, 9, 100, 11881, 143544361]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.