Reputation: 37
I'm trying to make a function that returns this:
42334
44423
21142
14221
From this:
polje = [[1, 2, 4, 4], [4, 1, 4, 2], [2, 1, 4, 3], [2, 4, 2, 3], [1, 2, 3, 4]]
The function just goes through the lists and prints their elements starting with the last ones. I've been able to get the right result by printing, but i'm trying to make it so that the function simply returns the result. How do i do it? I've tried generators, single line for loops etc. but notes on the internet are not plentiful and are often writen in a complicated way...
Here's the code i've got so far:
def izpisi(polje):
i = len(polje[0]) - 1
while i >= 0:
for e in polje:
print(e[i], end="")
i -= 1
print("\n")
return 0
Upvotes: 1
Views: 111
Reputation: 9727
def izpisi(polje):
return '\n'.join([ # inserts '\n' between the lines
''.join(map(str, sublst)) # converts list to string of numbers
for sublst in zip(*polje) # zip(*...) transposes your matrix
][::-1]) # [::-1] reverses the list
polje = [[1, 2, 4, 4], [4, 1, 4, 2], [2, 1, 4, 3], [2, 4, 2, 3], [1, 2, 3, 4]]
print izpisi(polje)
Upvotes: 0
Reputation: 133504
>>> polje = [[1, 2, 4, 4], [4, 1, 4, 2], [2, 1, 4, 3], [2, 4, 2, 3], [1, 2, 3, 4]]
>>> def izpisi(polje):
return zip(*map(reversed, polje))
>>> for line in izpisi(polje):
print(*line, sep='')
42334
44423
21142
14221
zip(*x)
transposes a matrix. However you start at the last column so I simply add map(reversed,)
to handle that.
The rest is just printing each line.
Upvotes: 2
Reputation: 2532
you can change your code to store the items in a list
instead of print them.
and store each list
in another list
in order to return all of them.
like this:
def izpisi(polje):
a = []
i = len(polje[0]) - 1
while i >= 0:
l = []
for e in polje:
l.append(e[i])
i -= 1
a.append(l)
return a
Upvotes: 1