Trevor Murphy - 9 months ago 25

Python Question

I have been working on this code for about a day now. A few hours on just this one part it keeps saying I have an attribute error on line 26. Unfortunately that is all the information I have. I have tried countless different ways to fix it and have searched many websites/forums. I appreciate any help. Here is the code:

`import itertools`

def answer(x, y, z):

monthdays = {31,

28,

31,

30,

31,

30,

31,

31,

30,

31,

30,

31}

real_outcomes = set()

MONTH = 0

DAY = 1

YEAR = 2

#perms = [[x, y, z],[x, z, y],[y, z, x],[y, x, z],[z, x, y],[z, y, x]]

possibilities = itertools.permutations([x, y, z])

for perm in possibilities:

month_test = perm[MONTH]

day_test = perm[DAY]

#I keep receiving an attribute error on the line below

* if month_test <= 12 and day_test <= monthdays.get(month_test):

real_outcomes.add(perm)

if len(realOutcomes) > 1:

return "Ambiguous"

else:

return "%02d/%02d/%02d" % realOutcomes.pop()

Answer

The problem is that `monthdays`

does not have a `get()`

method, and that is because `monthdays`

is a `set`

, not a `dict`

as you probably expect.

Looking at your code it seems that a list or tuple would be appropriate for `monthdays`

. A set is not useful because it is not ordered and can not include duplicates:

```
monthdays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
```

and then:

```
if month_test < len(monthdays) and day_test <= monthdays[month_test]:
```

Your code suggests that you eventually will want to handle years. In that case you should look at the `calendar`

module. It provides function `monthrange()`

that gives the number of days for a given year and month, and it handles leap years.

```
from calendar import monthrange
try:
if 1 <= perm[DAY] <= monthrange(perms[YEAR], perm[MONTH])[1]:
real_outcomes.add(perm)
except ValueError as exc:
print(exc) # or pass if don't care
```