0 Replies - 1672 Views - Last Post: 12 July 2012 - 12:01 PM

#1 atraub   User is offline

  • Pythoneer
  • member icon

Reputation: 830
  • View blog
  • Posts: 2,251
  • Joined: 23-December 08

Kolakoski Sequence Generator

Posted 12 July 2012 - 12:01 PM

Description: This is an example of an object oriented generator used for finding values of the Kolakoski sequence. Despite this being an object oriented generator, it still works exactly the same as any other generator would and this generator is Python2 and Python3 compatible. There are several unsolved questions regarding the Kolakoski sequence listed here: http://faculty.evans...eger/index.html Perhaps this generator will be used by the mathematician who solves some of them!
__author__ = "atraub"
__date__= "6/09/2012"

class Kolakoski:
    """Class based generator for the Kolakoski sequence"""
    def __init__(self):
        """Sets up the generator"""
        self.sequence = []
        self.i = 0
        self.currentNum = 1
        self.nextNum = 2

    def __next__(self):
        """Implements next() in Python 3"""
        return self.__realNext()

    def next(self):
        """Implements next() in Python 2"""
        return self.__realNext()

    def __realNext(self):
        """Underlying function to get the next value in the sequence"""
        if self.i == 0:
            """Base case for first value"""
            retVal = [1]
        elif self.i == 1:
            """Base case for second value"""
            retVal = [2,2]
            """Default case for all values after the first 2"""
            retVal = self.__getNext()

        return retVal
    def __getNext(self):
        """Gets the next value after the first two"""
        return [self.currentNum for a in range(self.sequence[self.i])]

    def __update(self,retVal):
        """Handles upkeep of the generator"""
        self.i += 1 #increments the index
        self.sequence.extend(retVal) #Adds newest value to underlying sequence
        self.currentNum,self.nextNum = self.nextNum,self.currentNum #sets the current number
    def __str__(self):
        """Creates a string representation of the underlying sequence"""
        return ",".join([str(a) for a in self.sequence])

    def getLast(self):
        """gets the last value generated by the sequence"""
        return self.last

Is This A Good Question/Topic? 0
  • +

Page 1 of 1