简体   繁体   English

如何在 Python 中返回递归 function 的列表

[英]How to return a list of a recursive function in Python

I'm trying to return a list of strings from the function that calculate all possibilites permutations without consecutives 0.我正在尝试从 function 返回一个字符串列表,该列表计算没有连续 0 的所有可能排列。

To do this, I'm running a recursive function that works, but I need to create a list with the results.为此,我正在运行一个有效的递归 function,但我需要创建一个包含结果的列表。

# Function to print all n–digit binary strings without any consecutive 0's
def countStrings(n, out="", last_digit=0):
    # if the number becomes n–digit, print it
    
    if n == 0:
        print(out)
        return
    
    # append 0 to the result and recur with one less digit
    countStrings(n - 1, out + '1', 0)
    
 
    # append 1 to the result and recur with one less digit
    # only if the last digit is 0
    if last_digit == 0:
        countStrings(n - 1, out + '0', 1)

When I run it eg: a = countStrings(3) , it print all possibilits but the variable "a" returs as "None":当我运行它时,例如: a = countStrings(3) ,它会打印所有可能性,但变量“a”返回为“无”:

results:结果:

111
110
101
011
010

type(a): Nonetype

I've tried to insert an append in some places, but with no result我尝试在某些地方插入 append,但没有结果

I don't have a clue what I'm missing我不知道我错过了什么

Is it what you are looking for?是你要找的吗?

# Function to print all n–digit binary strings without any consecutive 0's
def countStrings(n, out="", last_digit=0, acc=[]):
    # if the number becomes n–digit, print it
    
    if n == 0:
        print(out)
        acc.append(out)
        return acc
    
    # append 0 to the result and recur with one less digit
    countStrings(n - 1, out + '1', 0, acc)
    
 
    # append 1 to the result and recur with one less digit
    # only if the last digit is 0
    if last_digit == 0:
        countStrings(n - 1, out + '0', 1, acc)
    return acc

acc = countStrings(3)
print('acc', acc)

Output: Output:

111
110
101
011
010
('acc', ['111', '110', '101', '011', '010'])

If you don't want to use return you can create global parameter and call it once function finishes to execute:如果您不想使用return您可以创建global参数并在 function 完成执行后调用它:

res = []

def countStrings(n, out="", last_digit=0):
    global res
    # if the number becomes n–digit, print it
    if n == 0:
        print(out)
        res.append(out)
        return 
    
    # append 0 to the result and recur with one less digit
    countStrings(n - 1, out + '1', 0)
    
 
    # append 1 to the result and recur with one less digit
    # only if the last digit is 0
    if last_digit == 0:
        countStrings(n - 1, out + '0', 1)

Calling print(res) will give you:调用print(res)会给你:

['111', '110', '101', '011', '010']

solution A溶液A

I would suggest separating the program's concerns into multiple functions -我建议将程序的关注点分成多个功能 -

def binaries(n):
  for m in range(2 ** n):
    yield f"{m:>0{n}b}"
print(list(binaries(3)))
['000', '001', '010', '011', '100', '101', '110', '111']

Now we can write pairwise which iterates pairwise over an iterable -现在我们可以写成对的,它在一个可迭代的对象上pairwise地迭代——

from itertools import tee, islice

def pairwise(t):
  a, b = tee(t)
  yield from zip(a, islice(b, 1, None))
print(list(pairwise("011001")))
[('0', '1'), ('1', '1'), ('1', '0'), ('0', '0'), ('0', '1')]

Now it's easy to implement solution as a combination of all binaries of size n where pairwise analysis of any particular binary does not contain two adjacent zeroes -现在很容易将solution实现为大小为n的所有binaries的组合,其中任何特定二进制文件的pairwise分析不包含两个相邻的零 -

def solution(n):
  for b in binaries(n):
    for p in pairwise(b):
      if p == ('0','0'):
        break
    else:
      yield b
print(list(solution(3)))
['010', '011', '101', '110', '111']

If all only want a count of the solutions, we can write count_solutions as a specialisation of solutions -如果所有人都只想要解决方案的计数,我们可以将count_solutions写为solutions的专业化 -

def count_solutions(n):
  return len(list(solution(n)))
print(count_solutions(3))
5

Let's see it work on a larger example, n = 8 -让我们看一个更大的例子, n = 8 -

print(list(solutions(8)))
print(count_solutions(8))
['01010101', '01010110', '01010111', '01011010', '01011011', '01011101', '01011110', '01011111', '01101010', '01101011', '01101101', '01101110', '01101111', '01110101', '01110110', '01110111', '01111010', '01111011', '01111101', '01111110', '01111111', '10101010', '10101011', '10101101', '10101110', '10101111', '10110101', '10110110', '10110111', '10111010', '10111011', '10111101', '10111110', '10111111', '11010101', '11010110', '11010111', '11011010', '11011011', '11011101', '11011110', '11011111', '11101010', '11101011', '11101101', '11101110', '11101111', '11110101', '11110110', '11110111', '11111010', '11111011', '11111101', '11111110', '11111111']
55

solution B溶液 B

I've been thinking about this problem a little more and I didn't like how the numbers in the solution above are converted to strings before comparison.我一直在考虑这个问题,我不喜欢上面解决方案中的数字在比较之前如何转换为字符串。

First we write bitwise -首先我们bitwise写 -

def bitwise(n, e):
  if e == 0:
    return
  else:
    yield from bitwise(n >> 1, e - 1)
    yield n & 1
for n in range(2 ** 3):
  print(tuple(bitwise(n, 3)))
(0, 0, 0)
(0, 0, 1)
(0, 1, 0)
(0, 1, 1)
(1, 0, 0)
(1, 0, 1)
(1, 1, 0)
(1, 1, 1)

Then pairwise -然后pairwise -

from itertools import tee, islice

def pairwise(t):
  a, b = tee(t)
  yield from zip(a, islice(b, 1, None))
for n in range(2 ** 3):
  print(bin(n), list(pairwise(bitwise(n, 3))))
0b0 [(0, 0), (0, 0)]
0b1 [(0, 0), (0, 1)]
0b10 [(0, 1), (1, 0)]
0b11 [(0, 1), (1, 1)]
0b100 [(1, 0), (0, 0)]
0b101 [(1, 0), (0, 1)]
0b110 [(1, 1), (1, 0)]
0b111 [(1, 1), (1, 1)]

Finally solution -最后的solution -

def solution(e):
  for n in range(2 ** e):
    for p in pairwise(bitwise(n, e)):
      if p == (0, 0):
        break
    else:
      yield n
sln = list(map(bin, solution(3)))
print(sln)
print(len(sln))
['0b10', '0b11', '0b101', '0b110', '0b111']
5

And n = 8 - n = 8 -

sln = list(map(bin, solution(8)))
print(sln)
print(len(sln))
['0b1010101', '0b1010110', '0b1010111', '0b1011010', '0b1011011', '0b1011101', '0b1011110', '0b1011111', '0b1101010', '0b1101011', '0b1101101', '0b1101110', '0b1101111', '0b1110101', '0b1110110', '0b1110111', '0b1111010', '0b1111011', '0b1111101', '0b1111110', '0b1111111', '0b10101010', '0b10101011', '0b10101101', '0b10101110', '0b10101111', '0b10110101', '0b10110110', '0b10110111', '0b10111010', '0b10111011', '0b10111101', '0b10111110', '0b10111111', '0b11010101', '0b11010110', '0b11010111', '0b11011010', '0b11011011', '0b11011101', '0b11011110', '0b11011111', '0b11101010', '0b11101011', '0b11101101', '0b11101110', '0b11101111', '0b11110101', '0b11110110', '0b11110111', '0b11111010', '0b11111011', '0b11111101', '0b11111110', '0b11111111']
55

suggested reading建议阅读

If you've never seen a for..else loop in Python, please read the docs about this wonderful construct如果您从未在 Python 中看到for..else循环,请阅读有关这个奇妙构造的文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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