TypeError, I know why but not how!?

A.T.Hofkamp hat at se-162.se.wtb.tue.nl
Thu Jul 10 08:39:39 CEST 2008

On 2008-07-10, ssecorp <circularfunc at gmail.com> wrote:
> def validate(placed):
>     student = round(random.random()*401)
>     if student in placed:
>         validate(placed)
>     else:
>         placed.append(student)
>         return student, placed
> def pair(incompatibles, placed):
>     student1, placed = validate(placed)
>     student2, placed = validate(placed)
>     pair1 = (student1,student2)
>     pair2 = (student2,student1)
>     if (pair1 or pair2) in incompatibles:
>         placed.remove(student1)
>         placed.remove(student2)
>         pair(incompatibles, placed)
>     else:
>         return pair1, placed
> def generateList(dormlist,incompatibles, placed, rooms):
>     if len(dormlist) < (rooms + 1):
>         room, placed = pair(incompatibles, placed)
>         dormlist.append(room)
>         generateList(dormlist,incompatibles,placed,rooms)
>     else:
>         return dormlist

In each of the above functions, the 'if' part has no 'return', while the 'else'
part has. You should add a 'return' statement at every exit from the function.

If you don't expect the program to get at some point, you should add a check

raise ValueError("This shouldn't happen")

you'd be surprised how often 'impossible' things do happen (and writing such a
statement costs less than a minute, and saves you many hours debugging).

Some people so as far as demanding that there is exactly 1 return statement,
namely at the bottom of the function. While I don't favor that approach, it may
help you in always returning a value.

BTW: For performance and readability, you may want to replace your direct
recursion with iterations.


More information about the Python-list mailing list