简体   繁体   中英

What's the difference between these two pieces of code?

I'm currently looking at this answer on Stackoverflow about finding combinations of k elements given an n long string. However while making some changes to it (to learn more about it, adapt it to my needs, and convert it to c), I found some problems.

Taking this piece of code:

def comb(sofar, rest, k):
  if k == 0:
    print(sofar)
  else:
    for i in range(len(rest)):
       comb(sofar + rest[i], rest[i+1:], k-1)

and adding a variable "n" which is supposed to keep the length of the string:

def comb(sofar, rest, n, k):
  if k == 0:
    print(sofar)
  else:
    for i in range(0, n):
       comb(sofar + rest[i], rest[i+1:], n-1, k-1)

Technically shouldn't these do the same thing? I'm getting a "string index out of range error" but should len(rest) be the same as "n"?

edit:

comb is called with:

comb("", "12345", 3)

comb2 is called with:

comb("", "12345", 5, 3)

您调用comb( ..., rest[i+1:], n-1, ...)rest[i+1:]可以短于n-1

So here is the problem in your code:

comb(sofar + rest[i], rest[i+1:], n-1, k-1)

Your tail recursive call is not correct. You are using rest[i+1:] and it's length is not n - 1 for two reasons. You are not updating n and you are not modifying rest in place. So length of rest will always be less than n - 1 for all i > 0 .

You should replace it by n - i - 1 .

NOTE : The first method is the correct way to do anyways. Minimize your dependencies.

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