From 20f68e9ed48cd3f408bd87e9df1dd3a6d55e5781 Mon Sep 17 00:00:00 2001 From: Kristian Rother Date: Mon, 12 Feb 2024 10:30:43 +0100 Subject: [PATCH] add crypto task to builtin functions --- first_steps/builtin_functions.rst | 149 ++++++++++++++++++++++++++++++ first_steps/dictionaries.rst | 26 ++++++ first_steps/indexing.rst | 25 +++-- first_steps/statistics.rst | 15 ++- index.rst | 32 ++----- reference/builtin_functions.rst | 25 +++-- reference/introspection.rst | 71 -------------- 7 files changed, 227 insertions(+), 116 deletions(-) create mode 100644 first_steps/builtin_functions.rst delete mode 100644 reference/introspection.rst diff --git a/first_steps/builtin_functions.rst b/first_steps/builtin_functions.rst new file mode 100644 index 0000000..1e179bc --- /dev/null +++ b/first_steps/builtin_functions.rst @@ -0,0 +1,149 @@ +Substitution Cipher +=================== + +In this chapter you learn: +-------------------------- + +==== ============================================== +area topic +==== ============================================== +🚀 encrypt text with a substitution cipher +⚙ convert strings to lists and back +⚙ use a random seed +💡 use the ``random`` module +💡 use the ``string`` module +💡 use the ``zip`` function +🔀 use the ``dict(zip())`` pattern +🐞 fix IndexErrors +==== ============================================== + +Exercise 1: Random string +------------------------- + +The following code creates a random chiffre that we will use for encryption. +Insert ``alphabet``, ``chars``, ``join`` and ``random`` into the code: + +.. code:: python3 + + import random + + alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + + ___ = list(___) + ___.shuffle(chars) + chiffre = "".___(chars) + print(chiffre) + +Run the program a couple of times. + + +Exercise 2: Random seed +----------------------- + +Add the following line after the import: + +.. code:: python3 + + random.seed(77) + +Run the program a couple of times. +What changes? + +Also try running the program with different numbers. + + +Exercise 3: Chiffre indices +--------------------------- + +Output each character from the chiffre and its index +Simplify the following code using the function ``enumerate()``: + +.. code:: python3 + + i = 0 + for char in chiffre: + print(i, char) + i += 1 + + +Exercise 4: Lookup dictionary +----------------------------- + +Create a dictionary that maps unencrypted to encrypted characters: + +.. code:: python3 + + lookup = {} + i = 0 + while i < len(alphabet): + char = alphabet[i] + lookup[char] = chiffre[i] + i += 1 + print(lookup) + +Execute the program slowly on paper to make sure you understand the index operations. + +Exercise 5: Zip +--------------- + +Use the following code to make the program above simpler: + +.. code:: python3 + + for char, chif in zip(alphabet, chiffre) + print(char, chif) + +Once you understand what happens, also try: + +.. code:: python3 + + lookup = dict(zip(alphabet, chiffer)) + + +Exercise 6: Encrypt +------------------- + +Use the lookup dictionary to encrypt a message. +Use the following lines as a starting point: + +.. code:: python3 + + message = ... + result = "" + + for char in message: + result += ... +- +Exercise 7: Debugging +--------------------- + +What happens when you enter lowercase letters or special characters in the message? + +Try the expression: + +.. code:: python3 + + print(lookup.get(";", "X")) + +Fix the problem. + + +Exercise 7: Decrypt +------------------- + +Decrypt a message when all you know is the encrypted message and the random seed. + + +Reflection Questions +-------------------- + +- what does the ``enumerate()`` function do? +- what does the ``zip()`` function do? +- is a substitution cipher rather safe or unsafe? +- what is **symmetric encryption**? + +.. seealso:: + + **Further Reading** + + - `Kerckhoffs Principle `__ \ No newline at end of file diff --git a/first_steps/dictionaries.rst b/first_steps/dictionaries.rst index 5f1aad1..f16afd2 100644 --- a/first_steps/dictionaries.rst +++ b/first_steps/dictionaries.rst @@ -104,6 +104,32 @@ Unfortunately, it contains **five bugs**. Find and fix them. print("You have reached your destination") +Exercise 6: Zip +--------------- + +Simplify the following code using the function ``zip()``: + +.. code:: python3 + + fruits = ["apple", "banana", "orange", "cherries"] + prices = [0.5, 1.0, 1.5, 3.0] + + table = [] + i = 0 + while i < len(fruits): + row = (fruits[i], prices[i]) + table.append(row) + i += 1 + print(table) + +Try the expression: + +.. code:: python3 + + for a, b in zip(fruits, prices): + ... + + Reflection Questions -------------------- diff --git a/first_steps/indexing.rst b/first_steps/indexing.rst index 9ebc537..4c4be08 100644 --- a/first_steps/indexing.rst +++ b/first_steps/indexing.rst @@ -55,8 +55,21 @@ What do the following commands result in? numbers[2:-2] numbers[::2] +Exercise 3: Ranges +------------------ + +Use ``list(range())`` to create the following lists: + +.. code:: python3 + + [4, 7, 9, 12, 15] + + [10, 20, 30, 40, 50, 60] + + [33, 32, 31, 30] + -Exercise 3: Decypher +Exercise 4: Decypher -------------------- The following text contains an encrypted word: @@ -68,7 +81,7 @@ The following text contains an encrypted word: Print every second character, starting with the 2nds. -Exercise 4: Slicing puzzle +Exercise 5: Slicing puzzle -------------------------- Use the expressions to modify the list as indicated. Use each expression @@ -78,7 +91,7 @@ once. :alt: list funcs exercise1 -Exercise 5: Blocks +Exercise 6: Blocks ------------------ The following code is creating the first two blocks for a `transposition cipher `__ . @@ -95,7 +108,7 @@ Complete the code by creating the other two blocks as well. encrypted = block1 + block2 + block3 + block4 -Exercise 6: Transposition Cipher +Exercise 7: Transposition Cipher -------------------------------- Complete the program that encrypts a text using a transposition cipher: @@ -107,13 +120,13 @@ Complete the program that encrypts a text using a transposition cipher: for start in range(4): ___ -Exercise 7: Decrypt +Exercise 8: Decrypt ------------------- Write a program to decrypt an encrypted message again. -Exercise 8: Encryption Key +Exercise 9: Encryption Key -------------------------- Use an encryption key like ``2031`` that specifies a new order for the blocks. diff --git a/first_steps/statistics.rst b/first_steps/statistics.rst index b1d1c5e..db3f14e 100644 --- a/first_steps/statistics.rst +++ b/first_steps/statistics.rst @@ -15,6 +15,7 @@ area topic ⚙ implement a function ⚙ call a function you defined 💡 use the ``math`` module +💡 use the ``sum`` function 🔀 use a recursive function ==== ============================================== @@ -56,7 +57,15 @@ Write a function that calculates the arithmetic mean from the following numbers: Don't forget about the ``return`` statement. -Exercise 3: Standard Deviation +Exercise 3: Shortcut +-------------------- + +Simplify the mean function using the function ``sum()``. + +Use your own or the builtin ``sum()`` function. + + +Exercise 4: Standard Deviation ------------------------------ The following program calculates the standard deviation from a list of @@ -81,7 +90,7 @@ data – in a function. print(f"Standard Deviation: {stdev:8.2f}") -Exercise 4: Optional Parameters +Exercise 5: Optional Parameters ------------------------------- Explain the program: @@ -97,7 +106,7 @@ Explain the program: print(add(b=4)) -Exercise 5: Recursion +Exercise 6: Recursion --------------------- Explain the code: diff --git a/index.rst b/index.rst index b4d273e..53d0883 100644 --- a/index.rst +++ b/index.rst @@ -39,27 +39,18 @@ First Steps first_steps/dictionaries.md first_steps/indexing.rst first_steps/nested_lists.rst + first_steps/builtin_functions.rst first_steps/slideshow.rst first_steps/babynames.rst - --------------- - -Program Structures ------------------- - -.. toctree:: - :maxdepth: 1 - - structure/functions.md + first_steps/statistics.rst debugging/README.rst - structure/builtin_functions.md - structure/modules.md - structure/refactoring.rst + refactoring/refactoring.rst + challenges/text_adventure.rst -------------- -Challenges -========== +Coding Challenges +----------------- .. toctree:: :maxdepth: 1 @@ -67,24 +58,20 @@ Challenges challenges/ctree.rst challenges/pyramid.rst challenges/fizzbuzz.rst - challenges/tictac.rst challenges/quiz.rst challenges/checker.rst challenges/baby_name_generator.rst challenges/palindrome.rst challenges/anagrams.rst - challenges/spiral.rst - challenges/roman.rst - challenges/encrypt.rst + challenges/tictac.rst challenges/minesweeper.rst challenges/gcd.rst challenges/fibonacci.rst challenges/querprodukt.rst challenges/birthdays.rst - challenges/seven_peaks.rst + challenges/misty_mountains.rst challenges/count_words.rst - challenges/postcard.rst - challenges/text_adventure.rst + challenges/spiral.rst -------------- @@ -118,7 +105,6 @@ Examples of common Python commands reference/while.rst reference/builtin_functions.rst reference/functions.rst - reference/introspection.rst Appendix diff --git a/reference/builtin_functions.rst b/reference/builtin_functions.rst index 01b74f7..6c3c9ab 100644 --- a/reference/builtin_functions.rst +++ b/reference/builtin_functions.rst @@ -1,27 +1,26 @@ Builtin functions ================= -In Python, there is a basic set of about 70 functions called **builtin -functions**. Many of them are shortcuts that make your everyday -programming a lot easier. Here, the 24 most important ones are given. +Python 3.11 has 75 builtin functions. To start writing useful programs, +knowing about 20 of them is sufficient. +Many of them are shortcuts that make your everyday +programming a lot easier. -**These 24 functions are your basic vocabulary, knowing these is a must +**These 20 functions are your basic vocabulary, knowing these is a must to write Python efficiently!** -=============== ===== ===== ========= ============= -type conversion I/O math iterables introspection -=============== ===== ===== ========= ============= -int print abs range help -float input round len type -str open sum sorted dir +=============== ===== ===== ========= +type conversion I/O math iterables +=============== ===== ===== ========= +int print abs range +float input round len +str open sum sorted bool min reversed tuple max enumerate list zip dict set -=============== ===== ===== ========= ============= - -See the topic **introspection** to find out about the other functions. +=============== ===== ===== ========= Type Conversions ---------------- diff --git a/reference/introspection.rst b/reference/introspection.rst deleted file mode 100644 index f619c0c..0000000 --- a/reference/introspection.rst +++ /dev/null @@ -1,71 +0,0 @@ -Introspection -============= - -Introspection is a feature of Python by which you can examine objects -(including variables, functions, classes, modules) inside a running -Python environment (a program or shell session). - -Exploring the namespace ------------------------ - -In Python all objects (variables, modules, classes, functions and your -main program) are boxes called **namespaces**. You can imagine the -namespace of an object as the data and functions inside than object. You -can explore a namespace with the ``dir()`` function. - -Exploring the namespace of a variable -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -With a string object, you see all the string methods: - - -.. code:: python3 - - s = "Emily" - print(dir(s)) - -Exploring the namespace of a module: -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The same works for a module you import: - - -.. code:: python3 - - import time - print(dir(time)) - -Listing the builtin functions: -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You also can view all builtin functions: - - -.. code:: python3 - - print(dir(__builtins__)) - -The help function ------------------ - -You can get context-sensitive help to functions, methods and classes -with ``help()`` function. - - -.. code:: python3 - - import time - print help(time.asctime) - -``help()`` utilizes the triple-quoted comments called **docstrings**, so -that documentation you write for your own functions is also availabel -through ``help()``: - -Everything is an object ------------------------ - -One consequence of the dynamic typing is that Python can treat -everything it manages technically in the same way. **Everything is an -object** is a common phrase describing how Python works. There is no -fundamental difference between a function and an integer. Many advanced -features of Python are built on this concept.