I have been cracking my head the whole time. I am aware that this is a very simple task of loops, however, I am unable to get the second loop to be added into the code. please help me take a look.
So, in short this program is suppose to:
# Given a list of numbers and a number k,
# return whether any two numbers from the list add up to k.
# For example, given [10, 15, 3, 7] and k of 17,
# "return true since 10 + 7 is 17.
and I need some guide on the looping of the list. it is my day 2 on python. Thanks a lot for the help in advance!
So, I got the input ready, function to get 2 inputs from the list add them up and compare with K.
The issue is getting the numbers within the list to add with themselves.
import os
import subprocess
# Given a list of numbers and a number k,
# return whether any two numbers from the list add up to k.
# For example, given [10, 15, 3, 7] and k of 17,
# "return true since 10 + 7 is 17.
# Bonus: Can you do this in one pass
# get input for list untill enter
list = list()
num = int(input("how many number you want: "))
print("enter the number in array")
for i in range(int(num)):
n = int(input("num :"))
list.append(int(n))
print('Total number in Array: ', num)
# get input for k
try:
k = int(input("enter value of K: "))
except ValueError:
print("This is not a whole number.")
# show list and k
print('Value in Array: ', list, 'Value of k: ', k)
# check if any 2 add up to k
def addncompar(list1, list2, kinput):
print("---------------------start of function")
print("K is: ", kinput)
total = list1 + list2
print("a1 is :", list1)
print("b1 is :", list2)
print("sum is :", total)
print("---------------------end of function")
if total != kinput:
return False
else:
return True
# for each 1 item in the list compare to each item in the list.if condition
true= break,else compare another number.
i = 0
while i < int(num):
print("while i staring is ", i)
if i == num:
break
else:
for y in range(num):
print("y staring is ", y)
print("num staring is ", num)
if y + 1 == num:
y = 0
print("i staring in y loop is ", i)
if addncompar(list[i], list[y + 1], k) == True:
a1 = list[i]
b1 = list[y + 1]
break
else:
print("y has been added at else")
print("y ending is:", y)
if list[y + 1] == num:
print("i has been added")
i += 1
print("i has become :", i)
print("y after i added:", y)
else:
print("y has been added")
y += 1
# if true
# display
print("value 1 + value 2 = k")
print(a1, "+", b1, "=", k)
break
# else
{}button in the editor.