2 7 Structured Data Types En

Embed Size (px)

Citation preview

  • 7/31/2019 2 7 Structured Data Types En

    1/23

    Topic 2. Introduction to programming

    Universidad de Oviedo

    7-1

    Computer Science Fundamentals

    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. Variablescope.

    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.

  • 7/31/2019 2 7 Structured Data Types En

    2/23

    Topic 2. Introduction to programming

    Universidad de Oviedo

    7-2

    Computer Science Fundamentals

    Examples of data structures

    From basic data types, new data structures can be defined. Asingle 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/31/2019 2 7 Structured Data Types En

    3/23

    Topic 2. Introduction to programming

    Universidad de Oviedo

    7-3

    Computer Science Fundamentals

    Lists

    A list is an ordered sequence of data of any kind. Its length isnot fixed as they are allowed to grow. List values are

    expressed between brackets, separated by commas.

    >>>mylist=["speed",17,3.1416]

    >>>type(mylist)

    >>>len(mylist)

    3

  • 7/31/2019 2 7 Structured Data Types En

    4/23

    Topic 2. Introduction to programming

    Universidad de Oviedo

    7-4

    Computer Science Fundamentals

    Lists: Item access

    Items in a list are ordered and can be accessed by means ofan index value which always starts in 0.

    >>>mylist=["speed",17,3.1416]

    >>>printmylist[0]

    speed

    >>>type(mylist[2])

    >>>i=1

    >>>printmylist[i]

    17

  • 7/31/2019 2 7 Structured Data Types En

    5/23

    Topic 2. Introduction to programming

    Universidad de Oviedo

    7-5

    Computer Science Fundamentals

    Lists: operators

    Concatenation operator + Repetition operator * Slice operator [ : ] Relational operators == in is>>>p=[1,2,3,4]

    >>>printp+p

    [1,2,3,4,1,2,3,4]

    >>>q=p*3

    >>>printq[1,2,3,4,1,2,3,4,1,2,3,4]

    >>>printq[3:7]

    [4,1,2,3]

    >>>print3inpandpqTrue

    The result of using an operatorora function can be assigned to a

    new list

  • 7/31/2019 2 7 Structured Data Types En

    6/23

    Topic 2. Introduction to programming

    Universidad de Oviedo

    7-6

    Computer Science Fundamentals

    Slice operator

    It returns list items from begin to end-1, step by step.

    mylist[begin:end:step]

    If eitherbegin orend 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).

    numbers=["one","two","three","four","five"]

    numbers[1:4] ['two','three','four']

    numbers[2:-1] ['three',four']numbers[:] ['one','two','three','four','five']

    numbers[::2] ['one','three','five']

    numbers[::-1] ['five','four','three','two','one']

  • 7/31/2019 2 7 Structured Data Types En

    7/23Topic 2. Introduction to programming

    Universidad de Oviedo

    7-7

    Computer Science Fundamentals

    List functions

    Length len() Numeric list creation range() Numeric list functions sum()max()min() List sorting sorted()>>>p=range(1,5)>>>printp,len(p)

    [1,2,3,4]4

    >>>printsum(p),max(p),min(p)

    1041>>>printsorted(p*3)

    [1,1,1,2,2,2,3,3,3,4,4,4]

    >>>names=["Paula","Luis","Juan","Ines"]

    >>>printsorted(names)

    ['Ines','Juan','Luis','Paula']

  • 7/31/2019 2 7 Structured Data Types En

    8/23Topic 2. Introduction to programming

    Universidad de Oviedo

    7-8

    Computer Science Fundamentals

    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() .insert() Erase methods .pop() .remove()

    >>>numbers=["one","two","three","four"]

    >>>numbers[2]="five"

    >>>printnumbers['one','two','five','four']

    >>>numbers.append("six")

    >>>numbers.extend(["seven","eight","nine"])

    >>>printnumbers

    ['one','two','five','four','six','seven','eight','nine']

  • 7/31/2019 2 7 Structured Data Types En

    9/23Topic 2. Introduction to programming

    Universidad de Oviedo

    7-9

    Computer Science Fundamentals

    List modification

    >>>numbers.pop()

    'nine'

    >>>printnumbers

    ['one','two','five','four','six','seven','eight']

    >>>numbers.pop(2)

    'five'

    >>>printnumbers

    ['one','two','four','six','seven','eight']

    >>>numbers.remove("seven")

    >>>printnumbers

    ['one','two','four','six','eight']>>>numbers.insert(2,"three")

    >>>printnumbers

    ['one','two','three','four','six','seven','eight']

  • 7/31/2019 2 7 Structured Data Types En

    10/23Topic 2. Introduction to programming

    Universidad de Oviedo

    7-10

    Computer Science Fundamentals

    List iteration

    The forloop allows us to iterate over the elements of a list. It is alsopossible to access the items using index values.

    >>>p=[1,2,3,5,7,11,13,17]

    >>>forninp:

    ...printn**2,

    ...

    1492549121169289

    >>>

    >>>foriinrange(len(p)):...printp[i]**2,

    ...

    1492549121169289

  • 7/31/2019 2 7 Structured Data Types En

    11/23Topic 2. Introduction to programming

    Universidad de Oviedo

    7-11

    Computer Science Fundamentals

    Exercises

  • 7/31/2019 2 7 Structured Data Types En

    12/23Topic 2. Introduction to programming

    Universidad de Oviedo

    7-12

    Computer Science Fundamentals

    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)

    >>>printnombre[2],len(nombre)

    't'8

    >>>nombre[2]="p"

    TypeError:'str'objectdoesnotsupportitemassignment

  • 7/31/2019 2 7 Structured Data Types En

    13/23Topic 2. Introduction to programming

    Universidad de Oviedo

    7-13

    Computer Science Fundamentals

    Special characters

    Special characters are represented with a code after \

    \n carriagereturn

    \t tabulator

    \\

    backslash\\'\" Singleanddoublequotes

    >>>text="firstline\nsecond\t\"line\"">>>printtext

    firstlinesecond "line"

    >>>text'firstline\nsecond\t"line"'

  • 7/31/2019 2 7 Structured Data Types En

    14/23Topic 2. Introduction to programming

    Universidad de Oviedo

    7-14

    Computer Science Fundamentals

    String operators

    >>>name="Patricia"

    >>>print"tri"inname

    True>>>years=20

    >>>print"%sis%dyearsold"%(name,years)

    Patriciais20yearsold

    They are the same as in the case of lists +*[:]== in (it allows us to look for characters or substrings) Formatting operator % (special)

  • 7/31/2019 2 7 Structured Data Types En

    15/23Topic 2. Introduction to programming

    Universidad de Oviedo

    7-15

    Computer Science Fundamentals

    Functions and methods

    >>>printint("123")+float("12.3"),"123"+str(123)135.3123123

    >>>x="Asturias"

    >>>declaration="ILOVE"+x.upper()

    >>>printdeclarationILOVEASTURIAS

    >>>printdeclaration.replace("ILOVE","MEPRESTA")

    MEPRESTAASTURIAS

    >>>num=int(raw_input("Enteraninteger"))

    Reading raw_input() Number / string conversion int()float()str() Special methods .lower().upper().replace()

  • 7/31/2019 2 7 Structured Data Types En

    16/23Topic 2. Introduction to programming

    Universidad de Oviedo

    7-16

    Computer Science Fundamentals

    Arrays

    An array is an ordered sequence of items of the same type. It can havemultiple 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.

    >>>importnumpy

    >>>v=numpy.array([1,2,3,4,5])

    >>>type(v)

    >>>m=numpy.array([[1,2,3],[4,5,6]],float)

    >>>printm

    [[1.2.3.]

    [4.5.6.]]

  • 7/31/2019 2 7 Structured Data Types En

    17/23Topic 2. Introduction to programming

    Universidad de Oviedo

    7-17

    Computer Science Fundamentals

    Arrays

    An array has several attributes which define its shape and size.

    o .ndim: number of dimensionso .shape: Tuple containing the length of each dimensiono .size: Total number of itemsThey also exist as functions -> ndim() shape() and size()

    >>>m=numpy.array([[1,2,3],[4,5,6]],float)

    >>>printm.ndim,m.shape,m.size

    2(2,3)6

    >>>printrows=",m.shape[0],"\ncolumns=",m.shape[1]

    rows=2

    columns=3

  • 7/31/2019 2 7 Structured Data Types En

    18/23Topic 2. Introduction to programming

    Universidad de Oviedo

    7-18

    Computer Science Fundamentals

    Arrays: Accessing items

    Array items are accessible using index values (initial value = 0)

    A matrix can be considered as a vector when each item is a row, thereforeit is also possible to access each row.

    Arrays are mutable variables, which can be directly modified.

    >>>m=numpy.array([[1,2,3],[4,5,6]])

    >>>printm[0,2]

    3

    >>>m[1,0]=9

    >>>printm[1]

    [9,5,6]

    123

    456m=

  • 7/31/2019 2 7 Structured Data Types En

    19/23Topic 2. Introduction to programming

    Universidad de Oviedo

    7-19

    Computer Science Fundamentals

    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>>>printnumpy.arange(0,1,0.1)

    [0.0.10.20.30.40.50.60.70.80.9]

    >>>printnumpy.zeros((2,3))[[0.0.0.]

    [0.0.0.]]

    >>>printnumpy.ones(5,int)

    [11111]

  • 7/31/2019 2 7 Structured Data Types En

    20/23Topic 2. Introduction to programming

    Universidad de Oviedo

    7-20

    Computer Science Fundamentals

    Array operations

    Arithmetic operations involving one scalar number and an array will beperformed over each element.

    If two arrays are involved, the operation is performed with the correspondingitem on the second array. In this case the shape and dimensions of both arrayshave to be the same.

    >>>m=numpy.array([1,2,3,4])

    >>>printm+5.1,m*3,m**2

    [6.17.18.19.1][36912][14916]

    >>>printm>=3

    [FalseFalseTrueTrue]>>>n=numpy.array([2,1,3,0])

    >>>printm+n,m*n,m>n

    [3364][2290][FalseTrueFalseTrue]

  • 7/31/2019 2 7 Structured Data Types En

    21/23Topic 2. Introduction to programming

    Universidad de Oviedo

    7-21

    Computer Science Fundamentals

    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]

    Numpy also has lots of functions from linear algebra in order to work with

    vectors and matrices: product, transpose, inverse, determinant, equationsystem solving, etc.

    >>>x=numpy.arange(0,1,.1)

    >>>print0.5+numpy.sin(2*numpy.pi*x)

    [0.51.087785251.451056521.451056521.087785250.5

    -0.08778525-0.45105652-0.45105652-0.08778525]

    >>>printnumpy.dot(m,n)

    13

  • 7/31/2019 2 7 Structured Data Types En

    22/23

    Topic 2. Introduction to programming

    Universidad de Oviedo

    7-22

    Computer Science Fundamentals

    Array iteration

    The forloop, as in the case of the lists, allows us to iterate over thearray 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]])

    >>>forrowinmat:

    ...printrow,

    ...sum=0

    ...forninrow:sum=sum+n

    ...print"Sum=",sum

    ...

    [123]Sum=6

    [456]Sum=15

    [789]Sum=24

  • 7/31/2019 2 7 Structured Data Types En

    23/23

    i 2 d i i

    Universidad de Oviedo Computer Science Fundamentals

    Exercises