Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Sage beginners guide - Finch Kraigh copy.pdf
Скачиваний:
12
Добавлен:
10.02.2015
Размер:
5.86 Mб
Скачать

Introducing Python and Sage

if statements are not ideal for catching runtime errors. In Chapter 9, we will learn about exceptions, which are a much more elegant way to deal with runtime errors.

Storing data in a dictionary

Dictionaries are another fundamental data structure in Python. A dictionary is similar to a list in that it is comprised of a series of data elements. One important difference is that a dictionary uses "keys" instead of indices to access elements. The keys can be strings or other data types. While a list is a sequence, the elements in a dictionary don't have any intrinsic order. A dictionary is a good choice to collect different types of data.

Timeforaction–definingandaccessingdictionaries

Let's go back to our program that computes an analytical solution to a boundary value problem. Certain parameters are required to carry out the calculation. So far, we just stored the parameter as a collection of numbers. In a more complex program, this simplistic approach could introduce subtle bugs if we accidentally used one of the parameter variables for something else.

#Define parameters k = 0.1

l = 1.0 v1 = 0.0 v2 = 1.0 t = 1.0

num_x_steps = 10

#Store parameters in a dictionary parameters = { 'diffusion coefficient' : k,

'length' : l, 'left_BC' : v1, 'right_BC' :v2, 'time' : t,

'num_x_steps' : num_x_steps

}

#Access the dictionary

print("Value of time is {0}".format(parameters['time'])) parameters['time'] = 2.0

print("New value of time is {0}".format(parameters['time'])) print('')

print("Dictionary contains {0} items:".format(len(parameters)))

[ 108 ]

Chapter 4

for key, value in parameters.iteritems(): print('{0} : {1}'.format(key, value))

Run the script and review the output, which should look like this:

What just happened?

We have collected a variety of parameters into a single data structure using a dictionary. We used strings as keys to the dictionary to make it easy to recall parameter values. We defined the dictionary using curly brackets to enclose key-value pairs:

empty_dict = {}

my_dict = { key1:value1, key2:value2, …, keyN:valueN}

Many operations on dictionaries are analogous to operations on lists. We demonstrated how to get and set values of items in the dictionary using square brackets:

value = my_dict['key name']

Because the keys are not necessarily numbers, there is no equivalent of slices for dictionaries. The len function is also used to return the number of (key,value) pairs in a dictionary.

We then iterated over the dictionary to print the keys and values using the iteritems method:

for key, value in parameters.iteritems(): print(key)

print(value)

The method iterkeys iterates only over the keys, while itervalues iterates only over the values. A full list of dictionary methods can be found at http://docs.python.org/ library/stdtypes.html#dict

[ 109 ]

Introducing Python and Sage

Note that iterating over a dictionary won't necessarily print the items in the same order every time! An important distinction between dictionaries and lists is that the elements in a dictionary have no intrinsic order. You should not rely upon the elements of a dictionary being returned in any particular order.

Ordered dictionaries

Python 2.7 and versions above 3.1.3 contain a new class called OrderedDict, which works just like an ordinary dictionary except that it remembers the order in which items were inserted. This class is not available in Sage 4.6.1 because Sage is still using Python 2.6, but it should be available soon.

Lambdaforms

Sometimes you need to define a short, simple Python function. You can always use the def keyword to define the function and give it a name. You can also use the lambda keyword to define an anonymous function that consists of a single expression.

Timeforaction–usinglambdatocreateananonymous function

Why would you want an anonymous function? Let's try sorting a list of dictionaries:

data = [{'Name':'Albert', 'age':32}, {'Name':'Yuen', 'age':16}, {'Name':'Priya', 'age':45}]

print(sorted(data))

print(sorted(data, key=lambda item : item['age']))

The results should look like this:

What just happened?

We defined a list of dictionaries, each of which contains data about a person. We then used the sorted function to sort the items in the list. The first time we called sorted, it appeared that the list had been sorted alphabetically, by the first letter of each name. This behaviour is unpredictable—if we added a last name to each dictionary, would the first or last name be used as the sorting key? To prevent this kind of problem, we can use the keyword key to specify a function that is called on each item before sorting takes place. In

the second function call, we used lambda to define an anonymous function that returns the integer value of 'age' from the dictionary. We can see that the list is now sorted by age.

[ 110 ]

Chapter 4

The general syntax for declaring an anonymous function with lambda is:

lambda arg_1, arg_2, ... , arg_n : expression

There can be multiple arguments, but only one expression. Like nested functions, lambda forms can reference variables from their containing scope. Lambda forms are not used often in Python programming, but they do show up occasionally in Sage examples.

Summary

We learned about some key aspects of Python in this chapter. When combined with the information in Chapter 3, we now have all the tools we need to implement algorithms in Sage.

Specifically, we covered:

How to create and run Sage scripts

Basic principles of sequence types like lists, tuples, and strings

How to store data more permanently in text files

Repeating operations and iterating over lists with loops

Using conditional expressions and logic to make decisions in a program

How to use dictionaries to store data

This chapter provides a working knowledge of Python, but it is hardly complete. Refer to the Python documentation on the Web to learn more about the details of this powerful programming language. Now that we have been introduced to sequence types like lists, we can learn about specialized array and matrix types for performing mathematical calculations.

[ 111 ]

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]