Click here to Skip to main content
15,896,493 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a function called is_special_word that takes a string as input and returns a bool indicating whether this string is a "special word." A special word is one where at least one of the characters is a string representation of a number. I want to write a function that takes a string and returns a dictionary of special words in the string. I have this block of code but I am having trouble integrating my is_special_word perimeter.

What I have tried:

I have this:

Python
def word_count(s):
    s = s.lower()
    dct_cnt = {}
    count = 0 
    list_s = s.split()
    for word in list_s:
        if word in dct_cnt:
            count = dct_cnt[word]
            count += 1 
            dct_cnt.update({word: count})
        else:
            count = 1 
            dct_cnt.update({word: count})
            return dct_cnt 
the_string = input(" ")
Posted
Updated 28-Sep-22 2:24am
v2

Try
Python
def word_count(s):
    s = s.lower()
    dct_cnt = {}
    count = 0
    list_s = s.split()
    for word in list_s:
        if is_special(word):
            if word in dct_cnt:
                count = dct_cnt[word]
                count += 1
                dct_cnt.update({word: count})
            else:
                count = 1
                dct_cnt.update({word: count})
    return dct_cnt
 
Share this answer
 
Your return statement is indented too far, as it returns after the first word is added to the dictionary. It should be:
Python
for word in list_s:
    if word in dct_cnt:
        count = dct_cnt[word]
        count += 1
        dct_cnt.update({word: count})
    else:
        count = 1
        dct_cnt.update({word: count})
return dct_cnt

You should only return once the for loop has processed each word in the list.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900