232k views
1 vote
Write a Python program that takes a list of integers as input and finds the two numbers that add up to a given target sum (also input by the user). The program should return the indices of the two numbers as well as the numbers if they exist.

1 Answer

2 votes

def two_sum(nums, target):

num_to_index = {} # Dictionary to store numbers and their indices

for index, num in enumerate(nums):

complement = target - num

# Check if the complement exists in the dictionary

if complement in num_to_index:

return [num_to_index[complement], index], [complement, num]

# Store the current number and its index in the dictionary

num_to_index[num] = index

return None # If no solution is found

# Input

nums = list(map(int, input("Enter a list of integers separated by spaces: ").split()))

target = int(input("Enter the target sum: "))

result = two_sum(nums, target)

if result:

indices, numbers = result

print(f"The indices of the two numbers are {indices[0]} and {indices[1]}.")

print(f"The two numbers are {numbers[0]} and {numbers[1]}.")

else:

print("No solution found.")

User YohanRoth
by
8.0k points