Sequence `remove()` method not removing [duplicate] - python

This question already has answers here:
Strange result when removing item from a list while iterating over it
(8 answers)
How to remove items from a list while iterating?
(25 answers)
Closed last year.
I am learning Python and took on a few CodeWars exercises to get more familiar with its methods.
I have this function that creates the sum of all positive integers, and although I know there might be a "one liner" way to do this, this is approach I am taking as a beginner:
def positive_sum(arr):
for x in arr:
if x <= 0:
arr.remove(x)
if len(arr) == 0:
return 0
print(arr)
return sum(arr)
For some reason this method is not removing -2, and -4 from the array. Why is that?
#test.it("returns 0 when all elements are negative")
def negative_case():
test.assert_equals(positive_sum([-1,-2,-3,-4,-5]),0)

Here is a way you can do it.
x = [-6, -4, 3, 5]
x = sum([i for i in x if i>0])
print(x)

Related

Code which works on my VS code does not work in Code wars - Moving Zeros To The End task? [duplicate]

This question already has answers here:
Strange result when removing item from a list while iterating over it
(8 answers)
How to remove items from a list while iterating?
(25 answers)
Closed yesterday.
Was having fun with this task on code wars where on a given list as an input my function should find all of the zeroes and put them at the end of a given list maintaining the other numbers in the same order for example:
a = [1, 2, 0, 1, 0, 1] function should return a = [1, 2, 1, 1, 0, 0]
I wrote a code which in my VS code does the job but for some reason cant pass the initial tests (4/5).
The thing is on failed test where my function should return some values, IT ACTUALLY DOES, in my compiler but cant pass test??? I'm really confused. I did not want to look for solutions online...
Here is my code:
def zerotoanend(a:list):
b = []
for i in a:
if i==0:
b.append(0)
a.remove(i)
for zero in b:
a.append(zero)
return a
It is generally not a good idea to modify a list while iterating over it, as you can skip elements. Instead, you could count the number of zeros first, use a list comprehension to get all the non-zero elements, then add the required number of zeros to the end.
zeros = a.count(0)
return [x for x in a if x != 0] + [0] * zeros

Change elements in Python list with condition [duplicate]

This question already has answers here:
python: replace elements in list with conditional
(3 answers)
Replace values in list using Python [duplicate]
(7 answers)
Finding and replacing elements in a list
(10 answers)
Closed 1 year ago.
I have this list
x = [1,2,3,4,5,6]
I would like to convert elements greater than 3 as 0 so the list would become [1,2,3,0,0,0]
Here is my code
for i in range(len(x)):
if x[i] > 3:
x = 0
I got this error message " 'int' object is not subscriptable". could somebody tell me what I did wrong
Problem with your current code is, you are assigning 0 directly to x, not to the item at a particular index, the same way you are comparing the value.
for i in range(len(x)):
if x[i] > 3:
# x = 0
x[i] = 0 #<---- assign value at the index i
Or, you can just use a list-comprehension, and take 0 if the value is greater than 3, else take the value
>>> [0 if i>3 else i for i in x]
[1, 2, 3, 0, 0, 0]

Why do we have to put the range of iteration of for loop as range(0,len(list)), instead of range( 0,len(list)-1 ) [duplicate]

This question already has answers here:
Why does range(start, end) not include end? [duplicate]
(11 answers)
Why are slice and range upper-bound exclusive?
(6 answers)
Closed 1 year ago.
n = [3, 5, 7]
def print_list(x):
for i in range(0, len(x)):
print x[i]
print i
print_list(n)
I thought since the program is iterating through the index, having the range as len(list) would be out of range. However, this is apparently the correct way, and I'm not really sure why. Can somebody explain?
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops when it reaches the specified number.
https://docs.python.org/3/library/stdtypes.html#range

My .remove() isn't removing all the numbers from the list even though I'm passing it through an iterator. I can't seem to find the issue [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
How to remove list elements in a for loop in Python? [duplicate]
(6 answers)
Closed 3 years ago.
def thirdMax(nums):
highest = max(nums)
for i in nums:
if i == highest:
nums.remove(i)
print(nums)
secondHighest = max(nums)
for i in nums:
if i == secondHighest:
nums.remove(i)
thirdHighest = max(nums)
return thirdHighest
thirdMax([1,2,3,3,3,3,3,3,4,4,4,4,4,4,4])
My code is supposed to return the third highest distinct number. My code isn't seeming to work accordingly.
Sort the list (to make sure). Convert to a set. Convert back to a list and take the 3rd from the right.
l = [1,2,3,3,3,3,3,3,4,4,4,4,4,4,4]
l.sort()
s = set(l)
l = list(s)
third = l[-3]
You can combine some of these steps, but I wrote them all out for clarity :)

Python array algorithm [duplicate]

This question already has answers here:
How to find the cumulative sum of numbers in a list?
(25 answers)
Closed 6 years ago.
I'm working on writing a function where an array is given:
arrayA = [2,3,1]
The function needs to return a new array where:
newArray = [2,5,6]
This is almost like a Fibonacci function.
newArray[0] = arrayA[0]
newArray[1] = arrayA[0] + arrayA[1]
newArray[2] = arrayA[1] + arrayA[2] + arrayA[3]
Heres my code so far, but always end up with a empty list. arrayA is passed in as parameter.
def generateNewArray(A):
A=[]
newArray=[]
for i in range(len(A)):
newArray[i]=A[i]+A(i+1)
return newArray
print [sum(A[:i]) for i in range(1,len(A)+1)]
I guess ... I think theres actually a cumulative sum builtin somewhere ... or maybe its in numpy
numpy.cumsum(A)
You can also use a functional programming pattern:
Try this:
def generateNewArray(inputArray):
return map(lambda x: sum(inputArray[:x]), xrange(1, len(inputArray) + 1))
For example:
In [7]: generateNewArray([2, 3, 1])
Out[7]: [2, 5, 6]

Categories