简体   繁体   中英

Verify if two indices from a list add up to a target number

I am looking to see if any 2 indices add up to the inputed target number, and print the combination and index location of the respective pair. I honestly am not too sure how to approach this, my first reaction was using a for loop but due to inexperience i couldn't quite figure it out.

def length():
    global lst_length
    break_loop = False
    while break_loop == False:
        lst_length = int(input("Enter the length: "))
        if lst_length >= 10 or lst_length <= 2:
            print("Invalid list")
        elif lst_length >= 2 and lst_length <= 10:
            print('This list contains', lst_length, 'entries')
            break_loop == True
            break

def entries():
    i = 0
    x = 0
    global lst
    lst = []
    while i < lst_length:
        number = float(input("Enter the entry at index {0}:".format(x)))
        if i < 0:
            print('Invalid entry')
        else:
            lst = []
            lst.append(number)
            i += 1
            x += 1
def target():
    target_num = int(input("Enter the target number: "))


length()
entries()
target()

If I understand your question correctly, you want the user to insert numbers, and when finally two numbers match the wanted result, print them?

well, my code is pretty basic, and it gets the job done, please let me know if you meant something else.

for indices, I suppose you can fill in the gaps.


def check(wanted):
    numbers_saved = []
    checking = True
    while checking:
        x = float(input("enter a number: "))
        if x < 0:
            print("only numbers bigger than 0")
        else:
            for num in numbers_saved:
                if num +  x == wanted:
                    print(num, x)
                    checking = False
                    return
            numbers_saved.append(x)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM