FAQs and Hints

Running sage

If you cannot run Sage locally on your computer (it works fine on Linux and on Mac OS X) and you don't want to use virtualization or the web interface, use the local version installed on all CS linux computers (login to linux in the lab or ssh to nova).

Assignment 1

Problem 5 runs very slow

Use a % b to calculate the remainder of a modulo b.
mod(a,b) gives identical results (for integers) but is much much slower!

Python questions

Here are some basic python commands, see any python tutorial for these.
I like the official tutorial.

How to work with files?


returns a string containing the local file's contents.
If the file is on a web server, you can use
import urllib
T = urllib.urlopen("http://www.server.com/path/to/file.txt").read()

How to count how many times an element appears in a list?

if X is a string or a list, X.count(t) returns the number of appearances of t in X,
e.g., "hello, world".count("l") returns 3.

How to I read and display Hebrew text?

Here's a working example.

import urllib
addr = "http://www.benyehuda.org/"
print T[5183:5197]

output is


How to implement substitution ciphers?

Let's say you want to switch all os to ls and vice versa in the text hello, world.

txt = u"Hello, world" # note the u, must be a unicode string
mapping = { ord(u'o') : u'l', ord(u'l') : u'o' } # ord(source character) : dest_character

Let's say you want to shift all letters by one (a->b, b->c, …, z->a)

txt = u"Hello, world"
src_alphabet = u'abcdefghijklmnopqrstuvwxyz'
dst_alphabet = src_alphabet[1:] + u'a'
mapping = dict( (ord(x), y) for x,y in zip(src_alphabet, dst_alphabet))

Sage questions

Check also the official documentation.

How to plot more than one function on the same canvas?

Here's an example.

P = [(x, 10 * x + 7 + randint(-3,3)) for x in range(1,20)]
L = [(0,7),(20,207)]
point(P) + line(L, color="green")
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License