Dictionary

In [1]:
my_dict = {}
grades = {'Ana':'B', 'John':'A+', 'Denise':'A', 'Katy':'A'}
In [2]:
grades['John']
Out[2]:
'A+'
In [3]:
grades['sylvan']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-3-36a6785f0a13> in <module>()
----> 1 grades['sylvan']

KeyError: 'sylvan'
In [4]:
grades['Sylvan'] = 'A' # add an entry
grades['Sylvan']
Out[4]:
'A'
In [5]:
'John' in grades
Out[5]:
True
In [6]:
'Daniel' in grades
Out[6]:
False
In [7]:
del(grades['Ana'])
In [8]:
grades
Out[8]:
{'Denise': 'A', 'John': 'A+', 'Katy': 'A', 'Sylvan': 'A'}
In [10]:
grades.keys()
Out[10]:
dict_keys(['John', 'Denise', 'Katy', 'Sylvan'])
In [11]:
grades.values()
Out[11]:
dict_values(['A+', 'A', 'A', 'A'])
In [12]:
d = {4:{1:0}, (1,3):"twelve", 'const':[3.14,2.7,8.44]}
d
Out[12]:
{(1, 3): 'twelve', 4: {1: 0}, 'const': [3.14, 2.7, 8.44]}

Ví dụ - Analyze song lyrics

In [14]:
def lyrics_to_frequencies(lyrics):
    myDict = {}
    for word in lyrics:
        if word in myDict:
            myDict[word] += 1
        else:
            myDict[word] = 1
    return myDict
In [16]:
she_loves_you = ['she', 'loves', 'you', 'yeah', 'yeah', 'yeah',
'she', 'loves', 'you', 'yeah', 'yeah', 'yeah',
'she', 'loves', 'you', 'yeah', 'yeah', 'yeah',

'you', 'think', "you've", 'lost', 'your', 'love',
'well', 'i', 'saw', 'her', 'yesterday-yi-yay',
"it's", 'you', "she's", 'thinking', 'of',
'and', 'she', 'told', 'me', 'what', 'to', 'say-yi-yay',

'she', 'says', 'she', 'loves', 'you',
'and', 'you', 'know', 'that', "can't", 'be', 'bad',
'yes', 'she', 'loves', 'you',
'and', 'you', 'know', 'you', 'should', 'be', 'glad',

'she', 'said', 'you', 'hurt', 'her', 'so',
'she', 'almost', 'lost', 'her', 'mind',
'and', 'now', 'she', 'says', 'she', 'knows',
"you're", 'not', 'the', 'hurting', 'kind',

'she', 'says', 'she', 'loves', 'you',
'and', 'you', 'know', 'that', "can't", 'be', 'bad',
'yes', 'she', 'loves', 'you',
'and', 'you', 'know', 'you', 'should', 'be', 'glad',

'oo', 'she', 'loves', 'you', 'yeah', 'yeah', 'yeah',
'she', 'loves', 'you', 'yeah', 'yeah', 'yeah',
'with', 'a', 'love', 'like', 'that',
'you', 'know', 'you', 'should', 'be', 'glad',

'you', 'know', "it's", 'up', 'to', 'you',
'i', 'think', "it's", 'only', 'fair',
'pride', 'can', 'hurt', 'you', 'too',
'pologize', 'to', 'her',

'Because', 'she', 'loves', 'you',
'and', 'you', 'know', 'that', "can't", 'be', 'bad',
'Yes', 'she', 'loves', 'you',
'and', 'you', 'know', 'you', 'should', 'be', 'glad',

'oo', 'she', 'loves', 'you', 'yeah', 'yeah', 'yeah',
'she', 'loves', 'you', 'yeah', 'yeah', 'yeah',
'with', 'a', 'love', 'like', 'that',
'you', 'know', 'you', 'should', 'be', 'glad',
'with', 'a', 'love', 'like', 'that',
'you', 'know', 'you', 'should', 'be', 'glad',
'with', 'a', 'love', 'like', 'that',
'you', 'know', 'you', 'should', 'be', 'glad',
'yeah', 'yeah', 'yeah',
'yeah', 'yeah', 'yeah', 'yeah'
]

beatles = lyrics_to_frequencies(she_loves_you)
beatles
Out[16]:
{'Because': 1,
 'Yes': 1,
 'a': 4,
 'almost': 1,
 'and': 8,
 'bad': 3,
 'be': 10,
 'can': 1,
 "can't": 3,
 'fair': 1,
 'glad': 7,
 'her': 4,
 'hurt': 2,
 'hurting': 1,
 'i': 2,
 "it's": 3,
 'kind': 1,
 'know': 11,
 'knows': 1,
 'like': 4,
 'lost': 2,
 'love': 5,
 'loves': 13,
 'me': 1,
 'mind': 1,
 'not': 1,
 'now': 1,
 'of': 1,
 'only': 1,
 'oo': 2,
 'pologize': 1,
 'pride': 1,
 'said': 1,
 'saw': 1,
 'say-yi-yay': 1,
 'says': 3,
 'she': 20,
 "she's": 1,
 'should': 7,
 'so': 1,
 'that': 7,
 'the': 1,
 'think': 2,
 'thinking': 1,
 'to': 3,
 'told': 1,
 'too': 1,
 'up': 1,
 'well': 1,
 'what': 1,
 'with': 4,
 'yeah': 28,
 'yes': 2,
 'yesterday-yi-yay': 1,
 'you': 36,
 "you're": 1,
 "you've": 1,
 'your': 1}
In [18]:
def most_common_words(freqs):
    values = freqs.values()
    best = max(freqs.values())
    words = []
    for k in freqs:
        if freqs[k] == best:
            words.append(k)
    return (words, best)

(w, b) = most_common_words(beatles)
w
Out[18]:
['you']
In [20]:
def words_often(freqs, minTimes):
    result = []
    done = False
    while not done:
        temp = most_common_words(freqs)
        if temp[1] >= minTimes:
            result.append(temp)
            for w in temp[0]:
                del(freqs[w])  #remove word from dictionary
        else:
            done = True
    return result
In [21]:
print(words_often(beatles, 5))
[(['you'], 36), (['yeah'], 28), (['she'], 20), (['loves'], 13), (['know'], 11), (['be'], 10), (['and'], 8), (['that', 'should', 'glad'], 7), (['love'], 5)]

Ví dụ - Fibonacci

In [25]:
def fib_efficient(n, d):
    if n in d:
        return d[n]
    else:
        ans = fib_efficient(n-1, d) + fib_efficient(n-2, d)
        d[n] = ans
        return ans
    
d = {1:1, 2:2}
print(fib_efficient(33, d))
5702887
In [24]:
def fib(x):
    if x == 0 or x == 1:
        return 1
    else:
        return fib(x - 1) + fib(x - 2)
    
print(fib(33))
5702887

Biến toàn cục - Global variables

In [27]:
def fib(n):
    global numFibCalls
    numFibCalls += 1
    if n == 1 or n == 2:
        return n
    else:
        return fib(n-1) + fib(n-2)
    
def fibef(n, d):
    global numFibCalls
    numFibCalls += 1
    if n in d:
        return d[n]
    else:
        ans = fibef(n-1, d) + fibef(n-2, d)
        d[n] = ans
        return ans
    
numFibCalls = 0
fibArg = 34

print(fib(fibArg))
print('function calls', numFibCalls)

numFibCalls = 0

d = {1:1, 2:2}
print(fibef(fibArg, d))
print('function calls', numFibCalls)
9227465
function calls 11405773
9227465
function calls 65