• No results found

Compound Data Types 2

N/A
N/A
Protected

Academic year: 2022

Share "Compound Data Types 2"

Copied!
32
0
0

Loading.... (view fulltext now)

Full text

(1)

Compound Data Types 2

Prof. Mauro Gaspari: [email protected]

(2)

Objects and Values

We know that a and b both refer to a string, but we don’t know whether they refer to the same string.

There are two possible situations:

a and b refer to two different objects that have the same value.

a and b refer to the same object.

To check whether two variables refer to the same object, you can use the is operator.

a = "banana"

b = "banana"

(3)

Objects and Values

To check whether two variables refer to the same object, you can use the is operator.

The id function can be used too: if a and b are strings:

>>> id(a) 135044008

>>> id(b) 135044008

Note that variables are evaluated before Executing the id function.

(4)

Objects and Values

While if a and b are lists:

Note that the == operator still works anyway.

>>> a = [1, 2, 3]

>>> b = [1, 2, 3]

>>> id(a) 135045528

>>> id(b) 135041704

>>> a == b True

(5)

Aliasing

If a refers to an object and you assign a to b, then both variables refer to the same object.

The association of a variable with an object is called a reference.

In this example, there are two references to the same object.

>>> a = [1, 2, 3]

>>> b = a

Aliasing: two variables refer to the same list.

(6)

Warning aliasing it is error-prone

If the aliased object is mutable, changes made with one alias affect the other:

>>> b[0] = 5

>>> print(a) [5, 2, 3]

Although this behaviour can be useful, it is error-prone.

In general, it is safer to avoid aliasing when you are working with mutable objects.

(7)

Cloning

If we want to modify a list and also keep a copy of the original, we need to be able to make a copy of the list itself, not just the

reference.

This process is sometimes called cloning, to avoid the ambiguity of the word ``copy.''

Taking any slice of a creates a new list, if the slice is the whole list a clone of a is created.

>>> a = [1, 2, 3]

>>> b = a[:]

>>> print(b) [1, 2, 3]

(8)

Cloning

Now we are free to make changes to b without worrying about a.

>>> b[0] = 5

>>> print(a) [1, 2, 3]

(9)

Lists as arguments

When you pass a list to a function, the function gets a reference to the list.

def head(list):

return list[0]

# si usa cosí

>>> numbers = [1, 2, 3]

>>> head(numbers) 1

The list parameter and the numbers are alieses for the Same list..

(10)

Lists as parameters

If the function modifies a list parameter, the caller sees the change.

def deleteHead(list):

del list[0]

>>> numbers = [1, 2, 3]

>>> deleteHead(numbers)

>>> print(numbers) [2, 3]

(11)

Lists as results

When a function returns a list it returns a reference to that list.

def tail(list):

return list[1:]

>>> numbers = [1, 2, 3]

>>> rest = tail(numbers)

>>> print(rest)

[2, 3] Given that the slice operator is used the result is a new list.

(12)

Methods

A method is similar to a function—it takes arguments and returns a value—but the syntax is different.

For example, the method upper takes a string and returns a new string with all uppercase letters:

A method call is called an invocation; in this case, we would say that we are invoking upper on the word. The empty parentheses indicate that this method takes no argument.

>>> word = ‘banana’

>>> new_word = word.upper()

>>> print(new_word) BANANA

(13)

List Methods

Python provides methods that operate on lists. For example:

append adds a new element to the end of a list

extend takes a list as an argument and appends all of the elements.

Note that list methods are all void; they modify the list and return None. Thus they are different from string methods (which returns values) because lists are mutable.

>>> t = [’a’,’b’,’c’]

>>> t.append(‘d’)

>>> print(t)

[’a’,’b’,’c’,'d']

>>> t1 = [’a’,’b’,’c’]

>>> t2 = [’d’,’e’]

>>> t.extend(t2)

>>> print(t)

[’a’,’b’,’c’,'d','e']

(14)

Tuples

A tuple is a sequence of values. The values can be any type, and they are indexed by integers.

What is the difference between tuples and lists?

The important difference is that tuples are immutable.

Syntactically, a tuple is a comma-separated list of values.

>>> tuple = 'a', 'b', 'c', 'd', 'e'

(15)

Tuples

A tuple is a sequence of values. The values can be any type, and they are indexed by integers.

What is the difference between tuples and lists?

The important difference is that tuples are immutable.

Syntactically, a tuple is a comma-separated list of values.

>>> tuple = 'a', 'b', 'c', 'd', 'e'

(16)

Examples

To create a tuple with a single element, you have to include a final comma:

Although it is not necessary, it is common to enclose tuples in parentheses:

>>> tuple = ('a', 'b', 'c', 'd', 'e')

>>> t1 = ('a',)

>>> type(t1)

<type 'tuple'>

>>> t2 = ('a')

>>> type(t2)

<type 'string'>

Si tratta della stringa “a” tra parentesi

(17)

Working with tuples

Most list operators also work on tuples. The bracket operator indexes an element.

However tuples cannot be changed: they are immutable.

>>> tuple = ('a', 'b', 'c', 'd', 'e')

>>> tuple[0]

'a'

>>> tuple[1:3]

('b', 'c')

>>> tuple[0] = 'A'

TypeError: object doesn't support item assignment

(18)

Working with tuples

However, it is possible to replace one tuple with another.

>>> tuple = ('A',) + tuple[1:]

>>> tuple

('A', 'b', 'c', 'd', 'e')

(19)

Tuples and Assignment

It is often useful to swap the values of two variables. With

conventional assignments, you have to use a temporary variable.

>>> temp = a

>>> a = b

>>> b = temp

Python provides an elegant and high level solution to this task.

The solution is based on tuples as follows:

>>> a, b = b, a

(20)

Semantics of this assignment

The left side is a tuple of variables; the right side is a tuple of expressions.

Each value is assigned to its respective variable.

All the expressions on the right side are evaluated before any of the assignments.

The number of variables on the left and the number of values on the right have to be the same.

(21)

Example

>>> a, b, c, d = 1, 2, 3

ValueError: unpack tuple of wrong size

(22)

Tuples and Return Values

Strictly speaking, a function can only return one value, but if the value is a tuple, the effect is the same as returning multiple values.

For example, if you want to divide two integers and compute the quotient and remainder, it is inefficient to compute 1/2 and then 1%2. It is better to compute them both at the same time.

The built-in function divmod takes two arguments and returns a tuple of two values, the quotient and remainder. You can store the result as a tuple.

(23)

Examples

>>> t = divmod(7,3)

>>> print(t) (2,1)

>>> quot,rem=divmod(7,3)

>>> print(quot) 2

>>> print(rem) 1

(24)

Example

min and max are built-in functions that find the largest and smallest elements of a sequence.

The function below computes both and returns a

tuple of two values.

(25)

Dictionaries

A dictionary is like a list, but more general. In a list, the indices have to be integers; in a dictionary they can be (almost) any type.

You can think of a dictionary as a mapping between a set of indices (which are called keys) and a set of values.

Each key maps to a value. The association of a key and a value is called a key-value pair or sometimes an item.

Note that dictionaries are not sequences.

(26)

Example

We can start creating an empty dictionary and inserting key-value pairs..

An empty dictionary is denoted by {}.

>>> eng2sp = {}

>>> eng2sp['one'] = 'uno'

>>> eng2sp['two'] = 'dos'

>>> print(eng2sp)

{'one': 'uno', 'two': 'dos'}

(27)

Example

>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}

>>> print(eng2sp)

{'one': 'uno', 'three': 'tres', 'two': 'dos'}

What happens?

(28)

Accessing elements

Elements can be accessed efficiently using the key.

The len function and the in operator work with dictionaries

>>> print eng2sp['two']

'dos'

>>> len(eng2sp) 3

>>> 'one' in eng2sp True

(29)

Examples

>>> inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217}

>>> print(inventory)

{'oranges': 525, 'apples': 430, 'pears': 217, 'bananas': 312}

>>> del inventory['pears']

>>> print(inventory)

{'oranges': 525, 'apples': 430, 'bananas': 312}

# OPPURE

>>> inventory['pears'] = 0

>>> print(inventory)

{'oranges': 525, 'apples': 430, 'pears': 0, 'bananas': 312}

>>> len(inventory)

4 Dictionaries are mutable!

(30)

Exercise 1

Write a function that takes as parameters two lists of integers of any length respectively containing bases and exponents and returs the list of

exponentiation for any index if both the base and

the exponent exists.

(31)

Exercise 2

Define a function that takes two integers as

parameters N1,N2 and returns a matrix N1*N2 filled with random numbers in the interval:

0 → N1XN2.

(32)

Exercise 3

Emulate a cash dispenser which is able to deal with many accounts and is always ready for withdraw money.

The cash dispenser asks for a name, then asks for a password, checks if the password is correct. If the password is correct asks the user for an amount to withdraw, otherwise asks the user to type the password again (only 3 attempt should be supported). If the amount is available the cash dispenser prints done and the updated amount, otherwise it prints transaction cancelled. When the operation is completed the task dispenser asks for a name again and repeats the process.

Hint: store the data of the accounts using a list of lists as follows:

BANK = [[name1, paswd1, amount1], ….[nameN, paswdN, amountN]

References

Related documents

Biological control is the use of living organisms, such as predators, parasitoids, and pathogens, to control pest insects, weeds, or diseases.. Other items addressed

2) In northern Vietnam, an improved port would bring Western Chinese exports to market faster and more cheaply. A deep water port near the northern Vietnamese city of Hai Phong

Further, by showing that v τ is a modular unit over Z we give a new proof of the fact that the singular values of v τ are units at all imaginary quadratic arguments and obtain

Eichberger and Kelsey (2014) provide the following equilibrium existence result for games with positive externalities and increasing differences..

Scientific literature (particularly geodesy) often uses “ellipsoid” in place of “biaxial ellipsoid, rotational ellipsoid or ellipsoid revolution” (a = b &gt; c)..

By using genetic algorithm thousands of S-boxes can be generated and one can be selected which satisfies the performance criteria in the best way.. The S-boxes provide

One in two smokers were found to have airflow limitation; the predictors were Indian ethnicity, prolonged smoking pack-year history and Lung Function Questionnaire score ≤

(b) bills of exchange, travellers cheques, convertible currency, foreign government treasury bills, securities and bonds, promissory notes and balance in a bank payable otherwise