+ 1
Question on python.
Given An Integer Array, Move All Elements That Are Equal To O To The Left While Maintaining The Order Of Other Elements In The Array Given Array = { 5, 6, 7, 8, 9, 10, 0, 5, 6, 0} Output = Array = {0, 0, 5, 6, 7, 8, 9, 10, 5, 6}
10 odpowiedzi
+ 4
kinda looks like all you'd have to do is pop a 0 when found and insert it into the first index each time
+ 2
Collect the popped elements ( 0 here) into another list say zeroList then extend Array to zeroList
+ 2
Akash Gupta
lst = [5,6,7,8,9,10,0,5,6, 0, ]
zeroList = [0]*lst.count(0)
lst = list(filter(lambda i: i>0, lst))
zeroList.extend(lst)
print(zeroList)
+ 1
Slick right would you share your code.I want to see how you implement your logic.
+ 1
The braces around the arrays reveal that this problem must have been originally for a C or Java course. Python uses braces to denote dictionaries and sets, and square brackets for arrays or lists.
You can use Array.count(0) to determine how many 0s are in the list. Then Array.remove(0) that number of times in a loop. Finally, concatenate [0]*numZeros+Array.
+ 1
Mohd Aadil Brian
def array(arr, n):
count = 0
for i in range(n):
if arr[i] != 0:
arr[count] = arr[i]
count=count+1
while count < n:
arr[count] = 0
count += 1
arr = [5, 6, 7, 8, 9, 10, 0, 5, 6, 0]
n = len(arr)
array(arr, n)
print("Array after following condition:")
print(arr)
I try it run but it adding in end of array please modify it .I want 0 in starting of array.
+ 1
Mohd Aadil share your attempt bro if you do....
+ 1
Brian thanks
0
Mohd Aadil thanks bhai if you have time please correct my code.
0
Akash Gupta to fix your first attempt, you could change it to work from the end of the list toward the beginning.
def array(arr, n):
count = n-1
for i in range(n-1, -1, -1):
if arr[i] != 0:
arr[count] = arr[i]
count=count-1
while count >= 0:
arr[count] = 0
count -= 1