Last active
July 7, 2016 19:01
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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