friend_list = ['Ahmed', 'Ali', 'Samer'] # list
friend_list[1]
friend_tuple = ('Ahmed', 'Ali', 'Samer') # tuple
friend_tuple[1]
for name in friend_tuple: # loop using iteration variable
print(name)
for i in range(len(friend_tuple)): # loop using index
print(friend_tuple[i])
friend_tuple[2] = 'Mohammed' # error tuples are immputable
friend_list[2] = 'Mohammed' # mutable
print(friend_list)
(x, y) = (4, 'fred')
x
y
def my_divmod(x, y):
reminder = x % y
result = x // y
return reminder, result
my_divmod(23, 5)
(a, b) = my_divmod(23, 5)
a
b
bag = {'books': 1, 'candy': 3, 'pen': 1}
bag.items()
for k, v in bag.items():
print('{}\t{}'.format(k, v))
(0, 1, 2) < (5, 1, 2)
(0, 1, 3) < (5, 1, 2)
(0, 1, 2000000) < (0, 3, 4)
(1, 1, 2000000) < (0, 3, 4)
( 'Jones', 'Sally' ) < ('Jones', 'Sam')
d = {'a':10, 'c':22, 'b':1}
d.items()
sorted(d.items())
sorted(d.items(), reverse=True)
# can't compare different types
3 > 'a'
tmp = list() # tmp = []
for k, v in d.items():
tmp.append( (v, k) )
print(tmp)
sorted(tmp)
sorted(tmp, reverse=True)
sorted( [ (v,k) for k,v in d.items() ] )
sorted( [ (v, k) for k, v in d.items() ], reverse=True )
# top n elements
sorted([(v, k) for k, v in d.items() ], reverse=True)[:2]
Write a program take an input from the user and to:
text = 'the clown ran after the car and the car ran into the tent and the tent fell down on the clown and the car'
words = text.split()
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts)
# 1. print the word counts sorted alpabetically
print(sorted(counts.items()))
# 2. print the top 5 most frequent words
print(sorted([ (v,k) for k,v in counts.items()], reverse=True)[:5])