python中字典容器的用武之地

版权声明:本文为博主原创文章,转载请标明出处,蟹蟹 https://blog.csdn.net/fly_wt/article/details/85014827

储存稀疏矩阵

在这里插入图片描述
matrix = {(0, 3):1, (2, 1):2, (4, 3):3}

斐波那契数列

在这里插入图片描述
传统做法:

def fibonacci(n):
    if n == 0 or n == 1:
        return 1
    else:
        return fibonacci(n-1)+fibonacci(n-2)

使用字典加快运算

# 解决办法:将已经运行好的结果放在字典中
previous = {0:1, 1:1}
def Fibonacci(n):
    if n in previous:
        return previous[n]
    else:
        newValue = Fibonacci(n-1)+Fibonacci(n-2)
        previous[n] = newValue
        return newValue

计算字符串个数

letterCounts = {}
for letter in 'Mississippi':
    letterCounts[letter] = letterCounts.get(letter, 0) + 1

print(letterCounts)
print(letterCounts.items())

输出为:

{'M': 1, 'i': 4, 's': 4, 'p': 2}
dict_items([('M', 1), ('i', 4), ('s', 4), ('p', 2)])

猜你喜欢

转载自blog.csdn.net/fly_wt/article/details/85014827