+ 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}

28th Sep 2021, 12:26 PM
Akash Gupta
Akash Gupta - avatar
10 Respuestas
+ 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
28th Sep 2021, 12:30 PM
Slick
Slick - avatar
+ 2
Collect the popped elements ( 0 here) into another list say zeroList then extend Array to zeroList
28th Sep 2021, 3:58 PM
Mohd Aadil
Mohd Aadil - avatar
+ 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)
28th Sep 2021, 6:07 PM
Mohd Aadil
Mohd Aadil - avatar
+ 1
Slick right would you share your code.I want to see how you implement your logic.
28th Sep 2021, 1:27 PM
Akash Gupta
Akash Gupta - avatar
+ 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.
28th Sep 2021, 2:18 PM
Brian
Brian - avatar
+ 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.
28th Sep 2021, 5:52 PM
Akash Gupta
Akash Gupta - avatar
+ 1
Mohd Aadil share your attempt bro if you do....
28th Sep 2021, 5:52 PM
Akash Gupta
Akash Gupta - avatar
+ 1
Brian thanks
29th Sep 2021, 8:00 AM
Akash Gupta
Akash Gupta - avatar
0
Mohd Aadil thanks bhai if you have time please correct my code.
28th Sep 2021, 6:16 PM
Akash Gupta
Akash Gupta - avatar
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
28th Sep 2021, 6:44 PM
Brian
Brian - avatar