To create the print_grid function, my idea is to declare a string as empty and adding two types of of other strings("+---" and "| ") to it. Finally i want to print it out. But I am not sure how to print alternate grid lines and char line. Would you please give me some hints along with following code modification?
def print_grid(puzzle: str) -> None
"""
Displays the puzzle in a user-friendly format
Examples of calling print grid:
>>> print_grid("nevagonagiveu up")
+---+---+---+---+
| n | e | v | a |
+---+---+---+---+
| g | o | n | a |
+---+---+---+---+
| g | i | v | e |
+---+---+---+---+
| u | | u | p |
+---+---+---+---+
Parameters:
puzzle (str): the selected puzzle words in a string.
Returns:
none
"""
p = len(puzzle)/sqrt(len(puzzle))
result1 = ""
for i in range(p):
result1 += "+---"
return result1
result2 =""
for j in range (p):
result2 += "| "
return result2
print
I have come up with the following code:
import math
def print_grid(puzzle):
width = int(len(puzzle) / math.sqrt(len(puzzle)))
decorator = "+"
for i in range(width):
decorator += "---+"
print(decorator)
for j in range(0, len(puzzle), width):
line = "|"
for k in range(j, j + width):
line += f" {puzzle[k]} |"
print(line)
print(decorator)
It does not work for all string lengths, but your question was about printing alternate lines, so I am posting it as a temporary solution.
This will do the required job. (I imported math lib for ceil() but if that is not allowed too then you can put a simple condition for getting ceiling of the decimal):
import math
def print_grid(puzzle):
list1=[' ']+[' '+item+' |' for item in puzzle]
length=len(puzzle)
iter_=math.ceil(math.sqrt(length))
fallout=(iter_)**2-length
if fallout:
list1=list1+[' |']*fallout
for i in range(0,length,iter_):
print('+---'*(iter_)+'+')
pp=''.join(list1[i+1:i+iter_+1])
print('|'+ pp)
print('+---'*(iter_)+'+')
print_grid('nevagonagiveu up')
Output:
+---+---+---+---+
| n | e | v | a |
+---+---+---+---+
| g | o | n | a |
+---+---+---+---+
| g | i | v | e |
+---+---+---+---+
| u | | u | p |
+---+---+---+---+
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.