Exercise 109
Write a program in Python that asks the user to enter an integer n and return a dictionary whose keys are the integers 1, 2, 3, ... n and whose values are the sums 1, 1+ 2, 1 + 2 + 3,... 1 + 2 + 3 + ... + n.
Solution
# create a function which calculates the sum 1 + 2 + 3 + ... + n
def sumInt(n):
s = 0
for i in range(1, n + 1):
s = s + i
return s
# create an empty dictionary which will contains the key 1 , 2 , 3 , ... , n and their values
d= dict({})
n = int(input("Enter value of integer n"))
for i in range(1, n):
d[i] = sumInt(i)
# display obtained dictionary d
print("The obtained dictionary is d = " , d)
# The output is :
#The obtained dictionary is d = {1: 1, 2: 3, 3: 6, 4: 10, 5: 15, 6: 21}
Younes Derfoufi
my-courses.net
my-courses.net