Python array algorithm [duplicate] - python

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]

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

printing a new list as product of elements in two lists [duplicate]

This question already has answers here:
How can I use `return` to get back multiple values from a loop? Can I put them in a list?
(2 answers)
Element-wise addition of 2 lists?
(17 answers)
Closed 28 days ago.
So i'm trying to define a function which given two lists of the same size, returns a new list with the product of each element at a given index.
a = [1, 2, 3]
b = [1, 4, 5]
def list_mult(a, b):
if len(a) != len(b):
print("error, lists must be the same size")
for i in range(len(a)):
return [a[i] * b[i]]
print(list_mult(a, b))
The code is running, but it is only returning [1]. Not sure why, as I was under the impression that this for loops iterates over all i's in the range.
Don't return from inside the loop, as that will return after only 1 iteration. Keeping your current structure, you can instead add each product to a list and return that.
res = []
for i in range(len(a)):
res.append(a[i] * b[i])
return res
Alternatively, use a list comprehension with zip.
return [x * y for x, y in zip(a, b)]
Here's how I would solve the problem, catering for the edgecase of one array being larger than the other.
from typing import List
def multiply_arrays(a: List[int], b: List[int]):
result = []
for i in range(max(len(a), len(b))):
item_a = a[i] if i < len(a) else 1
item_b = b[i] if i < leb(b) else 1
result.append(item_a * item_b)
return result

Sequence `remove()` method not removing [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 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)

How do you swap two local variables within a function in python [duplicate]

This question already has answers here:
Is there a standardized method to swap two variables in Python?
(8 answers)
Closed 2 years ago.
I am trying to swap local variables within a function to rotate a 2 by 2 matrix by 90 degrees.
def twobytwo(m):
last = len(m)-1
for i in range(0, last):
swap(m[i][i], m[i][last])
swap(m[i][i], m[last][last])
swap(m[i][i], m[last][i])
return m
def swap(i, j):
temp = i
i = j
j = temp
print(twobytwo([[0, 1], [2, 3]]))
Currently, I am returned the original matrix but I want to see
[[2,0],[3,1]]
I think this is what you want to achieve:
def twobytwo(m):
last = len(m)-1
for i in range(0, last):
m[i][i], m[i][last] = m[i][last], m[i][i]
m[i][i], m[last][last] = m[last][last], m[i][i]
m[i][i], m[last][i] = m[last][i], m[i][i]
return m
print(twobytwo([[0, 1], [2, 3]]))
EDIT:
If you still want to maintain the function swap:
def swap(i, j):
return j, i
a, b = swap(a, b)
But I think a, b = b, a is good enough.
Your assumption is that the swap() parameters are modified in place (i.e. pass-by-reference). Python does not do that in your code: when you call something like swap(m[i][i], m[i][last]), it dereferences the values of m and calls swap(0,1). So swap() only modifies i,j; it does not modify your "matrix" (which technically is a list of lists).
Try rewriting your swap() function to take the "matrix" plus two pairs of indices: (i,j) and (k,l).

Python - for loop of a list of ordered pairs and finding the greatest pair [duplicate]

This question already has answers here:
Pythonic way to find maximum value and its index in a list?
(11 answers)
How does tuple comparison work in Python?
(4 answers)
Closed 7 days ago.
I have looked thoroughly, but have not found a clear (or roundabout) answer to the following question: How can I create a for loop that will allow me to find the greatest pair where x and y in (x,y) are greater than or equal to all other x's and y's in the list?
So, suppose I have a list of 20 pseudorandom integer ordered pairs and I want to find which ordered pair is the greatest using a for loop.
The code I currently have is:
np.random.seed(1234)
a = np.random.randint(0, 11,(20,2))
alst = list(allocationsset)
print alst
Where np is the imported form of numpy and which prints,
[[1,0],[8,9],[2,1],[3,2],[10,10] etc...]
Then, I attempt to make the for loop with the following function:
def dominantx (pairs):
def maxx (pairs):
maxlist = []
for [a,b] in pairs:
if a >= b:
maxlist.append([a,b])
return maxlist
dom = maxx(pairs)
domlist = []
for [a,b] in dom:
for [c,d] in dom:
if a > c:
domlist.append([a,b])
if a == c:
if b > d:
domlist.append([a,b])
if b == d:
domlist.append([a,b])
domlist.append([c,d])
else:
domlist.append([c,d])
else:
domlist.append([c,d])
return domlist
dominantx(alst)
I believe part of the problem I am having is replacing what is in "domlist" with the new greatest ordered pair and returning that as the answer, i.e. I don't want to append "domlist" with the new greatest ordered pair until I remove the old greatest ordered pair from domlist.
My first loop works fine, it is just the second for loop in defining dominantx where I am having trouble. I am relatively new to Python, so please forgive any simply fixes or errors. I am open to any suggestions that still implement a loop and, of course, any help is greatly appreciated. Thank you!
Just use max:
arr = [[1,0],[8,9],[2,1],[3,2],[10,10]]
print(max(arr))
[10, 10]
If you want actual pairs as in [1,1],[2,2] etc..
arr = [[1,1],[8,9],[2,2],[3,2],[13,10]]
pairs = [x for x in arr if x[0] == x[1]] # get all subelements with equal elements
print(max(pairs))
[2, 2]

Categories