# Retrieved from: http://en.literateprograms.org/Sierpinski_triangle_(Python)?oldid=9930 ##A one-dimensional cellular automaton is a linear space of cells, ##each of which has a state. The automaton changes in discrete time ##steps called generations. In each generation the state of each cell is ##decided according to a set of rules that is based on the states of ##neighboring cells. In the case of one-dimensional cellular automaton ##each cell has its state decided by considering three cells, itself and ##its left and right neighboring cells. Neighbouring the first and last ##cells of the space, we will assume virtual cells that are always in a ##default state. The Sierpinski cellular automaton has two states, ##Empty and Full. The only rule states that a cell will be set to Full ##if and only if of the three states considered exactly one or two are ##Full. #Simpler statement: If you look like your 2 neighbors (L & R) you are dead next. AUTOMATA_SIZE = 64 #Put 0's everywhere in row 0, except for the center 1 #0000000000000000000000000100000000000000000000000000 init_states = [0]*(AUTOMATA_SIZE/2 - 1) + [1] + [0]*(AUTOMATA_SIZE/2) rules = {(0, 0, 0):0, (0, 0, 1):1, (0, 1, 0):1, (0, 1, 1):1, (1, 0, 0):1, (1, 0, 1):1, (1, 1, 0):1, (1, 1, 1):0} #So next generation will be: #0000000000000000000000001110000000000000000000000000 def apply_rules(states): width = len(states) new_states = states[:] new_states[0] = rules[(0, states[0], states[1])] new_states[width - 1] = rules[(states[width - 2], states[width - 1], 0)] for i in range(1, width - 2): new_states[i] = rules[(states[i - 1], states[i], states[i + 1])] return new_states def state_to_char(state): if state==0: return '0' #replace with empty space ' ' to remove the 0's else: return '1' #replace with some other symbol like @ , * or # def states_to_string(states): return ''.join(map(state_to_char, states)) def run_and_display(n_gens): states = init_states for i in range(n_gens): print states_to_string(states) states = apply_rules(states) if __name__ == "__main__": run_and_display(32)