Skip to content Skip to sidebar Skip to footer

Creating A Dynamic Array In Python

I have a dynamic array in which I would like to update the userstring, e.g., for a 25 character single string like 'mannysattynastysillyfully'. there would be a 5x5 array . m a n n

Solution 1:

I think this may do what you are after:

>>> def two_dim(inval, width=5):
...     out = []
...     for i in range(0, len(inval) - 1, width):
...         out.append(list(inval[i:i + width]))
...     return out
...
>>> print(two_dim('mannysattynastysillyfully'))
[['m', 'a', 'n', 'n', 'y'], ['s', 'a', 't', 't', 'y'], ['n', 'a', 's', 't', 'y'], ['s', 'i', 'l', 'l', 'y'], ['f', 'u', 'l', 'l', 'y']]

And to print it like you have in the question:

>>> c = two_dim('mannysattynastysillyfully')
>>> for sub in c:
...     print " ".join(sub)
...
m a n n y
s a t t y
n a s t y
s i l l y
f u l l y

NOTE This will only create complete rows, so using a width that is not a factor of the length of the input string will result in lost data. This is easy to change if desired, but I will leave that as an exercise to the reader.

If you are looking to always create a square 2x2, then you could do something like

def is_square(l):
    return math.floor(math.sqrt(l))**2 == l

def two_dim_square(inval):
    if not is_square(len(inval)):
        raise Exception("string length is not a perfect square")
    width = math.sqrt(len(inval))
    # proceed like before with a derived width

EDIT 2

def two_dim(inval, width=5):
    out = []
    for i in range(0, len(inval) - 1, width):
        out.append(list(inval[i:i + width]))
    return out

def print_array(label, inval, joiner=' '):
    print label
    for sub in inval:
        print joiner.join(sub)
    print

print_array("3 by X", two_dim('mannysattynastysillyfully', 3))
print_array("4 by X", two_dim('mannysattynastysillyfully', 4))
print_array("5 by X", two_dim('mannysattynastysillyfully', 5))
print_array("6 by X", two_dim('mannysattynastysillyfully', 6))

Gives the output

3 by X
m a n
n y s
a t t
y n a
s t y
s i l
l y f
u l l

4 by X
m a n n
y s a t
t y n a
s t y s
i l l y
f u l l

5 by X
m a n n y
s a t t y
n a s t y
s i l l y
f u l l y

6 by X
m a n n y s
a t t y n a
s t y s i l
l y f u l l

EDIT 3
If you want all data to always be present, and use a default value for empty cells, then that would look like

def two_dim(inval, width=5, fill=' '):
    out = []
    # This just right-pads the input string with the correct number of fill values so the N*M is complete.
    inval = inval + (fill * (width - (len(inval) % width)))
    for i in range(0, len(inval) - 1, width):
        out.append(list(inval[i:i + width]))
    return out

Called with

print_array("3 by X", two_dim('mannysattynastysillyfully', 3, '*'))

OUTPUT

3 by X
m a n
n y s
a t t
y n a
s t y
s i l
l y f
u l l
y * *

Post a Comment for "Creating A Dynamic Array In Python"