I am working on the Two Sum Problem with Array in Python. I have set my target sum/ int as 22. Strangely when I run my code I get no actual output aside from the message 'Process finished with exit code 0.'
However, I need the output to print the pair values that equal to the target sum e.g. [22, -2] [14,6]
This is my code, I am trying to keep it as straightforward and understandable as possible. Where am I going wrong?
my_numbers = [-2, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22]
target_sum = 20
def two_number_sum(my_numbers, target_sum):
for x in range(len(my_numbers)-1):
for y in range(x 1, len(my_numbers)):
if my_numbers[x] my_numbers[y] == target_sum:
print(my_numbers[x], my_numbers[y])
return True
CodePudding user response:
'Process finished with exit code 0' merely means that your program compiled and ran successfully without any errors. The reason you're not seeing anything is because nothing is actually being run since all your statements are definitions. What you need to do is run the function so that the print statement executes. Try adding something like this to the end of your code and then run it again:
two_number_sum(my_numbers, target_sum)
Also, you may want to consider changing the parameter names in your function definition so they are not confused with the variables you have defined. Parameter names do not affect the parameters themselves, which are what you pass in when you actually call the function.
If you didn't intend to write this as a function, you can also just remove the function definition and run your code as:
my_numbers = [-2, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22]
target_sum = 20
for x in range(len(my_numbers)-1):
for y in range(x 1, len(my_numbers)):
if my_numbers[x] my_numbers[y] == target_sum:
print(my_numbers[x], my_numbers[y])
CodePudding user response:
This slightly reorganizes your code to meet your spec:
my_numbers = [-2, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22]
target_sum = 20
def two_number_sum(my_numbers, target_sum):
for x in range(len(my_numbers)-1):
for y in range(x 1, len(my_numbers)):
if my_numbers[x] my_numbers[y] == target_sum:
return my_numbers[x], my_numbers[y]
print(two_number_sum(my_numbers, target_sum))