I have a 2D square list of size n. My purpose is to run through it with a shape of a snake. For example:
array = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
For this case result should be [1, 2, 3, 6, 9, 8, 7, 4, 5].
def spiral_array(arr):
if arr == []: return []
up = 0; left = 0
down = len(arr)-1
right = len(arr[0])-1
direct = 0 # 0: go right 1: go down 2: go left 3: go up
res = []
while True:
if direct == 0:
for i in range(left, right+1):
res.append(arr[up][i])
up += 1
if direct == 1:
for i in range(up, down+1):
res.append(arr[i][right])
right -= 1
if direct == 2:
for i in range(right, left-1, -1):
res.append(arr[down][i])
down -= 1
if direct == 3:
for i in range(down, up-1, -1):
res.append(arr[i][left])
left += 1
if up > down or left > right: return res
direct = (direct+1) % 4
array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(spiral_array(array)) # [1, 2, 3, 6, 9, 8, 7, 4, 5]
source: https://leetcode.com/problems/spiral-matrix/
Related
Note: code created in python 2.7
I am taking a robotics class in school and we are learning python.
The task was to take
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
and print it out as such
1
2
3
4
5
6
7
8
9
When I tried my code out I got the error message
I tried looking at what this means online but I am just starting to learn python and I didn't understand any of the answers that I found.
What am I doing wrong? How do I fix my code?
First Post sorry about the mess
Reason why you get an error:
You get the error in the line
results.append(lists[numbers[each_list]])
because numbers is an integer and numbers[each_list] isn't a valid function. So instead use the square brackets correctly:
results.append(lists[numbers][each_list])
Other Methods:
You don't really need to use range function:
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
for i in n:
for j in i:
print(j)
or a one liner:
print('\n'.join(str(j) for i in n for j in i))
Or if you are flattening a nested list:
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
def flat(lis):
res = []
for i in lis:
for j in i:
res.append(j)
return res
flat_n = flat(n)
or a one-liner:
>>> n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
>>> flat = lambda x: [j for i in x for j in i]
>>> flat(n)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
or just simply:
flat_n = [j for i in n for j in i]
n=[[1,2,3],[4,5,6,7,8,9]]
def flatten(lists):
results=[]
for lists in n:
for numbers in lists:
results.append(numbers)
return results
new_list =(flatten(n))
for num in new_list:
print (num)
When Executed
1
2
3
4
5
6
7
8
9
>>>
How to change this [1, 5, 9, -3, -4, 8, -2] into this [1, 5, 9, 9, 16, 8, 4]
import math
val = [1, 5, -3, 7, -4, -2, 9]
for i in val:
if i < 0:
val[i] = math.sqrt(i)
print(val)
i get ValueError: math domain error if i do the code above
You can simply use a map function to get this done.
import math
val = [1, 5, -3, 7, -4, -2, 9]
val = list(map(lamda x: x * x if x < 0 else x, val))
You can refer below code:
val = [1, 5, -3, 7, -4, -2, 9]
for i in val:
val[i] = i *i
print(val)
Or
import math
val = [1, 5, -3, 7, -4, -2, 9]
for i in val:
if i < 0:
val[i] = math.sqrt(i*-1)
print(val)
Hi i want to classify indexes of same rows in 2D numpy array. Is there any function to do it ?
Something like this :
a= [[1,2,3] , [2,3,4] , [5,6,7] ,[1,2,3] ,[1,2,3] , [2,3,4]]
then f(a) returns same row indexes [[0,3,4],[1,5],[2]]
I would appreciate for your solutions
Here's one to output list of arrays of row indices -
def classify_rows(a):
sidx = np.lexsort(a.T)
b = a[sidx]
m = ~(b[1:] == b[:-1]).all(1)
return np.split(sidx, np.flatnonzero(m)+1)
If you need a list of lists as output -
def classify_rows_list(a):
sidx = np.lexsort(a.T)
b = a[sidx]
m = np.concatenate(( [True], ~(b[1:] == b[:-1]).all(1), [True]))
l = sidx.tolist()
idx = np.flatnonzero(m)
return [l[i:j] for i,j in zip(idx[:-1],idx[1:])]
Sample run -
In [78]: a
Out[78]:
array([[1, 2, 3],
[2, 3, 4],
[5, 6, 7],
[1, 2, 3],
[1, 2, 3],
[2, 3, 4]])
In [79]: classify_rows(a)
Out[79]: [array([0, 3, 4]), array([1, 5]), array([2])]
In [80]: classify_rows_list(a)
Out[80]: [[0, 3, 4], [1, 5], [2]]
For example:
Given list: [1, 2, 3, 4, 4, 8, 4]
Choose element, which last duplicate will be removed: 4
Output list: [1, 2, 3, 4, 4, 8]
I tried that way, but it just removes first needed element from list:
def list = [1, 2, 3, 4, 4, 8, 4]
def fruit = list.find { item -> item.equals(4)}
list.remove(fruit) //removes first matching item (one)
println list
I guess init(), last() or maybe toUnique() functions may be useful, but don't know, how to do this..
not sure if this is what you mean, but:
def list = [1, 2, 3, 4, 4, 8, 4]
def toremove = 4
list.remove(list.lastIndexOf(toremove))
assert list == [1, 2, 3, 4, 4, 8]
Is there any way to select the second, third (etc) value from a value in a list in Groovy? I'm still very new to programming in general and am just wondering if there is an easy way to do this.
For example, if I have the list
[1, 2, 3, 4, 5, 6]
I want to select the next two values after each value using a for loop:
for 1: (1, 2, 3)
for 2: (2, 3, 4)
...and so on.
Is that easily possible? Thanks in advance!
If you're using groovy 1.8.1 or later, you can use the take and drop methods:
def foo = [1, 2, 3, 4, 5, 6]
foo.size().times { i ->
println foo.drop(i).take(3)
}
This will result in
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]
[5, 6]
[6]
If you want the iteration to stop at the last group of three, try something like this:
def foo = [1, 2, 3, 4, 5, 6]
if (foo.size() > 2) {
(foo.size() - 2).times { i ->
println foo.drop(i).take(3)
}
}
which gives
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]
If you're not using Groovy 1.8.1+, then you can acheive a similar result by writing a function like so:
List split( List foo, int size ) {
(0..foo.size()-size).collect { foo[ it..it+size-1 ] }
}
Then, you can call this like:
split( [1, 2, 3, 4, 5, 6], 3 )
to print
[[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]]