How to write a program that finds the similarities and differences in pairs of characters in a better way

Question:

I’m new to Python and trying to learn more by doing exercises, now, I need to write a program that finds the similarities and differences between two lines of characters:

  1. user enters number of pairs
  2. then she enters pairs of characters in each line
  3. he can see each pair in the output with a new line below the pairs that shows the similarities and differences

For instance:
the number of pairs is 2
the input pairs of characters is like this

aaa
aaa

123
456

the desired result:

aaa
aaa
...

123
456
***

As you can see we show the similarities by a dot(.) and differences with (*). Below, you can see what I’ve written so far:

# Get the strings

number_of_pairs = int(input(""))
string_list = []

i = 0
while i < (number_of_pairs * 2):
    string_list.append(input())
    i += 1



first_item = ""
second_item = ""
result = []

j = 0

while j < len(string_list):
    first_item = list(string_list[j])       # ['a', 'a', 'a']
    second_item = list(string_list[j + 1])  # ['b', 'b', 'b']

    for i in range(len(first_item)):
        if first_item[i] == second_item[i]:
            result.append(".")
        else:
            result.append("*")
    print(string_list[j])
    print(string_list[j + 1])
    print(''.join(result))
    result.clear()

    j += 2
    first_item = ""
    second_item = ""

I was wondering if you could say whether there are better ways to write this piece of code. I want to be aware of other ways.

I wrote the code all by myself
since I’m new to Python programming, I need to know opinions of other experts.

Asked By: Pantea

||

Answers:

There is a standard function zip() that takes lists and joins then together positionally. Recalling that strings are kind of lists of characters we can do:

for char_a, char_b in zip("hello", "world"):
    print(char_a, char_b)

We get:

h w
e o
l r
l l
o d

This will help us compare these strings character by character:

for char_a, char_b in zip("hello", "world"):
    print(char_a == char_b)

giving us:

False
False
False
True
False

for example.

As long as we compare strings of equal length zip() is great but it only pairs things up until the shorter of the lists is exhausted. If we might allow our user to enter strings of differing lengths we might want to use itertools.zip_longest(). I leave that to you.

Now that we have a way to compare two strings character by character, the rest falls out as:

import itertools

## How many pairs to ask for:
number_of_pairs = int(input("How many pairs will you enter: "))

## ------------------------
## save pairs at a time to a list
## ------------------------
pairs = []
for i in range(number_of_pairs):
    print(f"Enter pair {i+1}")
    pairs.append([
        input("tFirst Entery: "),
        input("tSecond Entery: ")
    ])
## ------------------------

## ------------------------
## ------------------------
for pair in pairs:
    ## ------------------------
    ## compare characters positionally within the two strings
    ## ------------------------
    matches = "".join(
        "." if x==y else "*"
        for x,y
        in itertools.zip_longest(*pair)
    )
    ## ------------------------

    print(pair[0])
    print(pair[1])
    print(matches)
    print()
## ------------------------
Answered By: JonSG
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.