简体   繁体   中英

Using a For-Else executes both the conditions. How do I fix this?

I need to write a code, using loops, to find out if there is any common element in two lists. So, I wrote the following:

l1 = eval(input("Enter a list: "))
l2 = eval(input("Enter another list: "))
for i in range (len(l1)):
        for j in range (len(l2)):
                if l1[i] == l2[j]:
                        print("Overlapped")
                        break
else:
        print("Separated")

However, what I get as output is this:

Enter a list: [1,34,543,5,23,"apple"]
Enter another list: [54,23,6,213,"banana"]
Overlapped
Separated

Since the lists do have a common member, it should only print "Overlapped", but it ends up printing "Separated", too.

How do I fix this? I'm using python 3.7

Thank you so much!!

Create a list of tuples (i, j) and use a single for loop to traverse the list of tuples. So either the output is "Overlapped" and the loop is breaks out or the else clause is executed and the output is "Separated" :

for i, j in [(i, j) for i in range(len(l1)) for j in range(len(l2))]:
    if l1[i] == l2[j]:
        print("Overlapped")
        break
else:
    print("Separated")

Output:

 Enter a list: [1,34,543,5,23,"apple"] Enter another list: [54,23,6,213,"banana"] Overlapped

 Enter a list: [1,34,543,5,23,"apple"] Enter another list: [54,234567,6,213,"banana"] Separated

Alternatively you can create a list of tuples with the indices of the equal list elements. Finally check if the list is empty:

equal = [(i, j) for i in range (len(l1)) for j in range(len(l2)) if l1[i] == l2[j]]
if equal:
     print("Overlapped")
else:
     print("Separated")  

Since you'll need to break out of both loops for the else to work as you expect, I think it'll be easier to just not use the else at all here. If you define your code in a function, you can use return to break out of both loops at the same time.

For example:

def have_common_elements():
    l1 = eval(input("Enter a list: "))
    l2 = eval(input("Enter another list: "))
    for i in range (len(l1)):
        for j in range (len(l2)):
            if l1[i] == l2[j]:
                return True
    return False # will only happen if the previous `return` was never reached, similar to `else`

have_common_elements()

Sample:

Enter a list: [1,34,543,5,23,"apple"]
Enter another list: [54,23,6,213,"banana"]
True

Enter a list: [1,34,543,5,25,"apple"]
Enter another list: [54,23,6,213,"banana"]
False

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