3

I'm a beginner, its been ~2 months since i started learning python.

I've written a code about a function that takes two strings, and outputs the common characters between those 2 strings. The issue with my code is that it returns all common characters that the two inputs have. For example:

input: common, moron

the output is "oommoon" when ideally it should be "omn".

i've tried using the count() function, and then the replace function, but it ended up completely replacing the letters that were appearing more than once in the output, as it should.

how should i go about this? i mean it's probably an easy solution for most of the ppl here, but what will the simplest approach be such that i, a beginner with okay-ish knowledge of the basics, understand it?

perplexed.
  • 43
  • 3
  • 2
    Welcome to the site! Sometimes the hard part is knowing what to search for. The reference above should get you there. – Jimmy Smith Oct 20 '19 at 13:31

3 Answers3

1

You can use a set, as long as the order of the final characters does not matter.

First, join the two strings together with a set intersection.

string_1 = "common"
string_2 = "moron"
set_1 = set(string_1).intersection(set(string_2))

Finally, convert it back to a string by joining all the characters together.

result = "".join(set_1)

Or, all in one line:

"".join(set(string_1).intersection(set(string_2)))

This returns "mno".

Ben Soyka
  • 816
  • 10
  • 25
0

Maybe use this:

s1 = input('Word 1:  ')
s2 = input('Second word:  ')
difflist = []
for letter in s2:
    if letter in s1 and letter not in difflist: difflist.append(letter)
    else: continue
for letter in s1:
    if letter in s2 and letter not in difflist: difflist.append(letter)
    else: continue
for item in difflist:
    print(item)

Output:

============================== RESTART: D:\x.py ==============================
Word 1:  common
Second word:  moron
m
o
n
Sid
  • 2,174
  • 1
  • 13
  • 29
0

You can try this:

''.join(set(s1).intersection(set(s2)))

Dino
  • 7,779
  • 12
  • 46
  • 85
Toni Sredanović
  • 2,280
  • 1
  • 11
  • 13