Try an interactive version of this dialog: Sign up at solve.it.com, click Upload, and pass this URL.
Within each bank, you need to turn on exactly two batteries; the joltage that the bank produces is equal to the number formed by the digits on the batteries you've turned on. For example, if you have a bank like 12345 and you turn on batteries 2 and 4, the bank would produce 24 jolts. (You cannot rearrange batteries.)
def get_joltage(x):
l = sorted(list(set(x[:-1])))[-1]
idx = x.find(l)
nl = sorted(list(set(x[idx+1:])))[-1]
return int(l+nl)
[get_joltage(x) for x in samp.splitlines()]
def get_joltage(x):
idx = 0
digits = []
for i in range(11, -1, -1):
ss = x[idx:-i] if i > 0 else x[idx:]
d = sorted(list(set(ss)))[-1]
digits.append(d)
idx = ss.find(d)+idx+1
return "".join(digits)
get_joltage(x)
def solvea(samp): return sum([int(get_joltage(x)) for x in samp.splitlines()])
solvea(samp)
Looking at your code, I can see a few areas where you might improve things:
-
The
x[:-1]in part 1: Inget_joltage, you're usingx[:-1]when finding the largest digit, which excludes the last character. This works for the constraint that a two-digit number can't start on the last character, but it's a bit subtle. Is this intentional, or might it be clearer to use a different approach? -
Variable naming: Some names like
l,nl,d, andssare quite short. Would more descriptive names help you understand the code later? -
The slice logic in part 2: The
x[idx:-i] if i > 0 else x[idx:]works, but it's a bit tricky to follow. Have you considered whether there's a clearer way to express this?
Which of these would you like to explore first, or is there a specific part of your solution you're wondering about?
Sure! For the slicing logic, you could calculate how many characters you need to leave at the end and use that directly:
remaining = 12 - len(digits) # or (11 - i)
ss = x[idx:] if remaining == 0 else x[idx:-remaining]
Or even simpler, you could calculate the end index explicitly:
end_idx = len(x) - (11 - i)
ss = x[idx:end_idx]
This makes it clearer that you're selecting from idx up to a specific position, leaving exactly the right number of characters for the remaining digits.
Does this make sense? Would you like to try refactoring your loop with one of these approaches?