dubber
dubber

Reputation: 21

How do I save the value of an object into another variable only at a specific instance of a for loop?

I am currently working on a code golf problem where I have to output multiple trees of varying sizes using an asterisk. I have gotten down everything but one problem I have is that there must be a trunk at the bottom.

reference

    *
   ***
  *****
 *******
*********
    *

The row at the bottom must be identical to the one at the top. I created a for loop for my output, which prints all lines from the top to bottom. I wanted to know if I could return the value of my output variable at the beginning to reuse at the bottom.

If this is not possible, what else could I do as an alternative?

Please do not answer with code, as I would like to complete it by myself. I would rather be answered with advice on what to learn.

Edits: General,unoptimized rundown of my code

def myLoop(l,character):
    global output
    for i in range(l):
        output += character

def tree(length):
    global output
    o = ''
    asterisk = 1
    while length>-1:
        myLoop(length, ' ');myLoop(asterisk, '*')
        o += '\n'
        length -= 1;asterisk += 2
        print(o)

Upvotes: 0

Views: 146

Answers (1)

kosciej16
kosciej16

Reputation: 7128

You have few options there.

  1. Create a function that gets e.g. row number and return value which should be printed. In that case you could call it twice with row number = 1
  2. Remember that value in different variable. So it would be something like
for i in range(10):
    row = <some calculations>
    if i == 0:
        first_row = row

Upvotes: 1

Related Questions