0

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.

Priyanka
  • 9
  • 3

4 Answers4

1

When we use a elif it only get executed all previous if and elif conditions do not satisfied. Therefore, let's code like this

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

if(x in cube_nums for x in list2):
  pattern_exist=True
  print("Cubes are present")

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

If the if condition satisfied it simply terminate it will not run the block of elif.. you can convert into if condition.

You can see my another approach using set()

Code:-

def list_oper(list1,list2):

    square_nums = set(map(lambda x: x ** 2, list1))
    cube_nums = set(map(lambda x: x ** 3, list1))
    #print(square_nums)
    #print(cube_nums)
    if not square_nums.difference(set(list2)) and not cube_nums.difference(set(list2)):
        return "Squares and Cubes both are present"
    elif not square_nums.difference(set(list2)):
        return "Squares are only present"
    elif not cube_nums.difference(set(list2)):
        return "Cubes are only present"
    else:
        return "No such pattern present"
    

list1 = list(map(int,input("Enter the list1: ").split()))
list2 = list(map(int,input("Enter the list2: ").split()))
    
print(list_oper(list1,list2))

#Testcase 1 : when both cubes and squares are present

Enter the list1: 1 2 3
Enter the list2: 1 4 9 8 27
Squares and Cubes both are present

#Testcase 2: when square is present

Enter the list1: 1 2 3
Enter the list2: 1 4 9
Squares are only present

#Testcase 3: when cube are present

Enter the list1: 1 2 3
Enter the list2: 1 4 8 27
Cubes are only present

#Testcase 4: when no condition met!!

Enter the list1: 1 2 4
Enter the list2: 1 4 9
No such pattern present
Yash Mehta
  • 2,025
  • 3
  • 9
  • 20
0

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.

hyoeun
  • 7
  • 4
0

In

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

Change the elif into if, and also change the else aswell.