Combination Function Help

Dave Angel davea at davea.name
Wed Feb 12 13:38:15 EST 2014


 kjakupak at gmail.com Wrote in message:
> def choices(n, k):
>     if k == 1:
>         return n
>     if n == k:
>         return 1
>     if k == 0:
>         return 1
>     return choices(n - 1, k) + choices(n - 1, k - 1)
>     print ("Total number of ways of choosing %d out of %d courses: " % (n, k))
> 
> n = int(input("Number of courses you like: "))
> k = int(input("Number of courses you can register for: "))
> choices(n, k)
> 
> Changed it like you said, didn't work
> 

I see at least two problems with that code
:

The line with the print function will never get called, since it
 follows an unconditional return statement.  You shouldn't print
 there anyway,  just move it to top level,  after the two calls to
 input.  Don't forget to dedent it.

You don't use or save the return value of choices.  You should
 probably assign it to a name like combinations,  then print it on
 the following line.

The recursive function choices doesn't look right to me, but I'm
 not sure either way.  I have not tested it.

-- 
DaveA




More information about the Python-list mailing list