0

I have written the following code to produce pascal-triangle like pattern for three different heights. Each time, a different character is used to get the pattern. I am able to get the ones with '*' and '&', but the second call for printing with '=' never gets invoked. So, the corresponding pattern is missing on the screen. Tried to debug by interleaving input() statement between the three calls, but of no avail. Please help.

def draw_triangle(pattern_values):

    def draw(ht, ch):
        for i in range(1, ht+1):
            print('{txt:^{wid}}'.format(txt=i*(ch+' '),wid=2*ht))

    draw(pattern_values[0], pattern_values[1])
    yield pattern_values

    while True:
        pattern_values = yield pattern_values
        draw(pattern_values[0], pattern_values[1])

pattern_series = draw_triangle([10, '*'])
next(pattern_series)
pattern_series.send([12, '=']) # This does not produce any output
pattern_series.send([14, '&'])
Seshadri R
  • 1,192
  • 14
  • 24
  • You should know that **yield** working similar as **return**. Except one thing: it returns generator instead of result. So *code after your first yield will never be run*. – Vasiliy Rusin Sep 22 '17 at 03:39
  • No. Then, I should not have got a triangle printed with '&'. But, I do get this besides the starting one with '*'. To generate a series of odd numbers ad infinitum, you can use a next statement followed by send. The generator will have a simple yield followed by one inside an infinite loop (while True) to accomplish this. – Seshadri R Sep 22 '17 at 03:48

1 Answers1

1

So you can just use this fuction as generator without initial values.

def draw_triangle(pattern_values=""):

    def draw(ht, ch):
        for i in range(1, ht+1):
            print('{txt:^{wid}}'.format(txt=i*(ch+' '),wid=2*ht))

    while True:
        pattern_values = yield pattern_values
        draw(pattern_values[0], pattern_values[1])

pattern_series = draw_triangle()
next(pattern_series)
pattern_series.send([10, '*'])
pattern_series.send([12, '=']) # This does not produce any output
pattern_series.send([14, '&'])
Vasiliy Rusin
  • 955
  • 6
  • 13
  • Yes, it produces the desired output. But, may I know what happens to next(pattern_series) and the corresponding yield statement? Why don't I get the print() statement's output corresponding to this? – Seshadri R Sep 22 '17 at 04:34
  • @SeshadriR, [This](https://stackoverflow.com/questions/19892204/send-method-using-generator-still-trying-to-understand-the-send-method-and-quir) is good explanation of this behavior. – Vasiliy Rusin Sep 25 '17 at 22:04