Skip to content

Instantly share code, notes, and snippets.

@konstantinfarrell
Last active July 7, 2016 19:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save konstantinfarrell/8cc6a8a41dee75853fb28ca529d462d3 to your computer and use it in GitHub Desktop.
Save konstantinfarrell/8cc6a8a41dee75853fb28ca529d462d3 to your computer and use it in GitHub Desktop.
What originally was meant to be a quick script to determine how much total XP is needed to reach a certain level turned into an exercise showing the value of knowing the summation formula rather than simply going for the brute-force method
import timeit
import math
def total_xp(level):
"""
Uses a loop to compute the total amount of xp
needed to reach a certain level.
"""
total = 0
for i in range(1, level+1):
total += i*1000
return total
def quick_total_xp(level):
"""
Uses the sum of natural numbers formula to compute the total amount
of XP needed to reach a certain level
"""
return int(1000 * ((level * (level + 1))/2))
if __name__ == '__main__':
amount = 100000
print("Testing execution times between two functions")
message = "Loop Total XP: "
result = timeit.timeit("total_xp(1000)",
setup="from golevel import total_xp",
number=amount)
print(message, result)
message = "Formula Total XP: "
result = timeit.timeit("quick_total_xp(1000)",
setup="from golevel import quick_total_xp",
number=amount)
print(message, result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment