1

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
3
  • 6
    Please fix your indentation; that's especially important for nested loops. You can copy/paste your whole code block in one go, highlight it all, and use ctrl + k, or the {} button in the editor. Commented Jan 22, 2019 at 12:43
  • for most programming languages, one rather clean way to break out of a nested loop is to put the nested loop into a function/procedure/method/whatever and return from that Commented Jan 22, 2019 at 12:55
  • Yes I am aware that indentation is important infact it kept on prompting me when it comes to python. Thank you everyone for you help. I will take alook again with your example. I will take alook at putting loop into function. Trying to do a program per day. Thanks guys for a your help. Commented Jan 22, 2019 at 13:30

2 Answers 2

4

You could just use a boolean flag:

ret = False
i = 0
while i < int(num):
    ...
        for y in range(num):
            ...
            if addncompar(list[i], list[y + 1], k) == True:
                a1 = list[i]
                b1 = list[y + 1]
                ret = True
                break
            ...
        if ret:
            break
    ...

Or use the fancy else of a for loop:

i = 0
while i < int(num):
    ...
        for y in range(num):
            ...
            if addncompar(list[i], list[y + 1], k) == True:
                a1 = list[i]
                b1 = list[y + 1]
                break
            ...
        else:
            continue
        break
    ...

The else part is executed if the for was not "broken" (i. e, exited using breakstatement).

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the 2 different bits of advice, I shall take a look, all I was taught in school was break is something that everyone should avoid using.
Crazy teaching. What on earth else is one supposed to do, when searching for the first entity in a list satisfying some condition? Test all the others anyway?
Upvoted for the second example, using loop else clause to continue an outer loop. I'd never have thought of it. Beautiful.
0

Let's just keep it clean and nice:

import itertools

def isAdded(numList, k):
    for num in range(0, len(numList)):
            for subNums in itertools.combinations(numList, num):
                b = sum(int(i) for i in subNums)              
                if b == k:        
                   print("The numbers that add up ", k, " are: ", subNums)

k = 17
numList = [10, 15, 3, 7]
isAdded(numList, k)

OUTPUT:

The numbers that add up 17 are: (10, 7)

pyfiddle

9 Comments

for num in range(1, len(numList)+1): ?
@Mr_and_Mrs_D Ah, my bad. typo. fixed.
Wow thanks alot. Omg.. so many step all in these few lines.. regarding the import itertools. Is it like a recommend solution? Or is it best to avoid? Is it something like import re?
@Chris like I said, cleaner, nicer and shorter. combinations(numList, num) returns num length subsequences of elements from the input iterable. You can read more here: docs.python.org/2/library/itertools.html#itertools.combinations
@Mr_and_Mrs_D you're welcome to edit and identify any fixes, cheers.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.