开发者

Recursion, calling a function using input

I'm working on some recursion stuff. I've created some functions in the vein of the twelve days of xmas, but I can't think of a way to call a function using input. I'll give an example:

def day1():
    print 'A Partridge in a Pear Tree'
def day2():
    print '2 Turtle Dov开发者_StackOverflowes'
    day1()
def day3():
    print '3 French Hens'
    day2()

I tried going the route of using if statements inside a function such as

def DaysOfXmas(n):
    if n == 1:
        day1()
    if n == 2:
        day2()
    if n == 3:
        day3()

But this feels like a horrible and messy way of doing it. Any suggestions?


days = ['A Partridge in a Pear Tree',
        '2 Turtle Doves',
        '3 French Hens']

def sing(n=0):
    print days[n]
    try:
        sing(n+1)
    except IndexError:
        return

That's a simple example of looping with recursion. Don't do it in Python except to understand it, though. That function is much easier to write (and more efficient) with a for loop.


Well, you could do globals()['day%d' % n](), but that's even more horrible and messy.

Just put the functions into a collection. A list, for instance, or a dict if you need sparse or non-integer keys. day_funcs = [day0, day1, day, day3] (day0 should propably be a placeholder, a non-callable works if you check the input before blindly getting the item and calling it - if not, the user gets an ugly error that seems totally unrelated) and use day_funcs[n]() in the dispatcher. You can make this more DRY in several ways: The one that requires the last typing (but would also fall down for other naming schemes) would be putting the functions (and only those) into a seperate module and, after importing them, defining day_funcs = sorted(inspect.getmembers(the_module, isfunction)).


The idea behind recursion is that you have one consistent set of operations that you perform on any arbitrary input, and you set one or more base cases that will perhaps do something special, and end the recursive call.

If you want to do something different for 12 input values, either consider using a map of output for the given input (then calling the function again with a decremented input value), or you have 12 base cases.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜