# by default, only the result of the last expression in a cell is displayed after evaluation.
# the following forces display of *all* self-standing expressions in a cell.
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
This list supports the mutable sequence operations in addition to the common sequence operations.
l = [1, 2, 1, 1, 2, 3, 3, 1] # open bracket close bracket, comma
# tuple ( 1,2,3,4 ) immutable version of a list
# index 0 1 2 3
# not all elements in list (or tuple) need to be the same type
l
[1, 2, 1, 1, 2, 3, 3, 1]
len(l)
8
l[5]
3
l[1:-1] # start at index 1 end one before index -1
[2, 1, 1, 2, 3, 3]
l
[1, 2, 1, 1, 2, 3, 3, 1]
l + ['hello', 'world'] #creates a new list
_
[1, 2, 1, 1, 2, 3, 3, 1, 'hello', 'world']
[1, 2, 1, 1, 2, 3, 3, 1, 'hello', 'world']
l # `+` does *not* mutate the list!
[1, 2, 1, 1, 2, 3, 3, 1]
l.extend(l) #mutates the list
l
[1, 2, 1, 1, 2, 3, 3, 1, 1, 2, 1, 1, 2, 3, 3, 1]
l * 3
[1, 2, 1, 1, 2, 3, 3, 1, 1, 2, 1, 1, 2, 3, 3, 1, 1, 2, 1, 1, 2, 3, 3, 1, 1, 2, 1, 1, 2, 3, 3, 1, 1, 2, 1, 1, 2, 3, 3, 1, 1, 2, 1, 1, 2, 3, 3, 1]
l
[1, 2, 1, 1, 2, 3, 3, 1, 1, 2, 1, 1, 2, 3, 3, 1]
sum = 0
for x in l:
sum += x
sum
28
l=[]
l
[]
words=['dog','frog','cat']
for w in words:
print(w, len(w))
dog 3 frog 4 cat 3
l = [1, 2, 1, 1, 2, 3, 3, 1]
l[10]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-17-b20425bb8592> in <module> 1 l = [1, 2, 1, 1, 2, 3, 3, 1] ----> 2 l[10] IndexError: list index out of range
l[-10]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-18-080d95ce6835> in <module> ----> 1 l[-10] IndexError: list index out of range
if l:
print('true')
true
m=[]
if m:
print('true')
else:
print('false')
false
l = list('hell')
m = list((1,2,3)) # tuple to a List
l
m
['h', 'e', 'l', 'l']
[1, 2, 3]
n=str(m)
n
'[1, 2, 3]'
t=''
for i in m:
t=t+str(i)
t
'123'
l
['h', 'e', 'l', 'l']
l.append('o')
l
['h', 'e', 'l', 'l', 'o']
l.append(' there') #same as + except + makes a new list
l
['h', 'e', 'l', 'l', 'o', ' there']
del l[-1]
l
['h', 'e', 'l', 'l']
l.extend(' there')
l
['h', 'e', 'l', 'l', ' ', 't', 'h', 'e', 'r', 'e']
l[2:7]
['l', 'l', ' ', 't', 'h']
del l[2:7]
l
['h', 'e', 'e', 'r', 'e']
l[4]
'e'
# append at end any word in the list that is longer than 3 characters
words=['cat','dog','mouse', 'duck']
for w in words[:]: # make a slice of words and iterate that
if len(w) > 3:
words.append(w)
words
['cat', 'dog', 'mouse', 'duck', 'mouse', 'duck']
# randomly generate coin flips 0 and 1 into a list
# find if there is a sequence of exactly 3 000
import random
t=''
for i in range(100):
t=t+str(random.randint(0,1))
t
t.index('000') # does not find exact length
'1110000111100011100110010000101100111100001111110000011100010010111100110001011110010001101110000101'
3
# randomly generate coin flips 0 and 1 into a list
# find if there is a sequence of exactly 3 000
import random
t=''
for i in range(100):
t=t+str(random.randint(0,1))
t
t.index('10001') # does not find exact length
'1010100100100111110110111011100101100001011011100110001000011000000000110011111011010110110110010111'
50
# randomly generate coin flips 0 and 1 into a list
# find if there is a sequence of exactly 3 000
import random
t=''
for i in range(100):
t=t+str(random.randint(0,1))
t
if (t.index('000') and t[t.index('000')+3]=='1' . . . ..
# preprcess the list to create a list of run lengths
# and also keep track of what it is a run of 0 or 1
# 0s are postiive, 1s are negative
# 1 0 1 0 1 00100100111110110111
# -1 1 -1 1 -1 2-1 2
import random
t=''
for i in range(100):
t=t+str(random.randint(0,1))
runs=[]
previousLetter=t[0]
runlength=1
for s in t[1:]:
if s == previousLetter:
runlength+=1
else:
if previousLetter=='0':
runs.append(runlength)
else:
runs.append(-1*runlength)
runlength=1
previousLetter=s
if previousLetter=='0':
runs.append(runlength)
else:
runs.append(-1*runlength)
t
runs
runs.index(3)
runs.index(-3) # need to add up all the elements in runs prior to finding -3
'1000101111010010011101011000010111110010100110011101001010111011101101001101100010111110010101100100'
[-1, 3, -1, 1, -4, 1, -1, 2, -1, 2, -3, 1, -1, 1, -2, 4, -1, 1, -5, 2, -1, 1, -1, 2, -2, 2, -3, 1, -1, 2, -1, 1, -1, 1, -3, 1, -3, 1, -2, 1, -1, 2, -2, 1, -2, 3, -1, 1, -5, 2, -1, 1, -1, 1, -2, 2, -1, 2]
1
10
# comprehension is shorthand notation to make a sequence type
[x for x in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
l=[]
for x in range(10):
l.append(x)
l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[2*x+1 for x in range(10)] # odd numbers
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
[2*x+1 for x in range(10) if (2*x+1)>6]
[7, 9, 11, 13, 15, 17, 19]
# What circles of radius 1 to 5 have more area than squares with sides 1 to 5?
[ (radius, sides) for radius in range(1,6) for sides in range(1,6) if 3.14*radius*radius > sides*sides]
[(1, 1), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5)]
# list comprehension
# [ expressionToStoreInList forLoopPossiblyNested conditions]
adjs = ('hot', 'blue', 'quick')
nouns = ('table', 'fox', 'sky')
phrases = []
for adj in adjs:
for noun in nouns:
phrases.append(adj + ' ' + noun)
phrases
['hot table', 'hot fox', 'hot sky', 'blue table', 'blue fox', 'blue sky', 'quick table', 'quick fox', 'quick sky']
[adj + ' ' + noun for adj in adjs for noun in nouns if len(adj) > len(noun)]
['blue fox', 'blue sky', 'quick fox', 'quick sky']
A set is a data structure that represents an unordered collection of unique objects (like the mathematical set).
s = {1, 2, 1, 1, 2, 3, 3, 1}
s
{1, 2, 3}
2 in s
5 in s
True
False
s[0]
s[2]
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-5-ecc5012a6c51> in <module> ----> 1 s[0] 2 s[2] TypeError: 'set' object is not subscriptable
s
s.union({5}) # results in a new set
s
{1, 2, 3}
{1, 2, 3, 5}
{1, 2, 3}
t = {2, 3, 4, 5}
s.union(t)
s
t
{1, 2, 3, 4, 5}
{1, 2, 3}
{2, 3, 4, 5}
s.difference(t) #yields new set
s
{1}
{1, 2, 3}
s.intersection(t) #yields new set
s
t
{2, 3}
{1, 2, 3}
{2, 3, 4, 5}
u={4, -1, 3, 4.2222}
u
u.__str__()
u.__repr__()
{-1, 3, 4, 4.2222}
'{3, 4, 4.2222, -1}'
'{3, 4, 4.2222, -1}'
A dictionary is a data structure that contains a set of unique key → value mappings.
d = {
'Superman': 'Clark Kent', # key:value pair
'Batman': 'Bruce Wayne',
'Spiderman': 'Peter Parker',
'Ironman': 'Tony Stark'
}
d['Ironman']
'Tony Stark'
d['Ironman'] = 'James Rhodes'
d
{'Superman': 'Clark Kent', 'Batman': 'Bruce Wayne', 'Spiderman': 'Peter Parker', 'Ironman': 'James Rhodes'}
# list
a=[1,2,3]
a
# tuple
b=(4,'a')
b
c=list('matt')
d=tuple([1,2,3])
c
d
[1, 2, 3]
(4, 'a')
['m', 'a', 't', 't']
(1, 2, 3)
z=dict()
z
type(a)
type(b)
type(z)
{}
list
tuple
dict
d = {
'Superman': 'Clark Kent', # key:value pair
'Batman': 'Bruce Wayne',
'Spiderman': 'Peter Parker',
'Ironman': 'Tony Stark'
}
d['anyman']
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-28-61dee7bc907d> in <module> ----> 1 d['anyman'] KeyError: 'anyman'
#d['anyman'] # just like a get
d.get('Batman')
d.get('anyman', "default")
'Bruce Wayne'
'default'
d
'wonderwomen' in d
{'Superman': 'Clark Kent', 'Batman': 'Bruce Wayne', 'Spiderman': 'Peter Parker', 'Ironman': 'Tony Stark'}
False
d['a']='b'
d
{'Superman': 'Clark Kent', 'Batman': 'Bruce Wayne', 'Spiderman': 'Peter Parker', 'Ironman': 'Tony Stark', 'a': 'b'}
l=[1,2,3]
l[5]=0
l
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-35-e1d370a1447a> in <module> 1 l=[1,2,3] ----> 2 l[5]=0 3 l IndexError: list assignment index out of range
d['a']='matt'
d
{'Superman': 'Clark Kent', 'Batman': 'Bruce Wayne', 'Spiderman': 'Peter Parker', 'Ironman': 'Tony Stark', 'a': 'matt'}
for k in d:
print(k)
Superman Batman Spiderman Ironman a
for k in d.items():
print(k)
('Superman', 'Clark Kent') ('Batman', 'Bruce Wayne') ('Spiderman', 'Peter Parker') ('Ironman', 'Tony Stark') ('a', 'matt')
for k in d.values():
print(k)
Clark Kent Bruce Wayne Peter Parker Tony Stark matt
for k in d.items(): #k is a tuple
print("key"+k[0] + " value"+k[1])
keySuperman valueClark Kent keyBatman valueBruce Wayne keySpiderman valuePeter Parker keyIronman valueTony Stark keya valuematt
{e:2**e for e in range(0,100,10)}
{0: 1, 10: 1024, 20: 1048576, 30: 1073741824, 40: 1099511627776, 50: 1125899906842624, 60: 1152921504606846976, 70: 1180591620717411303424, 80: 1208925819614629174706176, 90: 1237940039285380274899124224}
[(x,y) for x in range(3) for y in range(10)]
{x:y for x in range(3) for y in range(10)}
[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (0, 9), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9)]
{0: 9, 1: 9, 2: 9}
sentence = 'a man a plan a canal panama'
{w:w[::-1] for w in sentence.split()}
{'a': 'a', 'man': 'nam', 'plan': 'nalp', 'canal': 'lanac', 'panama': 'amanap'}
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Complete the following function, which finds the sum of all the multiples of 3 or 5 below the argument n
.
def multiples_of_3_and_5(n):
sum=0
for i in range(1,n): # counts from 1 to n-1
if i%3==0 or i%5==0:
sum+=i
return sum
def multiples_of_3_and_5(n):
return sum([i for i in range(1,n) if i%3==0 or i%5==0])
import unittest
tc = unittest.TestCase()
tc.assertEqual(multiples_of_3_and_5(10), 23)
tc.assertEqual(multiples_of_3_and_5(500), 57918)
tc.assertEqual(multiples_of_3_and_5(1000), 233168)
For this next exercise, you'll need to complete the function gen_pattern
, which, when called with a string of length $\ge$ 1, will print an ASCII art pattern of concentric diamonds using those characters. The following are examples of patterns printed by the function (note the newline at the end of the last line!):
> gen_pattern('X')
X
> gen_pattern('XY')
..Y..
Y.X.Y
..Y..
> gen_pattern('WXYZ')
......Z......
....Z.Y.Z....
..Z.Y.X.Y.Z..
Z.Y.X.W.X.Y.Z
..Z.Y.X.Y.Z..
....Z.Y.Z....
......Z......
You ought to find the string join
and center
methods helpful in your implementation. They are demonstrated here:
> '*'.join('abcde')
'a*b*c*d*e'
> 'hello'.center(11, '*')
'***hello***'
Complete the gen_pattern
function, below:
def gen_pattern(chars):
max_length=2*(len(chars)+len(chars)-1)-1
# generates the longest line
rev_chars=chars[::-1]
x=rev_chars+chars[1:]
print('.'.join(x))
for i in range(1,len(chars)):
chars=chars[1:]
rev_chars=chars[::-1]
x=rev_chars+chars[1:]
print( '.'.join(x).center(max_length,'.'))
gen_pattern('ABC')
C.B.A.B.C ..C.B.C.. ....C....
# output:
# @
gen_pattern('@')
# output:
# ..%..
# %.@.%
# ..%..
gen_pattern('@%')
# output:
# ....C....
# ..C.B.C..
# C.B.A.B.C
# ..C.B.C..
# ....C....
gen_pattern('ABC')
# output:
# ........#........
# ......#.#.#......
# ....#.#.#.#.#....
# ..#.#.#.#.#.#.#..
# #.#.#.#.#.#.#.#.#
# ..#.#.#.#.#.#.#..
# ....#.#.#.#.#....
# ......#.#.#......
# ........#........
gen_pattern('#####')
# output:
# ..............................p..............................
# ............................p.o.p............................
# ..........................p.o.n.o.p..........................
# ........................p.o.n.m.n.o.p........................
# ......................p.o.n.m.l.m.n.o.p......................
# ....................p.o.n.m.l.k.l.m.n.o.p....................
# ..................p.o.n.m.l.k.j.k.l.m.n.o.p..................
# ................p.o.n.m.l.k.j.i.j.k.l.m.n.o.p................
# ..............p.o.n.m.l.k.j.i.h.i.j.k.l.m.n.o.p..............
# ............p.o.n.m.l.k.j.i.h.g.h.i.j.k.l.m.n.o.p............
# ..........p.o.n.m.l.k.j.i.h.g.f.g.h.i.j.k.l.m.n.o.p..........
# ........p.o.n.m.l.k.j.i.h.g.f.e.f.g.h.i.j.k.l.m.n.o.p........
# ......p.o.n.m.l.k.j.i.h.g.f.e.d.e.f.g.h.i.j.k.l.m.n.o.p......
# ....p.o.n.m.l.k.j.i.h.g.f.e.d.c.d.e.f.g.h.i.j.k.l.m.n.o.p....
# ..p.o.n.m.l.k.j.i.h.g.f.e.d.c.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p..
# p.o.n.m.l.k.j.i.h.g.f.e.d.c.b.a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p
# ..p.o.n.m.l.k.j.i.h.g.f.e.d.c.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p..
# ....p.o.n.m.l.k.j.i.h.g.f.e.d.c.d.e.f.g.h.i.j.k.l.m.n.o.p....
# ......p.o.n.m.l.k.j.i.h.g.f.e.d.e.f.g.h.i.j.k.l.m.n.o.p......
# ........p.o.n.m.l.k.j.i.h.g.f.e.f.g.h.i.j.k.l.m.n.o.p........
# ..........p.o.n.m.l.k.j.i.h.g.f.g.h.i.j.k.l.m.n.o.p..........
# ............p.o.n.m.l.k.j.i.h.g.h.i.j.k.l.m.n.o.p............
# ..............p.o.n.m.l.k.j.i.h.i.j.k.l.m.n.o.p..............
# ................p.o.n.m.l.k.j.i.j.k.l.m.n.o.p................
# ..................p.o.n.m.l.k.j.k.l.m.n.o.p..................
# ....................p.o.n.m.l.k.l.m.n.o.p....................
# ......................p.o.n.m.l.m.n.o.p......................
# ........................p.o.n.m.n.o.p........................
# ..........................p.o.n.o.p..........................
# ............................p.o.p............................
# ..............................p..............................
gen_pattern('abcdefghijklmnop')