Home > Enterprise >  How to print a string based on user input of height and width
How to print a string based on user input of height and width

Time:10-13

I’m sure this is a simple question, but my professor is terrible at explaining things and since I’m new to computer science I need help!! The assignment is to make a function that prints/returns a string given by the user in different formats based on their selected height and width.

for example, if the user string is ‘<..vvv..^’ and the given width is 3 and the given height is 3, it should print out:

     <..
     vvv
     ..^

Another example for the same function:

     >>>the_function(‘<.vv.v.v’,2,4)
     <.
     vv
     .v
     .v

Something else would be to make another function. This one takes a string, a random integer(x), an integer of width and an integer of height and returns the row of (x) so for example:

     >>>another_function(‘.<.>>>..v’, 1, 3, 3)
     ‘>>>’

Another example for the same function:

     >>>another_function(‘.v>..>..’, 0, 2, 8)
     ‘.v’

I have absolutely no idea how to do this or even how to go about searching up things that might help. Any help would be so so appreciated! Thank you!!

CodePudding user response:

I'll focus on the reshape function:

  • We import numpy because it has built-in reshaping functionality for arrays
  • Split the input string to a list of characters
  • Convert list of characters to array
  • Reshape array based on x,y params (the shape options depend on the object's size btw)
  • Loop through the top-level array objects
  • Rejoin each object to a string
  • Print each string
import numpy as np

def reshape_string(input_string,x,y):
    new = np.array(list(input_string)).reshape((x,y))
    for x in new:
        print(''.join(x))

CodePudding user response:

You can use a simple loop:

def the_function(s, w, h):
    for i in range(0, len(s), w):
        print(s[i:i w])

the_function('<.vv.v.v',2,4)

Output:

<.
vv
.v
.v

Note that h is not really needed as once you know the string length and desired with, the height is fixed.

You could however use this parameter to define a maximum number of lines to print:

def the_function(s, w, h):
    for n, i in enumerate(range(0, len(s), w)):
        if n>=h:
            break
        print(s[i:i w])

the_function('<.vv.v.v', 2, 3)

Output:

<.
vv
.v
  • Related