diff --git a/challenges/sierpinski.rst b/challenges/sierpinski.rst new file mode 100644 index 0000000..54648ae --- /dev/null +++ b/challenges/sierpinski.rst @@ -0,0 +1,72 @@ +Sierpinski Triangle +=================== + +**🎯 Construct a Sierpinski Triangle with a Cellular Automaton.** + +Consider the following rules: + +.. code:: python3 + + rules = { + ' ': ' ', + ' #': '#', + ' # ': '#', + ' ##': ' ', + '# ': '#', + '# #': ' ', + '## ': ' ', + '###': ' ', + } + +Now when you start with a string consisting of a single hash flanked by spaces: + +:: + + # + +The rules define how the next line looks like. +For the new line you look up character triplets from the original string. +The three triplets `" #", " # ", "# "` involving the original hash result in a new hash each. +So the second line is: + +:: + + ### + +If you propagate that line once again, the triplets with two hashes reult in a space: + +:: + + # # + +If you propagate once again, the first four lines look like: + +:: + + # + ### + # # + ### ### + +Write a program that propagates the following line 32 times: + +.. code:: python3 + + line = " " * 32 + "#" + " " * 32 + +Add an empty space at the beginning and end of each new line so that the line length stays the same. + +.. hint:: + + Experiment with the rule set defined by the dictionary by changing its values. + +What you can practise in this coding challenge +---------------------------------------------- + +- loops +- string operations +- looking up things in dictionaries + +.. seealso:: + + `Sierpinski Triangle on Wikipedia __` \ No newline at end of file diff --git a/index.rst b/index.rst index 53d0883..5603963 100644 --- a/index.rst +++ b/index.rst @@ -56,7 +56,6 @@ Coding Challenges :maxdepth: 1 challenges/ctree.rst - challenges/pyramid.rst challenges/fizzbuzz.rst challenges/quiz.rst challenges/checker.rst @@ -70,6 +69,7 @@ Coding Challenges challenges/querprodukt.rst challenges/birthdays.rst challenges/misty_mountains.rst + challenges/sierpinski.rst challenges/count_words.rst challenges/spiral.rst diff --git a/solutions/sierpinski.py b/solutions/sierpinski.py new file mode 100644 index 0000000..02f11df --- /dev/null +++ b/solutions/sierpinski.py @@ -0,0 +1,21 @@ + +code = { + ' ': ' ', + ' #': '#', + ' # ': '#', + ' ##': ' ', + '# ': '#', + '# #': ' ', + '## ': ' ', + '###': ' ', +} + +N = 32 +line = " " * N + "#" + " " * N +for _ in range(N): + print(line) + new = " " + for start in range(len(line) - 2): + sub = line[start: start + 3] + new += code[sub] + line = new + " "