Can anyone debug my program ? | Coursera Community
Coursera Header
Solved

Can anyone debug my program ?


Badge +3
code:
name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
name = "mbox-short.txt"
handle = open(name)
text = handle.read()



words = list()
for line in handle:
if not line.startswith("From:"): continue
line = line.split()
words.append(1)



counts = dict()
for line in handle:
words = line.split()
for word in words:
counts[word] = counts.get(word, 0) + 1


maxvalue = None
maxkey = None

for key,val in counts.items():

if maxvalue is None or val > maxvalue :
maxvalue = val
maxkey = key



print(maxkey,maxvalue)
icon

Best answer by hamster 12 May 2019, 01:28

Instead of telling you what the problem is, instead I'll try to help you solve it yourself.


So, the last line of your code is:
code:
 print(maxkey,maxvalue)


and we can see that the code returns (none, none).

this means that the following code block is not changing the values:

code:
for key,val in counts.items():

if maxvalue is None or val > maxvalue :
maxvalue = val
maxkey = key


How can we figure out what is going on? Well, one thing we can do is add additional print statements in order to see whats going on at different stages of the problem.

code:
debug_counter = 1

for key,val in counts.items():
print(debug_counter key, val, maxvalue, maxkey)
if maxvalue is None or val > maxvalue :

maxvalue = val
maxkey = key
debug_counter += 1


So now when (if) we enter the for-loop a lot of useful debugging info gets generated.

BUT what if we don't see any data being printed out? Well that would mean we are not entering the for-lop (which must mean counts.items() is empty and thus the error must be even earlier in the program).
View original

3 replies

Userlevel 2
Badge +2
what is the error you getting? possibly you can provide a screenshot.
Badge +3

Userlevel 5
Badge +4
Instead of telling you what the problem is, instead I'll try to help you solve it yourself.


So, the last line of your code is:
code:
 print(maxkey,maxvalue)


and we can see that the code returns (none, none).

this means that the following code block is not changing the values:

code:
for key,val in counts.items():

if maxvalue is None or val > maxvalue :
maxvalue = val
maxkey = key


How can we figure out what is going on? Well, one thing we can do is add additional print statements in order to see whats going on at different stages of the problem.

code:
debug_counter = 1

for key,val in counts.items():
print(debug_counter key, val, maxvalue, maxkey)
if maxvalue is None or val > maxvalue :

maxvalue = val
maxkey = key
debug_counter += 1


So now when (if) we enter the for-loop a lot of useful debugging info gets generated.

BUT what if we don't see any data being printed out? Well that would mean we are not entering the for-lop (which must mean counts.items() is empty and thus the error must be even earlier in the program).

Reply