Algorithms
[Link] |
Let’s recap the properties of an algorithm which we discussed after Reading 1.1:
a. an algorithm consists of a precisely stated, step-by-step list of instructions
b. a problem is computable if it is possible to build an algorithm which solves any instances
of the problem in a finite number of steps
LIST
>>> myList = [42, 'cat', 3.142]
>>> myList
[42, 'cat', 3.142]
>>> # find the length
>>> len(myList)
>>> # find the item at index 1
>>> myList[1]
'cat'
>>> # add a new item and display the list again
>>> [Link](269)
>>> myList
[42, 'cat', 3.142, 269]
>>> # change the item at index 1 and display the list
>>> myList[1] = 'dog'
>>> myList
[42, 'dog', 3.142, 269]
>>> # remove the item at index 0 and assign it to a variable
>>> result = [Link](0)
>>> # display the removed item and the list
>>> result
42
>>> myList
['dog', 3.142, 269]
>>> # remove the last item
>>> [Link]()
269
>>> # display the list
>>> myList
['dog', 3.142]
You may have noticed that two different mechanisms are at work in these examples. Some of the things
we can do with lists involve functions . For instance
len(myList)
We can also join two lists together using the + operator.
>>> aList = [1, 2, 3, 5] + [8, 13, 21]
>>> aList
[1, 2, 3, 5, 8, 13, 21]
Note that lists can contain multiple copies of the same item.
>>> aList = [1, 2, 3, 5] + [5, 8, 13, 21]
>>> aList
[1, 2, 3, 5, 5, 8, 13, 21]
A very useful operation is called slicing . The next examples illustrate its use.
Notice that if a list is too long to fit on one line we can just press Enter and then continue the list on the
following line.
>>> aList = ['ant', 'bee', 'cicada',
... 'dragonfly', 'earwig', 'flea']
# slice from index 2 up to but not including index 4
>>> aList[2:4]
['cicada', 'dragonfly']
>>> # slice from index 3 to the end of the list
>>> aList[3:]
['dragonfly', 'earwig', 'flea']
>>> # slice from the beginning of the list up to but not including index 2
>>> aList[:2]
['ant', 'bee']
>>> # the original list is still intact
>>> aList
['ant', 'bee', 'cicada', 'dragonfly', 'earwig', 'flea']
Lists in Python can grow or shrink as items are added or removed. It’s very common to start with an
empty list and add items to it.
>>> list2 = []
>>> [Link](2)
>>> [Link](7)
>>> [Link](1)
>>> [Link](8)
>>> list2
[2, 7, 1, 8]