Skip to content

Instantly share code, notes, and snippets.

@petrushev
Created March 6, 2016 18:38
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 petrushev/cb1cec0a8b3e0f991e50 to your computer and use it in GitHub Desktop.
Save petrushev/cb1cec0a8b3e0f991e50 to your computer and use it in GitHub Desktop.
def same(i):
a = next(i)
return _same(a, i)
def _same(a, i):
try:
b = next(i)
except StopIteration:
return True
if a != b:
return False
return _same(a, i)
assert same(iter([1,2,3])) is False
assert same(iter([1]))
assert same(iter([1,1,1]))
@sametmax
Copy link

sametmax commented Mar 6, 2016

In Python, it's important to remember you also have unsized interables so your solution is nice but recursion will fail if you got more than 1000 items on a standard CPython config. Plus that equality is not the same as idententy, and both should be something you want to check against. So:

def same(it, cmp=operator.eq):
    g = iter(it)
    s = next(g, None)
    return all(cmp(s, x) for x in g)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment