How do I extract common characters from two strings and eliminate duplication?

Asked 2 years ago, Updated 2 years ago, 19 views

Problem: Print common characters for two strings (no duplication)

word1=input('Enter a word(1)')  
word2 = input('Enter a word (2)') 

common_char='"
for c1 in word1:
    for c2 in word2:
        pass 
        # Please write the code you need after this

print(common_char)

As for the problem, I wrote the following and the output went wrong.
Please tell me why.I think the way of thinking about the for sentence is still ambiguous.

word1=input('Enter a word(1)')  
word2 = input('Enter a word (2)') 

common_char='"
for c1 in word1:
    for c2 in word2:
        pass 
        # Please write the code you need after this
        for c3 in common_char:
            if c1 == c2:
                if c1 == c3:
                    continue
                common_char+=c1

print(common_char) 

However, I understood the answer and wrote the following using the in function, and the output was correct.
I have no idea what was wrong with the above description.Thank you for your cooperation.

word1=input('Enter a word(1)')  
word2 = input('Enter a word (2)') 

common_char='"
for c1 in word1:
    for c2 in word2:
        pass 
        # Please write the code you need after this
        if c1 == c2:
            if c1 in common_char:
                continue
            common_char+=c1

print(common_char) 

python

2022-09-30 14:02

1 Answers

common_char='"
  ・
  ・
  ・
for c3 in common_char:
    if c1 == c2:
        if c1 == c3:
            continue
        common_char+=c1

In the above case, the for statement does not process the for statement because common_char contains no elements (that is, the number of elements is 0) before for c3 in common_char:
The number of elements is n = the number of times the for statement is processed is n times.

 if c1 in common_char:
    continue

Next, regarding the in operation in this if statement, the above code has not been processed because common_char contains no elements before ifc1 in common_char:.Try commenting out these two lines.


2022-09-30 14:02

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.