Home > Blockchain >  I'm trying to write a condition on the python list
I'm trying to write a condition on the python list

Time:12-08

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)

CodePudding user response:

arr_len = int(input("Input a length for list: "))

nums = [0] * arr_len
res = [False] * arr_len

for i in range (len(nums)): 
    num = -1
    while not(num >= 0 and num <= 20):
        num = input("Enter the elements between 0 and 20 : ") 
        num = nums[i] = int(num)
        if (num >= 0 and num <= 20):
            print('appended')
        else:
            print('that number is not between 0 and 20')
for i in range(1,len(res)):
    num = nums[i]
    prev_num = nums[i-1]
    if (abs(num-prev_num)) == 2 or prev_num == 4*num: 
        res[i] = True 
for i in range(len(nums)):
    print('i is: ', i , 'nums[i], ', nums[i],
              ', is allowed in array: ', res[i])
res = dict(zip(nums,res))
print(res)

CodePudding user response:

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)
  • Related