...

Wednesday, May 22, 2013

Computer Science 03

Recall that previously we made programs did approximation. We could print the approximations during the process onto the screen. However, these approximations are not recorded and you cannot really do anything with them.

We have three data structures to collect items in Python:
1) Tuples
2) Lists
3) Dictionaries

Tuples and Lists are Ordered Sequences of Objects. You can refer to the objects by using an index.
Dictionaries on the other hand, are NOT ordered.

You can declare a 'tuple' as such:

helloTuple = (1, 2, 3, 4, 5)

We can then print the 'tuple' as such

print(hello[1]) #Prints the second object in the tuple
print(hello) #Prints the contents of the tuple
print(len(hello)) #Prints the length of the tuple
print(hello[len(hello)-1]) #Prints the last element in the tuple


We can use tuples in a variety of ways. For example, to find numbers divisible by 3 from the range of 0 to 100, we can use:

divisor=5
divisible=() #This declares an empty tuple
for x in range(0,101):
     if x%divisor==0:
        divisible+=(x,)
print(divisible)


This would check if the number is divisible by divisor using the modulo (%) function, and if it is, it will append a tuple of length 1 to the back of the divisible tuple.

Tuples are Immutable. The values of tuples cannot be changed. For example, if we cannot use divisible[0]=1 at the end of our previous example.

Lists are Mutable. The value of the list object can be changed.

You can create lists using:

listNames = ['Kelvin', 'Ling']
listNames2 = ['Wynne', 'Elaine']


The difference is that we're using a square bracket instead of a normal one.

We can append lists as such:

listNames.append(listNames2)

Append is a method that actually Mutates the list. In this list, we have various items:
1) Object 0 is a 'str'
2) Object 1 is a 'str'
3) Object 2 is a 'list'

In this case, list2[0] and list1[2][0] is actually referring to the same object in memory. Modifying either will cause both to change since they're referring to the same thing. Append adds a Pointer to the list instead of simply copying.

The difference is that in the first example, if we are actually concatenating two tuples, a new tuple is created and it is assigned to the variable. We can treat tuples as Primitive Data-Types in Java, and tuples as Objects in Java.

If you concatenate a list into a tuple, a new tuple is created, with the list at the back. Suppose that tuple1[2] contains the Pointer to list1, tuple1[2][0] contains the same Pointer as list1[0], changing tuple1[2][0] actually changes list1[0]. The tuple1 has not changed, because it is Non-Mutable. The changes are applied to the list1 instead.

Assignment is changing the object to which an identifier binds to.
Mutation is changing the actual value of the object.

Lists and tuples can be sliced the same way as a 'str'.

You can loop through a tuple or list as such:

for x in list1
    print(x)


You can also use the remove() method to remove the first occurrence of a specified object:

allNumbers=[1,2,3,4,5,6,7,8,9]
unwantedNumbers=[1,3,7,8,9]
for x in unwantedNumbers:
    if x in allNumbers:
        allNumbers.remove(x)
print(allNumbers)


The code goes through every unwanted number and if it exists in the list of all numbers, it would remove the first occurrence of it. To remove all occurence, we use the loop "while x in unwantedNumbers" instead.

You can sort a list like this:

allNumbers.sort()

An important concept to note is highlighted here:

list1=[1]
list2=[list1,list1]
print(list2) #We should get [[1], [1]]
list1[0]='hello'
print(list2) #We should get [['hello], ['hello']]
list2[0]='a'
print(list2) #We should get ['a', ['hello']]
list1=['fish']
print(list2) #We should still get the same, which is ['a', ['hello']]


From the last print, we can see that the original list object pointed by list1 has not changed. Instead, The identifier list1 has actually been assigned to a different list.

When one Object have multiple names, we call it an Alias. We can get problems when dealing with Aliases for Mutable Objects. Take for example, the method for a list to another:

def copyList(listSource, listDestination):
    for x in listSource:
        listDestination.append(x)
        print(listDestination)


Copying list1 to list2 works, but if we copy list1 to list1, then we will have items adding to the source (when we add it to the destination), and we will never reach the end of the list.

You can slice, concatenate, index etc. with Lists and Tuples, but there is a built-in type, known as a Dictionary, which has the following propeties:

1) There is no order of things in a Dictionary
2) The indexes are called Keys and it can be of any Immutable type.

To create a dict:

dictionary = {'toilet':'paper', 'pencil':'eraser',3:'computer'}<\code>

It is in the format key:object. A dict is therefore a set of key:value pairs.

To select 'paper', we can use:

print(dictionary['toilet'])

If we want to view all the keys, we can use:

print(dictionary.keys())

We can delete items in the dictionary as such:

del(dictionary['pencil'])

We can use the keys returned by the dictionary to look up the dictionary as well:

for key in dictionary.keys():
    print(key,"=",dictionary[key])


In order to clone a Mutable type, we need to use the syntax:

item1=item2[:]

No comments :

Post a Comment

<