Date post: | 10-May-2015 |
Category: |
Technology |
Upload: | engr-ranel-padon |
View: | 1,069 times |
Download: | 6 times |
Engr. Ranel O. Padon
V. SEQUENCES & DICTIONARIES
PYTHON PROGRAMMING
1
PYTHON PROGRAMMING TOPICS
I • Introduction to Python Programming
II • Python Basics
III • Controlling the Program Flow
IV • Program Components: Functions, Classes, Packages, and Modules
V • Sequences (List and Tuples), and Dictionaries
VI • Object-Based Programming: Classes and Objects
VII • Customizing Classes and Operator Overloading
VIII • Object-Oriented Programming: Inheritance and Polymorphism
IX • Randomization Algorithms
X • Exception Handling and Assertions
XI • String Manipulation and Regular Expressions
XII • File Handling and Processing
XIII • GUI Programming Using Tkinter 2
SEQUENCES AND DICTIONARIES
I • Introduction to Python Programming
II • Python Basics
III • Controlling the Program Flow
IV • Program Components: Functions, Classes, Packages, and Modules
V • Sequences (List and Tuples), and Dictionaries
VI • Object-Based Programming: Classes and Objects
VII • Customizing Classes and Operator Overloading
VIII • Object-Oriented Programming: Inheritance and Polymorphism
IX • Randomization Algorithms
X • Exception Handling and Assertions
XI • String Manipulation and Regular Expressions
XII • File Handling and Processing
XIII • GUI Programming Using Tkinter 3
Data structures are structures that hold and organize data or information.
DATA STRUCTURES
4
Sequences, often called arrays in other languages, are data structures that store related data items.
SEQUENCES
5
Python supports three basic sequence data types: a string, a tuple, and a list.
SEQUENCES
6
A sequence element may be referenced by writing the sequence name followed by the element’s position number in square brackets ([ ]). The first element in a sequence is the zeroth element.
SEQUENCES
7
SEQUENCES
8
SEQUENCES
9
Sequences can be accessed from the end of the sequence by using negative subscripts.
SEQUENCES
10
Some types of sequences are immutable, that is, the sequence cannot be altered (e.g., changing the value of one of its elements). Python strings and tuples are immutable sequences. In other words, they are Read-Only.
SEQUENCES
11
SEQUENCES | IMMUTABLE
12
Python’s Tuple data structure is similar to Java’s native array and C’s native array, both of which have fixed length.
SEQUENCES
13
Some sequences are mutable or can be altered. Python lists are mutable sequences. In other words, they are Read/Write data structure.
SEQUENCES
14
SEQUENCES | MUTABLE
15
Python’s List data structure is analogous to Java’s ArrayList and Vector classes, both of which are extendable.
SEQUENCES
16
The length of the sequence is determined by the function call len(sequence ). This is useful when traversing the sequence.
SEQUENCES
17
The length of the sequence is determined by the function call len(sequence ). This is useful when traversing the sequence.
SEQUENCES | len FUNCTION
18
SEQUENCES | len FUNCTION
Same result with that of previous implementation, but more maintainable and scalable.
19
SEQUENCES | EMPTY STRING
20
SEQUENCES | EMPTY LIST
21
SEQUENCES | EMPTY TUPLE
22
SEQUENCES | TUPLE | SINGLETON
Tuple with single element must still include a comma. Parenthesis is optional in all type of Tuples, singleton or not.
23
Sequences can be unpacked, the values stored in the sequence are assigned to various identifiers. Unpacking is a useful programming shortcut for assigning values to multiple variables in a single statement.
SEQUENCES | TUPLE | (UN)PACKING
24
SEQUENCES | TUPLE | (UN)PACKING
25
SEQUENCES | TUPLE | (UN)PACKING
Tuple packing/unpacking is useful when swapping variables.
26
The += augmented assignment statement can insert a value in a list. When the value to the left of the += symbol is a sequence, the value to the right of the symbol must be a sequence also.
SEQUENCES
27
SEQUENCES
28
SEQUENCES
29
Lists are not restricted to homogeneous data types. Python programmers typically use lists to store sequences of homogeneous values (values of the same data type)
SEQUENCES
30
In general, a program uses a list to store homogeneous values for the purpose of looping over these values and performing the same operation on each value. Usually, the length of the list is not predetermined and may vary over the course of the program.
SEQUENCES
31
The for/in structure iterates over a sequence. The for structure starts with the first element in the sequence, assigns the value of the first element to the control variable and executes the body of the for structure. Then, the for structure proceeds to the next element in the sequence and performs the same operations.
SEQUENCES
32
SEQUENCES
33
SEQUENCES
34
Tuples store sequences of heterogeneous data. Each data piece in a tuple represents a part of the total information represented by the tuple. Usually, the length of the tuple is predetermined and does not change over the course of a program’s execution.
SEQUENCES
35
SEQUENCES
36
Python provides the slicing capability to obtain contiguous regions of a sequence. Slicing creates a new sequence; therefore, when a program passes a slice to a function, the original sequence is not affected.
SEQUENCES | SLICING
37
SEQUENCES | SLICING
38
is equivalent to the following expressions: sequence [ 0 : len( sequence ) ] sequence [ : len( sequence ) ] sequence [ 0 : ]
SEQUENCES | SLICING
39
The dictionary is a mapping construct that consists of key-value pairs. Like a physical dictionary, it has listing of words and definitions. Dictionaries (called associative arrays in PHP, hash maps/tables in Java, and analogous to JavaScript Object Notation), can be thought of as unordered collections of values where each value is accessed through its corresponding key.
DICTIONARIES
40
To create an empty dictionary, use empty curly braces.
DICTIONARIES | EMPTY DICTIONARY
41
To create a dictionary with values, use a comma-separated sequence of key-value pairs, inside curly braces. Each key-value pair is of the form key : value.
DICTIONARIES
42
DICTIONARIES
43
DICTIONARIES
44
Python dictionary keys must be immutable values, like strings, numbers or tuples, whose elements are immutable. Dictionary values can be of any Python data type.
DICTIONARIES
45
Dictionary values are accessed with the expression dictionaryName[ key ].
DICTIONARIES | READ
46
Accessing a non-existent dictionary key causes the program to exit and to display a “key error” message. Use a fail-safe approach.
DICTIONARIES | READ
47
To insert a new key-value pair in a dictionary, use the statement dictionaryName[ key ] = value.
DICTIONARIES | WRITE
48
The statement dictionaryName [ key ] = value modifies the value associated with key, if the dictionary already contains that key. Otherwise, the statement inserts the key-value pair into the dictionary.
DICTIONARIES | WRITE
49
A method performs the behaviors (tasks) of an object. To invoke an object’s method, specify the name of the object, followed by the dot (.) access operator, followed by the method invocation.
METHODS
50
List method append adds an items to the end of a list.
METHODS | APPEND
51
METHODS | APPEND
52
List method count takes a value as an argument and returns the number of elements in the list that have that value. If the list contains no elements with the specified value, method count returns 0.
METHODS | COUNT
53
METHODS | APPEND
54
METHODS | LIST
55
METHODS | SORT
56
Dictionary method items returns a list of tuples, where each tuple contains a key-value pair. Dictionary method keys returns an unordered list of the dictionary’s keys. Dictionary method values returns an unordered list of the dictionary’s values.
METHODS | ITEMS, KEYS, VALUES
57
METHODS | ITEMS, KEYS, VALUES
58
METHODS | ITEMS, KEYS, VALUES
59
METHODS | DICTIONARIES
60
METHODS | DICTIONARIES
61
METHODS | LIST | DEL
62
METHODS | DICTIONARY | DEL
63
Dictionary method copy returns a new dictionary that is a shallow copy of the original dictionary. In a shallow copy, the elements in the new dictionary are references only to the elements in the original dictionary.
METHODS | COPY
64
If the programmer wants to create a copy (called a deep copy), that is independent of the original dictionary, Python provides module copy. Function copy.deepcopy returns a deep copy of its argument.
METHODS | DEEP COPY
65
METHODS | DEEP COPY
66
METHODS | DEEP COPY
67
Python arguments are always passed by object reference, that is, the function receives references to the values passed as arguments.
PASS BY REFERENCE
68
If a function receives a reference to a mutable object (e.g., a dictionary or a list), the function can modify the original value of the object. It is as if the object had been passed by reference.
PASS BY REFERENCE
69
If a function receives a reference to an immutable object (e.g., a number, a string or a tuple whose elements are immutable values), the function cannot modify the original object directly. It is as if the object had been passed by value.
PASS BY VALUE
70
To pass a list argument to a function, specify the name of the list without square brackets.
SEQUENCES AS ARGUMENTS
71
SEQUENCES AS ARGUMENTS
72
Sequences can contain elements that are also sequences. Such sequences have multiple subscripts. A common use of multiple-subscripted sequences is to represent tables of values consisting of in formation arranged in rows and columns.
SEQUENCES | MULTI-DIMENSIONAL
73
To identify a particular table element, we must specify two subscripts:
the first identifies the element’s row,
the second identifies the element’s column.
SEQUENCES | MULTI-DIMENSIONAL
74
Python does not support multiple-subscripted sequences directly, but allows programmers to specify single-subscripted tuples and lists whose elements are also single-subscripted tuples and lists, thus achieving the same effect.
SEQUENCES | MULTI-DIMENSIONAL
75
The name of every element in a multiple-subscripted sequence is of the form a[ i ][ j ], where a is the name of the sequence, and
i and j are the subscripts that uniquely identify the row and column of each element in the sequence.
SEQUENCES | MULTI-DIMENSIONAL
76
SEQUENCES | MULTI-DIMENSIONAL
77
SEQUENCES | MULTI-DIMENSIONAL
78
SEQUENCES | MULTI-DIMENSIONAL
79
SEQUENCES | MULTI-DIMENSIONAL
Getting the sum of all elements in a 2-dimensional list. Useful for Reading values only.
80
SEQUENCES | MULTI-DIMENSIONAL
Getting the sum of all elements in a 2-dimensional list using the indices/subscripts. Subscripts are useful also for overriding the array data.
81
To compute pure numerical problems (i.e., multi-dimensional arrays), You might want to use the NumPy (Numerical Python) package This package contains modules that handle arrays and provides multi-dimensional array objects for efficient computation.
SEQUENCES | MULTI-DIMENSIONAL
82
Operator Description f(parameters) Function Call x.f(parameters) Method Call
x[index] Read from an Element x[index] = value Write to an Element x[start:end] Slicing/Copying (value, …) Tuple Expression/Packing [value, …] List Expression
{key:value, …} Dictionary Expression
END NOTES
83
Make a diagonal_elements(m) function so that a given 2D list, say matrix m, will have all of its diagonal elements be returned in a list be and printed.
def diagonal_elements(m)
print diagonal_elements(my_2d_list)
PRACTICE EXERCISE 1
84
Make a scalar_product(m, s) function so that a given 2D list, say matrix m, will have all of its elements be multiplied by the given scalar/number s. You could either modify the input matrix or return an independent copy of the modified matrix
def scalar_product(m, s)
print scalar_product(my_2d_list, 2)
PRACTICE EXERCISE 2
85
Make a column_sum(m, c) function so that a given 2D list, say matrix m, will have all of its elements along column c be added. Return a single number
def column_sum(m, c)
print column_sum(my_2d_list, 2)
PRACTICE EXERCISE 3
86
Make a transpose function so that a given 2D list, say, will be converted/transposed to this:
PRACTICE EXERCISE 4
87
REFERENCES
q Deitel, Deitel, Liperi, and Wiedermann - Python: How to Program (2001).
q Disclaimer: Most of the images/information used here have no proper source citation, and I do not claim ownership of these either. I don’t want to reinvent the wheel, and I just want to reuse and reintegrate materials that I think are useful or cool, then present them in another light, form, or perspective. Moreover, the images/information here are mainly used for illustration/educational purposes only, in the spirit of openness of data, spreading light, and empowering people with knowledge. J
88