Reputation: 97
How can I print a string based on the width height and depth given by the user? In other words: how can I write a function that prints/return a string given by the user in different formats based on their selected width, height, and depth?
For example, if the user string is .X.XXX.X..v.vXv.v.
and the given width is 3, the given height is 3, and the given depth is 2 it should print out:
.X.
XXX
.X.
.v.
vXv
.v.
Where the depth determines how many “blocks” of code there are (separated by a space).
All I can think of is:
def print_string(s, w, h, d):
for i in range (0, int(len(s)/D), w):
print (s[i:i+w])
for i in range(0, len(s), D):
print (“ “)
for i in range (int(len(s)/D), len(s), w):
print(s[i:i+w])
But that very much does not work.
Upvotes: 0
Views: 678
Reputation: 20611
out = ''
for i, ch in enumerate(s):
if i % w == 0:
out += '\n' # line separator
if i % (w * h) == 0:
out += '\n\n' # block separator
out += ch
print(out.strip())
Or, coming at it the other way round:
for z in range(d):
for y in range(h):
for x in range(w):
i = x + w * (y + (h * z))
print(s[i], end='')
print('')
print('\n')
We call this Horner's method.
It works out to an index i
of h w z + w y + x
;
1st term gets us to start of block,
2nd term to start of line,
and 3rd term is position within that line.
Upvotes: 0
Reputation: 1458
'''
@parm s: string to printed
@parm h: height of each chunk
@parm w: weight of each chunk
'''
def print_format(s:str, h:int, w:int):
print("".join([s[i] if (i+1)%w!=0 else (s[i]+"\n" if (i+1)%(w*h)!=0 else s[i]+"\n\n") for i in range(len(s))]))
print_format(".X.XXX.X..v.vXv.v.",3,3)
.X.
XXX
.X.
.v.
vXv
.v.
P.S.
height
and weight
instead of height
and depth
cause it is more straightforward. However if needed, weight
could be calculated through depth
.Upvotes: 0
Reputation: 11090
You can use nested loops. Loop over every 2D block of text, then over every line for each 2D block. Like this:
def print_string(s, w, h, d):
# per block
for i in range(0, w * h * d, w * h):
block = s[i:i + (w * h)]
# per line
for j in range(0, w * h, w):
print(block[j:j + w])
print("")
txt = input("input: ")
print_string(txt, 3, 3, 2)
Example run:
input: .X.XXX.X..v.vXv.v.
.X.
XXX
.X.
.v.
vXv
.v.
Upvotes: 1