我如何才能摆脱产量和使用另一个函数,而不是在我的cod

2024-03-28 09:50:41 发布

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

def mot (n) :
  if n==0 : 
    yield n
  else :
    for m in mot(n-1) :
      yield [m]
    for k in range(0,n-1) :    
      for l in mot(k) :
        for r in mot(n-2-k) :        
          yield (l,r)

def countFor(f,n) :
  for i in range(n) :
    count = 0
    for t in f(i) : 
      count+=1
    yield count

def countsFor(mes,f,n) :
  print(mes)
  print([c for c in countFor(f,n)])
  print("")

def showFor(mes,f,n) :
  print(mes)
  for t in f(n) :
    print(t)
  print("")


showFor('Motzkin trees',mot,4)
countsFor('Motzkin trees',mot,12)
print("done")

def test() :
  for n in range(6) :
    print(n,list(mot(n)))  

我有以下输出motzkin数的代码,我想把yield表达式改成另一个更简单的表达式或函数,我该怎么做,我该怎么做? 谢谢


Tags: infor表达式defcountrangetreesprint
3条回答

从生成有限序列的生成器函数中去掉yield就像将生成的值附加到列表中以返回一样简单。你知道吗

例如,您的mot函数可以在没有yield的情况下修改为:

def mot(n) :
  output = []
  if n==0 :
    output.append(n)
  else :
    for m in mot(n-1) :
      output.append([m])
    for k in range(0,n-1) :
      for l in mot(k) :
        for r in mot(n-2-k) :
          output.append((l,r))
  return output

但是,除非调用者需要对返回的列表执行基于索引的操作,否则不需要转换函数以返回列表,因为生成器速度更快,内存效率更高。你知道吗

作为一个动态规划:

def mot(t):
    M = [1, 1]
    for n in range(2, t+1):
        M.append(((2*n + 1)*M[n-1] + (3*n - 3)*M[n-2]) // (n + 2))
    return M

In []:    
mot(4)

Out[]:
[1, 1, 2, 4, 9]

In []:
mot(10)

Out[]:
[1, 1, 2, 4, 9, 21, 51, 127, 323, 835, 2188]

根据维基百科,莫普兹金数满足这个循环关系:

M_n = ((2n + 1)/(n + 2)) M_(n-1) + ((3n - 3)/(n+2)) M_(n-2)

这很容易翻译成代码:

from itertools import count

def mot():
    M_n1 = 1
    M_n2 = 1
    yield 1
    yield 1
    for n in count(2):
        M = ((2*n + 1)/(n + 2))*M_n1 + ((3*n - 3)/(n+2))*M_n2
        M = int(M)
        yield M
        M_n1, M_n2 = M, M_n1

现在我们可以循环遍历序列中的项,直到数字变得太大而无法存储,或者从列表的前面切几个:

from itertools import islice

print(list(islice(mot(), 10)))
# [1, 1, 2, 4, 9, 21, 51, 127, 323, 835]

相关问题 更多 >