不使用循环/函数的2个数组的Python交集

2024-09-28 03:15:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我对这项任务有一些问题:

write in recursive functions which (NOTE: you can't use loops.):

3.1 Will display on the screen the common part of two sorted arrays

3.2 Will write the back of the word/array on the screen

现在我有剩下的练习:

firstArray = [1, 2, 3, 4, 5]
secondArray = [4, 5, 6, 7, 8]

#1 function - print first element
def printFirstElement():
    firstElemenet = firstArray[0]
    print(firstElemenet)
    
printFirstElement()

#2 function - print all without first element
def printAllWithouthFirstElemenet():
   arrayWithoutFirstElement = firstArray[1:]
   print(arrayWithoutFirstElement)
   
printAllWithouthFirstElemenet()

#3 functin - return information if array is empty 
def checkArrayEmptiness():
    if firstArray:
        print("Array has somehting")
    else:
        print("Array is empty")
    
checkArrayEmptiness()

##rest code should be here

我真的不知道我还能写些什么,有人能帮我吗

编辑1

Without ready-made solutions


Tags: oftheondeffunctionelementarrayscreen
1条回答
网友
1楼 · 发布于 2024-09-28 03:15:43

您可以使用python set。 比如:

    print(set(firstArray).intersection(secondArray))

在大多数情况下,使用Python内置解决方案是明智的,因为它们在一般情况下更有效

但是,如果您确实需要它,请尝试查看这个重复的问题:Finding List Intersection using Python List Slices & recursion

相关问题 更多 >

    热门问题