Dict Challenges

Harold Nelson

9/30/2020

Ex1

Create a fruitful function squares(n). It’s only parameter is a positive integer. It returns a dictionary. The keys in this dictionary are the integers between 1 and n inclusive. The values are the squares of the keys. Test your function with the value 20.

Answer

def squares(n):
    result = {}
    for i in range(n):
        j = i + 1
        result[j] = j**2
    return(result)

print(squares(20))    
    
## {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225, 16: 256, 17: 289, 18: 324, 19: 361, 20: 400}

Ex2

Create a function divisors(n). Its single parameter is a positive integer n. It returns a dictionary. The keys in the dictionary are the integers between 3 and n inclusive. The values are lists of all of the divisors of the keys.