from IPython.core.display import HTML

HTML(open("custom.html", "r").read())
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Copyright (C) 2014-2023 Scientific IT Services of ETH Zurich,
Contributing Authors: Uwe Schmitt, Mikolaj Rybniski

Solution proposals¶

Script 01¶

print(2 ** 63 % 13)
8
import math

print(math.pi ** math.e, math.e ** math.pi)
22.45915771836104 23.140692632779263
import math

diameter = float(input("diameter? "))
area = diameter ** 2 / 4 * math.pi
circumference = diameter * math.pi

print("area is", area)
print("circumference is", circumference)
---------------------------------------------------------------------------
StdinNotImplementedError                  Traceback (most recent call last)
Cell In[4], line 3
      1 import math
----> 3 diameter = float(input("diameter? "))
      4 area = diameter ** 2 / 4 * math.pi
      5 circumference = diameter * math.pi

File ~/Projects/python-introduction/venv/lib/python3.10/site-packages/ipykernel/kernelbase.py:1186, in Kernel.raw_input(self, prompt)
   1184 if not self._allow_stdin:
   1185     msg = "raw_input was called, but this frontend does not support input requests."
-> 1186     raise StdinNotImplementedError(msg)
   1187 return self._input_request(
   1188     str(prompt),
   1189     self._parent_ident["shell"],
   1190     self.get_parent("shell"),
   1191     password=False,
   1192 )

StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.

Script 02¶

txt = "Python"

step_a = txt[::2]
step_b = txt[1::2]
step_c = step_a + step_b
step_d = step_c[::-1]
step_e = step_d[0] + "x" + step_d[1:]
step_f = step_e + "x"

print(step_f)
nxhyotPx
# Optional exercise

step_f = step_f.replace("h", ".").replace("x", "h").replace(".", "x")
print(step_f)
nhxyotPh

Script 03¶

def area_and_cirumference(diameter):
    area = diameter ** 2 / 4 * math.pi
    circumference = diameter * math.pi
    return area, circumference


area, circumference = area_and_cirumference(2.0)
print(area, circumference)
3.141592653589793 6.283185307179586
# Homework


def product(a, b=1, c=1):
    return a * b * c


print(product(2))
print(product(2, 3))
print(product(2, 3, 4))
2
6
24

Script 04¶

def double_if_even(x):
    if x % 2 == 0:
        return 2 * x
    return x


print(double_if_even(2))
print(double_if_even(3))
4
3
def detect_divider(n):
    if n % 3 == 0 and n % 4 == 0:
        print(n, "is divisible by 3 and 4")
    elif n % 3 == 0:
        print(n, "is divisible by 3 but not by 4")
    elif n % 4 == 0:
        print(n, "is divisible by 4 but not by 3")
    else:
        print(n, "is neither divisible by 3 nor by 4")


detect_divider(12)
detect_divider(16)
detect_divider(9)
detect_divider(11)
12 is divisible by 3 and 4
16 is divisible by 4 but not by 3
9 is divisible by 3 but not by 4
11 is neither divisible by 3 nor by 4
# Optional exercise


def sum_up_to_n(n):
    if n < 0:
        return 0
    if n <= 1:
        return n
    return n + sum_up_to_n(n - 1)


print(sum_up_to_n(10))
55

Script 05¶

def average(numbers):
    if len(numbers) == 0:
        return None
    sum_ = 0
    for number in numbers:
        sum_ += number
    return sum_ / len(numbers)


print(average([]))
print(average([1, 2, 3]))
None
2.0
def append(words):
    result = ""
    for word in words:
        result += word
    return result


print(append(["a", "bc", "def"]))
abcdef
def average_even(numbers):
    num_even = 0
    sum_ = 0
    for number in numbers:
        if number % 2 == 0:
            num_even += 1
            sum_ += number
    if num_even == 0:
        return None
    return sum_ / num_even


print(average_even([]))
print(average_even([1, 7, 3]))
print(average_even([1, 2, 3, 4]))
None
None
3.0
# optional
import random


def number_guessing():
    secret = random.randint(0, 100)
    while True:
        guess = int(input("please guess number between 0 and 100: "))
        if guess < secret:
            print("your number is to low, try again")
        elif guess > secret:
            print("your number is too high, try again")
        else:
            print("you got it!")
            break


number_guessing()
---------------------------------------------------------------------------
StdinNotImplementedError                  Traceback (most recent call last)
Cell In[15], line 18
     14             print("you got it!")
     15             break
---> 18 number_guessing()

Cell In[15], line 8, in number_guessing()
      6 secret = random.randint(0, 100)
      7 while True:
----> 8     guess = int(input("please guess number between 0 and 100: "))
      9     if guess < secret:
     10         print("your number is to low, try again")

File ~/Projects/python-introduction/venv/lib/python3.10/site-packages/ipykernel/kernelbase.py:1186, in Kernel.raw_input(self, prompt)
   1184 if not self._allow_stdin:
   1185     msg = "raw_input was called, but this frontend does not support input requests."
-> 1186     raise StdinNotImplementedError(msg)
   1187 return self._input_request(
   1188     str(prompt),
   1189     self._parent_ident["shell"],
   1190     self.get_parent("shell"),
   1191     password=False,
   1192 )

StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.
# optional


def collatz_iter(n):
    print(n)
    while n != 1:
        if n % 2 == 0:
            n //= 2  # integer division to avoid .0 in output
        else:
            n = 3 * n + 1
        print(n)


collatz_iter(17)
17
52
26
13
40
20
10
5
16
8
4
2
1

Script 06¶

def squares_of_odd_numbers(numbers):
    result = []
    for number in numbers:
        if number % 2 == 1:
            result.append(number ** 2)
    return result


print(squares_of_odd_numbers([1, 2, 3, 4, 5]))
[1, 9, 25]
# optional


def flatten(nested_list):
    result = []
    for list_ in nested_list:
        for item in list_:
            result.append(item)
    return result


print(flatten([[1], [2, 3], [4, 5, 6]]))
[1, 2, 3, 4, 5, 6]
# optional


def fib(n):
    if n <= 0:
        return []
    result = [1, 1]
    while len(result) < n:
        result.append(result[-2] + result[-1])
    return result[:n]  # fix for n = 1!


for n in range(1, 6):
    print(n, fib(n))
1 [1]
2 [1, 1]
3 [1, 1, 2]
4 [1, 1, 2, 3]
5 [1, 1, 2, 3, 5]
# optional
def f(x, a=[]):
    print("a=", a)  # added for debugging
    a.append(x)
    return len(a)


f(0)
f(1)
f(0)
a= []
a= [0]
a= [0, 1]
3

Explanation: the default value is only created once when the Python interpreter scans the code, so a always returns to the same list which is changed within the function.

Script 07¶

def squares(n):
    result = {}
    for i in range(1, n + 1):
        result[i] = i ** 2
    return result


print(squares(10))
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}
def remove_even_keys(dd):
    result = {}
    for key in dd.keys():
        if key % 2 == 0:
            continue
        result[key] = dd[key]
    return result


dd = squares(10)
filtered = remove_even_keys(dd)
print(filtered)
{1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
# optional


def revert(dd):
    result = {}
    for key in dd.keys():
        value = dd[key]
        if value not in result.keys():
            result[value] = []
        result[value].append(key)
    return result


print(revert({1: 2, 2: 2, 3: 4, 4: 3}))
{2: [1, 2], 4: [3], 3: [4]}

Script 08¶

with open("squares.txt", "w") as fh:
    for n in range(1, 11):
        print(n ** 2, file=fh)
with open("squares.txt", "r") as fh:
    print(fh.readlines())
['1\n', '4\n', '9\n', '16\n', '25\n', '36\n', '49\n', '64\n', '81\n', '100\n']
# optional

import csv

with open("ten_times_ten.txt", "w") as fh:
    writer = csv.writer(fh, delimiter=",")
    for i in range(1, 11):
        row = []
        for j in range(1, 11):
            row.append(i * j)
        writer.writerow(row)
!cat ten_times_ten.txt









def sumup_entries(file_name):
    sum_ = 0
    with open(file_name, "r") as fh:
        reader = csv.reader(fh)
        for row in reader:
            for cell in row:
                sum_ += int(cell)
    return sum_


print(sumup_entries("ten_times_ten.txt"))
3025

Script 09¶

data = [2, 3, 5, 7, 11]
print([2 * x for x in data if x < 7])
[4, 6, 10]
def to_upper(s):
    return s.upper()


print(sorted(["ab", "AC"], key=to_upper))
['ab', 'AC']
# optional
matrix = [[i * j for j in range(1, 11)] for i in range(11)]

from pprint import pprint  # pretty printer for nested data structures

pprint(matrix)
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
 [2, 4, 6, 8, 10, 12, 14, 16, 18, 20],
 [3, 6, 9, 12, 15, 18, 21, 24, 27, 30],
 [4, 8, 12, 16, 20, 24, 28, 32, 36, 40],
 [5, 10, 15, 20, 25, 30, 35, 40, 45, 50],
 [6, 12, 18, 24, 30, 36, 42, 48, 54, 60],
 [7, 14, 21, 28, 35, 42, 49, 56, 63, 70],
 [8, 16, 24, 32, 40, 48, 56, 64, 72, 80],
 [9, 18, 27, 36, 45, 54, 63, 72, 81, 90],
 [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]]