Session 7 - Computer Science

Download Report

Transcript Session 7 - Computer Science

Computer Science of
Graphics and Games
MONT 105S, Spring 2009
Lecture 7
Strings, Lists
1
Generating Random Numbers
Python provides libraries of functions that perform useful tasks.
One of these libraries allows us to generate random numbers.
To use the library, we must first import it:
import random
#This should be at the beginning of
#the program
To generate a random integer between 0 and x-1:
myNumber = random.randrange(x)
To generate a random number between low and high - 1:
myNumber = random.randrange(low, high)
Examples:
points = random.randrange(10)
target = random.randrange(2, 11)
#random number between 0 and 9
#random number between 2 and 10
2
Example using random
# Program: points.py
# Purpose: Generate random numbers of points
import random
# import library for random numbers
count = 0
while count < 5:
points = random.randrange(1, 11)
print "You got", points, "points!"
count = count + 1
#What is the output?
3
Collections
Python provides several classes called collection that allow us to
group data together.
Sequential Collections:
Strings--A sequential collection of characters
Lists--A sequential collection of python objects
Tuples--A specialized list whose items cannot be modified.
Non-sequential Collections:
Dictionaries-- Nonsequential collections of pairs of items.
Each pair has a key and a value.
The key can be used to look up the value.
4
Recall Strings
A string is a sequential collection of characters.
The value of a string is given within quotes:
"dog" "alpha centauri" "$37.62"
Each character in a string can be accessed by its position.
>>> monster = "fire-breathing dragon"
>>> monster[0]
'f'
>>> monster[2]
'r'
5
Things we can do with Strings
Operation
Operator
Concatenation +
Example
"my " + "goodness" -> "my goodness"
Repetition
*
"ha" * 3 -> "hahaha"
Length
len
len("fire") -> 4
Substring
[:]
monster[1:4] -> "ire"
# monster = "fire-breathing dragon"
Membership
in
"ir" in monster -> True
"w" in monster -> False
6
Other Methods with Strings
Object: A member of a class
Method: An action the object can take
To have an object carry out a method, we use "dot notation"
myObject.methodName( )
myString.count(item)
Example:
>>> monster = "troll"
>>> monster.count("l")
2
>>> monster.count("rol")
1
#number of occurrences of item in
#myString
7
More String Methods
myString.upper( )
#returns a string with all upper case
myString.lower( )
#returns a string with all lower case
myString.find(substring) #returns index of 1st occurrence of
#substring, or -1 if not found
Examples:
>>> monster = "troll"
>>> monster.upper( )
"TROLL"
>>>monster
"troll"
>>> monster.find("ll")
3
8
Lists
A list is a sequential collection of python objects.
A list is written as a set of objects separated by commas,within
square brackets:
[1, 5, 7]
["dog", "cat", "bird"] [3.7, "spam", 46]
[]
We can access an element of a list by its position:
Example:
>>>inventory = ["Axe", "gold coins", "torch"]
>>>inventory[2]
"torch"
9
Things we can do with Lists
Operation
Concatenation
OperatorExample
+
[4.5, "Mary"] + [6, 2] -> [4.5, "Mary", 6, 2]
Repetition
*
["house"] * 3 -> ["house", "house", "house"]
Length
len
inventory = ["Axe", "gold coins", "torch"]
len(inventory) -> 3
Sublist
[:]
prices = [2.98, 5.67, 1.36, 14.92]
prices[1:3] -> [5.67, 1.36]
Membership
in
5.67 in prices -> True
10
Changing an item in a list
A list is stored in memory as a set of sequential id's referencing
objects.
alist = [3, "dog", "purple", 5.6]
id
alist
3
id
"dog"
id
"purple"
id
5.6
We can use indexing to assign a new value to any item in the list:
>>> alist[2] = 6.7
>>> alist
[3, "dog", 6.7, 5.6]
Note: You cannot change a character in a string this way.
11
More fun with lists
alist.append(item)
#adds item to the end of the list
alist.insert(i, item)
#inserts item at the ith position in list
alist.pop(i)
#removes and returns the ith item
alist.sort( )
#Sorts the list
alist.reverse( )
#Reverses the list
alist.index(item)
#Returns the index of the 1st
#occurrence of item
alist.count(item)
#Returns the number of occurrences
#of item
alist.remove(item)
#Removes 1st occurrence of item
12
Some List examples
>>> inventory = ["Axe", "Gold", "Torch"]
>>> inventory.append("Matches")
>>> inventory
["Axe", "Gold", "Torch", "Matches"]
>>> inventory.index("Gold")
1
>>> inventory.sort( )
>>> inventory
["Axe", "Gold", "Matches", "Torch"]
13