ICT582 Topic 06
ICT582 Topic 06
6.0001 LECTURE 5 2
Today
§ Collections
§ Sets
§ Dictionaries
§ Use of dictionaries to solve problems
§ Sequence
§ Common characteristics of sequences
3
6.0001 LECTURE 6
Collection
$ py setOrder.py
{'banana', 'cherry', 'apple'}
$ py setOrder.py
{'cherry', 'banana', 'apple'}
$ py setOrder.py
{'banana', 'apple', 'cherry'}
$
1
6.0001 LECTURE 6 0
Add and Remove Items from Set
# alternatively
for k,v in grades.items():
2
6.0001 LECTURE 6 0
print("%s : %0.1f " %(k, v/numStudents * 100))
Dictionary Alias and Clone
2
6.0001 LECTURE 6 2
Common Characteristics of
Sequences
§ Sequence types share many common operations and
characteristics (with exceptions)
Ø Indexing
Ø Slicing
Ø Repetition, eg, "abc"*3 => "abcabcabc"
Ø Length: such as len([1,2,3,4,5]) => 5
Ø Membership: in operation and not in operator
Ø Iteration: as in the for loop
§ Note, some of sequences are mutable, such as lists,
others are immutable, such as strings, tuples and
ranges
2
6.0001 LECTURE 6 3
Sequence: indexing
2
6.0001 LECTURE 6 4
Sequence: indexing
Ø Range
r = range(10) # 0,1,2,3,4,5,6,7,8,9
r[2] # 2
r.index(4) # 4
r2 = range(1,10,2) # 1,3,5,7,9
r2[2] # 5
r2.index(5) # 2
2
6.0001 LECTURE 6 5
Sequence: slicing
2
6.0001 LECTURE 6 8
Sequence: length
2
6.0001 LECTURE 6 9
Sequence: membership
3
6.0001 LECTURE 6 1
Example: Word Frequency
def lyrics_to_frequencies(lyrics):
myDict = {}
for word in lyrics:
if word in myDict:
myDict[word] += 1
else:
myDict[word] = 1
return myDict
3
6.0001 LECTURE 6 2
Example: Word Frequency
def most_common_words(freqs):
values = freqs.values()
best = max(values)
words = []
for k in freqs:
if freqs[k] == best:
words.append(k)
return (words, best)
3
6.0001 LECTURE 6 3
Example: Word Frequency
3
6.0001 LECTURE 6 4
Example: Word Frequency
beatles = '''
Love, love me do Love, love me do
You know I love you You know I love you
I'll always be true I'll always be true
So please, love me do So please, love me do
Whoa, love me do Whoa, love me do
wordList = beatles.split()
wordFreq = lyrics_to_frequencies(wordList)
print(words_often(wordFreq, 5))
3
6.0001 LECTURE 6 5
Example: Word Frequency
hong$ py word_freq.py
[(['love'], 20), (['me', 'do'], 14), (['you', 'Whoa,'], 5)]
hong$
3
6.0001 LECTURE 6 6
References
3
6.0001 LECTURE 6 7