I've just started picking up Python for my new job, and I've found the best way for me to practice new syntax is to tackle old problems in a new language. In this post, I'll explore various ways to solve the Staircase Problem in Python.
The Problem
In this problem, we are given a number of levels, n, and are asked to print out a staircase with n levels ascending from left to right, like this:
staircase(4)
// Result:
#
##
###
####
If you haven't already. check out my original post for more discussion of the problem and general strategies to tackle this problem. Rather than repeat, I'll just focus on my Python solutions in this post.
String Repeat Strategy and Solution
My first strategy was to build a single loop, and print out a string of repeated characters at the end of each iteration. Python makes it really straightforward to repeat characters in a string using the *
symbol.
def staircase(n):
for i in range(1,n+1):
print(' '*(n-i)+'#'*(i))
Iteration Strategy
Another option is to use an iteration strategy with nested loops to build out a staircase based on a character's position in each column and row. The range()
function in Python makes it really easy to set up the nested loops for rows and columns.
def staircase(n):
for row in range(n):
string = ""
for col in range(n):
if col <= row:
string += "#"
else:
string = " " + string
print(string)
Recursion Strategy
This can also be solved recursively. Although this is certainly not a very straightforward solution, it did give me a chance to practice the Python syntax for conditional logic and ternary statements. While this code produced the correct output in a repl sandbox, it does not pass the HackerRank challenge. I believe this is due to the high runtime.
def staircase(n, row=0, string=""):
if n == row:
return
if n == len(string):
print(string)
return staircase(n, row+1)
add = "#" if len(string) <= row else " "
staircase(n, row, add+string)
How would you solve this in Python? What are your favorite Python syntax tips and tricks for solving code challenges in Python?
Top comments (2)
An alternative using
rjust
:What a perfect method for this! Thank you for introducing me to
rjust()
.