-
Notifications
You must be signed in to change notification settings - Fork 17
Data Structures
- Make sure you've done the Hello World Exercise.
Tuples allow us to pack multiple values together into one variable. See the python documentation for tuples for more information.
Open tuples.py
for examples.
def gen_tuple(s):
"""
Returns a tuple of (input, length of input)
"""
return (s, len(s))
v = gen_tuple("foood")
print v
(s, n) = v
print s
print n
You should see the following output: (python tuples.py
)
('foood', 5)
foood
5
Make sure you are in the examples
directory.
Strings are groups of characters strung together. You can think of a string as a sequence of chars. Open up strings.py
:
s = "foood cake cheese"
# print out the length of the string
# len() is a builtin.
print len(s)
# split string by spaces, return list of words
words = s.split()
print words
print len(words)
# keyfunc and keyfunc2 are exactly the same
# lambdas are just syntactic sugar to allow you
# to declare one-liner functions.
keyfunc = lambda word : len(word)
def keyfunc2(word):
return len(word)
# sort words by length of the word
# The "key" argument of sorted tells us how to sort the list.
#
# Example:
# For the list: ["a", "aaa", "aa"],
# keyfunc will be appled on all the elements: [1, 3, 2]
# and then sorted: [1, 2, 3]
# and then replaced with their original entries: ["a", "aa", "aaa"]
words_sorted = sorted(words, key=keyfunc)
print words_sorted
# What else can you call on s?
# (i.e. for what `foo` can we do `s.foo()`?)
# To see what methods you can call on a variable, open up the top
# level, then enter:
#
# s = "food"
# dir(s)
#
# This will dump a list of all the things you can call the variable with.
# E.g. "join" will be in that list if you called dir() on a string.
# This means that you call `s.join()`.
#
# To see what it does, you can call:
#
# help(s.join)
#
# At the top level to open the documentation for the join function.
If you run it python strings.py
, you should see this output:
17
['foood', 'cake', 'cheese']
3
['cake', 'foood', 'cheese']
If you've programmed in C/C++/Java, lists are similar to arrays, except they can dynamically change in size. See the python list documentation for more information on what you can do with lists.
Open up lists.py
for examples.
# Declare a list of strings
l = ["food", "cat", "bar"]
print l
print len(l) # print the length of the list
print l[1] # print "cat"
# append to the end of the list
l.append("dog")
l[2] = "homer" # replace "bar" with "homer"
print l
print len(l)
# Traverse the list
for s in l:
print s
# Slicing a list
m = list(range(20))
print "m", m
print "m[-1]", m[-1] # last element
print "m[10:]", m[10:] # print the rest of list starting starting at index 10
print "m[:10]", m[:10] # print from the beginning of the list up to but not includinx index 10
print "m[5:15]", m[5:15] # print starting from 5 and up to but not including 15
print "m[5:-2:3]", m[5:-2:3] # print every 3rd element, starting at index 5 and going up-to-but-not-including the second-to-last element
This should be your output: (python lists.py
):
['food', 'cat', 'bar']
3
cat
['food', 'cat', 'homer', 'dog']
4
food
cat
homer
dog
m [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
m[-1] 19
m[10:] [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
m[:10] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
m[5:15] [5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
m[5:-2:3] [5, 8, 11, 14, 17]
Sets are like lists, except they do not contain duplicates, and they don't contain a notion of order (e.g. if s
is a set, s[0]
makes no sense). See the python documentation on sets for more information.
Open up sets.py
for examples.
s = set([5, 6, 7, 5, 6, 7, 1, 5, 6, 7])
print s
print "length", len(s)
for item in s:
print item
print "is 4 in set", 4 in s
s.add(4)
print "is 4 in set", 4 in s
print "sum", sum(s)
You should have this output:
set([1, 5, 6, 7])
length 4
1
5
6
7
is 4 in set False
is 4 in set True
sum 23
Think of a dictionary that can map keys to values. Each key can have exactly one value. Key can be anything (immutable), and value can be anything. See the python documentation for dictionaries for more information.
Open dicts.py
for examples.
d = {"cat" : 2, "tiger": 0}
d["food"] = 5
d["cheese"] = 7
d["apple"] = "orange"
d[8] = "penguin"
print d
print len(d) # number of keys
for key in d:
print key, d[key]
for key, value in d.items():
print key, value
print "check if food is in d", "food" in d
del d["food"]
print "check if food is in d", "food" in d
If you run it, you should get this output: (python dicts.py
)
{'cheese': 7, 'apple': 'orange', 'food': 5, 'cat': 2, 'tiger': 0, 8: 'penguin'}
6
cheese 7
apple orange
food 5
cat 2
tiger 0
8 penguin
cheese 7
apple orange
food 5
cat 2
tiger 0
8 penguin
check if food is in d True
check if food is in d False