None
from numpy.linalg import matrix_power
from random import choice
import itertools
import numpy
import random
# problem 1
def sphere_volume(r):
"""Returns the volume of a sphere"""
return 4/3 * 3.14159 * r**3
sphere_volume(5)
# 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)
# problem 3.1
def first_half(string):
half = int(len(string)/2) # int() removes the comma
print(string[:half])
first_half("12345")
# problem 3.2
def backward(string):
print(string[::-1]) # [start:end:step]
backward("abcd")
# 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()
# 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")
# 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())
# 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))
# 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)
# problem 8
def list_info(lst):
return min(lst), max(lst), sum(lst)/len(lst)
print(list_info((2, 3, 4, 5)))
# 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)))
# 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)
# problem 11
# example of how to generate random numbers
print(random.randrange(1, 100)) # 100 is not included
# 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.
# 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)
# 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()
# 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
# 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)
# 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))
# 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()
# 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()
# 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()
# problem 21
def fancyZeroes(A):
B = A.copy()
B[B < 0] = 0
return B
fancyZeroes(numpy.array([[-10, 5], [-30, 20]]))
# 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()
# 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]]))