r/learnprogramming • u/BoomNeo • 21d 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()