Reputation: 97
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!!
Upvotes: 1
Views: 574
Reputation: 1458
This solution advances in both memory and run-time performance compared with for-loop-check methods.
'''
@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('.vv.v.', 2, 3)
.v
v.
v.
Upvotes: 0
Reputation: 262484
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
For the other function, you just need to calculate the start position and print once. Here again the last parameter is useless:
def another_function(s, n, w, h):
print(s[n*w:(n+1)*w])
another_function('.<.>>>..v', 1, 3, 3)
Output: >>>
Upvotes: 1
Reputation: 258
I'll focus on the reshape function:
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))
Upvotes: 1