None python_rasmus

Solutions to Sheet 3 by Rasmus Kornbeck

In [1]:
from numpy.linalg import matrix_power
from random import choice
import itertools
import numpy
import random
In [2]:
# problem 1
def sphere_volume(r):
    """Returns the volume of a sphere"""
    return 4/3 * 3.14159 * r**3

sphere_volume(5)
Out[2]:
523.5983333333332
In [3]:
# problem 2
def isolate(a, b, c, d, e):
    """Print first two values with 5 spaces rest with one"""
    print(a, b, sep="     ", end="     ")
    print(c, d, e)

isolate(1, 2, 3, 4, 5)
1     2     3 4 5
In [4]:
# problem 3.1
def first_half(string):
    half = int(len(string)/2)  # int() removes the comma
    print(string[:half])

first_half("12345")
12
In [5]:
# problem 3.2
def backward(string):
    print(string[::-1]) # [start:end:step]

backward("abcd")
dcba
In [6]:
# problem 4
def list_ops():
    lst = ["bear", "ant", "cat", "dog"];    print("1: {}".format(lst))
    lst.append("eagle");                    print("2: {}".format(lst))
    lst[2] = "fox";                         print("3: {}".format(lst))
    lst.pop(1);                             print("4: {}".format(lst))
    lst.reverse();                          print("5: {}".format(lst))
    lst[lst.index("eagle")] = "hawk";       print("6: {}".format(lst))
    lst.append("hunter");                   print("7: {}".format(lst))
    return lst

list_ops()
1: ['bear', 'ant', 'cat', 'dog']
2: ['bear', 'ant', 'cat', 'dog', 'eagle']
3: ['bear', 'ant', 'fox', 'dog', 'eagle']
4: ['bear', 'fox', 'dog', 'eagle']
5: ['eagle', 'dog', 'fox', 'bear']
6: ['hawk', 'dog', 'fox', 'bear']
7: ['hawk', 'dog', 'fox', 'bear', 'hunter']
Out[6]:
['hawk', 'dog', 'fox', 'bear', 'hunter']
In [7]:
# problem 5
def pig_latin(word):
    vowels = ("a", "e", "i", "o", "u")
    if word[0].lower() in vowels:
        word = word + "hay"
        print(word)
    else:
        word = word + word[0] + "ay"
        word = word.replace(word[0], "")
        print(word)


pig_latin("aesop rock")
aesop rockhay
In [8]:
# problem 6
def palindrome():
    palindromes = []
    for i in range(100, 1000):
        for j in range(100, 1000):
            product = i * j
            if str(product) == str(product)[::-1]: # [start:end:step]
               palindromes.append(product)
    #print(palindromes) # list of all palindromes
    return max(palindromes)


print(palindrome())
906609
In [9]:
# problem 7 - w/ list comprehension
def alt_harmonic(n):
    return sum([(-1)**(i+1)/i for i in range(1, n+1)])


print(alt_harmonic(5))
0.7833333333333332
In [10]:
# problem 7 - w/o list comprehension
def alt_harmonic_alternative(n):
    elements = []
    for i in range(1, n+1):
        elements.append((-1)**(i+1)/i)
        
    return sum(elements)


alt_harmonic_alternative(5)
Out[10]:
0.7833333333333332
In [11]:
# problem 8
def list_info(lst):
    return min(lst), max(lst), sum(lst)/len(lst)

print(list_info((2, 3, 4, 5)))
(2, 5, 3.5)
In [12]:
# problem 9
int1 = 1
int2 = int1
int1 = 3
print("int1: {}, int2: {}, equals?: {}".format(int1, int2, int1 == int2))
print("int1 id: {}, int2 id: {}, equals?: {}\n".format(
    id(int1), id(int2), id(int1) == id(int2)))

str1 = "foo"
str2 = str1
str1 = "bar"
print("str1: {}, str2: {}, equals?: {}".format(str1, str2, str1 == str2))
print("str1 id: {}, str2 id: {}, equals?: {}\n".format(
    id(str1), id(str2), id(str1) == id(str2)))

list1 = [1, 2, 3]
list2 = list1 # solve using list1.copy()
list1[0] = 10
print("list1: {}, list2: {}, equals?: {}".format(list1, list2, list1 == list2))
print("list1 id: {}, list2 id: {}, equals?: {}\n".format(
    id(list1), id(list2), id(list1) == id(list2)))

tuple1 = (1, 2, 3)
tuple2 = (1, 2, 3)
tuple1 += (1,)
print("tuple1: {}, tuple2: {}, equals?: {}".format(
    tuple1, tuple2, tuple1 == tuple2))
print("tuple1 id: {}, tuple2 id: {}, equals?: {}\n".format(
    id(tuple1), id(tuple2), id(tuple1) == id(tuple2)))

set1 = {1, 2, 3}
set2 = set1 # solve using set1.copy()
set1.pop()
print("set1: {}, set2: {}, equals?: {}".format(set1, set2, set1 == set2))
print("set1 id: {}, set2 id: {}, equals?: {}\n".format(
    id(set1), id(set2), id(set1) == id(set2)))
int1: 3, int2: 1, equals?: False
int1 id: 4388964720, int2 id: 4388964656, equals?: False

str1: bar, str2: foo, equals?: False
str1 id: 4396523312, str2 id: 4396523440, equals?: False

list1: [10, 2, 3], list2: [10, 2, 3], equals?: True
list1 id: 4584247744, list2 id: 4584247744, equals?: True

tuple1: (1, 2, 3, 1), tuple2: (1, 2, 3), equals?: False
tuple1 id: 4550627792, tuple2 id: 4428778368, equals?: False

set1: {2, 3}, set2: {2, 3}, equals?: True
set1 id: 4428894720, set2 id: 4428894720, equals?: True

In [13]:
# problem 10
# calculator.py
from math import sqrt
def my_sum(addend1, addend2):
    return addend1 + addend2

def product(factor1, factor2):
    return factor1 * factor2

# other_file.py

# from calculator.py import *
def hypotenuse(side1, side2):
    return my_sum(product(side1, side1), product(side2, side2))
    
hypotenuse(2, 3)
Out[13]:
13
In [14]:
# problem 11
# example of how to generate random numbers
print(random.randrange(1, 100)) # 100 is not included
2
In [15]:
# problem 12
def calcPowerSet(lst):
    sets = [0]
    for i in range(1, len(lst)+1):
        for element in itertools.combinations(lst, i):
            # combinations generate combinations with the length of the second argument
            sets.append({''.join(element)}) # joins an iterable
    return sets

calcPowerSet(('1', '2', '3'))

# why not set of sets? because sets are not hashable.
Out[15]:
[0, {'1'}, {'2'}, {'3'}, {'12'}, {'13'}, {'23'}, {'123'}]
In [16]:
# problem 13
class Backpack:
    """A Backpack object class. Has a name, color, max size, and
       a list of contents.

    Attributes:
        name (str): the name of the backpack's owner.
        color (str): the color of the backpack
        max_size (int): the max size
        contents (list): the contents of the backpack.
    """

    # Problem 13: Modify __init__() and put(), and write dump().
    def __init__(self, name, color, max_size=5):
        """Set the name, color, max size, and initialize
           an empty list of contents.

        Parameters:
            name (str): the name of the backpack's owner.
            color (str): the color of the backpack
            max_size(int, optional): max size of backpack

        """
        self.name = name
        self.color = color
        self.max_size = max_size
        self.contents = []

    def put(self, item):
        """Add an item to the backpack's list of contents unless it is full."""
        if len(self.contents) == self.max_size:
            print("No room!")
        else:
            self.contents.append(item)

    def take(self, item):
        """Remove an item from the backpack's list of contents."""
        self.contents.remove(item)

    def dump(self):
        """Remove all items from backpack."""
        self.contents.clear()

    # Magic Methods -----------------------------------------------------------

    # Problem 15: Write __eq__() and __str__().
    def __add__(self, other):
        """Add the number of contents of each Backpack."""
        return len(self.contents) + len(other.contents)

    def __lt__(self, other):
        """Compare two backpacks. If 'self' has fewer contents
        than 'other', return True. Otherwise, return False.
        """
        return len(self.contents) < len(other.contents)

    def __eq__(self, o):
        q = 0
        if self.name == o.name:
            q += 1
        if self.color == o.color:
            q += 1
        if self.contents == o.contents:
            q += 1
        if q == 3:
            return True
        else:
            return False

    def __str__(self):
        return "<<Owner:\t{}\nColor:\t\t{}\nSize:\t\t{}\nMax Size:\t{}\nContents:\t{}>>".format(
            self.name, self.color, len(self.contents), self.max_size, self.contents)
In [17]:
# problem 13 - test function
def test_backpack():
    test = Backpack("foo", "green", max_size=4)
    if test.name != "foo":
        print("Name is incorrect.")
    for item in ["book", "pencil case"]:
        test.put(item)
    print("Contents: ", test.contents)

    # problem 15 - test magic methods
    print(str(test))
    test2 = Backpack("foo", "green", max_size=4)
    for item in ["book", "pencil case"]:
        test2.put(item)
    print(test == test2)


test_backpack()
Contents:  ['book', 'pencil case']
<<Owner:	foo
Color:		green
Size:		2
Max Size:	4
Contents:	['book', 'pencil case']>>
True
In [18]:
# Problem 14: Write a 'Jetpack' class that inherits from the 'Backpack' class.
class Jetpack(Backpack):
    """A jetpack that inherints from backpack.

    Attributes:
    - name (str): name of owner
    - color (str): color of backpack
    - max_size (int): max size of backpack
    - fuel: current fuel of the backpack"""

    def __init__(self, name, color, max_size=2, fuel=10):
        """Call the super class' constructor and initialize fuel

        Parameters:
        - name (str): name of owner
        - color (str): color of backpack
        - max_size (int): max size of backpack
        - fuel: current fuel of the backpack"""
        Backpack.__init__(self, name, max_size)
        self.fuel = fuel

    def fly(self, fuel_val):
        """Reduce the fuel amount for flying."""
        if self.fuel - fuel_val <= 0:
            print("Not enough fuel!")
        else:
            self.fuel -= fuel_val

    def dump(self):
        """Dump the contents of the backpack and fuel"""
        self.contents.clear()
        self.fuel = 0
In [19]:
# problem 16
# warning: don't execute in here, use ipython
def random_walk(max_iters=1e12):
    walk = 0
    directions = [1, -1]
    try:
        for i in range(int(max_iters)):
            walk += choice(directions)
    except KeyboardInterrupt:
        print("Process interupted at iteration " + str(i))
    else:
        print("Process completed")
    return walk

random_walk(10)
Process completed
Out[19]:
-4
In [20]:
# problem 17
# warning: don't execute here, use ipython if the file does not exist
class ContentFilter:
    def __init__(self, given_file_name):
        self.file_name = ""
        self.contents = ""
        try:
            with open(given_file_name, "r") as f:
                self.file_name = given_file_name
                self.contents = f.read()
        except IOError:
            print("File not found. Try another name.")
            while (True):
                input_file_name = input()
                try:
                    with open(input_file_name, "r") as f:
                        self.file_name = input_file_name
                        self.contents = f.read()
                        break
                except IOError:
                    print("File not found. Try another name.")

content_filter = ContentFilter("foo.txt")
print("Name: {}, Contents: {}".format(content_filter.file_name, content_filter.contents))
File not found. Try another name.
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-20-ecbc6df4aac5> in <module>
     21                     print("File not found. Try another name.")
     22 
---> 23 content_filter = ContentFilter("foo.txt")
     24 print("Name: {}, Contents: {}".format(content_filter.file_name, content_filter.contents))

<ipython-input-20-ecbc6df4aac5> in __init__(self, given_file_name)
     12             print("File not found. Try another name.")
     13             while (True):
---> 14                 input_file_name = input()
     15                 try:
     16                     with open(input_file_name, "r") as f:

~/Library/Python/3.9/lib/python/site-packages/ipykernel/kernelbase.py in raw_input(self, prompt)
    846                 "raw_input was called, but this frontend does not support input requests."
    847             )
--> 848         return self._input_request(str(prompt),
    849             self._parent_ident,
    850             self._parent_header,

~/Library/Python/3.9/lib/python/site-packages/ipykernel/kernelbase.py in _input_request(self, prompt, ident, parent, password)
    890             except KeyboardInterrupt:
    891                 # re-raise KeyboardInterrupt, to truncate traceback
--> 892                 raise KeyboardInterrupt("Interrupted by user") from None
    893             except Exception as e:
    894                 self.log.warning("Invalid Message:", exc_info=True)

KeyboardInterrupt: Interrupted by user
In [21]:
# problem 18
def multiply_matrices():
    A = numpy.array([[3, -1, 4], [1, 5, -9]])
    B = numpy.array([[2, 6, -5, 3], [5, -8, 9, 7], [9, -3, -2, -3]])
    return A @ B

multiply_matrices()
Out[21]:
array([[ 37,  14, -32, -10],
       [-54,  -7,  58,  65]])
In [22]:
# problem 19
def mult_matrix_with_self():
    A = numpy.array([[3, 1, 4], [1, 5, 9], [-5, 3, 1]])
    return -matrix_power(A, 3) + 9*matrix_power(A, 2) - 15*A

mult_matrix_with_self()
Out[22]:
array([[0, 0, 0],
       [0, 0, 0],
       [0, 0, 0]])
In [27]:
# problem 20
def array_creation():
    A = numpy.triu(numpy.ones((7, 7)))
    print(A)
    B1 = -numpy.ones((7, 7))
    B2 = numpy.triu(numpy.full((7, 7), 6))
    B3 = numpy.eye(7) * -6
    B = B1 + B2 + B3
    return A @ B @ A

array_creation()
[[1. 1. 1. 1. 1. 1. 1.]
 [0. 1. 1. 1. 1. 1. 1.]
 [0. 0. 1. 1. 1. 1. 1.]
 [0. 0. 0. 1. 1. 1. 1.]
 [0. 0. 0. 0. 1. 1. 1.]
 [0. 0. 0. 0. 0. 1. 1.]
 [0. 0. 0. 0. 0. 0. 1.]]
Out[27]:
array([[ -7.,  -8.,  -3.,   8.,  25.,  48.,  77.],
       [ -6., -12., -12.,  -6.,   6.,  24.,  48.],
       [ -5., -10., -15., -14.,  -7.,   6.,  25.],
       [ -4.,  -8., -12., -16., -14.,  -6.,   8.],
       [ -3.,  -6.,  -9., -12., -15., -12.,  -3.],
       [ -2.,  -4.,  -6.,  -8., -10., -12.,  -8.],
       [ -1.,  -2.,  -3.,  -4.,  -5.,  -6.,  -7.]])
In [24]:
# problem 21
def fancyZeroes(A):
    B = A.copy()
    B[B < 0] = 0
    return B

fancyZeroes(numpy.array([[-10, 5], [-30, 20]]))
Out[24]:
array([[ 0,  5],
       [ 0, 20]])
In [25]:
# problem 22
def stacking():
    A = numpy.array([[0, 2, 4], [1, 3, 5]])
    B = numpy.array([[3, 0, 0], [3, 3, 0], [3, 3, 3]])
    C = numpy.array([[-2, 0, 0], [0, -2, 0], [0, 0, -2]])
    col1 = numpy.vstack((numpy.zeros((2, 3)), A, B))
    col2 = numpy.vstack((A.T, numpy.zeros((2, 2)), numpy.zeros((2, 2))))
    col3 = numpy.vstack((numpy.eye(3), numpy.zeros((1, 3)), C))
    return numpy.hstack((col1, col2, col3))

stacking()
Out[25]:
array([[ 0.,  0.,  0.,  0.,  1.,  1.,  0.,  0.],
       [ 0.,  0.,  0.,  2.,  3.,  0.,  1.,  0.],
       [ 0.,  2.,  4.,  4.,  5.,  0.,  0.,  1.],
       [ 1.,  3.,  5.,  0.,  0.,  0.,  0.,  0.],
       [ 3.,  0.,  0.,  0.,  0., -2.,  0.,  0.],
       [ 3.,  3.,  0.,  0.,  0.,  0., -2.,  0.],
       [ 3.,  3.,  3.,  0.,  0.,  0.,  0., -2.]])
In [26]:
# problem 23
def stochasticMat(A):
    # it is a row vector when it should be column
    # Equivalent: return A/A.sum(axis=1).reshape(3,1)
    return A/A.sum(axis=1)[:, None]

stochasticMat(numpy.array([[2, 3],[3, 2]]))
Out[26]:
array([[0.4, 0.6],
       [0.6, 0.4]])