Skip to content

Instantly share code, notes, and snippets.

@sgammon
Created September 13, 2011 19:26
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 sgammon/1214810 to your computer and use it in GitHub Desktop.
Save sgammon/1214810 to your computer and use it in GitHub Desktop.
## Input - can be any length
input = 1234567890
## Turn into a list of the input's digits (input should now be [1,2,3, n...])
input = [int(i) for i in list(str(input))]
## 1: Generate index pairs that need to be added (i.e. [(0, 1), (1, 2), n...]). Chop off last input digit.
## 2: Once we have a list of index int tuples, add the two spots in the input number corresponding to those indexes (i, i+1).
## 3: Once we have a list of the added digit pairs, add those from left to right.
print reduce(lambda x, y: x+y, [input[i1]+input[i2] for i1, i2 in map(lambda x: (x, x+1), [i for i in range(0, len(input[0:-1]))])])
###### Alternate Way (avoids the overhead of generating a list of tupled index pairs, and the overhead of a reduce-based sum routine):
## 1: Generate index pairs that need to be added (i.e. [(0, 1), (1, 2), n...]). Chop off last input digit. Use the pairs directly instead of keeping them.
## 2: Once we have a list of the added digit pairs, add those from left to right.
print sum(map(lambda x: input[x] + input[x+1], range(0, len(input[0:-1]))))
###### Long-Form Way (functionally the same as above, just long-form, and therefore easier to read):
total = 0
for index in range(0, len(input[0:-1])): ## chop off the last digit, because lists are zero-indexed
first_number = input[index]
second_number = input[index+1]
current_sum = int(first_number) + int(second_number)
total = total+current_sum
print total
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment