Skip to content

Instantly share code, notes, and snippets.

@chipbell4
Created August 22, 2014 02:30
Show Gist options
  • Save chipbell4/f6ffe3b03e791845b4af to your computer and use it in GitHub Desktop.
Save chipbell4/f6ffe3b03e791845b4af to your computer and use it in GitHub Desktop.
My Solution For Digit Sum (Still buggy) for Practice 8/21/2014
def buildDigits(digit_list):
# sort the digit list
# TODO: Here's where the bug is. Because the 0's get pushed to the front of the list, I put 0's at the beginning of numbers.
# What would need to happen is potentially a sort, and then pushing 0's back in the list a couple spaces?
digit_list.sort(reverse = True)
summands = ['', '']
# Here's the basic idea for the algorithm: Sort the digits, then divide them equally (in sorted order) among two strings
# that you build. Ideally you want the lowest digits to the left, since they minimize the value of the sum (hence the sort).
# For cases with an odd number of digits, just put the first digit in the first bin. That seems to work (but I'm not
# exactly sure why... Any ideas?
if len(digit_list) % 2 is 1:
summands[0] = digit_list.pop()
summand_to_add_to = 0
while len(digit_list) > 0:
# concat the new digit onto the end of the current bin
summands[ summand_to_add_to ] = summands[ summand_to_add_to ] + digit_list.pop()
# Swap between bin 0 and 1
summand_to_add_to = (summand_to_add_to + 1) % 2
# convert them to integers and return the sum
return sum(map(int, summands))
# This is case I'm failing on. I'm not handling those zeros correctly.
print(buildDigits([ '0', '1', '2', '3', '4', '0', '1', '2', '3' ]))
# My algorithm for parsing input woudl be simple (this part is untested): Read the line, convert all to integers:
while True:
digit_count, digits = map(int, input().strip().split())
if digit_count is 0:
break
print(buildDigits(digits))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment