r/learnprogramming • • 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()
1 Upvotes

23 comments sorted by

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/BoomNeo 23d ago

Could you give me examples of taking a problem like the one I posted and breaking it down into smaller easier to solve problems? I'm trying to do that with this problem, but my mind is going blank on smaller problems to solve in order to figure out the complete solution.

1

u/[deleted] 23d ago

Nobody is going to do your homework for you.

1

u/BoomNeo 23d ago

That's not what I'm asking. I'm not asking people to do the problem for me, I'm asking ways for thinking and methods to help me better solve my problem. Respectfully if you aren't going to contribute anything helpful, please don't comment.

1

u/FatDog69 23d ago

Your program is pretty simple so let me add a little complexity.

DESIGN

  • Need to take a file name or a folder name of .txt files to analyze.
  • Need to handle a file name that does not exist.
  • When processing a .txt file we might want to report the file size, number of paragraphs, word count and other stats. Make sure we have a clear 'analyzeFile()' routine where all the metric logic will live.
  • Reporting - simple print statement vs simple HTML vs Single File report vs analysis of all files in a folder. Make sure we have a 'reportSingleFile()' and 'reportDirectory()' to handle different report formats for single file vs directory.

See the important differences? A 'analyzeFile()' to hold all the different logic that will come later and a separate 'report' set of functions to handle output (that will probably change).

These extra functions are sign posts for the next developer that may have to make changes to your code. You have a place in the code to analyze a file, you have a separate place to report things.

1

u/boomer1204 24d ago

This big time. Writing psuedo code and breaking it down into like every little step really really helped me when I was first starting out and got. my first job

1

u/FatDog69 24d ago

It's not popular in these days of 'vibe coding' but the thing that separates a new grad from an experienced developer is blocks or libraries of code that do a few related, important things and nothing else. It needs to be clear to the Next developer where error checking is done, where data hygiene is done, where the constantly changing business rules live, etc.

You don't become an expert until you have had to go in and modify existing code for months at a time. You will rarely write brand new programs in your professional capacity but you will come in and fix/modify existing code daily. How your code looks to the next developer is important.

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/BoomNeo 24d ago

I think you have a good thought process. Here's a dumb question, would recommend writing down each simple step on paper as a good way to convey my thoughts on how to solve the problem?

1

u/BrannyBee 24d ago

Personally yes 100%. I kept a white board in my desk for the longest time, and only stopped using it after buying a tablet that I use. If I'm ever not confident that i 100% know what to code start to finish, I draw it out with basically short hand and pseuodo code.

Ive been told Im a really fast coder, but it only looks that way if you look at my IDE. If I have an hour to solve a problem, im drawing pictures with arrows and different colors to indicate certain things for the first 45 minutes, and then I start typing. At my level, Ive done certain things and see certain patterns thousands of times, so they're memorized and I dont need to do that anymore, but the second my typing slows down and I feel lost I stop coding and start drawing my little pictures.

Along with that comes practice. If written thousands of loops in Python, Im not thinking of the order things have to go or the syntax Python uses, all the brain power gets to be used on solving the problem. If you're coding, you dont want to waste brain power on solving the problem. If you're solving the problem, then dont waste any brain power on remembering syntax or how Python is written. Solve the problem without code, and you get to use 100% of your brain on solving the problem. Then when you code, you get to use 100% of your brain on the code.

If you're given a problem and the first thing you do is start coding, half your brain is working on one thing and half is working on another. You're probably way smarter than I am, Im a fucking idiot. But I promise you that if I use 100% of my dumb brain, Ill seem much smarter than you if you're only using 50% of your brain.

Closing the IDE and buying a white board with some colored markers is a cheat code imho. Some people "graduate" from using a white board for every problem and can visualize the flow of a program, others have a big white board in their fancy office at Google. Both of them are doing the same thing, they're working out the problem before they even think about the code. Some people like me have frantic drawings with seemingly random arrows drawn everywhere that only I can understand, others use a very specific pseudo code that makes it very easy to "translate". Experiment a little bit and find what works for you. I draw boxes around "data" and functions are circles, when use red when Im not sure if theres more digging to be done. Try a bunch of stuff and see if your method can explain the entire program to a non-developer. If they can understand it, then there's a good chance a conputer can understand it

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.

  1. You are only changing prevCaracter inside the conditional. It needs to be updated regardless of condition (unconditionally)
  2. You missed the part of "two or more new line characters (\n) in a row." - you count as soon as there are two new line characters, yet, what if there is a third? You would count this one as a new paragraph, where it isn't one.
  3. You also missed: "New lines at the start of the file should be ignored."

Personally, I would see this as a typical parsing approach: a finite state machine.

  1. My state machine would start reading the file in "init" state. It reads until the first "non new line" character appears.
  2. The next state would be "in paragraph - waiting for new line" - here, I would keep reading characters until the first "new line" character.
  3. The next state would be "in new line - waiting for start of next paragraph" where I would keep reading and counting only new line characters until a "non new line" character arrives - at which point I would check the count of new line characters and depending on that (>=2) increase the paragraph count and go back to the "in paragraph" state (2)

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.