Doctest expecting True but keeps on receiving False

94 views Asked by At

Ok so I need to pass the following doctests:

"""
Does it work on files where no error checking is needed on the fields

>>> sumRows("rows1.csv") == {'tim': 36.0, 'bob': 11.0, 'anna': 54.0}
True

Does it ignore headers if requested?

>>> sumRows("rows1.csv", header=True) == {'tim': 36.0, 'anna': 54.0}
True

Does it work on files with empty fields or fields which aren't numbers?

>>> sumRows("rows2.csv") == {'tim': 24.0, 'bob': 11.0, 'anna': 13.0}
True
"""

I have created this piece of code which in my eyes looks fine, however it just refuses to return "True" during the doctests and will only return "False"

def sumRows(filename, header=False):
x = {}
import csv
rdr = csv.reader(open(filename))
for l, row in enumerate(rdr):
    if header == True and l == 0:
        pass
    else:
        amount = 0
        for num in row[1:0]:
            if num.isdigit():
                amount += int(num)
            x[row[0]] = amount
return x

Any idea of what is the problem?

2

There are 2 answers

1
Fumbo On

Seems like this line :

for num in row[1:0]:

Will always do nothing, because you try to iterate through an empty list.

list[1:0] # from position 1 (included) to 0 (excluded) is always []

0
dirn On

Doctests don't compare values, they compare strings.

While the following comparison is True, as a doctest it will evaluate to False

>>> {'bob': 11.0, 'anna': 54.0, 'tim': 36.0} == {'tim': 36.0, 'bob': 11.0, 'anna': 54.0}

This can happen because dicts are unordered. In order to perform this comparison as a doctest, you need to store the values in an ordered type.

>>> list(sorted(sumRows('rows1.csv').items())) == list(sorted({{'tim': 36.0, 'bob': 11.0, 'anna': 54.0}}.items()))
True