I've been going through some code challenges. And one struck me in particular. CodeAbbey has a Weighted Sum of Digits challenge. And this was my answer.
# open and read a file, hardcoded numbers, etc. Here is a sample
raw_data = (6, 19, 64, 6527226, 12345146)
for number in raw_data:
wsd = 0 # Stores sum
number_list = list(str(number)) # Converts the number into a list.
for i, k in enumerate(number_list): # Enumerates each number
wsd += (int(i+1) * int(k)) # Multiplies and adds product to wsd
print(wsd)
output >>> 6, 19, 14, 114, 137
Anyone with more experience able to see a better way of getting the sum?
This can be done entirely using math operations. Look how the sum is generated, e.g. for 12345146:
So firs you add last digit, then last and previous, then last, previous and previous etc. until you add all digits. And this can be simply implemented by following algorithm:
On my computer this is about two times faster than algorithms using enumeration and string conversion (I multiplied raw_data 100000 times, thus getting 500000 elements for comparison).
If using map: