Write a function named compare_list that takes two lists and returns True if they have at least one common element, and returns False otherwise
时间: 2023-12-06 11:39:43 浏览: 18
Here's a Python function that achieves this:
```python
def compare_list(list1, list2):
for item in list1:
if item in list2:
return True
return False
```
The function takes two lists as input and iterates through the first list. For each element in the first list, it checks if that element is also in the second list. If it finds a common element, it immediately returns True. If it iterates through the entire first list without finding a common element, it returns False.
相关问题
Write a function named compare_list that takes two lists and returns True if they have at least one common element, and returns False otherwise.
Sure, here's the function:
```python
def compare_list(list1, list2):
"""
This function takes two lists as input and returns True if they have at least one common element, and False otherwise.
"""
for element in list1:
if element in list2:
return True
return False
```
You can use this function to compare two lists and check if they have at least one common element. For example:
```python
list1 = [1, 2, 3, 4, 5]
list2 = [5, 6, 7, 8, 9]
if compare_list(list1, list2):
print("The two lists have at least one common element.")
else:
print("The two lists do not have any common element.")
```
Output:
```
The two lists have at least one common element.
```
Write a function link_to_list that takes in a linked list and returns the sequence as a Python list. You may assume that the input list is shallow; none of the elements is another linked list. Try to find both an iterative and recursive solution for this problem!
Iterative solution:
```python
def link_to_list(head):
lst = []
current = head
while current:
lst.append(current.val)
current = current.next
return lst
```
This solution traverses the linked list from the head node to the last node, appending the value of each node to a Python list. Once the end of the linked list is reached (i.e., the current node is `None`), the list is returned.
Recursive solution:
```python
def link_to_list(head):
if head is None:
return []
else:
return [head.val] + link_to_list(head.next)
```
This solution is a recursive implementation of the same logic. The base case is when the head node is `None`, in which case an empty list is returned. Otherwise, the function recursively calls itself on the next node in the linked list and appends the value of the current node to the resulting list. The final result is the concatenation of all these lists.