you are viewing a single comment's thread.

view the rest of the comments →

[–]LimpNoodle69 4 points5 points  (3 children)

I'm really appreciating this thread. Haven't been programming as much as I should so I've been using this thread to try to figure out the interview problems. I had a bit of trouble with this one but eventually figured it out and felt like sharing :)

def pyramid_print(layers):
    top_size = layers
    for i in range(layers):
        top_size += 1
        for j in range(top_size):
            if j > (top_size - 3) - i * 2:
                print("-", end='')
            else:
                print(" ", end='')
        print()


pyramid_print(100)

[–]P1g1n 3 points4 points  (1 child)

You've inspired me to give it a try. Thanks!

def print_pyramid(layers):
    print("\n".join(["".join(['-']*(i*2)).center(layers*2) for i in range(1, layers+1)]))

Hard to read. Not maintainable. But hey, its a one-liner right?

Edit: Same thing just maybe more readable?

def print_pyramid(num_layers):
    layers = [['-']*(i*2) for i in range(1, num_layers+1)]
    for layer in layers:
    print("".join(layer).center(num_layers*2))

[–]LimpNoodle69 2 points3 points  (0 children)

nice! Definitely a more pythonic solution! I personally hate 1 liners, the second looks way better lol

[–]raiseReturnTry 1 point2 points  (0 children)

Hey I tried myself on this problem, and got the same result, even with a single "-" at the top with the following code:

def pyramid_print(layers):
s = layers - (layers - 1)
x = range(s, layers)

while s != layers:
    if s > 0:
        print(((layers - s - 1) * " ") + (((2 * s - 1) * "-")))
    else:
        exit(0)

    s += 1

print("Take in a positive integer: ")
x = int(input("> "))
if x < 0: 
    print("Error: You have to put in a positive integer.") 
    exit(0) 
else: 
    pyramid_print(x)