Search code examples
pythonyield-keywordmotzkin-numbers

How can I get rid of yield and use another function instead in my code


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)))  

I have the following code that outputs the motzkin numbers, I want to change the yield expressions to another, more simple expressions or functions, how can I do that , what can I do? thanks


Solution

  • Getting rid of yield from a generator function that generates a finite sequence is as easy as appending the yielded values to a list for return instead.

    For example, your mot function can be revised without yield as:

    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
    

    But unless the caller needs to perform index-based operations with the returning list, there's no need to convert the function so it returns a list, as generators are both faster and more memory-efficient.