Search code examples
pythonpython-3.xzipany

Python any() and zip() built-in functions explanation?


I was playing some clash of code at codingame.com and saw somebody's code, but didn't quite understand it.

The goal is to check if there's any double characters in the string in a row. So the string "Hello" should return True, since the double "l" in a row. But the string "Mama" should return False since the characters "a" are not behind each other.

Could someone explain this code?

w="Hello".lower()
print(str(any(c==k for c,k in zip(w[:-1],w[1:]))).lower())

This was my code

w = "Hello"
f = False
for i, c in enumerate(w):
    if i + 1 < len(w):
        if c.lower() == w[i+1].lower():
            print("true")
            f = True
            break
if not f: print("false")

Solution

  • zip creates pairs like the 4 columns in this table. (First and last table column does not form a pair, they don't count):

    h  e  l  l  o  -  # original string in lower case
    -  h  e  l  l  o  # same string shifted one position
    -----------------
    -  F  F  T  F  -  # equal? (False/True)
    

    any returns True if it finds anything true (in boolean sense). Otherwise it returns False. Here it returns True after seeing the third value.