The appearance of an extra word in a line from list 2

Viewed 36
def checkio(line1: str, line2: str) -> str:
    result = ''
    for word in line1.split(','):
        if word in line2:
            result += word + ','
    result = ','.join(sorted(result.split(',')))
    return result[1:]


if __name__ == "__main__":
    print("Example:")
    print(checkio("mega,cloud,two,website,final", "window,penguin,literature,network,fun,cloud,final,sausage")) 

Maybe a stupid question, but after a cycle of comparing two strings, "two" appears in the result variable, although it is not in the 2nd list

4 Answers

The problem is that you use the "in"(substring) operator instead of the (equal)"==" operator. So the "two" it finds is the "two" which is inside of the word "neTWOrk".

Yes... "two" is in "window,penguin,literature,network,fun,cloud,final,sausage"

The sequence of 3 characters: t, w, o is present in line2, thus it is in the result.

You should compare sets by splitting line2.

def checkio(line1: str, line2: str) -> str:
  result = ''

  for word in line1.split(','):
    if word in line2.split(','):
        result += word + ','

  result = ','.join(sorted(result.split(',')))
  return result[1:]

The word two is in the second string (in network).

It's better and easier to split both strings into sets and then return the intersection of these in a join.

def checkio(line1: str, line2: str) -> str:
    s1 = set(line1.split(','))
    s2 = set(line2.split(','))
    return ','.join(s1 & s2)


if __name__ == "__main__":
    print("Example:")
    print(checkio(
        "mega,cloud,two,website,final", 
        "window,penguin,literature,network,fun,cloud,final,sausage"))

You must split line2 with "," and make a list.Your problem is that you search in a string and "two" is in "network". I just add a line in your function.

'''

def checkio(line1: str, line2: str) -> str:
    #just add following line
    line2_list=line2.split(",")
    result = ''
    for word in line1.split(','):
        if word in line2_list:
            result += word + ','
    result = ','.join(sorted(result.split(',')))
    return result[1:]


if __name__ == "__main__":
    print("Example:")
    print(checkio("mega,cloud,two,website,final", 
    "window,penguin,literature,network,fun,cloud,final,sausage")) 

'''

Related