简体   繁体   中英

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]

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. Output: This function returns a list of the corresponding K sequence. The k sequence is k(n) = (k(n-1) + k(n-2))^2

You have mixed up assignment and equality in 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 is a valid python statement; 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 n == 1:
    n_new == 1

This leaves n_new = 0 , so I assume you meant:

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:

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM