Home > Software engineering >  How can I modify this code in such a way multiple corresponding characters are printed out once in o
How can I modify this code in such a way multiple corresponding characters are printed out once in o

Time:09-16

p occurred twice in the output because of the word apples.

I am trying to modify the code in such a way p is printed once in the output. Thanks

def in_both(word1, word2):
    for letter in word1:
        if letter not in word2:
            print (letter)

print(in_both("apples", "oranges"))

CodePudding user response:

You need to store letters already seen in a data structure. In this case a set() is most appropriate since you can have O(1) lookup and addition

def in_both(word1, word2):
    known_letters = set()
    for letter in word1:
        if letter not in word2 and letter not in known_letters:
            print(letter)
            known_letters.add(letter)

print(in_both("apples", "oranges"))

Also your code will print a final None since it's the return value of in_both, so I would suggest removing the print call arround in_both("apples", "oranges")

  • Related