一个Python函数,它将两个列表作为输入,执行某些操作并返回字符串

72qzrwbm  于 2022-12-30  发布在  Python
关注(0)|答案(4)|浏览(134)

此函数将两个列表作为输入,并检查list1中元素的正方形和立方体是否出现在list2中。如果list1中所有元素的正方形或立方体都出现在list2中,则此函数应返回string。

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

当我传递list1 =[1,2,3,4]和list2 =[1,8,27,64,100]时,它只显示正方形,而不是立方体。

8ehkhllq

8ehkhllq1#

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

将elif改为if,并将else也改为if。

nx7onnlm

nx7onnlm2#

当我们使用一个elif时,它只会执行之前所有不满足的ifelif条件。

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

mhd8tkvw3#

如果满足if条件,则只需终止,它不会运行elif块。您可以转换为if条件。
您可以看到我使用set()的另一种方法

    • 代码:-**
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))

测试用例1:当立方体和正方形都存在时

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

测试用例2:当存在正方形时

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

测试用例3:当存在立方体时

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

测试用例4:当不满足任何条件时!!

Enter the list1: 1 2 4
Enter the list2: 1 4 9
No such pattern present
vjhs03f7

vjhs03f74#

正确,1 ** 2 == 1如果您只想打印所有匹配的列表,

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

elif语句。

相关问题