String manipulation
Description
Part 1
Given a sequence of digits, determine which digits recur immediately in the sequence. Return the sum of all such digits.
Consider the sequence circular: the final digit in the sequence can recur as the first digit in the sequence.
Part 2
Given a circular sequence of an even number of digits, determine which digits recur at an interval of half the total length of the sequence. (For a sequence of ten digits, the recurrence interval would be five digits.)
My solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def solution_part1(digit):
sum = 0
try:
for idx, elt in enumerate(digit):
if elt == digit[idx + 1]:
sum += int(elt)
except IndexError:
if elt == digit[0]:
sum += int(elt)
return sum
def solution_part2(digit):
sum = 0
interval = int(len(digit) / 2)
for idx, elt in enumerate(digit):
try:
if elt == digit[idx + interval]:
sum += int(elt)
except IndexError:
if elt == digit[idx % interval]:
sum += int(elt)
return sum
Tests
1
2
3
4
5
6
7
8
9
10
11
12
13
def test_solution1():
assert solution_part1('1122') == 3
assert solution_part1('1111') == 4
assert solution_part1('1234') == 0
assert solution_part1('91212129') == 9
def test_solution2():
assert solution_part2('1212') == 6
assert solution_part2('1221') == 0
assert solution_part2('123424') == 4
assert solution_part2('123123') == 12
assert solution_part2('12131415') == 4