Skip to content

Instantly share code, notes, and snippets.

@hughdbrown
Last active September 1, 2021 02:47
Show Gist options
  • Save hughdbrown/4173afb63d837152de0aae78af9ccb9f to your computer and use it in GitHub Desktop.
Save hughdbrown/4173afb63d837152de0aae78af9ccb9f to your computer and use it in GitHub Desktop.
Come sort of code challenge
from itertools import groupby
def cumulative(arr):
return [arr[i] - arr[i - 1] for i in range(1, len(arr))]
def stable_particle(arr):
"""
>>> stable_particle([-1, 1, 3, 3, 3, 2, 3, 2, 1, 0])
5
>>> stable_particle([2] * 10000)
49985001
>>> stable_particle([1, 3, 5, 7, 9])
6
>>> stable_particle([7, 7, 7, 7])
3
"""
x = cumulative(arr)
xx = cumulative(x)
count_stable = 0
for k, v in groupby(xx):
if k == 0:
n = len(list(v))
count_stable += (n * (n + 1)) // 2
return count_stable
def stable_particle2(arr):
"""
>>> stable_particle2([-1, 1, 3, 3, 3, 2, 3, 2, 1, 0])
5
>>> stable_particle2([2] * 10000)
49985001
>>> stable_particle2([1, 3, 5, 7, 9])
6
>>> stable_particle2([7, 7, 7, 7])
3
"""
# Rewrite code with generator
x = cumulative(arr)
xx = cumulative(x)
group_by_gen = (len(list(v)) for k, v in groupby(xx) if k == 0)
return sum((n * (n + 1)) // 2 for n in group_by_gen)
def main(particles):
print(stable_particle(particles))
if __name__ == '__main__':
from doctest import testmod
testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment