Skip to content Skip to sidebar Skip to footer

Making A Hollow Box In Python To These Specifications?

I'm to 'Write a python program that prompts the user to input a positive integer n. The program then prints a hollow rectangle with n rows and 2*n columns. For a example an input o

Solution 1:

My solution:

# Response to StackOverflow post:# Making a hollow box in Python# The multiplication operator (*) is the same as repeated# concatenation when applied to strings in Python.# I solved the problem by creating an array with N elements# and gluing them together (str.join(array)) with newline# characters.# I trust you're already familiar with string formatting and# concatenation, but in case you're not, please feel free to# ask for clarification.defmain():
    n = int (input("Enter an integer between 1 and 15"))
    box = "\n".join(["*"*(2*n)] + ["*%s*" % (" "*(2*n-2))]*(n-2) + ["*"*(int(n>1)*2*n)])
    print (box)


if __name__ == '__main__':
    main()
    input() # Prevents the console from closing immediately

As for your solution. it seems to me like the loop conditions are messed up; the column and row loops are in reverse order and the argument to range() in the column loop should be 2*n (since that's the number of columns intersecting each row). You should also take a second look at the conditions in the first print statement.

Solution 2:

The code should be like:

line =  "*"*(2*n)
print line
s  = "*" + " "*(n-2) + "*"for i in range(n-2):
    print s
print line         

The line:

"*"*(2*n)

specifies a string of "*", repeated 2*n times. You wanted 2*n column right.. This prints 2*n "*"

Solution 3:

defmake_box():       
    size = int(input('Please enter a positive integer between 1 and 15: '))
    for i inrange(size):
        if i == 0or i == size - 1:
            print("*"*(size+2))
        else:
            print("*" + " "*size + "*")


make_box()

Output: (n=15)

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

Solution 4:

Code:

def printStars(length):
    l = ['*'*length]
    l+= ['*' + ' '*(length-2) + '*'] * (length-2)
    l+= ['*'*length]

    return l

if __name__=='__main__':
    print('\n'.join(printStars(15)))

Output:

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

Hope this helps :)

EDIT:Fixed Some Formatting

Solution 5:

My solution is more elementary. Please consider it :

row = abs(eval(input('Enter row: ')))
col = abs(eval(input('Enter column: ')))
print ('*'*col)

for i inrange (row-2):
      print ('*'+' '*(col-2)+'*')
print ('*'*col)

Post a Comment for "Making A Hollow Box In Python To These Specifications?"