Computer Science, asked by latikatrslatikatrs, 9 months ago

write the pyton code for which has 'n' as the list elements and add the integers to display the sum​

Answers

Answered by ankita2006mishra
1

Answer:

The easiest way I know of :

  1. start = 1 # Start of your range
  2. end = 10 # End of your range
  3. num_list = range(start, end + 1) # List of all numbers in given range
  4. final_sum = sum(num_list)
  5. print "Final Sum =", final_sum
  6. #Combining all of it together in a single line
  7. print "Final Sum =", sum(range(start, end + 1))
  8. 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