pythonlistzipprogram-slicing

Python: Given a list of integers x, write a single expression that returns True if all odd index values are twice their preceding values


Given a list of integers, say, x = [5, 10, 6, 12, 10, 20, 11, 22] write a single expression that returns True if all odd index values are twice their preceding values. We need to use skip slicing, zip, all, and list comprehension

I'm new to Python programming (extensive experience in Java though). This is just a basic question on python syntax, but I'm not able to do it. I tried the following:

list(zip(x[::2], x[1::2]))

this expression returns me a list like below [(5, 10), (6, 12), (10, 20), (11, 22)]

After this I'm lost how to check the condition on the pairs. Looking for something like

print(all([False for pair in list(zip(x[::2],x[1::2]))]) "write something in proper format that checks pair values for double condition")


Solution

  • Using Zip, Slicing & List Comprehension

    x = [5, 10, 6, 12, 10, 20, 11, 22]
    all([b == 2*a for a, b in zip(x[::2], x[1::2])])  # True
    

    Explanation

    Generator for number pairs

    zip(x[::2], x[1::2]) # produces [(5, 10), (6, 12), (10, 20), (11, 22)]
    

    Loop through the tuples (setting to a, b as we go)

    for a, b in zip(x[::2], x[1::2]) 
    

    Check condition

    b == 2*a   # second number is twice 1st
    

    Check if True everywhere

    all(...)