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")

3

There are 3 answers

1
DarrylG On BEST ANSWER

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(...)
4
idar On

How about this:

In [123]: x
Out[123]: [5, 10, 6, 12, 10, 20, 11, 22]

In [124]: all([x[i]/x[i-1]==2 for i in range(1, len(x) - 1, 2)])
Out[124]: True
2
Jan Stránský On

This?

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