ValueError: invalid literal for int() with base 10: 'O' - numpy

I am relatively new to python, and as such I don't always understand why I get errors. I keep getting this error:
Traceback (most recent call last):
File "python", line 43, in <module>
ValueError: invalid literal for int() with base 10: 'O'
This is the line it's referring to:
np.insert(arr, [i,num], "O")
I'm trying to change a value in a numpy array.
Some code around this line for context:
hOne = [one,two,three]
hTwo = [four,five,six]
hThree = [seven, eight, nine]
arr = np.array([hOne, hTwo, hThree])
test = "O"
while a != Answer :
Answer = input("Please Enter Ready to Start")
if a == Answer:
while win == 0:
for lists in arr:
print(lists)
place = int(input("Choose a number(Use arabic numerals 1,5 etc.)"))
for i in range(0,len(arr)):
for num in range(0, len(arr[i])):
print(arr[i,num], "test")
print(arr)
if place == arr[i,num]:
if arr[i,num]:
np.delete(arr, [i,num])
np.insert(arr, [i,num], "O")
aiTurn = 1
else:
print(space_taken)
The number variables in the lists just hold the int version of themselves, so one = 1, two = 2 three = 3, etc
I've also tried holding "O" as a variable and changing it that way as well.
Can anyone tell me why I'm getting this error?

Related

I get this error when i try to use Wolfram Alpha in VS code python ValueError: dictionary update sequence element #0 has length 1; 2 is required

This is my code
import wolframalpha
app_id = '876P8Q-R2PY95YEXY'
client = wolframalpha.Client(app_id)
res = client.query(input('Question: '))
print(next(res.results).text)
the question I tried was 1 + 1
and i run it and then i get this error
Traceback (most recent call last):
File "c:/Users/akshi/Desktop/Xander/Untitled.py", line 9, in <module>
print(next(res.results).text)
File "C:\Users\akshi\AppData\Local\Programs\Python\Python38\lib\site-packages\wolframalpha\__init__.py", line 166, in text
return next(iter(self.subpod)).plaintext
ValueError: dictionary update sequence element #0 has length 1; 2 is required
Please help me
I was getting the same error when I tried to run the same code.
You can refer to "Implementing Wolfram Alpha Search" section of this website for better understanding of how the result was extracted from the dictionary returned.
https://medium.com/#salisuwy/build-an-ai-assistant-with-wolfram-alpha-and-wikipedia-in-python-d9bc8ac838fe
Also, I tried the following code by referring to the above website....hope it might help you :)
import wolframalpha
client = wolframalpha.Client('<your app_id>')
query = str(input('Question: '))
res = client.query(query)
if res['#success']=='true':
pod0=res['pod'][0]['subpod']['plaintext']
print(pod0)
pod1=res['pod'][1]
if (('definition' in pod1['#title'].lower()) or ('result' in pod1['#title'].lower()) or (pod1.get('#primary','false') == 'true')):
result = pod1['subpod']['plaintext']
print(result)
else:
print("No answer returned")

How to remove the list index out of range?

The code runs perfectly with the custom input but while running in competetive programming platform, it shows runtime error.
I have searched about this but couldn't resolve it.
def GCD(num1, num2):
if num1 < num2:
small = num1
else:
small = num2
for i in range(1, small + 1):
if (num1 % i == 0) and (num2 % i == 0):
gcd = i
return gcd
arr = [int(i) for i in input().split(' ')]
print(GCD(arr[0], arr[1]))
Runtime Error
Traceback (most recent call last): File Main.py , line 10, in print(GCD(arr[0], arr[1])) IndexError: list index out of range
In the last line you are printing the GCD of the first and the second element of the array which are of the index 0 and 1. But if user only enters a single number then index 1 is out of range. So you can just check if the size of array is less than two then simply print the element at the index 0.
if len(arr) is 1:
print(arr[0])
else:
print(GCD(arr[0], arr[1]))
Furthermore, if you are trying to find the GCD of the array then the algorithm is wrong. You will have to iterate over the array and find the GCD.
if len(arr) is 1:
print(arr[0])
else:
answer = arr[0];
for i in range(len(arr)):
answer = GCD(answer,arr[i])
print(answer)

Error in using np.NaN is vectorize functions

I am using Python 3 on 64bit Win1o. I had issues with the following simple function:
def skudiscounT(t):
s = t.find("ITEMADJ")
if s >= 0:
t = t[s + 8:]
if t.find("-") == 2:
return t
else:
return np.nan # if change to "" it will work fine!
I tried to use this function in np.Vectorize and got the following error:
Traceback (most recent call last):
File "C:/Users/lz09/Desktop/P3/SODetails_Clean_V1.py", line 45, in <module>
SO["SKUDiscount"] = np.vectorize(skudiscounT)(SO['Description'])
File "C:\PD\Anaconda3\lib\site-packages\numpy\lib\function_base.py", line 2739, in __call__
return self._vectorize_call(func=func, args=vargs)
File "C:\PD\Anaconda3\lib\site-packages\numpy\lib\function_base.py", line 2818, in _vectorize_call
res = array(outputs, copy=False, subok=True, dtype=otypes[0])
ValueError: could not convert string to float: '23-126-408'
When I replace the last line [return np.nan] to [return ''] it worked fine. Anyone know why this is case? Thanks!
Without otypes the dtype of the return array is determined by the first trial result:
In [232]: f = np.vectorize(skudiscounT)
In [234]: f(['abc'])
Out[234]: array([ nan])
In [235]: _.dtype
Out[235]: dtype('float64')
I'm trying to find an argument that returns a string. It looks like your function can also return None.
From the docs:
The data type of the output of vectorized is determined by calling
the function with the first element of the input. This can be avoided
by specifying the otypes argument.
With otypes:
In [246]: f = np.vectorize(skudiscounT, otypes=[object])
In [247]: f(['abc', '23-126ITEMADJ408'])
Out[247]: array([nan, None], dtype=object)
In [248]: f = np.vectorize(skudiscounT, otypes=['U10'])
In [249]: f(['abc', '23-126ITEMADJ408'])
Out[249]:
array(['nan', 'None'],
dtype='<U4')
But for returning a generic object dtype, I'd use the slightly faster:
In [250]: g = np.frompyfunc(skudiscounT, 1,1)
In [251]: g(['abc', '23-126ITEMADJ408'])
Out[251]: array([nan, None], dtype=object)
So what kind of array do you want? float that can hold np.nan, string? or object that can hold 'anything'.

PyOmo/Ipopt fails with "can't evaluate pow"

I am using PyOmo to generate a nonlinear model which will ultimately be solved with Ipopt. The model is as follows:
from pyomo.environ import *
from pyomo.dae import *
m = ConcreteModel()
m.t = ContinuousSet(bounds=(0,100))
m.T = Param(default=100,mutable=True)
m.a = Param(default=0.1)
m.kP = Param(default=20)
m.P = Var(m.t, bounds=(0,None))
m.S = Var(m.t, bounds=(0,None))
m.u = Var(m.t, bounds=(0,1), initialize=0.5)
m.Pdot = DerivativeVar(m.P)
m.Sdot = DerivativeVar(m.S)
m.obj = Objective(expr=m.S[100],sense=maximize)
def _Pdot(M,i):
if i == 0:
return Constraint.Skip
return M.Pdot[i] == (1-M.u[i])*(M.P[i]**0.75)
def _Sdot(M,i):
if i == 0:
return Constraint.Skip
return M.Sdot[i] == M.u[i]*0.2*(M.P[i]**0.75)
def _init(M):
yield M.P[0] == 2
yield M.S[0] == 0
yield ConstraintList.End
m.Pdotcon = Constraint(m.t, rule=_Pdot)
m.Sdotcon = Constraint(m.t, rule=_Sdot)
m.init_conditions = ConstraintList(rule=_init)
discretizer = TransformationFactory('dae.collocation')
discretizer.apply_to(m,nfe=100,ncp=3,scheme='LAGRANGE-RADAU')
discretizer.reduce_collocation_points(m,var=m.u,ncp=1,contset=m.t)
solver = SolverFactory('ipopt')
results = solver.solve(m,tee=False)
Running the model results in the following error:
Error evaluating constraint 1: can't evaluate pow'(0,0.75).
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.5/dist-packages/pyomo/opt/base/solvers.py", line 577, in solve
"Solver (%s) did not exit normally" % self.name)
pyutilib.common._exceptions.ApplicationError: Solver (asl) did not exit normally
The first part of the error comes from Ipopt whereas the second part comes from PyOmo. Evidently the issue has something ot do with the term M.P[i]**0.75 in the constraints, but changing the power does not resolve the issue (though 2.0 did work).
How can I resolve this?
The error message states that pow'(0,0.75) cannot be evaluated. The ' character in this function indicates the first derivative ('' would indiate the second derivative). The message is effectively saying that the first derivative does not exist or results in an infinity at zero.
Resolving the issue is easy: bound your variables to a non-zero value as follows:
m.P = Var(m.t, bounds=(1e-20,None))
m.S = Var(m.t, bounds=(1e-20,None))
I would add to Richard's answer:
you might also need to update the initial value of your variable as ipopt assumes 0 if not specified, so it will evaluate the variable at 0 for the first iteration.
hence:
m.P = Var(m.t, bounds=(1e-20,None), initialize=1e-20)
m.S = Var(m.t, bounds=(1e-20,None), initialize=1e-20)
instead of 1e-20 as initialize you might use a value more relevant to your problem

Guess number, no such attribute, python 3

I'm learning OOP in python and was trying to run this small game in OOP style, but for some reason system doesn't find object's attributes.
Here's the problem:
Traceback (most recent call last):
File "HelloUsername.py", line 47, in <module>
newGameGTN = GuessTheNumber()
File "HelloUsername.py", line 6, in __init__
self.start_game()
File "HelloUsername.py", line 32, in start_game
player = player_choice()
NameError: name 'player_choice' is not defined
On this code in python 3:
from random import randint
class GuessTheNumber(object):
"""docstring for GuessTheNumber"""
def __init__(self):
self.start_game()
self.player_choice()
self.compare_numbers()
def player_choice(self):
choice = int(input("Choose your number: "))
if choice in range(101):
return(choice)
else:
print("Please enter a number 0-100")
player_choice()
def compare_numbers(self, computer, player):
if player == computer:
return(0)
elif player > computer:
return(1)
elif player < computer:
return(-1)
def start_game(self):
computer = randint(0, 100)
turn = 0
for turn in range(3):
player = player_choice()
x = compare_numbers(computer, player)
print(computer)
if x == -1:
print("too small")
elif x == 1:
print("too big")
elif x == 0:
print("you win")
break
turn += 1
print("game over")
newGameGTN = GuessTheNumber()
newGameGTN.start_game()
NameError is not the same as AttributeError (which you mention in the question's summary). A NameError exception means that the name referenced in your code does not exist. A name can be a local variable, or a variable in an enclosing scope.
All methods in a class need to be called on an instance of that class. (staticmethods and classmethods not withstanding) Instead of name = player_choice() you need to write name = self.player_choice(). Likewise for all other occurrences where you call a method defined in the class.