Python: Function produces different output after coverting it to a generator function : I created the following algorithm to create a function for the generation of the Baum-Sweet-Sequence ([Wikipedia][1])

    def baum_sweettest(number_as_byte):
        counter = 0
        for bit in str(number_as_byte):
          print("bit = ", bit)
          if bit == "0":
            counter += 1 
          if bit == "1":
            if counter%2 !=0 or counter == 1:
              counter = 0
              return 0
        print("counter = ", counter)
        if counter%2 !=0 or counter == 1:
          counter = 0
          return 0
        else:
          return 1
    
    print(baum_sweettest(110))

I am fairly new to Python so I am aware, that this is probably far from the best way to solve it. Any feedback on this is welcome, however I am primarily interested in why this function creates different results, when converted to the following generator-function:

    def baum_sweet():
    yield 1
    counter = 0
    for n in range(1,1000):
        number_as_binary = bin(n)[2::]
        for bit in str(number_as_binary):
            if bit == "0": 
                counter += 1 
            if bit == "1":
                if counter%2 !=0 or counter == 1:
                    counter = 0
                    yield 0
        if counter%2 !=0 or counter == 1:
            counter = 0
            yield 0
        else:
            counter = 0
            yield 1

baum_sweettest returns 0 when tested for the number 6 (110) which is correct.

The generator-object created by baum_sweet delivers yields correct results up to the number 6, where it yields 1.

Since the algorithm is the same in both cases I guess this is due to a different behavior in generator functions. Reading through the documentation I found, that those are not terminated, but rather just continued until the next yield-statement. So I made shure, that my counter will be reset manually before every yield. However the generator-version of my algorithm still yields different results at some point, as the same algorithm in a "non-generator-function".

Can someone elaborate why those two functions return/yield different results?


  [1]: https://en.wikipedia.org/wiki/Baum%E2%80%93Sweet_sequence