Академический Документы
Профессиональный Документы
Культура Документы
2.7 Basic data types and structures 2.1 Problem abstraction for programming. Basic concepts. 2.2 Variables, expressions, assignment 2.3 Console input / output 2.4 Basic structures for control flow handling: sequential, choice and repetitive. 2.5 Definition and use of subprograms and functions. Variable scope. 2.6 File input / output 2.7 Basic data types and structures 2.8 Steps in the development of a program: from high level to CPU execution.
Topic 2. Introduction to programming 7-1
Universidad de Oviedo
Examples of data structures From basic data types, new data structures can be defined. A single variable will be needed to store all the information. Lists -> Sequences of elements of distinc type Text strings -> Sequences of characters Arrays -> Sequences of elements of the same type Dictionaries -> Values determined by keys Sets -> Sets of elements of the same type etc
7-2
Universidad de Oviedo
Lists A list is an ordered sequence of data of any kind. Its length is not fixed as they are allowed to grow. List values are expressed between brackets, separated by commas.
>>> mylist = ["speed", 17, 3.1416] >>> type(mylist) <type 'list'> >>> len(mylist) 3
7-3
Universidad de Oviedo
Lists: Item access Items in a list are ordered and can be accessed by means of an index value which always starts in 0.
>>> mylist = ["speed", 17, 3.1416] >>> print mylist[0] speed >>> type(mylist[2]) <type 'float'> >>> i = 1 >>> print mylist[i] 17
7-4
Universidad de Oviedo
Lists: operators
Concatenation operator + Repetition operator * Slice operator [ : ] Relational operators == <>
The result of using an operator or a function can be assigned to a new list
in
is
>>> p = [1, 2, 3, 4] >>> print p+p [1, 2, 3, 4, 1, 2, 3, 4] >>> q=p*3 >>> print q [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4] >>> print q[3:7] [4, 1, 2, 3] >>> print 3 in p and p<>q True
7-5
Universidad de Oviedo
Slice operator
It returns list items from begin to end-1, step by step.
mylist[begin:end:step]
If either begin or end parameters are omitted, the first and last items are used. Negative values mean positions to be omitted from the end (-1) to the beginning. If the step parameter is not provided, it takes the default value (1).
7-6
Universidad de Oviedo
List functions
Length len()
Numeric list creation range()
Numeric list functions sum()
max()
min()
List sorting sorted()
>>> p = range(1,5) >>> print p, len(p) [1, 2, 3, 4] 4 >>> print sum(p), max(p), min(p) 10 4 1 >>> print sorted(p*3) [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4] >>> names = ["Paula", "Luis", "Juan", "Ines"] >>> print sorted(names) ['Ines', 'Juan', 'Luis', 'Paula']
7-7
Universidad de Oviedo
List modification
Lists are mutable variables. This means that the contents of a variable can be changed without having to create a new one. Direct item assignment p[1] = 7 Insertion methods .append() .extend() Erase methods .pop() .remove() .insert()
>>>
numbers
=
["one",
"two",
"three",
"four"]
>>>
numbers[2]
=
"five"
>>>
print
numbers
['one',
'two',
'five',
'four']
>>>
numbers.append("six")
>>>
numbers.extend(["seven",
"eight",
"nine"])
>>>
print
numbers
['one','two','five','four','six','seven','eight','nine']
Topic 2. Introduction to programming 7-8
Universidad de Oviedo
List modification
>>>
numbers.pop()
'nine'
>>>
print
numbers
['one',
'two',
'five',
'four',
'six',
'seven',
'eight']
>>>
numbers.pop(2)
'five'
>>>
print
numbers
['one',
'two',
'four',
'six',
'seven',
'eight']
>>>
numbers.remove("seven")
>>>
print
numbers
['one',
'two',
'four',
'six',
'eight']
>>>
numbers.insert(2,
"three")
>>>
print
numbers
['one',
'two',
'three',
'four',
'six',
'seven',
'eight']
7-9
Universidad de Oviedo
List iteration
The for loop allows us to iterate over the elements of a list. It is also possible to access the items using index values.
>>> p = [1, 2, 3, 5, 7, 11, 13, 17] >>> for n in p: ... print n**2, ... 1 4 9 25 49 121 169 289 >>> >>> for i in range(len(p)): ... print p[i]**2, ... 1 4 9 25 49 121 169 289
7-10
Universidad de Oviedo
Exercises
7-11
Universidad de Oviedo
Strings
A string is a special type of list, where the items are characters (digits, letters, signs and control characters, such as tabulators) and are expressed between double quotes. Single and double quotes are equivalent. They are inmutable, therefore their contents can not be directly modified.
>>>
name
=
"Patricia"
>>>
type(nombre)
<type
'str'>
>>>
print
nombre[2],
len(nombre)
't'
8
>>>
nombre[2]="p"
TypeError:
'str'
object
does
not
support
item
assignment
Topic 2. Introduction to programming 7-12
Universidad de Oviedo
Special characters
Special characters are represented with a code after \
\n \t \\ \' \"
>>> text = "first line \n second \t \" line \" " >>> print text first line second " line " >>> text 'first line \n second \t " line " '
7-13
Universidad de Oviedo
String operators
They are the same as in the case of lists +
*
[:]
==
<>
in (it allows us to look for characters or substrings) Formatting operator % (special)
>>> name = "Patricia" >>> print "tri" in name True >>> years = 20 >>> print "%s is %d years old" % (name, years) Patricia is 20 years old
7-14
Universidad de Oviedo
>>>
print
int("123")
+
float("12.3"),
"123"
+
str(123)
135.3
123123
>>>
x
=
"Asturias"
>>>
declaration
=
"I
LOVE
"
+
x.upper()
>>>
print
declaration
I
LOVE
ASTURIAS
>>>
print
declaration.replace("I
LOVE",
"ME
PRESTA")
ME
PRESTA
ASTURIAS
>>>
num
=
int(raw_input("Enter
an
integer"))
Topic 2. Introduction to programming 7-15
Universidad de Oviedo
Arrays
An array is an ordered sequence of items of the same type. It can have multiple variable-size dimensions. The numpy library defines the ndarray type and several functions. The array() function converts a sequence (e.g., a list) in an array.
>>>
import
numpy
>>>
v=numpy.array([1,
2,
3,
4,
5])
>>>
type(v)
<type
'numpy.ndarray'>
>>>
m
=
numpy.array([[1,
2,
3],
[4,
5,
6]],
float)
>>>
print
m
[[
1.
2.
3.]
[
4.
5.
6.]]
Topic 2. Introduction to programming 7-16
Universidad de Oviedo
Arrays
An array has several attributes which define its shape and size. o .ndim: number of dimensions o .shape: Tuple containing the length of each dimension o .size: Total number of items They also exist as functions -> ndim() shape() and size()
>>>
m
=
numpy.array([[1,
2,
3],
[4,
5,
6]],
float)
>>>
print
m.ndim,
m.shape,
m.size
2
(2,
3)
6
>>>
print
rows
=",
m.shape[0],
"\ncolumns
=",
m.shape[1]
rows
=
2
columns
=
3
Topic 2. Introduction to programming 7-17
Universidad de Oviedo
>>>
m
=
numpy.array([[1,
2,
3],
[4,
5,
6]])
>>>
print
m[0,
2]
3
1
2
3
>>>
m[1,
0]
=
9
m
=
4
5
6
>>>
print
m[1]
[9,
5,
6]
Topic 2. Introduction to programming 7-18
Universidad de Oviedo
Array creation
Several functions can be used to create arrays o arange(): It creates a vector containing a sequence (like range()) o zeros() and ones(): They create an array of zeros or ones with a specified shape and type (float by default) o empty(): It creates an empty array >>>
print
numpy.arange(0,
1,
0.1)
[
0.
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9]
>>>
print
numpy.zeros((2,3))
[[
0.
0.
0.]
[
0.
0.
0.]]
>>>
print
numpy.ones(5,
int)
[1
1
1
1
1]
Topic 2. Introduction to programming 7-19
Universidad de Oviedo
Array operations
Arithmetic operations involving one scalar number and an array will be performed over each element. If two arrays are involved, the operation is performed with the corresponding item on the second array. In this case the shape and dimensions of both arrays have to be the same.
>>>
m
=
numpy.array([1,
2,
3,
4])
>>>
print
m+5.1,
m*3,
m**2
[6.1
7.1
8.1
9.1]
[
3
6
9
12]
[
1
4
9
16]
>>>
print
m
>=
3
[False
False
True
True]
>>>
n
=
numpy.array([2,
1,
3,
0])
>>>
print
m
+
n,
m
*
n,
m
>
n
[3
3
6
4]
[2
2
9
0]
[False
True
False
True]
Topic 2. Introduction to programming 7-20
Universidad de Oviedo
Array operations
Universal functions defined in numpy, work with arrays item by item. Ex. Evaluate the function y = 0.5+sin(2 x) , in 10 points in the range [0,1.0] >>>
x=numpy.arange(0,
1,
.1)
>>>
print
0.5
+
numpy.sin(2*numpy.pi*x)
[
0.5
1.08778525
1.45105652
1.45105652
1.08778525
0.5
-0.08778525
-0.45105652
-0.45105652
-0.08778525]
Numpy also has lots of functions from linear algebra in order to work with vectors and matrices: product, transpose, inverse, determinant, equation system solving, etc. >>>
print
numpy.dot(m,n)
13
Topic 2. Introduction to programming 7-21
Universidad de Oviedo
Array iteration
The for loop, as in the case of the lists, allows us to iterate over the array items in sequential way. We have to take into account that each element of a matrix is a row array.
>>>
mat
=
numpy.array([[1,
2,
3],
[4,
5,
6],
[7,
8,
9]])
>>>
for
row
in
mat:
...
print
row,
...
sum=0
...
for
n
in
row:
sum
=
sum
+
n
...
print
"Sum
=",
sum
...
[1
2
3]
Sum
=
6
[4
5
6]
Sum
=
15
[7
8
9]
Sum
=
24
7-22
Universidad de Oviedo
Exercises
7-23