def update_basis(A, basis, i, j):
for k, var in enumerate(basis):
idx = int(var[1:])
if A[i][j] == 1:
basis[k] = "x" + str(j+1)
break
return basis
I wrote the above code, and I am getting error as stated. I even tried range(enumerate(basis)), after reading one of the answers here. That too doesn't seem to work. How do I get around this?
PS. I took this code from - https://github.com/pyaf/operations-research/blob/master/simplex-method/utils.py
I know there are many similar questions on this, but I just cant get one that answers me problem.
Full traceback error:
TypeError Traceback (most recent call last)
<ipython-input-7-9809e74f4f64> in <module>
120 print("\nIteration number : %d" % iter_num)
121 #updating basis as variables enter and leave
--> 122 basis= update_basis(i,j,basis,nonbasic)
123 #updating table
124 A,b,c= row_operations(A,b,c,i,j)
<ipython-input-7-9809e74f4f64> in update_basis(A, basis, i, j)
76
77 def update_basis(A, basis, i, j):
---> 78 for k, var in enumerate(basis):
79 idx = int(var[1:])
80 if A[i][j] == 1:
TypeError: 'int' object is not iterable
The reason you get this error is because the function update_basis is called with the incorrect signature. Somewhere in this code (which you will see in the error message), an int is passed as the basis parameter, when this in fact should be an iterable collection. The problem is not in the function itself, but rather where it is called.
So to solve it, find where the function is called that produces this error and correct the argument
Your update_basis function is defined in https://github.com/pyaf/operations-research/blob/master/simplex-method/utils.py, and then used in https://github.com/pyaf/operations-research/blob/master/simplex-method/simplex.py, where one can see that basis is expected to be an array / list. So, the error will disappear if you pass a list as second argument, instead of a number.
EDIT:
I think now that this
basis = update_basis(i, j, basis, nonbasic)
is your problem. You mixed up the order of the arguments. In the function definition, they are like this:
def update_basis(A, basis, i, j):
So, it should work if you change line 122 to:
basis = update_basis(nonbasic, basis, i, j)
Related
I'm plotting a function over a range of values, so naturally I fed a numpy.arange() into the function to get the dependent values for the plot. However, some of the values are going to NaN or infinity. I know why this is happening, so I went back into the function and included some conditionals. If they were working, these would replace values leading to the NaN outputs only when conditions are met. However, based on the errors I'm getting back, it appears the operations are being performed on every entry in the inputs, rather than only when those conditions are met.
My code is as follows
import matplotlib.pyplot as plt
import numpy as np
import math
k=10
l=50
pForPlot = np.arange(0,1,0.01)
def ProbThingHappens(p,k,l):
temp1 = (((1-p)**(k-1)*((k-1)*p+1))**l)
temp2 = (((1-p)**(1-k))/((k-1)*p+1))
if float(temp2) <= 1.0*10^-300:
temp2 = 0
print("Temp1 = " + str(temp1))
print("Temp2 = " + str(temp2))
temp = temp1*(temp2**l-1)
if math.isnan(temp):
temp = 1
print("Temp = " + str(temp))
return temp
plt.plot(pForPlot,ProbThingHappens(pForPlot,k,l))
plt.axis([0,1,0,1])
plt.xlabel("p")
plt.ylabel("Probability of thing happening")
plt.rcParams["figure.figsize"] = (20,20)
plt.rcParams["font.size"] = (20)
plt.show()
And the error it returns is:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-20-e707ad24af01> in <module>
20 return temp
21
---> 22 plt.plot(pForPlot,ProbAnyOverlapsAtAll(pForPlot,k,l))
23 plt.axis([0,1,0,0.01])
24 plt.xlabel("p")
<ipython-input-20-e707ad24af01> in ProbAnyOverlapsAtAll(p, k, l)
10 temp1 = (((1-p)**(k-1)*((k-1)*p+1))**l)
11 temp2 = (((1-p)**(1-k))/((k-1)*p+1))
---> 12 if float(temp2) <= 1.0*10^-300:
13 temp2 = 0
14 print("Temp1 = " + str(temp1))
TypeError: only size-1 arrays can be converted to Python scalars
How do I specify within the function that I only want to operate on specific values, rather than the whole array of values being produced? I assume that if I know how to get float() to pick out just one value, it should be straightforward to do the same for other conditionals. I'm terribly sorry if this question has been asked before, but I searched for answers using every phrasing I could imagine. I'm afraid in this case I may simply not know know the proper terminology. Any assistance would be greatly appreciated.
I was getting this error:
> float() argument must be a string or a number
So, why does this happen?(I tried commands like np.asarray() but it keeps failing).
mp.mpc(cmath.rect(a,b)))
The items in raizes are actually mpmath.mpc instances rather than native Python complex floats. numpy doesn't know how to deal with mpmath types, hence the TypeError.
You didn't mention mpmath at all in your original question. The problem would still have been easy to diagnose if you had posted the full traceback, rather than cutting off the most important part at the end:
In [10]: np.roots(Q)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-10-f3a270c7e8c0> in <module>()
----> 1 np.roots(Q)
/home/alistair/.venvs/mpmath/lib/python3.6/site-packages/numpy/lib/polynomial.py in roots(p)
220 # casting: if incoming array isn't floating point, make it floating point.
221 if not issubclass(p.dtype.type, (NX.floating, NX.complexfloating)):
--> 222 p = p.astype(float)
223
224 N = len(p)
TypeError: float() argument must be a string or a number, not 'mpc'
Whenever you ask for help with debugging on this site, please always post the whole traceback rather than just (part of) the last line - it contains a lot of information that can be helpful for diagnosing the problem.
The solution is simple enough - just don't convert the native Python complex floats returned by cmath.rect to mpmath.mpc complex floats:
raizes = []
for i in range(2*n):
a, f = cmath.polar(l[i])
if((f>np.pi/2) or (f<-np.pi/2)):
raizes.append(cmath.rect(a*r,f))
Q = np.poly(raizes)
print(np.roots(Q))
# [-0.35372430 +1.08865146e+00j -0.92606224 +6.72823602e-01j
# -0.35372430 -1.08865146e+00j -1.14467588 -9.11902316e-16j
# -0.92606224 -6.72823602e-01j]
def profits(q):
range_price = range_p(q)
range_profits = [(x-c(q))*demand(q,x) for x in range_price]
price = range_price[argmax(range_profits)] # recall from above that argmax(V) gives
# the position of the greatest element in a vector V
# further V[i] the element in position i of vector V
return (price-c(q))*demand(q,price)
print profits(0.6)
print profits(0.8)
print profits(1)
0.18
0.2
0.208333333333
With q (being quality) in [0,1], we know that the maximizing quality is 1. Now the question is, how can I solve such an equation? I keep getting the error that either q is not defined yet (which is only natural as we are looking for it) or I get the error that some of the arguments are wrong.
q_firm = optimize.fminbound(-profits(q),0,1)
This is what I've tried, but I get this error:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-99-b0a80dc20a3d> in <module>()
----> 1 q_firm = optimize.fminbound(-profits(q),0,1)
NameError: name 'q' is not defined
Can someone help me out? If I need to supply you guys with more information to the question let me know, it's my first time using this platform. Thanks in advance!
fminbound needs a callable, while profits(q) tries to calculate a single value. Use
fminbound(lambda q: -profits(q), 0, 1)
Note that the lambda above is only needed to generate a function for negative profits. Better define a function for -profits and feed it to fminbound.
Better still, use minimize_scalar instead of fminbound.
I have written a code in python to generate a sequence of ARIMA model's and determine their AIC values to compare them.The code is as below,
p=0
q=0
d=0
for p in range(5):
for d in range(1):
for q in range(4):
arima_mod=sm.tsa.ARIMA(df,(p,d,q)).fit()
print(arima_mod.params)
print arima_mod.aic()
I am getting a error message as below,
TypeError Traceback (most recent call last)
<ipython-input-60-b662b0c42796> in <module>()
8 arima_mod=sm.tsa.ARIMA(df,(p,d,q)).fit()
9 print(arima_mod.params)
---> 10 print arima_mod.aic()
global arima_mod.aic = 1262.2449736558815
11
**TypeError: 'numpy.float64' object is not callable**
Remove the brackets after print arima_mod.aic(). As I read it, arima_mod.aic is 1262.2449736558815, and thus a float. The brackets make python think it is a function, and tries to call it. You do not want that (because it breaks), you just want that value. So remove the brackets, and you'll be fine.
I run
import sys
print "x \tx^3\tx^3+x^3\t(x+1)^3\tcube+cube=cube+1"
for i in range(sys.argv[2]): // mistake here
cube=i*i*i
cube2=cube+cube
cube3=(i+1)*(i+1)*(i+1)
truth=(cube2==cube3)
print i, "\t", cube, "\t", cube + cube, "\t", cube3, "\t", truth
I get
Traceback (most recent call last):
File "cube.py", line 5, in <module>
for i in range(sys.argv[2]):
IndexError: list index out of range
How can you use command line parameter as follows in the code?
Example of the use
python cube.py 100
It should give
x x^3 x^3+x^3 (x+1)^3 cube+cube=cube+1
0 0 0 1 False
1 1 2 8 False
2 8 16 27 False
--- cut ---
97 912673 1825346 941192 False
98 941192 1882384 970299 False
99 970299 1940598 1000000 False
Use:
sys.argv[1]
also note that arguments are always strings, and range expects an integer.
So the correct code would be:
for i in range(int(sys.argv[1])):
You want int(sys.argv[1]) not 2.
Ideally you would check the length of sys.argv first and print a useful error message if the user doesn't provide the proper arguments.
Edit: See http://www.faqs.org/docs/diveintopython/kgp_commandline.html
Here are some tips on how you can often solve this type of problem yourself:
Read what the error message is telling you: "list index out of range".
What list? Two choices (1) the list returned by range (2) sys.argv
In this case, it can't be (1); it's impossible to get that error out of
for i in range(some_integer) ... but you may not know that, so in general, if there are multiple choices within a line for the source of an error, and you can't see which is the cause, split the line into two or more statements:
num_things = sys.argv[2]
for i in range(num_things):
and run the code again.
By now we know that sys.argv is the list. What index? Must be 2. How come that's out of range? Knowledge-based answer: Because Python counts list indexes from 0. Experiment-based answer: Insert this line before the failing line:
print list(enumerate(sys.argv))
So you need to change the [2] to [1]. Then you will get another error, because in range(n) the n must be an integer, not a string ... and you can work through this new problem in a similar fashion -- extra tip: look up range() in the docs.
I'd like to suggest having a look at Python's argparse module, which is a giant improvement in parsing commandline parameters - it can also do the conversion to int for you including type-checking and error-reporting / generation of help messages.
Its sys.argv[1] instead of 2. You also want to makes sure that you convert that to an integer if you're doing math with it.
so instead of
for i in range(sys.argv[2]):
you want
for i in range(int(sys.argv[1])):