How to Build a Square in Python

0 min read 111 words

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.

Example

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

+++
+++
+++

The solution in Python

Option 1:

def generateShape(i):
    return (i-1)*(('+'*i)+'\n')+('+'*i)

Option 2:

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

Option 3:

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

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++++++++')
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags