r/learnprogramming • u/BoomNeo • 24d ago
Code Review What should I be thinking in my head while I'm doing a programming problem?
Hello, I am a computer science who is currently taking an Introduction to Programming class where we use Python. I am really obsessed with not only learning Python, but I really want to become a master at problem solving and logical thinking. I have this one assignment that takes text files and returns the amount of paragraphs in the text file. I want to know, what kinds of questions should I be asking myself in order to get closer to a solution to this problem? What are some general rules of problem solving that I should use whenever I do a problem like this? I will include the code I have modified in this post. If you want more details, please let me know!
'''
Instructions:
Complete the definition of the function `countParagraphs(filename)`, which
should count the number of paragraphs in the file referenced by `filename`.
Paragraphs are separated by one or more blank lines -- that is, two or more
new line characters (\n) in a row. New lines at the start of the file should
be ignored. Your solution should use a loop that iterates over the
*characters* in the text and you should keep track of whether or not you're
in a run of two or more newlines or not and update the paragraph count
accordingly.
There are two test files for you to play around with: sample.txt (4
paragraphs) and raven.txt (225 paragraphs).
'''
def countParagraphs(filename):
'''Counts the number of paragraphs in the given file.
Paragraphs are delineated by two or more new lines. New lines
at the start of the file are ignored.
Parameters:
filename (str): The name of the file to process.
Returns (int): The number of paragraphs.
'''
# TODO complete this function.
# My own code for this problem
textFile = open(filename, 'r', encoding= 'utf-8')
text = textFile.read()
count = 0
prevCharacter = ''
for character in text:
if character == '\n' and prevCharacter == '\n':
prevCharacter = character
count = count + 1
return count
def main():
filename = input('Enter the name of the file to count paragraphs in: ')
print(f'Paragraphs: {countParagraphs(filename)}')
if __name__ == '__main__':
main()
5
u/FatDog69 24d ago
The first thing you should do is DESIGN. Break down the problem into smaller parts. (Not really necessary for this assignment but an important step.)
The next thing is 'what could go wrong'. You need to test that the file name exists or print a good error message and exit.
Bonus would be if the file exists you print something like "Counting paragraphs in file: filename".
Then every 10 or so paragraphs print " 20 paragraphs found" so the user sees the program is running.
1
u/BrannyBee 24d ago edited 24d ago
My last comment on my profile has a pretty long breakdown of my thought process approaching a programming problem if you care to look. It was made to another similar post to someone struggling with programming.
In fact the made up problem in qiestion was a more beginner version of your example (take a single word and count the vowels in the word). Only warning being that the comment was tailored more towards a veteran so maybe the language was a bit more course than you'd usually find, otherwise it might be wotth reading
A short tldr i suppose would be this. Forget the code, work on the problem and find every individual step of the process. When you've done that, break down those steps into even smaller steps by asking yourself the dumbest question possible that a person could ask about that step. Eventually you'll have steps to get from point A to poi t B that are simple and all thats left is to "translate" that stuff to the programming language.
Forget the code and solve the problem by taking each step and breaking them down to as small units as possible. When you've done that, keep making them smaller. In my example, my mental model had given me a "step" that anyone could clearly tell required a variable. But then I asked myself what the dumbest qiestion possible could be about that step, and I imagined some idiot asking me "what is a word", and that thought process brought me to the conclusion that i dont need just any variable, i need a string.
Comment in question: https://www.reddit.com/r/learnprogramming/s/Q795ESWULM
If you have solved the problem mentally, all thats left is translating it to code. If that part is hard, you just need practice. If that part is any more complicated thab simply translating english to Python, or whatever, than your mental model is too complicated. That means you havent broken it down enough, and you need to ask yourself what is an even dumber way to simplify each of your steps in your mental model. You don't code to do this, you think. And you dont think smarter, you think dumber. Otherwise you're overcomplicating things, and idiots like me will always be better at writing and reading code than you
1
u/buzzon 24d ago
It's mostly "How can I achieve that?" on and on, but once you complete a piece of coffee, you should also critically examine it with questions "Is everything ok here?" (e.g. variable names and time complexity) and "Can anything be improved?"
1
u/bestjakeisbest 24d ago
Personally i think in pictures while i solve a problem, and i use the pictures to manually go through the process of doing what my program should be doing. Aside from that i keep track of the big O of the function i am working on and look for shortcuts and simple optimizations as i go. If i need better optimization than that i wait until i have a working program first.
1
u/Conscious_Bank9484 24d ago
I think of it as a series of tasks. Some people use flow code, but I’ve always just done lists.
When I’m doing something particularly long, sometimes I will write the comments all out before I write the code.
AI has kinda ruined my ability to write code, but I’m on day 3 of a pretty big project I’m writing out myself to make sure it works the way I intend it to. I don’t trust the version AI built for me because I can’t follow along in the code, so it’s kinda a black box to me in that way.
1
u/Seferil 24d ago
My process is usually to start with identifying what each function needs to do, what each thing that's being done needs in order to be done (variables, loops, counters, etc.), then lay out each step of the program in order to create a prototype. After that, identify edge cases and modify that prototype to account for them.
Your assignment tells you what the function is supposed to do. You have a variable for your text file, the text in the text file, the paragraph count, and what the previous character read was, and you have it wrapped in a loop to iterate over the entire text. All of that is good.
Your main function flow checks whether the current character is a new line character and if the previous character was a new line character, then updates the previous character and paragraph count if true.
There's a bug there that will never allow that check to be true.
After that gets fixed, find edge cases. A few I can see that should be considered are:
"What happens if there are more than 2 new line characters in a row?"
"What if there are 2 or more new lines characters at the start of the text?"
"What if there are 2 or more new lines characters at the end of the text?"
1
u/Upstairs_Jelly_1082 24d ago
basically break down the problem. figure out if a statement is asking you do something or if its just filling things up.
in this case, basically its creating a function, read a file and loops.
what I'd suggest is keep a list of the basic elements of writing a python code and as you read, check whether there's something that you'd have to do making use of those.
1
u/desrtfx 24d ago edited 24d ago
Your approach is not entirely wrong, some good thought process, but it is still far from correct.
prevCaracterinside the conditional. It needs to be updated regardless of condition (unconditionally)Personally, I would see this as a typical parsing approach: a finite state machine.
This way, I would toggle back and forth between "in paragraph" (2) and "in new line" (3) until I reach the end of the file, where I would increase the paragraph count once more (final paragraph).
There are alternative approaches using regular expressions, counters, etc.
1
u/JGhostThing 24d ago
The very first thing that you need to do is to define a paragraph. This may already be defined for you.
The second thing you need to know is the format of the text file.
The third thing you need to know is the expected output. If you only get credit if you say, "The number of paragraphs is 17." then you will need to do this, replacing 17 with the actual number of paragraphs.
If I were asking this, I would suggest that a single \n both ends a paragraph and starts a new one. If there is no newline at the end, then there is a paragraph there also.
This way you could use a couple regular expressions to find the number of paragraphs. Plus it's a system used in word processors.
1
u/DanKegel 24d ago
Try test driven development, i.e. think first of the smallest two or three test cases, and what it would take to pass them.
1
u/SwiftQuest 23d ago
One habit that helped me a lot is to make a tiny input like "a\n\nb" and walk through it one character at a time on paper, writing down what each variable holds after every step. You'll usually spot the exact spot where your loop does something you didn't expect, like prevCharacter only getting updated inside the if. Then ask yourself what changes with 3 newlines in a row, or a file that starts with a blank line. Those edge cases are where most of these assignments get tricky.