Return the number of times a word appears in a string

  • Context: Comp Sci 
  • Thread starter Thread starter ver_mathstats
  • Start date Start date
  • Tags Tags
    String
Click For Summary

Discussion Overview

The discussion revolves around a coding problem where participants are trying to return the number of times the string "code" appears in a given string using Python. The focus includes debugging code, understanding function structure, and exploring alternative methods for counting occurrences.

Discussion Character

  • Homework-related
  • Technical explanation
  • Debate/contested

Main Points Raised

  • One participant presents a function to count occurrences of "code" but expresses uncertainty about its functionality and formatting.
  • Another participant points out potential index range errors in the loop and emphasizes the need for proper indentation in Python code.
  • A later reply acknowledges mistakes and thanks others for their help, indicating some learning has occurred.
  • Some participants suggest using code tags for better formatting when sharing code snippets.
  • Alternative methods are proposed, including using the built-in string method .count(), though some express concern about whether this approach aligns with the instructor's expectations.
  • Discussion includes a mention of regular expressions (REGEX) as a more advanced method for counting substrings, with varying opinions on its necessity for the task at hand.
  • One participant notes that the return statement in the function is incorrectly indented, which would cause the function to return prematurely.
  • Another participant emphasizes the importance of learning the underlying concepts rather than just obtaining the correct answer.

Areas of Agreement / Disagreement

Participants generally agree on the importance of proper coding practices and the need for debugging, but there are multiple competing views regarding the best approach to solve the problem, particularly concerning the use of built-in methods versus manual counting techniques.

Contextual Notes

Some participants mention specific requirements from their instructor regarding coding methods, which may limit the approaches they can take. There is also uncertainty about the appropriateness of using shortcuts like .count() in the context of their assignment.

Who May Find This Useful

This discussion may be useful for students learning Python programming, particularly those focused on string manipulation and debugging techniques in coding assignments.

ver_mathstats
Messages
258
Reaction score
21
Homework Statement
Return the number of times that the string "code" appears anywhere in a given string
Relevant Equations
Using python
Python:
def count_code(str):
       count = 0
       for c in range(len(str)-1):
              if str[c] == 'c' and str[c+1] == 'o' and str[c+2] == 'd' and str[c+3] == 'e':
                          count+=1
              return count
Here is my code so far, I did use some test results with print statements but nothing comes up when I run my code and I am unsure of where I am going wrong.

Any help would be greatly appreciated. Thank you.
<mentor add code tags>
 
Last edited by a moderator:
Physics news on Phys.org
I would think the term str[c+3] would give an index range error when c points at the 2nd and 3rd last chars of the string. That could be something to do with why the results are not what expected. Only let c run up to the fourth-last character.

Also, you have no indentation for the function, the for statement or the if statement. It won't work without indentation. If the latter is an artefact of formatting on this website, enclose your code within delimiters [code] and [/code] when posting on here so the indentation does not disappear.
 
Yes I realized some mistakes and fixed it. Thank you. And yes I am sorry about that I do have it indented in python, I just did not know how exactly to format it on PhysicsForum but thank you, will use that now. Thank you for the help.
 
Use code tags - they look like this with no spaces:
[ c o d e = python ]
... code lines here ...
[ / c o d e ]
 
jim mcnamara said:
Use code tags - they look like this with no spaces:
[ c o d e = python ]
... code lines here ...
[ / c o d e ]
Yes thank you. Greatly appreciated.
 
ver_mathstats said:
Homework Statement:: Return the number of times that the string "code" appears anywhere in a given string
Relevant Equations:: Using python

Python:
def count_code(str):
       count = 0
       for c in range(len(str)-1):
              if str[c] == 'c' and str[c+1] == 'o' and str[c+2] == 'd' and str[c+3] == 'e':
                          count+=1
              return count
Here is my code so far, I did use some test results with print statements but nothing comes up when I run my code and I am unsure of where I am going wrong.

Any help would be greatly appreciated. Thank you.
<mentor add code tags>
I don't see a good reason in this instance for your not presenting the whole script.

If it were up to me, I'd code it as:
Python:
givenstring = 'code some code and then code some more'
print givenstring.count('code')
but I'm not confident that your instructor wouldn't take a dim view of your using the .count shortcut. :wink:
 
  • Like
Likes   Reactions: jim mcnamara
The return count statement is too much indented. The function will return the first time around the for loop, so it can only return 1 if the input starts with 'code' and 0 otherwise..
 
  • Like
Likes   Reactions: ver_mathstats and FactChecker
sysprog said:
but I'm not confident that your instructor wouldn't take a dim view of your using the .count shortcut. :wink:
I agree. There is a lot of general programming that this exercise teaches. In any case, there are functions for using regular expressions that, IMHO, one should eventually learn.
 
  • Like
Likes   Reactions: ver_mathstats, sysprog and jim mcnamara
I second @FactChecker comment about learning REGEX (regular expressions)
 
  • Like
Likes   Reactions: ver_mathstats and sysprog
  • #10
In python a ##\mathtt{\text{regex}}## command (not just ##\mathtt{\text{re}}## ) can be configured to allow recursion and to use an extenal stack. Technically that makes it a context-free grammar instead of properly or strictly regular.

Even so, it's helpful to have the regex iterator in the Boost library if you want to get all instances of a substring in a string -- https://www.boost.org/doc/libs/1_72_0/libs/regex/doc/html/boost_regex/ref/regex_iterator.html
 
  • Like
Likes   Reactions: ver_mathstats
  • #11
sysprog said:
I don't see a good reason in this instance for your not presenting the whole script.

If it were up to me, I'd code it as:
Python:
givenstring = 'code some code and then code some more'
print givenstring.count('code')
but I'm not confident that your instructor wouldn't take a dim view of your using the .count shortcut. :wink:
Sorry, we're asked to do it in a specific way with concepts we had learned the previous week. Thank you for the help though.
 
  • Informative
Likes   Reactions: sysprog
  • #12
ver_mathstats said:
Sorry, we're asked to do it in a specific way with concepts we had learned the previous week. Thank you for the help though.
That seems right to me. Getting a correct answer isn't all that you're seeking. It's important to build the concepts and skills.
 
  • Like
Likes   Reactions: FactChecker and jim mcnamara

Similar threads

  • · Replies 2 ·
Replies
2
Views
2K
Replies
4
Views
3K
  • · Replies 12 ·
Replies
12
Views
3K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 18 ·
Replies
18
Views
2K
  • · Replies 10 ·
Replies
10
Views
2K
  • · Replies 6 ·
Replies
6
Views
20K
  • · Replies 5 ·
Replies
5
Views
3K
Replies
1
Views
2K
  • · Replies 40 ·
2
Replies
40
Views
4K