Neighborhood with most restaurants

The code I used gave me the expected result. Unfortunately I received “Your code did not pass our answer checks”

Screen Link:

My Code:

from csv import reader
file = open("restaurants.csv")
reader = reader(file)
rows = list(reader)
file.close()

neighborhood = {}
for r in rows[1:]:
    n = r[1]
    if n in neighborhood:
        neighborhood[n] += 1
    else:
        neighborhood[n] = 1
        
maximum = 0
most_restaurants = None
for k in neighborhood:
    if neighborhood[k] > maximum:
        maximum = neighborhood[k]
        most_restaurants = k

I expected to see my answer validated, but it is not. Can someone please explain me why?

2 Likes

Hello @blondel.md,

Cases where a function name such as reader is used as a variable name is not advisable in python programming.

I would rather assign the output from the reader(file) to a different variable name which is not a keyword nor a function name such as :

read_file = reader(file)
rows = list(read_file)
5 Likes

@doyinsolamiolaoye You’re right. Thanks for pointing that out. Now the result is validated.

Can anyone breakdown the maximum=0 variable and the most_restaurants =None for me.
I want to understand the concept and why its used

Hi @chautran0729,

Unlike some other programming languages, Python doesn’t allow declaring variables without values. So in this case, we are just using 0 and None as a means to make the python interpreter happy. We can set both variables to None or both to 0. However, it totally depends on the situation, sometimes it is better to use 0 as the initial value, sometimes it is best to use None.

For example, in case we are planning to increment the value or performing arithmetic operations on it, it would be best to use 0. otherwise, we will get errors like this:

>>> a = None
>>> a += 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +=: 'NoneType' and 'int'

On the other hand, this error can be useful to prevent incorrect results. For example in the below scenario we forgot to call the measure_temperature function:

>>> def measure_temperature():
...     return 37
... 
>>> celsius = 0
>>> fahrenheit = celsius * (9/5) + 32
>>> print(fahrenheit)
32.0
>>> def measure_temperature():
...     return 37
... 
>>> celsius = None
>>> fahrenheit = celsius * (9/5) + 32
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for *: 'NoneType' and 'float'

Best,
Sahil

3 Likes

Thank you, this worked for me too - strange though, because for all of the previous practice problems involving the csv.reader method, I’ve saved the file to a var named “reader” and this hasn’t been an issue.