livepython.net

214. Python Program to Find the Items Two Lists Have in Common

MediumPhase 2 · Practice

A few steps here, with three tools you know: split(), in and not in.

Overview

Finding the items two lists have in common is a common interview question. A set can do it, but interviewers often ask for the loop way, because it also keeps the order.

Problem Statement

Sipho and Thandi each write a shopping list. They want to know which things are on both lists, so they do not buy them twice.

  • An item is in common when it is on both lines. Items must match exactly: Tea and tea are different.
  • Print the items in the order of the first line.
  • Print each item only once, even if it appears more than once.
  • Print In common: <items>, with one space between the items. If no item is on both lines, print Nothing in common.
  • Use loops and lists, not a set: a set would lose the order.

Examples

Example 1. Input:

apple kiwi plum
plum grape apple

gives:

In common: apple plum

Why: apple and plum are on both lines. apple comes first on line 1, so it is printed first.

Example 2. Input:

1 2 3
4 5 6

gives:

Nothing in common

Why: no number is on both lines.

Input

Two lines. Each line holds words or numbers, with one space between them (1 item or more). Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.

Output

One line: In common: <items> or Nothing in common. The tests try 7 different inputs, also items that repeat and words with capital letters.

Try it first. The solution opens when you solve this question, or after 3 tries with Submit.

Finish this chapter firstChapter 12 · Working With Strings
solution.py
# write your code here

EXPECTED OUTPUT

1In common: apple plum

YOUR OUTPUT

Press Run to see your output here. Lines are compared with the expected output.