Pattern I'm trying to print is upside down

Viewed 63

Ok, I know this is super basic, and I probably should know what i'm doing here, but I'm stuck trying to flip this dang triangle. I keep getting confused with which variable I need to swap. This triangle starts with a single star and iterates down to form a full triangle. I need it to start big and work down to a single star. Somewhat like a funnel. Please and thank you, and please again.

Here's the code:

def up_arrow(arrow):
    char = arrow
    index = 0
    size = 6
    while index < size:
        spaces = " " * (6 - index)
        print(spaces + char)
        char += arrow * 2
        index += 1
1 Answers

In your loop, you keep increasing index by 1, until it reaches 6 and you keep increasing the length of char with two arrows, so that it ends at 6*2-1 arrowss. So, have you tried reversing that?

Start with a string of size*2-1 arrows, set index to size, decrement index every iteration, and keep going until you reach 0, as well as removing two characters from char every time:

def down_arrow(arrow):
    size = 6
    index = size
    char = arrow * (size * 2 - 1)
    while index > 0:
        spaces = " " * (6 - index)
        print(spaces + char)
        char = char[2:]
        index -= 1


down_arrow('.')

Note that I've tried to stick with the way you wrote it originally, there's more optimal ways to achieve this.

For example, while still just printing this type of arrow, this function can do both:

def arrow(ch, size, up=True):
    for i in range(1, size + 1) if up else range(size, 0, -1):
        print(' ' * (size - i) + ch * (2 * i - 1))


arrow('.', 6)
arrow('.', 6, up=False)
Related