A simple function returns error :"'function' object does not support item assignment"
Can I fix that without making a Class?
import numpy as np
def board(n):
return ( np.ones((n,n)))
def cdiag(brd,i,j,n):
m = i
l = i
for k in range(j+1,n-1,1):
m = m-1
l = l+1
if m >=0:
brd[m, k] = 0.
if l < n:
brd[l,k]=0
return
myboard = board(8)
print(myboard)
cdiag(myboard, 0,4,8)
print(myboard)
line : brd[m, k] = 0 returns error:
TypeError: 'function' object does not support item assignment
Thank you Guys!!
Have retyped the thing and now it is working.
Still do not know what was wrong before
Related
I'm trying to multiply a square array and a row array with nested for loops but I am running into errors such as object of type numpy.int64' has no len().
I need to be able to calculate the product with two nested for loops but I am unsure where I can change my code to optimise and fix my errors.
def matvec_row_variant_scalar(A,x):
product_array = np.zeros((len(A),len(A)),dtype=int)
for i in range(len(A)):
for j in range(len(x[0])):
for k in range(len(x)):
product_array[i][j] += A[i][k] * x[k][j]
return product_array
# Test arrays
square_array = np.array([[1,2],[3,4]])
row_array = np.array([2,2])
matvec_row_variant_scalar(square_array,row_array)
I think the code has two problems.
On the second for loop you used len(x[0]). as declaration x is 1D array and then x[0] is an Integer and calculating length on integer will thrown type error .
print(len(2)) #TypeError: object of type int has no len()
On product_array[i][j] += A[i][k] * x[k][j], again you should consider x is 1D!
Here is your fixed code.
import numpy as np
def matvec_row_variant_scalar(A,x):
product_array = np.zeros((len(A),len(A)),dtype=int)
for i in range(len(A)):
for j in range(len(A[i])):
for k in range(len(x)):
product_array[i][j] += A[i][k] * x[j]
return product_array
# Test arrays
square_array = np.array([[1,2],[3,4]])
row_array = np.array([2,2])
matvec_row_variant_scalar(square_array,row_array)
The returned Result is
array([[ 6, 6],
[14, 14]])
Okay, I figured it out. Thanks for the help from everyone. Here's the code for anyone interested:
import numpy as np
def matvec_row_variant_scalar(A,x):
product_array = np.zeros((len(A),len(A)),dtype=int)
for i in range(len(A)):
for j in range(len(A[i])):
product_array[i][j] += x[i] * A[i][j]
column_sum = product_array.sum(axis=0)
return column_sum
square_array = np.array([[1,2],[3,4]])
row_array = np.array([2,2])
matvec_row_variant_scalar(square_array,row_array)
I am used to write code in c++ but now I am trying to learn python. I came to know about the Python language and it is very popular among everyone. So I thought, let's give it a shot.
Currently I am preparing for companies interview questions and able to solve most of them in c++. Alongside which, I am trying to write the code for the same in Python. For the things which I am not familiar with, I do a google search or watch tutorials etc.
While I was writing code for my previously solved easy interview questions in python, I encountered a problem.
Code : Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Given an array of integers, print the indices of the two numbers such that they add up to a specific target.
def twoNum(*arr, t):
cur = 0
x = 0
y = 0
for i in range (len(arr) - 1):
for j in range (len(arr) - 1):
if(i == j):
break
cur = arr[i] + arr[j]
if(t == cur):
x = arr[i]
y = arr[j]
break
if(t == cur):
break
print(f"{x} + {y} = {x+y} ")
arr = [3, 5, -4, 8, 11, 1, -1, 6]
target = 10
twoNum(arr, t=target)
So here is the problem: I have defined x, y in function and then used x = arr[i] and y = arr[j] and I m printing those values.
output coming is : is 0 + 0 = 10 (where target is 10)
This is I guess probably because I am using x = 0 and y = 0 initially in the function and it seems x and y values are not updating then I saw outline section in VSCode there I saw x and y are declared twice, once at the starting of the function and second in for loop.
Can anyone explain to me what is going on here?
For reference, here is an image of the code I wrote in C++
Change this:
def twoNum(*arr, t):
to this:
def twoNum(arr, t):
* is used to indicate that there will be a variable number of arguments, see this. It is not for pointers as in C++.
Basically what you are trying to do is to write C code in python.
I would instead try to focus first on how to write python code in a 'pythonic' way first. But for your question - sloving it your way using brute force in python:
In [173]: def two_num(arr, t):
...: for i in arr:
...: for j in arr[i + 1: ]:
...: if i + j == t:
...: print(f"{i} + {j} = {t}")
...: return
Here's a way to implement a brute force approach using a list comprehension:
arr = [1,3,5,7,9]
target = 6
i,j = next((i,j) for i,n in enumerate(arr[:-1]) for j,m in enumerate(arr[i+1:],i+1) if n+m==target)
output:
print(f"arr[{i}] + arr[{j}] = {arr[i]} + {arr[j]} = {target}")
# arr[0] + arr[2] = 1 + 5 = 6
Perhaps even more pythonic would be to use iterators:
from itertools import tee
iArr = enumerate(arr)
i,j = next((i,j) for i,n in iArr for j,m in tee(iArr,1)[0] if n+m==target)
When you get to implementing an O(n) solution, you should look into dictionaries:
d = { target-n:j for j,n in enumerate(arr) }
i,j = next( (i,d[m]) for i,m in enumerate(arr) if m in d and d[m] != i )
The Problem occurs in line 29:
It is a Type Error
I can't figure out where I went wrong with my parameters. It should assign every a[i][k] with a value but it just ends up with the following error message:
a[i][k].append(g * m[i] * dr[k]/d3)
TypeError: 'int' object is not subscriptable
Here the full code:
import numpy as np
from numpy import absolute
from numpy import power
r = [[1,1,1],[1,1,1],[0,0,0]]
v = [[0,0,0],[0,0,0],[0,0,0]]
a = [[0,0,0],[0,0,0],[0,0,0]]
m = [1,1,1]
O = -1
N = 3
def beschleunigung(O, N, m, r, a):
i = 0
k = 0
dr = [0,0,0]
d3 = 0
g = 1
for k in range(1,3):
a[i][k] = 0
for i in range(1,N):
if i != O:
for k in range(1,3):
a = (r[i][k])
b = (r[0][k])
dr[k] = a - b
d3 = np.power(np.absolute(dr),3)
for k in range(1,3):
a[i][k].append(g * m[i] * dr[k]/d3)
beschleunigung(O,N,m,r,a)
print(a[1])
When your code executes the line a = (r[i][k]), a becomes an integer, rather than a list of lists as it was in the input to this function. This causes your append to fail as you cannot append to an integer.
I expect that you intended to create another variable to use in your subtraction with b - make sure to use a name that is not already defined in your scope.
This is a followup question from the one I posted a few minutes ago. The problem I was having with multiplying int with float is fixed, thanks to user2357112 in the comments. However, it's come across another roadblock.
Code:
from __future__ import division
from fractions import Fraction
import numpy as np
from numpy import linalg as LA
def gcd(m,n):
if m < n:
return gcd(n,m)
return gcd(n,m%n)
def lcm(m,n):
return (m*n)/(gcd(m,n))
def answer(m):
tbd = []
l = len(m)
for i in range(l):
s = sum(m[i])
if s == 0:
tbd.append(i)
m[i][i] = 1
else:
for j in range(l):
m[i][j] /= s
tbd.sort(reverse=True)
a = np.array(m)
r = np.diag([1.0 for x in range(l)])
for i in range(100):
r *= a
initial = [0 for x in range(l)]
initial[0] = 1
final = initial * r
for i in tbd:
del final[i]
dens = []
for i in range(len(final)):
final[i] = final[i].limit_denominator()
dens.append(final[i].denominator)
lc = dens[0]
for j in range(1,len(dens)):
lc = lcm(lc,dens[j])
for i in range(len(final)):
final[i] = int(final[i] * lc)
final.append(lc)
return final
def main():
print answer([[1,2],[2,1]])
print answer([[0,1,0,0,0,1],[4,0,0,3,2,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0]])
main()
Code in ideone: http://ideone.com/DO1otS
Error:
Traceback (most recent call last):
File "prog.py", line 51, in <module>
File "prog.py", line 48, in main
File "prog.py", line 37, in answer
AttributeError: 'numpy.ndarray' object has no attribute 'limit_denominator'
I am confused about why final[i] was recognized as a numpy.ndarray object. I thought that, since final is a 1-dimensional array, final[i] will therefore return the value (a float) within that array at index i. I'm not sure why that is not the case. Thank you in advance!
This is the answer to your question "I am confused about why final[i] was recognized as a numpy.ndarray object." In the following snippet of code
r = np.diag([1.0 for x in range(l)])
initial = [0 for x in range(l)]
final = initial * r
I skipped non-essential code. The code above shows that r is a numpy.ndarray and initial is a list. Then final is a product of a numpy.ndarray and a list. The result of this product is a numpy.ndarray.
What is also important is that r is an array of floats. Therefore final is also an array of floats and not fraction objects. Therefore you cannot call limit_denominator() on elements of final.
In addition, code such as:
for i in tbd:
del final[i]
looks quite suspicious.
My code is method of Euller for second ODE. I already try to do a function to define f this way
{def inicial():
global f
f=matrix(M,N)}
But I had problem in the same line. I don't know how to recognize my function in that line.
N=101
x_min = -10.0
x_max = 10.0;
dx = (x_max - x_min)/(N-1)
dt = 0.25*dx*dx
t=0
t_max = 1000
Q=1
j=0
M=2
f = [N , M]
def f_xx(i,t):
return ((f[i+1][t]-2*f[i][t]+f[i-1][t])/(dx*dx))
def guess(x):
return ((pi*Q/x_max)*x +(pi*Q))
for i in range (N):
for j in range(j):
x = x_min + i*dx
f[i][j] = guess(x)
for j in range(t_max+1):
for i in range(N-1):
x = x_min + i*dx
f[i][j+1] = f[i][j]+(f_xx(i,j)-sin(f[i][j]))*dt <<<error
for i in range (N-1):
f[i][j] = f[i][j+1]
What does mean 'int' object has no attribute getitem? Could anyone help fix it?
f is a list containing two ints. f[i] refers to the the i'th int; so f[i][j], will try and get the j'th value of an int, which cannot possibly work, whatever the value of j.
It's not clear what you are trying to do with this call, though.
You are trying to use f as a list of lists (i.e. like a 2-dimensional array), but it's really just one list: [101, 2].
I'm rusty on ODEs but I think you were trying to create a 101x2 grid of 0s. If so try f = [[0.0]*M for x in range(N)].