Download CSC326 Python Sequences: Understanding Strings, Lists, Dictionaries, and Tuples and more Lecture notes Programming Languages in PDF only on Docsity!
i
CSC326 Python Sequences
ii
REVISION HISTORY
NUMBER DATE DESCRIPTION NAME
1.0 2011-09 JZ
1 Agenda
- iteration construct
- sequences
- string
- list
- dictionary
- tuple
2 while Statement
- recall recursive construction of countdown
- cost of function calls
- good old while loop
def countdown( n ) : while n > 0 : print n n = n - 1 print ’Blastoff!’
while True : line = raw_input( ’> ’ ) if line == ’done’ : break print line print ’Done’
- square root approximation algorithm
while True: print x y = (x + a/x) / 2 if y == x: break x = y
- Newton’s algorithm
- A few caveats
epsilon = 0. def sra( a ) : x = a / 2 while True: print x y = (x + a/x) / 2 if abs(y-x) < epsilon : break x = y return x
- Recap
- Multiple assignment: vars are initialized and assigned more than once
- loop often has loop index, incremented by one each iteration
- conditional evaluation and branch forming cycle
3 Sequence Overview
- an ordered collection (set) of values
- membership test
- subset
- eumeration
- another angle: a mapping from an index to value
- lookup
- reverse lookup (searching, content address memory)
- data structures in C
- native data types with native operators in Python
- make python enjoyable to read and write!
4 String
- We have already seen one: string is a sequence!
- sequence of characters
- indexed lookup using []
>>>> fruit = ’banana’
>>>> print fruit[0]
>>>> print fruit[1]
- index has to be an integer
>>>> letter = fruit[1.5]
TypeError: string indices must be integers
>>>> len(fruit)
- index has to be within range
>>>> letter = fruit[len(fruit)]
IndexError: string index out of range
def in_both( word1, word2 ) : for letter in word1 : if letter in word2 : print letter
>>>> string1 = ’hello’
>>>> string2 = ’he’ + ’llo’
>>>> print string1 == string
True
- Python strings are values C strings are references
strcpy( string1, "hello1" );
strcpy( string2, "he" );
strcat( string2, "llo" );
printf( "%d", string1 == string2 )
- How do we compare by reference? is operator
>>>> string1 = ’hello’
>>>> string2 = ’he’ + ’llo’
>>>> print string1 is string
False
- !=, <, >, ⇐, >= works too!
5 Lists
- Strings are sequence of values of fixed type: characters
- Lists are sequence of values (element, item) of arbitary types
- Form:
- [ a, b, c,... ]
- [] : empty list
- Examples
[10, 20, 30, 40] #uniform types [’spam’, 2.0, 5, [10, 20]] #non-uniform types, even nested!
- Indexed lookup [source,python] fruit = [appple orange lemon] print fruit[0]
- index has to be within range
- if negative value: counts back from the end
- Mutable [source,python] fruit[0] = grape
- Eumeration
for cheese in cheeses : print cheese
- range(.) create a integer sequence from a scalar
for i in range( len(numbers) ) : numbers[i] = numbers[i] (^) * 2
- Concatenation and Repetitiong (just like strings)
print [1, 2, 3] + [4, 5, 6] print [0] (^) * 4 print [1, 2, 3] (^) * 4
t = [’a’, ’b’, ’c’, ’d’] t[1.3] = [’x’, ’y’]
This gives you:
Traceback (most recent call last):
File "", line 1, in
TypeError: list indices must be integers, not float
- Comparison (same as string)
- By value: == !=
- By reference: is
- assignment is always by reference
- assignment create alias
6 Dictionary
- The index of list has to be integers
- The index of dictionary can be arbitary types
- Form:
- { key:val, key:val,... }
- {}: empty dictionary
- dict(): empty dictionary
>>> print { 0: 2, 1: 3, 2: 5}
>>> eng2sp = { ’one’:’uno’, ’two’:’dos’, ’three’:’tres’ }
>>> print type(eng2sp)
>>> print eng2sp[’one’]
def fibonacci(n) : if n in [0,1] : result = n else : result = fibonacci(n-1) + fibonacci(n-2) return result
- Souce of inefficiency
- Dictionary comes to the rescue
cache = {} def fibonacci(n) : if( n in cache ) : return cache[n] if n in [0,1] : result = n else : result = fibonacci(n-1) + fibonacci(n-2) cache[n] = result return result
cache = { 0:0, 1:1 } def fibonacci(n) : if( n in cache ) : return cache[n] result = fibonacci(n-1) + fibonacci(n-2) cache[n] = result return result
Note We have used global variable cache if a variable is reassigned in a function, by default it is considered as a local variable (scope is within function). To tell Python it is a global variable, use global foo
7 Tuples
- Sequence of values (just like list)
- Immutables!
- Forms
- a, b, c,...
- (a, b, c,... )
- ()
- tuple()
- Lookup(Index), Subsetting(Slice), Enumeration (for) works as usual
- Tuple variable assignment
temp = a; a = b; b = temp;
a, b = b, a
quot, rem = divmod( 7, 3 ) print quot # gives 2 print rem # gives 1
def min_max( t ) : # t is a sequence return min(t), max(6) # min/max are builtin functions
- Variable argument: Gather
void printall( ... ) { va_list va;
va_start( va, ... );
for( ... ) {
arg = va_arg( va, int );
printf( "%d ", arg );
va_end( va );
- In Python (* operator): Gather all arguments into a tuple
def printall(*args) : print args
>>> print printall( 1, 2.0, ’3’ )
- Scatter: expand tuple into arguments
>>> t = (7,3)
>>> print divmod( *t )