write the pyton code for which has 'n' as the list elements and add the integers to display the sum
Answers
Answered by
1
Answer:
The easiest way I know of :
- start = 1 # Start of your range
- end = 10 # End of your range
- num_list = range(start, end + 1) # List of all numbers in given range
- final_sum = sum(num_list)
- print "Final Sum =", final_sum
- #Combining all of it together in a single line
- print "Final Sum =", sum(range(start, end + 1))
- The last line is the most pythonic way of doing it. However it is not the most optimal way. It has a time complexity of O(n) where n is the size of range = end - start
You can sum up a given range in constant time by using a simple formula -
∑ni=1i=n∗(n+1)2
∑bi=ai=b∗(b+1)2−a∗(a−1)2
Using this simple equation, we can optimise our method to -final_sum = ((end * (end + 1)) - (start * (start - 1))) / 2 ft
This method takes constant time i.e, O(1).
plzz mark me as brainliest
Similar questions
Math,
4 months ago
Math,
4 months ago
Social Sciences,
9 months ago
Chemistry,
1 year ago
English,
1 year ago