I have never used SageMath in my life and I am relying on the internet for a crash course on how to get what I want out of SageMath (to plot an elliptic curve over a finite field).
I'm using this code, pasted below:
#interact
def f(label='37a', p=tuple(prime_range(1000))):
try: E = EllipticCurve(label)
except:
print "invalid label %s"%label; return
try:
show(graphics_array([plot(E,thickness=3),plot(E.change_ring(GF(p)))]),frame=True)
except Exception, msg:
print msg
There seems to be a bracket missing, but I don't have the experience to know where it should go. The error message I get is:
Error in lines 1-6
Traceback (most recent call last):
File "/projects/sage/sage-6.10/local/lib/python2.7/site-packages/smc_sagews/sage_server.py", line 905, in execute
exec compile(block+'\n', '', 'single') in namespace, locals
File "<string>", line 4
except:
^
IndentationError: unindent does not match any outer indentation level
The error you've given seems to indicate that the line after except: is not indented more than except: is indented. Python cares about indentation levels a lot.
You might try the following.
#interact
def f(label='37a', p=tuple(prime_range(1000))):
try:
E = EllipticCurve(label)
except:
print "invalid label %s"%label; return
try:
show(graphics_array([plot(E,thickness=3), plot(E.change_ring(GF(p)))]), frame=True)
except Exception, msg:
print msg
Aside: You should use four spaces before code to have them display as a codeblock. For more, see How do I format My Code Blocks?
Related
It seems that the python code in R reticulate is not indenting automatically. E.g. when I write
if x < 0:
print("negative")
else:
print("positive")
the third line should move automatically at the same level of if but, it actually does not and I get the message IndentationError: unexpected indent (<string>, line 1)
Is this bug or can it be corrected?
This can be solved by correcting the indentation of you code, following Python rules :
You need to unindent the else so it's indentation match the if ones. Rstudio don't indent correctly for Python to this day.
if x < 0:
print("negative")
else:
print("positive")
This is my code for the 1st beginner level question on SPOJ:
rewrite small numbers from input to output. Stop processing input after reading in the number 42. All numbers at the input are integers of one or two digits.
My code:
b=[]
while True:
n=int(input('Enter the number less than 100 : '))
if(n>100):
continue
else:
b.append(n)
if n==42:
break
for i in b:
print(i)
but it throws error saying:
Runtime error #stdin #stdout #stderr 0.15s 23320KB
Traceback (most recent call last):
File "./prog.py", line 4, in <module>
EOFError: EOF when reading a line
I hope I was clear, and please point out my mistakes in a kind way:) as I am a beginner and self-taught.
Thank You.
Try using the try and except for your code.
Insert all of the code under try and then except pass
try:
b = []
while True:
n=int(input('Enter the number less than 100 : '))
if(n>100):
continue
else:
b.append(n)
if n==42:
break
for i in b:
print(i)
except:
pass
I'm trying to parse indented blocks with pyparsing and indentedBlock
Here my code
from pyparsing import *
indent_stack = [1]
line = ungroup(restOfLine)
block = ungroup(indentedBlock(line, indent_stack))
# Work
data = """ foo
bar
tar
"""
block.parseString(data).pprint()
The problem is that parseString won't return. It seems to be waiting for more input or maybe I hit an infinite loop. If I put an unidnented line in the block start to work
data = """ foo
bar
tar
end
"""
But I want to be able to parse up to unindented line (the working case), or to the end of string (the not working case)
This is a bug in pyparsing. indentedBlock uses OneOrMore internally to implement the repetition of the embedded lines. But restOfLine does not fail if it is at the end of a line, and so once you get to the end of the string, indentedBlock's repetition just keeps finding empty restOfLines, and so indentedBlock just loops forever.
A workaround for now, until this bug gets fixed and released, is to change your definition of line from:
line = ungroup(restOfLine)
to
line = ungroup(~StringEnd() + restOfLine)
I couldn't figure out exactly why the code is doing this. I even tried running it in Debug mode and pausing, but it wouldn't even pause so that I could see where it was getting stuck.
A workaround you could use for now is modifying the data to add an unindented line:
from pyparsing import *
indent_stack = [1]
line = ungroup(restOfLine)
block = ungroup(indentedBlock(line, indent_stack))
# Work
data = """ foo
bar
tar
"""
block.parseString(data + "\nend").pprint()
# Result: [['foo'], ['bar'], ['tar']]
I am learning from the book Learn Python The Hard Way 3.6, by Zed Shaw
There are a series of 6 target.write commands towards the bottom of the script and he wants me to simplify them into a single target.write command using strings formats and escapes. However, I am stuck.
Here is the original code:
from sys import argv
script, filename = argv
print(f"We're going to erase {filename}")
print("If you don't want that, hit CTRL-C (^C).")
print("If you do want that, hit RETURN.")
input("?")
print("Opening the file...")
target = open(filename,'w')
print("Truncating the file. Goodbye!")
target.truncate()
print("Now I'm going to ask you for three lines")
line1 = input("line 1:")
line2 = input("line 2:")
line3 = input("line 3:")
print("Im going to write these to the file.")
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print("And finnaly, we close it")
target.close()
So far I have tried
target.write(line1),(line2),(line3)
but this gives a logical error of only writing to one line not all three.
target.write(line1) + (line2) + (line3)
with this one I get error
'unsupported operand types for +: 'int' + 'str'
target.write(line1),\n,(line2)\n(line3),\n
with this one I get error:
unexpected character after line continuation character
(<string>,line 22)
I have been googling and searching here for answers but have not found anything. One person posted a very similar question except for Zed's 2.7 book. However I am reading Zed's 3.6 book so the answers were no help to me unfortunately.
I'm not sure what you have and haven't covered so far in the book as I'm not familiar with it but one way to do what you want is to format the string first and then pass it to the write method like this:
target.write("{0}\n{1}\n{2}\n".format(line1, line2, line3))
So, I am essentially just dreaming up ideas right now.
I was wondering if it was possible to make a python program that can read a document, take a line from the document, make an if/else statement with it (Like if the text on that line is equal to Hello, than say hello back), and then continue onto the next line. I have already kind of done this in a shell fashion but I want to see if it is possible to have python read the line of a document, interpret it, display something, and move on to the next line of the document.
(I am prepared for this post to get tons of -1's for not knowing how to program a lot of python, and probably just not being clear enough. So before you -1, just add a comment saying what you need me to be clear about.)
The version of python of my choice would be 2.5.
Since you don't know any Python, try this:
with open("file.txt") as f:
for line in f:
if line.strip() == "Hello":
print "Hello back"
or without the exception-safe clause:
for line in open("file.txt"):
if line.strip() == "Hello":
print "Hello back"
the strip() removes the ending newline \n from the line
That is actually a very simple task in Python:
file = open("file.txt") # open the file
while True:
word = file.readline() # read a line from the file
print word # print it to the console
if word == "": # if out of words...
file.close() # ...close the file
break # and break from while loop and exit program