1

I'd like to create a single for loop using 2 variables, instead of a for loop and an external variable.

Is there a way to do something unpacking tuples with range?

Here is what I have:

space = height
for h in range(height):
    # code using both h & space

Here is the code I'm trying to improve:

# Get positive integer between 1 - 8
while True:
    height = int(input("Height: "))
    if height > 0 and height < 9:
        break

space = height  # Control space count

# Build the pyramid
for h in range(height):
    print(" " * (space - 1),"#" * (h + 1), end="")
    print(" ", end="")
    print( "#" * (h + 1), " " * (space - 1), end="")
    space -= 1

    print()  # Get prompt on \n
4
  • Since space depends decreases as h increase, why don't you just compute the offset, e.g. as height - h -1? Commented May 4, 2020 at 16:57
  • Isn't this a CS50 problem? Commented May 4, 2020 at 17:16
  • @MisterMiyagi - Interesting, I see how that could work. Then there would be just one variable. Thanks for pointing that out. Commented May 4, 2020 at 17:45
  • @agastya Yes, it is. I wanted to do something like C using 2 variables in a single loop. Commented May 4, 2020 at 17:54

1 Answer 1

4

You can use a second range object (from height to 0) and then zip to iterate both ranges at once:

# Get positive integer between 1 - 8
while True:
    height = int(input("Height: "))
    if height > 0 and height < 9:
        break

# Build the pyramid
for h, space in zip(range(height), range(height, 0, -1)):
    print(" " * (space - 1),"#" * (h + 1), end="")
    print(" ", end="")
    print( "#" * (h + 1), " " * (space - 1), end="")

    print()  # Get prompt on \n
Sign up to request clarification or add additional context in comments.

2 Comments

OK, 25 seconds faster than my same solution. Will delete it now.
I figured it should be possible to construct something like this, but I was not familiar with zip(). Thank you for pointing this out!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.