Click here to Skip to main content
15,305,577 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I try to stack n blocks by increasing them by 1, 2, 3, 4, 5... in order from the top.
If 12 blocks are given, you can build a 4-story tower with 10 (1+2+3+4) blocks, and the remaining 3 blocks are discarded. (15 blocks required to build up to 5th floor (1+2+3+4+5))
When building a tower with n blocks, write a function that tells how many floors the tower can be. Enter the number of blocks into the function and output the correct answer.
I know how to solve it using a for statement, but I'm not sure how to fix it. Thank you for any advice or answers.

ex)

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


What I have tried:

Python
<pre lang="Python">
def block123(n):
    for i in range(1, n):
        for j in range(n-1-i):
            print(' ', end="")
        for j in range(1, i, 1):
            print("*", end="")
    print('')
Posted
Updated 16-Dec-21 20:06pm

1 solution

Start by indenting the final line one place more:
Python
def block123(n):
    for i in range(1, n):
        for j in range(n-1-i):
            print(' ', end="")
        for j in range(1, i, 1):
            print("*", end="")
        print('')
Tah way, it will be executed at the end of every trip round the outer loop rather than ones after the loop has ended.
Then look at the pattern it generates.
How many rows does it have for a given input? How many should it have?
Think about what your code does and what your assignment asks you to produce: for 12 blocks, you need four rows - and you haven't looked at that at all.

I'd start by ignoring the "pyramid" entirely, and get it printing the right number of rows first,
Then that works, start getting it to print the right number of stars.
When that works, I'd look at printing the right number of spaces at the start.

Focus on one thing at a time, and get it working and tested before you move on to another. It's a lot easier to do that than try to do the whole task at once!
This may help: How to Write Code to Solve a Problem, A Beginner's Guide[^]
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900