0

I have an assignment to write a code to count words in a string. I haven't learned split yet so I can't use it. I can only use functions, loops and conditionals. He's deliberately added three extra spaces to a string and I have to figure out how to get it to treat it as just one. I'm stuck. Help!

def wordCount(myString):
    try:
        spaceCount = 0
        char = ""
        for i in myString:
            char += i
            if char == "  ":
                spaceCount == 1
                pass
            elif char == " ":
                spaceCount += 1
        return spaceCount+1
    except:
        return "Not a string"

print("Word Count:", wordCount("Four words are here!"))
print("Word Count:", wordCount("Hi   David"))
print("Word Count:", wordCount(5))
print("Word Count:", wordCount(5.1))
print("Word Count:", wordCount(True))
6
  • Right off the bat, let me give you some advice: try to make your try-except blocks wrap the smallest amount of code that is possible/useful. And always explicitly catch some error-type, naked except clauses can mask errors you weren't expecting! Commented Apr 24, 2017 at 1:21
  • How are you stuck? What is or is not happening? Commented Apr 24, 2017 at 1:21
  • Stack overflow isn't for people to solve your homework, but here's a hint: make a variable to track the previous character. If you get a space but the last character was also a space you know not to count that one. Commented Apr 24, 2017 at 1:29
  • Hi! I suggest you elaborate a little on what isn't working. Asking questions about your homework is OK, as long as the question is specific. See the discussion here. And consider @dlsso hint! Commented Apr 24, 2017 at 1:39
  • 2
    Also, for questions like this, I think it is best to take out pencil and paper and move through your string yourself, character by character, and figure out how you would "count" words delimited by whitespace. Do it for a few examples, then try to translate what you've intuited into code! Forget about working with special cases, like inputs that aren't a string, and get the core of your approach worked out nicely before you start adding other stuff. Commented Apr 24, 2017 at 1:40

2 Answers 2

1

This kind of works :

def wordCount(myString):
    try:
        words = 0
        word = ''
        for l in myString : 
            if ( l == ' ' and word != '' ) or ( l == myString[-1] and l != ' ' ) : 
                words += 1
                word = ''
            elif l != ' ' : 
                word += l
        return words
    except Exception as ex :
        return "Not a string"

print("Word Count:", wordCount("Four words are here!"))
print("Word Count:", wordCount("Hi   David"))
print("Word Count:", wordCount(5))
print("Word Count:", wordCount(5.1))
print("Word Count:", wordCount(True))

Result :

'Word Count:', 4
'Word Count:', 2
'Word Count:', 'Not a string'
'Word Count:', 'Not a string'
'Word Count:', 'Not a string'
Sign up to request clarification or add additional context in comments.

1 Comment

Glad i could help :)
1
def wordCount(s):
    try:
        s=s.strip()
        count = 1 
        for i,v in enumerate(s):
            #scan your string in pair of 2 chars. If there's only one leading space, add word count by 1.
            if (len(s[i:i+2]) - len(s[i:i+2].lstrip()) == 1):
                count+=1
        return count
    except:
        return "Not a string"
print("Word Count:", wordCount("Four words are here!  "))
print("Word Count:", wordCount("Hi   David"))
print("Word Count:", wordCount(5))
print("Word Count:", wordCount(5.1))
print("Word Count:", wordCount(True))

6 Comments

I like your logic, but what if there are spaces at the beginning or the end ?
I've updated the code which should handle the case you mentioned.
Not yet, you missed the beginning
Handled spaces from both sides.
Nice , i would take down my post but i 'll keep it since i used less functions ( none )
|

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.