# Test 12: Sum check Given a list of numbers and a number k, write a Python program to check whether the sum of any two numbers from the list is equal to k or not. Sample data: ([12, 5, 0, 5], 10) ([20, 20, 4, 5], 40) ([1, -1], 0) ([1, 1, 0], 0) Sample output: True True True False
时间: 2024-01-08 19:04:03 浏览: 93
python比较两个列表是否相等的方法
Here's a Python program that checks whether the sum of any two numbers from a given list is equal to a given number k or not:
```python
def sum_check(lst, k):
# Initialize a set to hold the values seen so far
seen = set()
# Iterate over the list of numbers
for num in lst:
# Check if the complement of the current number is in the set
if k - num in seen:
return True
# Add the current number to the set
seen.add(num)
# If no pair of numbers was found, return False
return False
# Test the function with the given sample data
data = [([12, 5, 0, 5], 10),
([20, 20, 4, 5], 40),
([1, -1], 0),
([1, 1, 0], 0)]
for lst, k in data:
result = sum_check(lst, k)
print(f"List: {lst}, k: {k}, Result: {result}")
```
Output:
```
List: [12, 5, 0, 5], k: 10, Result: True
List: [20, 20, 4, 5], k: 40, Result: True
List: [1, -1], k: 0, Result: True
List: [1, 1, 0], k: 0, Result: False
```
I hope this helps! Let me know if you have any more questions.
阅读全文