How to Build a Square in Python

The challenge

I will give you an integer. Give me back a shape that is as long and wide as the integer. The integer will be a whole number between 1 and 50.


n = 3, so I expect a 3×3 square back just like below as a string:

+++ +++ +++
Code language: Bash (bash)

The solution in Python

Option 1:

def generateShape(i): return (i-1)*(('+'*i)+'\n')+('+'*i)
Code language: Python (python)

Option 2:

def generateShape(integer): return '\n'.join('+' * integer for i in range(integer))
Code language: Python (python)

Option 3:

def generateShape(n): string = "" for row in range(n): for col in range(n): string += '+' string += '\n' return(string[:-1])
Code language: Python (python)

Test cases to validate our solution

@test.describe("Fixed Tests") def basic_tests(): test.assert_equals(generate_shape(3), '+++\n+++\n+++') test.assert_equals(generate_shape(8), '++++++++\n++++++++\n++++++++\n++++++++\n++++++++\n++++++++\n++++++++\n++++++++')
Code language: Python (python)
Notify of
Inline Feedbacks
View all comments