def flatten_array(arr):
# Write your code here
flattened = []
for obj in arr:
if type(obj)==list:
for num in obj:
flattened.append(num)
else:
flattened.append(obj)
flattened.sort()
return flattened
print(flatten_array([1, 2, [3, 4, 5, 123, 2341, -223], 6, [7, 8], 9]))
def flatten_array(arr):
num = []
for i in range(len(arr)):
if isinstance(arr[i], list):
for j in range(len(arr[i])):
num.append(arr[i][j])
else:
num.append(arr[i])
return num
print(flatten_array([1, 2, [3, 4, 5], 6, [7, 8], 9]))
its an error because you are using for j in i you should be using for j in arr[i]
I’ll post how I did it if you want help on how it should be done (not like I wasn’t going to post it anyways)
def flatten_array(arr):
# Write your code here
h= []
for i in range(len(arr)):
if type(arr[i]) != int:
for j in range(len(arr[i])):
h.append(arr[i][j])
else:
h.append(arr[i])
return h
print(flatten_array([1, 2, [3, 4, 5], 6, [7, 8], 9]))
def flatten_array(arr):
# Write your code here
return retour(arr)
retour = lambda x:[x for i in x for x in retour(i)] if type(x)==list else[x]
print(flatten_array([1, 2, [3, 4, 5], 6, [7, 8], 9]))
def flatten_array(arr):
new_arr = []
for i, j in enumerate(arr):
if type(arr[i]) == list:
for k in arr[i]:
new_arr.append(k)
else:
new_arr.append(j)
return new_arr
print(flatten_array([1, 2, [3, 4, 5], 6, [7, 8], 9]))
def flatten_array(arr):
flat_arr = list()
for i in arr:
if type(i) == list: flat_arr += i
else: flat_arr.append(i)
return flat_arr
print(flatten_array([1, 2, [3, 4, 5], 6, [7, 8], 9]))
Checking for type “list”/“no list” and appending elements accordingly. For a general solution that can deal with arrays of arbitrary dimension (e.g. [1, [[2, 3], 4]]), one could invoke flatten_array recursively in line 4:
def flatten_array(arr):
flattened = []
for num in arr:
if type(num) != int:
for ext in num:
flattened.append(ext)
else:
flattened.append(num)
return flattened
def flatten_iterable(iterable):
for item in iterable:
if hasattr(item, "__next__") or hasattr(item, "__iter__"):
for sub in flatten_iterable(item):
yield sub
else:
yield item
def flatten_array(arr):
return list(flatten_iterable(arr))
And here’s the same recursive function version given in some of the previous posts:
def flatten_array(arr):
# Write your code here
lst = []
for i in arr:
if not isinstance(i, list): # check if the element is not a list
lst.append(i)
else: # else loop trouh the inner list in arr and append to our new list.
for x in i:
lst.append(x)
return lst
print(flatten_array([1, 2, [3, 4, 5], 6, [7, 8], 9]))
def flatten_array(arr):
arr2 = []
for i in arr:
try:
for x in i:
arr2.append(x)
except:
arr2.append(i)
return(arr2)
print(flatten_array([1, 2, [3, [4], 5], 6, [7, 8], 9]))
I sadly couldn’t understand the codes that use this thing “recursive”. I will have to learn about it now.