07-Some_basics



In [1]:
from __future__ import absolute_import, division, print_function

Github

A few Python Basics


In [2]:
# Create a [list] 
days = ['Monday', # multiple lines 
        'Tuesday', # acceptable 
        'Wednesday',
        'Thursday',
        'Friday',
        'Saturday',
        'Sunday', 
       ] # trailing comma is fine!

In [3]:
days


Out[3]:
['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

In [4]:
# Simple for-loop
for day in days:
    print(day)


Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

In [5]:
# Double for-loop
for day in days:
    for letter in day:
        print(letter)


M
o
n
d
a
y
T
u
e
s
d
a
y
W
e
d
n
e
s
d
a
y
T
h
u
r
s
d
a
y
F
r
i
d
a
y
S
a
t
u
r
d
a
y
S
u
n
d
a
y

In [6]:
print(days)


['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

In [7]:
print(*days)


Monday Tuesday Wednesday Thursday Friday Saturday Sunday

In [10]:
# Double for-loop
for day in days:
    for letter in day:
        print(letter)
    print()


M
o
n
d
a
y

T
u
e
s
d
a
y

W
e
d
n
e
s
d
a
y

T
h
u
r
s
d
a
y

F
r
i
d
a
y

S
a
t
u
r
d
a
y

S
u
n
d
a
y


In [12]:
for day in days:
    for letter in day:
        print(letter.lower())


m
o
n
d
a
y
t
u
e
s
d
a
y
w
e
d
n
e
s
d
a
y
t
h
u
r
s
d
a
y
f
r
i
d
a
y
s
a
t
u
r
d
a
y
s
u
n
d
a
y

List Comprehensions


In [13]:
length_of_days = [len(day) for day in days]
length_of_days


Out[13]:
[6, 7, 9, 8, 6, 8, 6]

In [14]:
letters = [letter for day in days
                    for letter in day]

In [15]:
print(letters)


['M', 'o', 'n', 'd', 'a', 'y', 'T', 'u', 'e', 's', 'd', 'a', 'y', 'W', 'e', 'd', 'n', 'e', 's', 'd', 'a', 'y', 'T', 'h', 'u', 'r', 's', 'd', 'a', 'y', 'F', 'r', 'i', 'd', 'a', 'y', 'S', 'a', 't', 'u', 'r', 'd', 'a', 'y', 'S', 'u', 'n', 'd', 'a', 'y']

In [17]:
letters = [letter for day in days for letter in day]
print(letters)


['M', 'o', 'n', 'd', 'a', 'y', 'T', 'u', 'e', 's', 'd', 'a', 'y', 'W', 'e', 'd', 'n', 'e', 's', 'd', 'a', 'y', 'T', 'h', 'u', 'r', 's', 'd', 'a', 'y', 'F', 'r', 'i', 'd', 'a', 'y', 'S', 'a', 't', 'u', 'r', 'd', 'a', 'y', 'S', 'u', 'n', 'd', 'a', 'y']

In [18]:
[num for num in xrange(10) if num % 2]


Out[18]:
[1, 3, 5, 7, 9]

In [19]:
[num for num in xrange(10) if num % 2 else "doesn't work"]


  File "<ipython-input-19-2891a8980b2c>", line 1
    [num for num in xrange(10) if num % 2 else "doesn't work"]
                                             ^
SyntaxError: invalid syntax

In [20]:
[num if num % 2 else "works" for num in xrange(10)]


Out[20]:
['works', 1, 'works', 3, 'works', 5, 'works', 7, 'works', 9]

In [22]:
[num for num in xrange(10)]


Out[22]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [23]:
sorted_letters = sorted([x.lower() for x in letters])
print(sorted_letters)


['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'e', 'e', 'e', 'f', 'h', 'i', 'm', 'n', 'n', 'n', 'o', 'r', 'r', 'r', 's', 's', 's', 's', 's', 't', 't', 't', 'u', 'u', 'u', 'u', 'w', 'y', 'y', 'y', 'y', 'y', 'y', 'y']

In [24]:
unique_sorted_letters = sorted(set(sorted_letters))

In [25]:
print("There are", len(unique_sorted_letters), "unique letters in the days of the week.")
print("They are:", ''.join(unique_sorted_letters))


There are 15 unique letters in the days of the week.
They are: adefhimnorstuwy

In [28]:
print("They are:", '; '.join(unique_sorted_letters))


They are: a; d; e; f; h; i; m; n; o; r; s; t; u; w; y

In [ ]:
def first_three(input_string):
    """Takes an input string and returns the first 3 characters."""
    return input_string[:3]

In [ ]:
import numpy as np

In [ ]:
# tab
np.linspace()

In [ ]:
[first_three(day) for day in days]

In [ ]:
def last_N(input_string, number=2):
    """Takes an input string and returns the last N characters."""
    return input_string[-number:]

In [ ]:
[last_N(day, 4) for day in days if len(day) > 6]

In [ ]:
from math import pi

print([str(round(pi, i)) for i in xrange(2, 9)])

In [ ]:
list_of_lists = [[i, round(pi, i)] for i in xrange(2, 9)]
print(list_of_lists)

In [ ]:
for sublist in list_of_lists:
    print(sublist)

In [ ]:
# Let this be a warning to you!

# If you see python code like the following in your work:

for x in range(len(list_of_lists)):
    print("Decimals:", list_of_lists[x][0], "expression:", list_of_lists[x][1])

In [ ]:
print(list_of_lists)

# Change it to look more like this: 

for decimal, rounded_pi in list_of_lists:
    print("Decimals:", decimal, "expression:", rounded_pi)

In [ ]:
# enumerate if you really need the index

for index, day in enumerate(days):
    print(index, day)

Dictionaries

Python dictionaries are awesome. They are hash tables and have a lot of neat CS properties. Learn and use them well.


In [4]:
from IPython.display import IFrame, HTML
HTML('<iframe src=https://en.wikipedia.org/wiki/Hash_table width=100% height=550></iframe>')


Out[4]:

In [30]:
fellows = ["Jonathan", "Alice", "Bob"]
universities = ["UCSD", "UCSD", "Vanderbilt"]

In [31]:
for x, y in zip(fellows, universities):
    print(x, y)


Jonathan UCSD
Alice UCSD
Bob Vanderbilt

In [32]:
# Don't do this
{x: y for x, y in zip(fellows, universities)}


Out[32]:
{'Alice': 'UCSD', 'Bob': 'Vanderbilt', 'Jonathan': 'UCSD'}

In [34]:
# Doesn't work like you might expect
{zip(fellows, universities)}


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-34-b238f9ef0459> in <module>()
      1 # Doesn't work like you might expect
----> 2 {zip(fellows, universities)}

TypeError: unhashable type: 'list'

In [33]:
dict(zip(fellows, universities))


Out[33]:
{'Alice': 'UCSD', 'Bob': 'Vanderbilt', 'Jonathan': 'UCSD'}

In [35]:
fellows


Out[35]:
['Jonathan', 'Alice', 'Bob']

In [36]:
fellow_dict = {fellow.lower(): university 
                   for fellow, university in zip(fellows, universities)}

In [37]:
fellow_dict


Out[37]:
{'alice': 'UCSD', 'bob': 'Vanderbilt', 'jonathan': 'UCSD'}

In [38]:
fellow_dict['bob']


Out[38]:
'Vanderbilt'

In [ ]:
rounded_pi = {i:round(pi, i) for i in xrange(2, 9)}

In [ ]:
rounded_pi[5]

In [ ]:
sum([i ** 2 for i in range(10)])

In [ ]:
sum(i ** 2 for i in range(10))

In [ ]:
huh = (i ** 2 for i in range(10))

In [ ]:
huh.next()