The first time I run this block of code from Notebook it works fine:
#Which letters and how many
letters = ["a","b","c"]
noOfLetters = len(letters)
#Looking for all permutations
resultA = []
from itertools import permutations
for i in range(noOfLetters):
resultA.append(list(permutations(letters,i+1)))
If I run it again (without restarting the Kernel) I get the following error:
TypeError Traceback (most recent call last)
<ipython-input-5-4050a4ce7a36> in <module>()
7 from itertools import permutations
8 for i in range(noOfLetters):
----> 9 resultA.append(list(permutations(letters,i+1)))
TypeError: 'list' object is not callable
Assuming "notebook" is Jupyter (previously ipython notebooks), you must be careful that jupyter keeps the state of all variables.
--> that means that the second run starts with variables already initialized at the value they had at the end of the first run.
One way to avoid that is to restart the kernel; another is to delete all variables; one more is to initialize all your variables each time you run.
from the docs:
To restart the kernel (i.e. the computational engine), click on the menu Kernel -> Restart. This can be useful to start over a computation from scratch (e.g. variables are deleted, open files are closed, etc...).
Related
"""The following program populates dictionary with (i,i*i) \
for all numbers btw 1 to n for the users input"""
def intDict():
n=int(input('Enter an integer for which you want to populate the dictionary: '))
d=dict()
for i in range(1,n+1):
d[i]=i**2
print(d)
intDict()
The above program runs well in python but occurs an error when runs in Jupyter. This is just one of the problems, I have done so many similar codes that run fine in python but fails in Jupyter.
I am new to coding in general so I cant find the source of the bug, all I know is that when I put the input() within the function it gives error, while if I place it outside it works just as fine in Jupyter(runs great in python both ways).
Enter an integer for which you want to populate the dictionary: 4
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_6700/1184304996.py in <module>
7 d[i]=i**2
8 print(d)
----> 9 intDict()
~\AppData\Local\Temp/ipykernel_6700/1184304996.py in intDict()
2 for all numbers btw 1 to n for the users input"""
3 def intDict():
----> 4 n=int(input('Enter an integer for which you want to populate the dictionary: '))
5 d=dict()
6 for i in range(1,n+1):
TypeError: 'float' object is not callable
Above is just one of the error.
I have tried restarting kernel, reopening the notebook etc..
Thanks in advance
I have a boolean subsetting function that works on a pandas dataframe:
def operational(df):
return df[(df['cf'] != 0) & (df['ta'] > 0)]
it works well in a script and in a jupiter notebook, when entered in cell:
#df = ...
df2 = operational(df)
However, if I keep function definiton in pick.py and import in to jupyter, things go unexpected. It seems upon import of a module jupiter does not reconise the types of variables inside a function:
import pick
pick.operational(df).head()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-16-374442fd7c0a> in <module>()
1 import pick
----> 2 pick.operational(df).head()
C:\Users\Евгений\Documents\GitHub\sandbox\pick.py in operational(_df)
11
12 def operational(df):
---> 13 return df[(df['cf'] != 0) & (df['ta'] > 0)]
14
15
TypeError: 'method' object is not subscriptable
Is importing something to notebook a generally bad idea? I use jupiter lab, if that matters.
Okay, from the comments it sounds like you were expecting the notebook to automatically pick up changes in an imported script. By default, Python caches imports, so most of the time changes to imported modules won't get picked up until you restart Python.
Fortuitously, Jupyter notebooks run on IPython, which supplies a code reloading cell magic. All you need to do is run:
%autoreload 2
in any cell, and your notebook should, from then on, automatically pick up any changes in pick.py as you make them (you still have to save the changes to disk before the reload magic can see them, of course).
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.
I'm working on some machine learning code and today I've lost about 6 hours because simple typo.
It was this:
numpy.empty(100,100)
instead of
numpy.empty([100,100])
As I'm not really used to numpy, so I forgot the brackets. The code happily crunched the numbers and at the end, just before saving results to disk, it crashed on that line.
Just to put things in perspective I code on remote machine in shell, so IDE is not really an option. Also I doubt IDE would catch this.
Here's what I already tried:
running pylint - well pylint kinda works. After I've disabled everything apart of errors and warnings, it even seem to be usefull. But pylint have serious issue with imported modules. As seen on official bug tracker devs know about it, but cannot/won't do anything about it. There is suggested workaround, but ignoring whole module, would not help in my case.
running pychecker - if I create code snippet with the mistake I made, the pychecker reports error - same error as python interpreter. However if I run pychecker on the actual source file (~100 LOC) it reported other errors (unused vars, unused imports, etc.); but the faulty numpy line was skipped.
At last I have tried pyflakes but it does even less checking than pychecker/pylint combo.
So is there any reliable method which can check code in advance? Without actually running it.
A language with stronger type checking would have been able to save you from this particular error, but not from errors in general. There are plenty of ways to go wrong that pass static type checking. So if you have computations that takes a long time, it makes sense to adopt the following strategies:
Test the code from end to end on small examples (that run in a few seconds or minutes) before running it on big data that will consume hours.
Structure long-running computations so that intermediate results are saved to files on disk at appropriate points in the computation. This means that when something breaks, you can fix the problem and restart the computation from the last save point.
Run the code from the interactive interpreter, so that in the event of an exception you are returned to the interactive session, giving you a chance of being able to recover the data using a post-mortem debugging session. For example, suppose I have some long-running computation:
def work(A, C):
B = scipy.linalg.inv(A) # takes a long time when A is big
return B.dot(C)
I run this from the interactive interpreter and it raises an exception:
>>> D = work(A, C)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "q22080243.py", line 6, in work
return B.dot(C)
ValueError: matrices are not aligned
Oh no! I forgot to transpose C! Do I have to do the inversion of A again? Not if I call pdb.pm:
>>> import pdb
>>> pdb.pm()
> q22080243.py(6)work()
-> return B.dot(C)
(Pdb) B
array([[-0.01129249, 0.06886091, ..., 0.08530621, -0.03698717],
[ 0.02586344, -0.04872148, ..., -0.04853373, 0.01089163],
...,
[-0.11463087, 0.15048804, ..., 0.0722889 , -0.12388141],
[-0.00467437, -0.13650975, ..., -0.13894875, 0.02823997]])
Now, unlike in Lisp, I can't just set things right and continue the execution. But at least I can recover the intermediate results:
(Pdb) D = B.dot(C.T)
(Pdb) numpy.savetxt('result.txt', D)
Do you use unit tests? There is really no better way.
[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.