Skip to content
Advertisement

I’m trying to write a condition on the python list

I tried writing a Python program to accept a list of integers starting with 0 and ending with 20 from the user. Each integer of the said list either differs from the previous one by two or is four times the previous one. Return true or false

Can someone correct the condition which I have written

lst = []

n = int(input("Enter the no of elements in the list :"))

for i in range (0,n):
    elem = int(input("Enter the elements between 0 and 20 : "))
    lst.append(elem)

if elem >= 0 and elem <=20:
    print(lst)
    
for i in elem:
    if (i+1) >= 2(i) or 4(i+1) == i:
        print(True)
else:
    print(False)

Advertisement

Answer

You can use zip to pair up items with their successors. This will let you compare them and check your condition using any() or all() depending on your requirement:

if any(abs(a-b)==2 or a*4==b for a,b in zip(lst,lst[1:]):
   print(True) # at least one number pair meets the criteria
else:
   print(False)

or

if all(abs(a-b)==2 or a*4==b for a,b in zip(lst,lst[1:]):
   print(True) # all numbers meets the criteria
else:
   print(False)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement