I really don't like how massive this code is. Is there a way I don't see to optimize it?
def to0Depth(arr0,_arr=[],old_arr=[], depth=0, INDEXES=[0],prevdepth=0):
if len(INDEXES)-1 < depth:
INDEXES.append(0)
length = (range(len(arr0)),range(INDEXES[depth],len(arr0)))[INDEXES[depth] != 0 and depth<prevdepth]
for i in length:
if depth==0:
old_arr = []
if INDEXES[depth] != 0 and depth<prevdepth:
i=INDEXES[depth]
INDEXES[depth]=0
if isinstance(arr0[i],list):
old_arr.append(arr0)
INDEXES[depth]=i+1
return to0Depth(arr0[i],_arr,old_arr,depth+1, INDEXES,depth)
else:
_arr.append(arr0[i])
if depth !=0:
return to0Depth(old_arr[depth-1], _arr,old_arr,depth-1,INDEXES,depth)
return _arr
#Random Matrixes
a = [[1,2,8,6,[5,2,[452,258],1]],52,3,9,[52,1,2,[52,[12,52],5],90,8],8]
print(to0Depth(a))
#Output: [1, 2, 8, 6, 5, 2, 452, 258, 1, 52, 3, 9, 52, 1, 2, 52, 12, 52, 5, 90, 8, 8]
I really don't like how massive this code is. Is there a way I don't see to optimize it?
def to0Depth(arr0,_arr=[],old_arr=[], depth=0, INDEXES=[0],prevdepth=0):
if len(INDEXES)-1 < depth:
INDEXES.append(0)
length = (range(len(arr0)),range(INDEXES[depth],len(arr0)))[INDEXES[depth] != 0 and depth<prevdepth]
for i in length:
if depth==0:
old_arr = []
if INDEXES[depth] != 0 and depth<prevdepth:
i=INDEXES[depth]
INDEXES[depth]=0
if isinstance(arr0[i],list):
old_arr.append(arr0)
INDEXES[depth]=i+1
return to0Depth(arr0[i],_arr,old_arr,depth+1, INDEXES,depth)
else:
_arr.append(arr0[i])
if depth !=0:
return to0Depth(old_arr[depth-1], _arr,old_arr,depth-1,INDEXES,depth)
return _arr
#Random Matrixes
a = [[1,2,8,6,[5,2,[452,258],1]],52,3,9,[52,1,2,[52,[12,52],5],90,8],8]
print(to0Depth(a))
#Output: [1, 2, 8, 6, 5, 2, 452, 258, 1, 52, 3, 9, 52, 1, 2, 52, 12, 52, 5, 90, 8, 8]
Share
Improve this question
edited 7 hours ago
cards
5,0641 gold badge11 silver badges26 bronze badges
asked 7 hours ago
RokweMICHAELRokweMICHAEL
93 bronze badges
1
|
1 Answer
Reset to default 0Yes. You could try to optimize it with a recursive function. For example:
def flatten(arr0):
result = []
for item in arr0:
if isinstance(item, list):
result.extend(flatten(item)) # Recursively flatten sub-lists
else:
result.append(item) # Add the non-list item directly
return result
In this way you looks at each item in the list: if it's another list, it goes inside it and keeps doing this until it reaches the end while if it's not a list, it simply adds the item to the final result. Doing:
a = [[1, 2, 8, 6, [5, 2, [452, 258], 1]], 52, 3, 9, [52, 1, 2, [52, [12, 52], 5], 90, 8], 8]
print(flatten(a))
you should obtain the same desired result.
ndarray.flatten
innumpy
– cards Commented 7 hours ago