Manik
Manik

Reputation: 595

How to make a for loop iterate together with the inside for loop both iterating on an array in python?

I am trying to make a program that can add by literally counting. But for that I have 2 for loops which need to work together. for example if I input 3 and 2 the outside for loop iterates till "3" in the array and then another for loop iterates on the array till "2" in such a way that the outside for loop should(but doesn't) iterate with it and the position it is at eventually is printed out(which should be 5). How can I achieve this? because right now the inside loop will finish its iteration and break.

arr = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
#print(arr[0])
a = str(input()) #first number
b = str(input()) #second number

for i in arr:
    if i == a:
        for j in arr:
            if j == b:
                print(i)
                break

this program outputs 3 for input 3 and 2 but I want 5

Upvotes: 0

Views: 193

Answers (2)

Tyrion
Tyrion

Reputation: 485

Here is my solution:

arr = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
num_list = list(range(int(arr[-1])*2+1))

new_dict = dict()
for index, value in enumerate(num_list):
    new_dict[value] = set()
    for item1 in arr:
        for item2 in arr:
            if int(value) == int(item1) + int(item2):
                new_dict[value].add((item1, item2))

a = str(input())  # first number
b = str(input())  # second number

target = (a, b)

for key, value in new_dict.items():
    if target in value:
        print(int(key))

Hope it helps. I am interested if you can achieve the goal without using any "+". Please share if you find it. Thanks in advance!

Upvotes: 0

Rob Bricheno
Rob Bricheno

Reputation: 4653

You could use another variable to keep track of the count, like this:

arr = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]

a = str(input())  # first number
b = str(input())  # second number

counter = 0
for i in arr:
    if i == a:
        for j in arr:
            if j == b:
                print(counter)
                break
            counter += 1
    counter += 1

We can write a program to achieve a similar behaviour significantly more simply:

a = int(input())  # first number
b = int(input())  # second number

counter = 0

for _ in range(a):
    counter += 1
for _ in range(b):
    counter += 1
print(counter)

and this has the advantage that we aren't restricted to inputs in arr.

Upvotes: 2

Related Questions