I719 Fundamentals of Python/lecture6: Difference between revisions
No edit summary |
add solutions for part 1 |
||
Line 8: | Line 8: | ||
<pre>['cat', 'dog']</pre> | <pre>['cat', 'dog']</pre> | ||
=== Solution: Imperative === | |||
You must know how to do this solution | |||
<source lang="python">def uppercase_list(l): | |||
result = [] | |||
for i in l: | |||
result.append(i.upper()) | |||
return result</source> | |||
=== Solution: Functional === | |||
<source lang="python">def uppercase_list(l): | |||
return list(map(lambda i: i.upper(), l))</source> | |||
=== Solution: Modern === | |||
<source lang="python">def uppercase_list(l): | |||
return [i.upper() for i in l]</source> | |||
== TASK 2 == | == TASK 2 == | ||
Line 15: | Line 32: | ||
<pre>{'cat': 'kass', 'dog': 'koer'}</pre> | <pre>{'cat': 'kass', 'dog': 'koer'}</pre> | ||
== | === Solution: Imperative === | ||
You need to understand how this solution works | |||
<source lang="python">def uppercase_dict_values(d): | |||
result = {} | |||
for k, v in d.items(): | |||
result[k] = v.upper() | |||
= | return result</source> | ||
=== Solution: Modern === | |||
<source lang="python">def uppercase_dict_values(d): | |||
return {k: v.upper() for k, v in d.items()}</source> | |||
== TASK 3 == | == TASK 3 == | ||
Line 34: | Line 50: | ||
call it with <code>range(0, 30)</code> | call it with <code>range(0, 30)</code> | ||
=== Solution: Imperative === | |||
<source lang="python">def exclude_divisible_by_3_and_5(l): | |||
result = [] | |||
for i in l: | |||
if not (i % 3 == 0 or i % 5 == 0): | |||
result.append(i) | |||
return result</source> | |||
=== Solution: Functional === | |||
<source lang="python">def is_not_divisible_by_3_and_5(n): | |||
if not (n % 3 == 0 or n % 5 == 0): | |||
return True | |||
else: | |||
return False | |||
def exclude_divisible_by_3_and_5(l): | |||
result = filter(is_not_divisible_by_3_and_5, l) | |||
return list(result)</source> | |||
== Slicing == | == Slicing == | ||
Line 66: | Line 101: | ||
my_sort_function(my_list) | my_sort_function(my_list) | ||
[10, 11, 177, 9, 199]</source> | [10, 11, 177, 9, 199]</source> | ||
=== Solution === | |||
<source lang="python">def reverse_digit_order(n): | |||
"""Revere the order of the digits in a number""" | |||
return str(n)[::-1] | |||
def sort_list_by_smallest_digit(l): | |||
return sorted(l, key=reverse_digit_order)</source> | |||
= Interlude: Packages and Requirements = | = Interlude: Packages and Requirements = | ||
Line 88: | Line 132: | ||
<code>import numpy as np</code> | <code>import numpy as np</code> | ||
== Solve system of linear equations == | == Solve system of linear equations == |
Revision as of 18:30, 9 March 2017
Lists and Arrays
TASK 1
Write a function that makes all characters in a list uppercase!
call it with the following list, and print the result
['cat', 'dog']
Solution: Imperative
You must know how to do this solution
def uppercase_list(l):
result = []
for i in l:
result.append(i.upper())
return result
Solution: Functional
def uppercase_list(l):
return list(map(lambda i: i.upper(), l))
Solution: Modern
def uppercase_list(l):
return [i.upper() for i in l]
TASK 2
Write a function that makes all character in the values of a dict uppercase!
call it with the following dict and print the results.
{'cat': 'kass', 'dog': 'koer'}
Solution: Imperative
You need to understand how this solution works
def uppercase_dict_values(d):
result = {}
for k, v in d.items():
result[k] = v.upper()
return result
Solution: Modern
def uppercase_dict_values(d):
return {k: v.upper() for k, v in d.items()}
TASK 3
write a function that filters out numbers divisible by 3 and 5
call it with range(0, 30)
Solution: Imperative
def exclude_divisible_by_3_and_5(l):
result = []
for i in l:
if not (i % 3 == 0 or i % 5 == 0):
result.append(i)
return result
Solution: Functional
def is_not_divisible_by_3_and_5(n):
if not (n % 3 == 0 or n % 5 == 0):
return True
else:
return False
def exclude_divisible_by_3_and_5(l):
result = filter(is_not_divisible_by_3_and_5, l)
return list(result)
Slicing
In [1]: a = "Hello World"
In [2]: a[:2]
Out[2]: 'He'
In [3]: a[2:]
Out[3]: 'llo World'
In [4]: a[-2:]
Out[4]: 'ld'
In [5]: a[:-2]
Out[5]: 'Hello Wor'
In [6]: a[:-2:2]
Out[6]: 'HloWr'
In [7]: a[::2]
Out[7]: 'HloWrd'
In [8]: a[::-1]
Out[8]: 'dlroW olleH'
TASK 4
write a function that sorts numbers in a list by the smallest digit of the integer.
i.e.
my_list = [11, 10, 9, 177, 199]
my_sort_function(my_list)
[10, 11, 177, 9, 199]
Solution
def reverse_digit_order(n):
"""Revere the order of the digits in a number"""
return str(n)[::-1]
def sort_list_by_smallest_digit(l):
return sorted(l, key=reverse_digit_order)
Interlude: Packages and Requirements
python application often include a requirements.txt
that lists pip dependencies
python packages are formatted as
package_name/ package_name/ __init__.py setup.py
and setup.py include information on depedencies
see: https://github.com/pypa/sampleproject/blob/master/setup.py
Numpy
- it is faster
- it allows multidimensional arrays
- meant for math
Basics
import numpy as np
Solve system of linear equations
x - y = 3 7x - y = -3
becomes in matrix multiplaction
A = [[1, -1] . [[x], = [[3], [7, -1]] [y]] [-3]]
In [68]: a = np.array([[1, -1],[7, -1]]) In [69]: a Out[69]: array([[ 1, -1], [ 7, -1]]) In [70]: b = np.array([[3],[-3]]) In [71]: b Out[71]: array([[ 3], [-3]]) In [72]: a_inverse = np.linalg.inv(a) In [73]: a_inverse Out[73]: array([[-0.16666667, 0.16666667], [-1.16666667, 0.16666667]]) In [74]: a_inverse.dot(b) Out[74]: array([[-1.], [-4.]])
Task 3
solve for x,y, and z
x + y + z = 6 2y + 5z = -4 2x + 5y - z = 27
Pandas
https://blockchain.info/charts/market-price?timespan=1year
download the csv
Open the the csv with pandas
import pandas as pd
btc_price = pd.read_csv('~/Downloads/market-price.csv', names=['datetime', 'usd'], parse_dates=[0])
TASKS
show only days where price is above 1000USD
How many days was the price above 1000USD?
What was the price 6 months ago?
What was the average price last year?
What was the average price in august?
Plot the days on a line graph
import matplotlib.pyplot as plt
import pandas as pd
btc_price = pd.read_csv('~/Downloads/market-price.csv', names=['datetime', 'usd'], parse_dates=[0])
x = btc_price.datetime
y = btc_price.usd
plt.plot(x, y)
plt.xlabel('Date')
plt.ylabel('USD')
plt.title('BTC to USD')
plt.grid(True)
plt.show()