Files
30-seconds-of-code/snippets/sum_of_powers.md
Isabelle Viktoria Maciohsek 96a3c7890b Add new snippets
2020-10-04 14:21:41 +03:00

683 B

title, tags
title tags
sum_of_powers math,intermediate

Returns the sum of the powers of all the numbers from start to end (both inclusive).

  • Use range() in combination with a list comprehension to create a list of elements in the desired range raised to the given power, sum() to add the values together.
  • Omit the second argument, power, to use a default power of 2.
  • Omit the third argument, start, to use a default starting value of 1.
def sum_of_powers(end, power = 2, start = 1):
  return sum([(start + i) ** power for i in range(0, end + 1 - start)])
sum_of_powers(10) # 385
sum_of_powers(10, 3) # 3025
sum_of_powers(10, 3, 5) # 2925