0

Hi what I am trying to do is count the specific occurrences of the characters common to each string in the list below and print out each string and how many times the common characters appear example barack a appears 2 barack r appears 1 when I run my code it prints that each character appears 1

list1 = ['barack', 'obar?ma', '?america?', 'war', 'russia?', 'mak?er'] 

common = set.intersection(*map(set,list1))

new_list = list(common)

for i in list1:
    for a in new_list:
        if a in i:
            x = new_list.count(a)
            print([i] + [a])
            print(x)

1 Answer 1

1

Change x = new_list.count(a) to x = i.count(a). At the moment you are counting how many as in 'a'; you want to count how many as in barack.

The new code with this modification:

list1 = ['barack', 'obar?ma', '?america?', 'war', 'russia?', 'mak?er']

common = set.intersection(*map(set,list1))

new_list = list(common)

for i in list1:
    for a in new_list:
        if a in i:
            x = i.count(a)
            print([i] + [a])
            print(x)

prints this:

['barack', 'a']
2
['barack', 'r']
1
['obar?ma', 'a']
2
['obar?ma', 'r']
1
['?america?', 'a']
2
['?america?', 'r']
1
['war', 'a']
1
['war', 'r']
1
['russia?', 'a']
1
['russia?', 'r']
1
['mak?er', 'a']
1
['mak?er', 'r']
1
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.