Download code

Jump to: navigation, search

Back to Sierpinski_triangle_(Python)

Download for Windows: single file, zip

Download for UNIX: single file, zip, tar.gz, tar.bz2

sierpinski.py

 1 # The authors of this work have released all rights to it and placed it
 2 # in the public domain under the Creative Commons CC0 1.0 waiver
 3 # (http://creativecommons.org/publicdomain/zero/1.0/).
 4 # 
 5 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 # 
13 # Retrieved from: http://en.literateprograms.org/Sierpinski_triangle_(Python)?oldid=19207
14 
15 AUTOMATA_SIZE = 80
16 init_states = [0]*(AUTOMATA_SIZE/2 - 1) + [1] + [0]*(AUTOMATA_SIZE/2)
17 rules = {(0, 0, 0):0, 
18          (0, 0, 1):1,
19          (0, 1, 0):1,
20          (0, 1, 1):1,
21          (1, 0, 0):1,
22          (1, 0, 1):1,
23          (1, 1, 0):1,
24          (1, 1, 1):0}
25 def apply_rules(states):
26     width = len(states)
27     new_states = states[:]
28     new_states[0] = rules[(0, states[0], states[1])]
29     new_states[width - 1] = rules[(states[width - 2], states[width - 1], 0)]
30     for i in range(1, width - 2):
31         new_states[i] = rules[(states[i - 1], states[i], states[i + 1])]
32     return new_states
33 def state_to_char(state):
34     if state==0: 
35         return ' '
36     else: 
37         return '@'
38         
39 def states_to_string(states):
40     return ''.join(map(state_to_char, states))
41     
42 def run_and_display(n_gens):
43     states = init_states
44     for i in range(n_gens):
45         print states_to_string(states)
46         states = apply_rules(states)
47 
48 if __name__ == "__main__":
49     run_and_display(32)


hijacker
hijacker
hijacker
hijacker