Today, Monk has come to visit a huge castle called the Castle of Programming. Monk desperately wants to visit the castle. However, to do so, the Master of the castle kept a challenge in front of him. Monk has been given a series of numbers from 1 to 10.The series includes each number from 1 to
10 exactly once. Monk just needs to find the sum of all the numbers in this series.
There are numerous ways to solve the problem. @bayoishola20’s code will get Monk into the Castle of Programming.
Another approach would be to write and call a function. Monk could use the function as a master key that provides entry into other castles that require sums from 1 to different numbers. See below …
def monk_key(n):
# provide the key to get into the castle,
# which is the sum of all numbers from 1 to n
return n * (n + 1) // 2
# Get into the Castle of Programming (1 to 10)
print(monk_key(10))
# Get into the Castle of Machine Learning (1 to 1000)
print(monk_key(1000))
The function uses the expression n * (n + 1) // 2, which gives the sum of all numbers from 1 to n.
I just did. it. You needed to comment out the initial exercise. See full code below:
'''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
print 'hello, world!'''
import math
a = (1,2,3,4,5,6,7,8,9,10)
print sum(a)