Home > OS >  Python function that takes two lists as input ,perform certain operations and return string
Python function that takes two lists as input ,perform certain operations and return string

Time:12-29

Function that takes two lists as input and checks for squares and cubes of elements in list1 are present in list2. It should return string if squares or cubes of all elements in list1 are present in list2.

def list_oper(list1,list2):

    square_nums = list(map(lambda x: x ** 2, list1))
    cube_nums = list(map(lambda x: x ** 3, list1))
 

    if (x in square_nums for x in list2):
      print("Squares are only present")

    elif(x in cube_nums for x in list2):
      print("Cubes are only present")

    else:
        print("No such pattern is present")

if __name__=='__main__':
    list1 = ast.literal_eval(input())
    list2 = ast.literal_eval(input())
    
    print(list_oper(list1,list2))
   

When I passed list1=[1,2,3,4] and list2=[1,8,27,64,100], it printed Squares are only present instead of cubes are present.

CodePudding user response:

Instead of elif(x in cube_nums for x in list2): use

pattern_exist=false
if (x in square_nums for x in list2):
  print("Squares are only present")

if(x in cube_nums for x in list2):
  print("Cubes are only present")

if (!pattern_exist):
    print("No such pattern is present")

CodePudding user response:

Exactly, 1 ** 2 == 1 if you want to print when only all matched list,

if all(x in square_nums for x in list2):
  print("Squares are only present")

elif statement too.

  • Related