Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Gauld A.Learning to program (Python)_1.pdf
Скачиваний:
23
Добавлен:
23.08.2013
Размер:
1.34 Mб
Скачать

Other Collection Types

Array or Vector

A list of items which are indexed for easy and fast retrieval. Usually you have to say up front how many items you want to store. Lets say I have an array called A, then I can extract the 3rd item in A by writing A[3]. Arrays are fundamental in BASIC, in fact they are the only built in collection type. In Python arrays are simulated using lists and in Tcl arrays are implemented using dictionaries.

An example of an array in BASIC follows:

DIM Myarray(20) REM Create a 20 element array

MyArray(1) = 27

MyArray(2) = 50

FOR i =1 TO 5

PRINT MyArray(i)

NEXT i

Notice that the index starts at 1 in BASIC, this is unusual and in most languages the index will start at 0. There are no other operations on arrays, all you can do is create them, assign values and read values.

Stack

Think of a stack of trays in a restaurant. A member of staff puts a pile of clean trays on top and these are removed one by one by customers. The trays at the bottom of the stack get used last (and least!). Data stacks work the same way: you push an item onto the stack or pop one off. The item popped is always the last one pushed. This property of stacks is sometimes called Last In First Out or LIFO. One useful property of stacks is that you can reverse a list of items by pushing the list onto the stack then popping it off again. The result will be the reverse of the starting list. Stacks are not built in to Python, Tcl or BASIC. You have to write some program code to implement the behaviour. Lists are usually the best starting point since like stacks they can grow as needed.

Bag

A bag is a collection of items with no specified order and it can contain duplicates. Bags usually have operators to enable you to add, find and remove items. In Python and Tcl bags are just lists. In BASIC you must build the bag from a large array.

Set

A set has the property of only storing one of each item. You can usually test to see if an item is in a set (membership). Add, remove and retrieve items and join two sets together in various ways corresponding to set theory in math (eg union, intersect etc). None of our sample languages implement sets directly but they can be easily implemented in both Python and Tcl by using the built in dictionary type.

Queue

A queue is rather like a stack except that the first item into a queue is also the first item out.This is known as

First In First Out or FIFO behaviour.

There's a whole bunch of other collection types but these are the main ones that you might see. (In fact we'll only be dealing with a few of these in this tutor!)

29