Different output from a function with the same arguments [duplicate] - python

This question already has answers here:
List of lists changes reflected across sublists unexpectedly
(17 answers)
Closed 2 years ago.
Why is my function 'increment' return different values for matrix that i create by other function and different for manual matrix?
n = 2
m = 3
indices = [[0,1],[1,1]]
def matrixpopulation(n,m):
row=[]
matrix=[]
row+=(0 for _ in range(0,m))
matrix+=(row for _ in range(0,n))
return matrix
def increment(indices,matrixa):
for v,k in indices:
for i in range(3):
matrixa[v][i]+=1
for i in range(2):
matrixa[i][k]+=1
return matrixa
matrixa=matrixpopulation(n,m)
filled_matrix=increment(indices,matrixa)
print(matrixpopulation(n,m))
print(filled_matrix)
manualmatrix=[[0,0,0],[0,0,0]]
print(manualmatrix)
print(increment(indices,manualmatrix))

matrix+=(row for _ in range(0,n))
When you make matrix here you actually add the reference to the same row n-times. When you modify some element in one 'row', all other rows are modified as well. For example:
a = [1, 2]
b = [a, a]
a[0] = 3
Check b now.

Related

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

How Pytorch Tensor get the index of elements? [duplicate]

This question already has answers here:
How Pytorch Tensor get the index of specific value
(10 answers)
Closed 3 years ago.
I have 2 Tensors named x and list and their definitions are below:
x = torch.tensor(3)
list = torch.tensor([1,2,3,4,5])
Now I want to get the index of element x from list. The expected output is an Integer:
2
How can I do in an easy way?
import torch
x = torch.tensor(3)
list = torch.tensor([1,2,3,4,5])
idx = (list == x).nonzero().flatten()
print (idx.tolist()) # [2]
list = torch.tensor([1,2,3,3,5])
idx = (list == x).nonzero().flatten()
print (idx.tolist()) # [2, 3]

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).

Subtracting one list from another in Python [duplicate]

This question already has answers here:
Remove all the elements that occur in one list from another
(13 answers)
Closed 5 years ago.
What I want to happen: When given two lists (list a and list b), remove the numbers in list a that are in list b.
What currently happens: My first function works only if list a has only one number to be removed.
What I've tried: Turning the lists into sets, then subtracting a - b
def array_diff(a, b):
c = list(set(a) - set(b))
return c
Also tried: Turning the list into sets, looking for n in a and m in b, then if n = m to remove n.
def array_diff(a, b):
list(set(a))
list(set(b))
for n in (a):
for m in (b):
if n == m:
n.remove()
return a
Possibly thought about: Using the "not in" function to determine if something is in b or not.
Sample Input/Output:
INPUT: array_diff([1,2], [1]) OUTPUT: [2]
INPUT: array_diff([1,2,2], [1]) OUTPUT: [2] (This should come out to be [2,2]
Just use it like that :
c = [x for x in a if x not in b]

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