My OS doesn't support Sage 5.4 so I'm stuck with 5.0 for now.
Defining this function registers no syntax errors in python, and I don't think it makes errors in Sage 5.4 (I'd appreciate confirmation if possible.) I'd like to know why it is failing in 5.0.
def num_matchings(G):
if min(G.degree_sequence())== 0 or G.num_edges()==0:
return 0
elif G.num_edges()==1:
if G.edges()[0][2] ==None:
return 1
else:
return G.edges()[0][2]
else:
H = copy(G)
K = copy(G)
e = G.edges()[0]
if e[2] ==None:
w=1
else:
w = e[2]
H.delete_edge(e)
K.delete_vertices([e[0],e[1]])
return num_matchings(H) + w*num_matchings(K)
The first error I get when I try to define is
File "<ipython console>", line 4
==Integer(1):
^
SyntaxError: invalid syntax
and they pile on after that. To my eye, the syntax looks fine.
I'm on Mac OS 10.5 with GCC 4.0.1.
Any help much appreciated.
[Aside: typo in .delete_vertives().]
Your syntax itself is fine. From the error message, though, it looks like you've simply copied and pasted code into the console. That will only work in certain very simple cases. You're also using tabs for indentation, which can cause a whole other set of headaches too. You should really switch to 4-space tabs instead.
If you want to insert code into a live console, you can use %paste (which copies from the clipboard if it can), or %cpaste instead.
For example, if I copy and paste your code, I get:
sage: def num_matchings(G):
....: if min(G.degree_sequence())== 0 or G.num_edges()==0:
....: return 0
....: elif G.num_edges()==1:
------------------------------------------------------------
File "<ipython console>", line 4
==Integer(1):
^
SyntaxError: invalid syntax
sage: if G.edges()[0][2] ==None:
....: return 1
------------------------------------------------------------
File "<ipython console>", line 2
SyntaxError: 'return' outside function (<ipython console>, line 2)
but if I use %cpaste with the 4-space equivalent (unfortunately %paste isn't working on my 5.4.1 install at the moment):
sage: %cpaste
Pasting code; enter '--' alone on the line to stop.
:
:def num_matchings(G):
: if min(G.degree_sequence())== 0 or G.num_edges()==0:
: return 0
[etc.]
: K.delete_vertices([e[0],e[1]])
: return num_matchings(H) + w*num_matchings(K)
:--
sage: num_matchings(graphs.LadderGraph(5))
8
Related
Language: Python 3
Platform : Jupyter Notebook
I want to count the amount of messages sent by the same user at the same date and time in a dataframe. I tried to do it using a recursive function, following this example.
Define recursive function in Pandas dataframe
below is my attempt.
interaction = 0
for i, row in df.iterrows():
if ((df2['names'].iloc[i] == (df2['names'].iloc[i-1]) & (df2['time'].iloc[i] == df2['time'].iloc[i-1]) & (df2['date'].iloc[i]== df2['date'].iloc[i-1]))
interaction = interaction
else:
interaction = interaction+1
return interaction
but it returns this error,
File "<ipython-input-171-9670327f0e8e>", line 6
interaction = interaction
^
SyntaxError: invalid syntax
I am sorry that the question is so basic, but I am bummed. I've tried changing the variabel names, but it keeps returning the same error. when I changed it into return, like this,
interaction = 0
for i, row in df.iterrows():
if ((df2['names'].iloc[i] == (df2['names'].iloc[i-1]) & (df2['time'].iloc[i] == df2['time'].iloc[i-1]) & (df2['date'].iloc[i]== df2['date'].iloc[i-1]))
return interaction
else:
return (interaction+1)
return interaction
it returns this error.
File "<ipython-input-179-99d835a6b0e6>", line 5
return interaction
^
SyntaxError: invalid syntax
I deleted colon after in if after the condition because it's a syntax error as well.
thank you for your help.
Edit: this is the error if I included the colon
File "<ipython-input-184-041229eea329>", line 5
& (df2['date'].iloc[i]== df2['date'].iloc[i-1])):
^
SyntaxError: invalid syntax
You are missing : at the end of the if statement
I tried to test a found code in the site of the bempp library (http://nbviewer.jupyter.org/github/bempp/tutorials/blob/master/notebooks/osrc_burton_miller.ipynb). It is a library implemented in python. I have problems when executing the following istructions :
from scipy.sparse.linalg import gmres
it_count = 0
def iteration_counter(x):
global it_count
it_count += 1
x, info = gmres(discrete_op, rhs_coefficients, callback=iteration_counter)
I got the following error message :
from scipy.sparse.linalg import gmres
>>>
>>> it_count = 0
>>> def iteration_counter(x):
... global it_count
... it_count += 1
...
... x, info = gmres(discrete_op, rhs_coefficients, callback=iteration_counter)
File "<stdin>", line 5
x, info = gmres(discrete_op, rhs_coefficients, callback=iteration_counter)
^
SyntaxError: invalid syntax
Could you help me solving this syntaxe problem please ?
In interactive mode, you need to enter an empty line to terminate multi-line statements. You entered a line with four spaces, which Python interprets as you wanting to continue your function definition.
Why am I getting the following error? The last print statement should not be a part of the while loop.
>>> while n>= 0:
... n = n-1
... print(n)
... print ("TO A!!")
File "<stdin>", line 4
print ("TO A!!")
^
SyntaxError: invalid syntax
You need to press enter after your while loop to exit from the loop
>>> n = 3
>>> while n>=0:
... n = n-1
... print (n)
... # Press enter here
2
1
0
-1
>>> print ("To A!!")
To A!!
Note:- ... implies that you are still in the while block
The default python shell works OK for typing but it really does not understand pasting from clipboard. The real solution is to install ipython, which is an advanced shell for python with many niceties:
% ipython3
Python 3.4.2 (default, Oct 8 2014, 13:08:17)
Type "copyright", "credits" or "license" for more information.
IPython 2.3.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: n = 5
In [2]: while n >= 0:
...: n = n-1
...: print(n)
...: print ("TO A!!")
...:
4
3
2
1
0
-1
TO A!!
In [3]:
I guess that the error shows up because python shell don't support that. It want you to do one thing in a time.! I do the same things in my python 2.7 shell and it said:
File "<pyshell#4>", line 4
print 'to all'
^
IndentationError: unindent does not match any outer indentation level
when I do the same thing in my python 3.4 shell, it said: unexpected indent.
Not able to make loop and statement after it.
Example:
wls:/ADMIN_server/serverConfig> serverRuntime()
Location changed to serverRuntime tree. This is a read-only tree with ServerRuntimeMBean as the root.
For more help, use help(serverRuntime)
wls:/ADMIN_server/serverRuntime> dsMBeans = cmo.getJDBCServiceRuntime().getJDBCDataSourceRuntimeMBeans()
wls:/ADMIN_server/serverRuntime> ds_name = "ADMIN_DB"
wls:/ADMIN_server/serverRuntime> for ds in dsMBeans:
...
Traceback (innermost last):
(no code object) at line 0
File "<console>", line 2
SyntaxError: invalid syntax
Not sure is it need to import something before that options like and for that reason not able to make loop with statement:
import time
import sys
You shouldn't need to import anything specific to have access to the looping mechanism in WLST. For instance, try the following:
slist=range(1,4)
for i in slist: print 'i = ' + str(i);
The result should be:
i = 1
i = 2
i = 3
The syntax of your statements after the for loop are probably causing a problem in your python script OR if you are manually typing the commands in, you need to make sure you put a space after ... for it to interpret the next line like:
wls:/offline> j = 0
wls:/offline> while j<4:
... print 'j = ' + str(j)
... j = j + 1
...
jms 0
jms 1
jms 2
jms 3
Notice it is very important to type in a space character after ... or you will have the invalid syntax error.
I tried to do this problem at spoj.com, but I keep getting the error runtime error (NZEC). I code in python. I don't know why. Here is my code,
import sys
def unique(lines, exact=True):
for L in lines:
if L.count('#') != 1 and exact:
return False
if L.count('#') > 1 and not exact:
return False
return True
def resolve(N, lines):
diags = [
[lines[i][i+j] for i in range(max(0, -j), min(N, N-j))]
for j in range(-N+1, N)]
anti_diags = [
[lines[i][N-1 -(i+j)] for i in range(max(0, -j), min(N, N-j))]
for j in range(-N+1, N)]
if unique(lines) and unique(zip(*lines)) and unique(diags, False) and unique(anti_diags, False):
return "YES"
return "NO"
input_file = sys.stdin
output_file = sys.stdout
T = int(raw_input())
for i in range(1, T + 1):
n = int(raw_input())
lines = []
for _ in range(n):
line = raw_input().strip()
lines.append(list(line))
print resolve(n, lines)
It works fine locally with input like:
2
3
..#
#..
.#.
4
.#..
...#
#...
..#.
When I run your code, I get the following:
$ python spoj.py < input
Traceback (most recent call last):
File "spoj.py", line 38, in <module>
print resolve(n, lines)
File "spoj.py", line 15, in resolve
for j in range(-N+1, N)]
IndexError: list index out of range
That's the runtime error you're getting. But the problem is actually in this part:
for _ in range(n):
line = raw_input().strip()
lines.append(list(line))
print resolve(n, lines)
Since the print statement is indented, your program reads a single line, appends to line and calls resolve before reading the following lines. After removing the extra indent, it works fine on my computer.
There's plenty of room to further improve this program, both in style and logic. Let me know if you would like some further advice.
EDIT:
You mentioned in the comments that this indentation problem was a copypasting error. In that case, as sp1r pointed out in his comment, it's most likely that, as a comment in the problem's page suggests, the input used by the online judge is malformed.
In that case, you have to do more rigorous parsing of the input, as it may not be formatted as the example input suggests. That is, instead of:
2
3
..#
#..
.#.
(etc)
you could have something more like:
2 3
..#
#.. .#.
(etc)
That might break your code because it assumes whoever posted the problem was competent enough to make an input that looks like the example. That is not always the case in SPOJ, a lot of the input files is malformed and you can find other cases where malformed input causes otherwise correct programs to fail.
Spoj does not use sys and sys.stdin and sys.stdout. use raw_input() and print.
"I am on windows not on linux. I simply change this line to switch to console modes for tests."
In any language and in any os, these works fine.
#for Python
spoj.py < input.txt > output.txt
#If you are using C/C++, for any EXE file
spoj.exe < input.txt > output.txt
Spoj will nether test this in your computer nor using any UI. They will test your code, in a "console" and it might be a linux / any-OS machine. Use this input / output to Test your code.