Python: 'float' object is not subscriptable when iteration function - python

I am teaching myself Python and am trying out a challenge I found to create a quote program for a gardener. I have almost all of it working and have added in iteration so that the user can make more than one quote without re-starting the program.
It produces the quote perfectly the first time but on the second run it presents this error:
Traceback (most recent call last):
File "/Users/shaunrogers/Desktop/Plymstock Prep/GCSE CS/SOL/Controlled Assessment/Sample Papers Solutions/gardening Task 2.py", line 105, in <module>
lawn = m2_items("lawn",0)
File "/Users/shaunrogers/Desktop/Plymstock Prep/GCSE CS/SOL/Controlled Assessment/Sample Papers Solutions/gardening Task 2.py", line 23, in m2_items
minutes = area*time[index]
TypeError: 'float' object is not subscriptable
I have the following code as a function that is producing the error:
def m2_items (item,index):
global costs, time, LABOUR
length = int(input("How long is the "+ item+"?\n"))
width = int(input("How wide is the "+item+"?\n"))
area = length*width
cost_m2 = float(costs[index])
total_cost = area*cost_m2
minutes = area*time[index]
hours = int(minutes/60)
labour = LABOUR*hours
labour_cost=round(labour,2)
m2_details = [area, cost_m2, total_cost,hours, labour_cost]
return m2_details
I have tried re-setting the local variables on the running of the function (but I didn't think this was needed as the variables should be removed from memory once the function has run).
I hope the question is clear and that I can get some insight. To re-iterate, what I want the program to do is allow me to call this function multiple times.

You are using the global time variable, which is initially subscriptable (probably an array). As your program continues, some other part of your code will assign a new value to time, maybe accidentally because you wrote time = some_calculation() instead of time[i] = some_calculation(), or maybe you are using the name time somewhere else without realizing it's already in use.
Do a search for all the places where you use the name time and you will probably find your error.
This is a common problem with global variables. Sometimes something updates them from another part of the code, and the error will sneak up on you like this.

Related

Python 3: How do i change variables in different scripts?

So, kind of new to python, as I kinda started learning it a few months ago. I'm currently trying to make my own game (not expecting it to be super good, but I want it to work decently) The game is basically going around a dungeon, fighting monsters, leveling up, doing puzzles, and then fighting the final boss. Basically, your average RPG game. I am making it all text though. Currently stuck on a bit of code for my levelup script and my stats script. I have a variable in stats called "constitution", and whenever i level up (if exp >= expmax) i add 3 to the value of constitution. (starts out at 10)
import LevelUP
constitution = 10
that one is my code in the Stats script, and the one is the code in the LevelUP script.
import Stats
level = 1
expMax = 100
exp = 100
if exp >= expMax:
level=level+1
exp = 0
expMax = expMax+expMax*0.5
Stats.constitution = Stats.constitution+3
Stats.strength = Stats.strength+4
Stats.dexterity = Stats.dexterity+4
Stats.intelligence = Stats.intelligence+3
Stats.wisdom = Stats.wisdom+3
Stats.charisma = Stats.charisma+2
Stats.luck = Stats.luck+2
This is the error that comes up
Traceback (most recent call last):
File "main.py", line 3, in <module>
import Stats
File "/home/runner/Stats.py", line 1, in <module>
import LevelUP
File "/home/runner/LevelUP.py", line 9, in <module>
Stats.constitution = Stats.constitution+3
AttributeError: module 'Stats' has no attribute 'constitution'
exited with non-zero status
Kind of new to the site, but I have looked around for something like this and all i could find was using print() in different scripts.
There is a cyclic import in your code. Please see Circular imports in Python with possible undesired behaviours.
Anyway, it seems that your Stats module does not need LevelUp (does it?). I suggest rethinking your architecture.

TypeError in Numpy happening randomly

I'm having a weird issue with numpy right now on a current assignment. I'm making an ant colony AI for a class (based on the Google AI Ants Challenge), and I'm using a diffusion based approach where I essentially diffuse out a scent from food/enemy hills on each turn. I've been using numpy since each turn basically consists of doing a lot of matrix manipulations, but I just recently got a weird bug that I can't figure out.
At the beginning of each turn, I update the field associated with each scent before I run the diffusion iterations:
# Here I update the "potential" field (hills_f) and the
# diffusion values (hills_l) for the hills scent. Diffusion values
# (lambda values) are 1 except for on ants, where they are higher
# or lower depending on their colony.
self.hills_f *= TURN_DECAY
self.hills_l = np.ones_like(self.hills_l)
# Update the lambda matrix
for r,c in ants.my_ants():
self.hills_l[r][c] = MY_HILLS_LAMBDA
for r,c in ants.enemy_ants():
self.hills_l[r][c] = ENEMY_HILLS_LAMBDA
So this code runs at the beginning of each turn (along with a similar snippet for the food scent), but on a random turn (ranges from 10-40), I get the following error:
Traceback (most recent call last):
File "long_file_path...", line 167, in run
bot.do_turn(ants)
File "MyBot.py", line 137, in do_turn
self.hills_l[r][c] = ENEMY_HILLS_LAMBDA
TypeError: 'numpy.float64' object does not support item assignment
It looks like it randomly turns self.hills_l into a scalar between the two for-loops, which doesn't make any sense to me. It's also weird that there's similar code for the food scent, which doesn't crash ever, and that this problem shows up so non-deterministically.
I can post more code if necessary, but I think everything should be there, especially since the problem seems to occur between the for loops.
Thanks!

I didnt get my pacman to reach to its destination.. nd having an error mentioned below

[SearchAgent] using function depthFirstSearch
[SearchAgent] using problem type PositionSearchProblem
Path found with total cost of 999999 in 0.0 seconds
Search nodes expanded: 1
Traceback (most recent call last):
File "C:\Documents and Settings\vpn\My Documents\Aptana Studio 3 Workspace\Project 1 - Search\pacman.py", line 672, in <module>
runGames( **args )
File "C:\Documents and Settings\vpn\My Documents\Aptana Studio 3 Workspace\Project 1 - Search\pacman.py", line 638, in runGames
game.run()
File "C:\Documents and Settings\vpn\My Documents\Aptana Studio 3 Workspace\Project 1 - Search\game.py", line 662, in run
action = agent.getAction(observation)
File "C:\Documents and Settings\vpn\My Documents\Aptana Studio 3 Workspace\Project 1 - Search\searchAgents.py", line 121, in getAction
if i < len(self.actions):
TypeError: object of type 'NoneType' has no len()
m working on a project in which i have to test my pacman agent to reach to its destination in less possible space and time complexity by applying DFS(Depth First Algorithm)
My code for it is
stack = util.Stack()
explored = list()
start = problem.getStartState()
for item in problem.getSuccessors(start):
state = item[0]
path = list()
path.append(item[1])
stateInfo = (state, path)
stack.push(stateInfo)
explored.append(start)
while stack.isEmpty():
state = stack.pop()
if problem.isGoalState(state[0]):
return state[1]
for states in problem.getSuccessor(state[0]):
newstate = states[0]
newpath = list(state[1])
newpath.append(states[1])
newstateInfo = (newstate, newpath)
stack.push(newstateInfo)
explored.append(state[0])
What should i suppose to do now.. my pacman agent get stuck to its starting position in east dirction opposite to its destination.
The supporting files to run the agent is mentioned in https://www.edx.org/courses/BerkeleyX/CS188.1x/2012_Fall/courseware/Week_2/Project_1_Search/
I think I know what is going on (though I can't be certain given the limited amount of code in the question).
My guess is that the code you've posted is getting called to set up the variable self.actions where you're getting an error. The error is happening because you're getting None returned from the function, rather than the list you expect.
The underlying bug is that your main loop has it's test backwards. You want while not stack.isEmpty(), rather than what you have. Because you've just pushed several values onto the stack, the loop as written exits immediately. After the loop you reach the end of the function, which is equivalent to returning None in Python. That None is causing the exception later.
Even if you fix the broken loop, falling off the end of the function can happen anyway if a path cannot be found to the goal state. I suggest adding code to detect this, and respond appropriately. You could raise an exception (since it shouldn't happen in normal situations), or maybe return an empty list.
There's another issue where you're not checking if a newly visited state has already been explored. This could lead to an infinite loop, as you search from one state to a neighbor and then back. A set will also be better than a list for explored. You can check it with if state in explored (which also works on lists, but less efficiently).
As a side issue, some of your variables are very poorly named. state different types at different times, and having a second variable states makes it even more confusing, especially with indexing thrown in.
I suggest unpacking the tuples you pushed onto the stack with the code state, path = stack.pop(), which will solve part of the issue. Then just rename states to something else (or perhaps unpack it too, with something like for neighbor, direction in problem.getSuccessor(state)) and you'll be good to go.
You can also save a few lines of code by pushing the start state to your stack, rather than doing an extra loop over its neighbors in the setup code.

TypeError: 'int' object is not callable' in Python 3.2? [duplicate]

This question already has answers here:
TypeError: 'int' object is not callable
(10 answers)
Closed 6 years ago.
so i'm coding a tic tac toe game in python 3.2 and i have spent night and day trying to fix this and going over my code, script, or whatever you want to call it, so many times and still can't find it. i've googled it and all the answers are all to confusing or the person is scripting something way different from my tic tac toe game. and please beware, i'm just a beginner at python. when i try and run it an error comes up:
Traceback (most recent call last):
File "/Users/user/Desktop/tic tac toe game.py", line 41, in <module>
input = input("Select a spot:")
TypeError: 'int' object is not callable"
what does that mean? here's the code it says it's having a problem with:
while True:
input = input("Select a spot:")
input = int(input)
if you could help me, that would mean so much. it's been so annoying and i've been trying my hardest to fix it.
input() is a Python function, and you are using it both as the function and an identifier.
Using input as a variable name will work the first time, but the 2nd time through the loop there won't be an input() function any longer as that name now is associated with an integer variable.
So instead of function input() you just have a variable named input, hence the error (also as mentioned by #poke and #DSM in the comments)
Using answer as your variable name would be a better idea:
while True:
answer = input("Select a spot:")
answer = int(answer)
You're using the name input for the result, which replaces the input function you're trying to call. Use a different name.
Edit: When you loop through, by the time the second iteration rolls around, you have rebound the variable input to your user input, so it's not longer a builtin function, it's the integer you just converted the user input to. The name input can't refer to two different things at the same time.
The first time you call
input("Select a spot:")
it works properly - returns a string, you convert it to int and store it to input.
The second time you call input, it takes the integer you just stored and tries to run it as a function. This fails, with the error message you have seen.

Help with Python UnboundLocalError: local variable referenced before assignment

I have post the similar question before,however,I think I may have misinterpreted my question,so may I just post my origin code here,and looking for someone can help me,I am really stuck now..thanks alot.
from numpy import *
import math as M
#initial condition All in SI unit
G=6.673*10**-11 #Gravitational constant
ms=1.9889*10**30 #mass of the sun
me=5.9742*10**24 #mass of the earth
dt=10 #time step
#Creat arrays
vs=array([[0,0,0]]) #1st element stand for x component of V of earth
ve=array([[29770,0,0]])
rs=array([[0,0,0]])
re=array([[0,1.4960*10**11,0]])
#First update velocity in order to start leapfrog approximation
fs=-G*ms*me*((rs-re)/(M.sqrt((rs-re)[0][0]**2+(rs-re)[0][1]**2+(rs-re)[0][2]**2))**3)
fe=-fs
vs=vs+fs*dt/ms
ve=ve+fe*dt/me
n=input('please enter the number of timestep you want it evolve:')
#update force
def force(n,ms,me,rs,re,G):
rs,re=update_r(rs,re,n,dt)
fs=-G*ms*me*((rs-re)/(M.sqrt((rs-re)[0][0]**2+(rs-re)[0][1]**2+(rs-re)[0][2]**2))**3)
fe=-fs
return fs,fe
#update velocities
def update_v(n,vs,ve,ms,me,dt,fs,fe):
fs,fe=force(n,ms,me,rs,re,G)
i=arange(n)
vs=vs+fs[:]*i[:,newaxis]*dt/ms
ve=ve+fe[:]*i[:,newaxis]*dt/me
return vs,ve
#update position
def update_r(rs,re,n,dt):
vs,ve=update_v(n,vs,ve,ms,me,dt,fs,fe)
i=arange(n)
rs=rs+vs[:]*i[:,newaxis]*dt
re=re+ve[:]*i[:,newaxis]*dt
return rs,re
#there is start position,v,r,f all have initial arrays(when n=0).
#then it should calculate f(n=1) then use this to update v(n=0)
#to v(n=1),then use v(n=1) update r(n=0) to r(n=1),then use r(n=1)
#update f(n=1) to f(n=2)....and so on until finish n.but this code seems doesnt do this,,how can I make it? –
when i call force python gives:
please enter the number of timestep you want it evolve:4Traceback (most recent call last):
File "<pyshell#391>", line 1, in <module>
force(n,ms,me,rs,re,G)
File "/Users/Code.py", line 24, in force
rs,re=update_r(rs,re,n,dt)
File "/Users/Code.py", line 39, in update_r
vs,ve=update_v(n,vs,ve,ms,me,dt,fs,fe)
UnboundLocalError: local variable 'vs' referenced before assignment
can anyone give me some tips?thanks......
where do you call force in this code?
In any event, the problem is in update_r. You reference vs in the first line of update_r even though vs is not defined in this function. Python is not looking at the vs defined above. Try adding
global vs
as the first line of update_r or adding vs to the parameter list for update_r
In the first line of update_r, you have vs,ve=update_v(n,vs,ve,ms,me,dt,fs,fe). Look at the function that you are calling. You are calling update_v with a bunch of parameters. One of these parameters is vs. However, that is the first time in that function that vs appears. The variable vs does not have a value associated with it yet. Try initializing it first, and your error should disappear
Put an additional global statement containing all your globals after each def statement. Otherwise, all globals are transformed into locals within your def without it.
def update_v(n,vs,ve,ms,me,dt,fs,fe):
global vs, ve, ...
On line 39 you do
vs,ve=update_v(n,vs,ve,ms,me,dt,fs,fe)
while you are inside a function.
Since you defined a global variable called vs, you would expect this to work.
It would have worked if you had:
vs_new,ve_new = update_v(n,vs,ve,ms,me,dt,fs,fe)
because then the interpreter knows vs in the function arguments is the global one. But since you had vs in the left hand side, you created an uninitialized local variable.
But dude, you have a much bigger problem in your code:
update_r calls update_v, update_v calls force, and force calls update_r - you will get a stack overflow :)
I got that error when my class name was assigned to a variable that is called exactly like its name. example ClassName = ClassName. You may do this if you come from .Net

Categories

Resources