Contents
This notebook is based on "Think Python, 2Ed" by Allen B. Downey
https://greenteapress.com/wp/think-python-2e/
In [1]:
a_tuple = ( 'a', 'b', 'c', 'd', 'e' )
a_tuple = 'a', 'b', 'c', 'd', 'e'
a_tuple = 'a',
type( a_tuple )
Out[1]:
,
) after the value, but don’t add parenthesistuple
In [2]:
a_tuple = tuple()
print( a_tuple )
a_tuple = tuple( 'lupins' )
print( a_tuple )
In [3]:
a_tuple = ( 'a', 'b', 'c', 'd', 'e' )
print( a_tuple[1:3] )
print( a_tuple[:3] )
print( a_tuple[1:] )
# Uncomment to see error
# a_tuple[0] = 'z'
In [4]:
a = 5
b = 6
# Conventional value swap
temp = a
a = b
b = temp
print( a, b )
In [5]:
a, b = b, a
print( a, b )
In [6]:
addr = 'monty@python.org'
uname, domain = addr.split( '@' )
print( uname )
print( domain )
In [7]:
quotient, remainder = divmod( 7, 3 )
print( quotient )
print( remainder )
In [8]:
def min_max( a_tuple ):
return min( a_tuple ), max( a_tuple )
numbers = ( 13, 7, 55, 42 )
min_num, max_num = min_max( numbers )
print( min_num )
print( max_num )
min
and max
are built-in functions
In [9]:
def printall( *args ):
print( args )
printall( 1 , 2.0 , '3' )
In [10]:
a_tuple = ( 7, 3 )
# divmod( a_tuple ) # Uncomment to see error
divmod( *a_tuple )
Out[10]:
In [11]:
a_string = 'abc'
a_list = [ 0, 1, 2 ]
for element in zip( a_string, a_list ):
print( element )
In [12]:
for element in zip( 'Peter', 'Tony' ):
print( element )
In [13]:
a_list = [ ('a', 0), ('b', 1), ('c', 2) ]
for letter, number in a_list:
print( letter, number )
zip
, for
and tuple assignment to traverse two (or more) sequences at the same time
In [14]:
def has_match( tuple1, tuple2 ):
result = False
for x, y in zip( tuple1, tuple2 ):
if( x == y ):
result = True
return result
enumerate
function
In [15]:
for index , element in enumerate( 'abc' ):
print( index, element )
In [16]:
a_dict = { 'a': 0, 'b':1, 'c':2 }
dict_items = a_dict.items()
print( type( dict_items ) )
print( dict_items )
for element in dict_items:
print( element )
items
, tuple assignment, and a for
loop is an easy way to traverse the keys and values of a dictionary
In [17]:
for key, value in a_dict.items():
print( key, value )
In [18]:
directory = dict()
directory[ 'Smith', 'Bob' ] = '555-1234'
directory[ 'Doe', 'Jane' ] = '555-9786'
for last, first in directory:
print( first, last, directory[last, first] )
return
statement)sort
or reverse
themmax
and min
can take any number of arguments, but sum
does not. Write a function called sum_all
that takes any number of arguments and returns their sum.print_all
that takes a variable number of arguments and prints each one on its own line.distance
that takes two (2) two-dimensional points and returns the distance between them. Then, extend your function to use three-dimensional points. Can you generalize it to take two points of any dimension?merge
that takes two (2) sorted tuples and returns a new tuple that contains all the elements in the two tuples in sorted order. Write both a recursive and an iterative solution.