Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using print() inside recursive functions in Python3

I am following the book Introduction to Computing Using Python, by Ljubomir Perkovic, and I am having trouble with one of the examples in recursion section of the book. The code is as follows:

def pattern(n):
    'prints the nth pattern'
    if n == 0:    # base case
        print(0, end=' ')
    else:    #recursive step: n > 0
        pattern(n-1)         # print n-1st pattern
        print(n, end=' ')    # print n
        pattern(n-1)         # print n-1st pattern

For, say, pattern(1), the output should be 0 1 0, and it should be displayed horizontally. When calling the function pattern(1), nothing prints out, however. But if this is followed by a print statement without arguments, then the results are displayed.

>>>pattern(1)
>>>print()
0 1 0

If I remove the end argument of the print() functions inside the recursive function, I get correct output (albeit it displays it vertically):

>>> pattern(1)
0
1
0

This makes me think that the recursive code itself is correct (plus I confirmed it was with the source provided by the book's website, and with the errata sheet). I am not sure, however, why the print statement isn't printing the output as the functions run, if the end parameter is included. Any help would be greatly appreciated.

like image 459
gos1 Avatar asked Apr 25 '13 20:04

gos1


People also ask

Can you use print in a function Python?

Python print() FunctionThe print() function prints the specified message to the screen, or other standard output device. The message can be a string, or any other object, the object will be converted into a string before written to the screen.

What is recurse in Python?

Python also accepts function recursion, which means a defined function can call itself. Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result.

How recursive functions work in Python?

Recursive Functions in Python A recursive function is a function defined in terms of itself via self-referential expressions. This means that the function will continue to call itself and repeat its behavior until some condition is met to return a result.


1 Answers

The print function doesn't always flush the output. You should flush it explicitly:

import sys

def pattern(n):
    'prints the nth pattern'
    if n == 0:    # base case
        print(0, end=' ')
    else:    #recursive step: n > 0
        pattern(n-1)         # print n-1st pattern
        print(n, end=' ')    # print n
        pattern(n-1)         # print n-1st pattern
    sys.stdout.flush()

Note that on python3.3 print has a new keyword argument flush that you can use to forcibly flush the output(and thus avoid using sys.stdout.flush).


On a general note I'd decouple the output from the pattern, doing, for example:

def gen_pattern(n):
    if n == 0:
        yield 0
    else:
        for elem in gen_pattern(n-1):
            yield elem
        yield n
        for elem in gen_pattern(n-1):
            yield elem

def print_pattern(n):
    for elem in gen_pattern(n):
        print(elem, end=' ')
     sys.stdout.flush()

This makes the code more flexible and reusable, and has the advantage of calling flush only once, or you could also call it once every x elements(actually I believe print already does this. It flushes if trying to write many characters on the screen).

In python3.3 the code could be simplified a little:

def gen_pattern(n):
    if n == 0:
        yield 0
    else:
        yield from gen_pattern(n-1)
        yield n
        yield from gen_pattern(n-1)
like image 93
Bakuriu Avatar answered Sep 29 '22 13:09

Bakuriu