How to print a string based on width height and depth

Question:

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.

Asked By: Iplaysoccer

||

Answers:

out = ''
for i, ch in enumerate(s):
    if i % w == 0:
        out += 'n'  # line separator
    if i % (w * h) == 0:
        out += 'nn'  # 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.

Answered By: J_H

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.

Answered By: Michael M.

One line solution

'''
@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]+"nn") for i in range(len(s))]))

Demo

print_format(".X.XXX.X..v.vXv.v.",3,3)
  • Output
.X.
XXX
.X.

.v.
vXv
.v.

P.S.

  • The one-line solution uses height and weight instead of height and depth cause it is more straightforward. However if needed, weight could be calculated through depth.
  • The one-line solution also advanced in both memory and run-time performance.
Answered By: Xin Cheng
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.