Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download

All published worksheets from http://sagenb.org

Views: 168730
Image: ubuntu2004

1 语句和语法

SAGE 语句中有一些基本规则和特殊字符:

  • 井号 (”#”) 表示之后的字符为注释;
  • 反斜线 (”\”) 继续上一行;
  • 分号 (”;”) 将两个语句连接在一行;
  • 冒号 (”:”) 区分代码块的头和体 (如 for,if);
  • 语句 (代码块) 用缩进块的方式体现;
  • 不同的缩进深度分割不同的代码块.

下述程序运行错误

money=10000;years=0 while money<20000: years=years+1 money=money*1.069
Traceback (most recent call last): File "<stdin>", line 1, in <module> File "_sage_input_4.py", line 10, in <module> exec compile(u'open("___code___.py","w").write("# -*- coding: utf-8 -*-\\n" + _support_.preparse_worksheet_cell(base64.b64decode("bW9uZXk9MTAwMDA7eWVhcnM9MAp3aGlsZSBtb25leTwyMDAwMDoKICAgIHllYXJzPXllYXJzKzEKICAgbW9uZXk9bW9uZXkqMS4wNjk="),globals())+"\\n"); execfile(os.path.abspath("___code___.py"))' + '\n', '', 'single') File "", line 1, in <module> File "/tmp/tmpYeSoA5/___code___.py", line 6 money=money*_sage_const_1p069 ^ IndentationError: unindent does not match any outer indentation level

出错的主要原因是第四行程序缩进和第三行不同造成的.

2 变量赋值

Sage 的赋值操作符号是”=”, 且支持多种赋值语法: 增量赋值、多重赋值、多元赋值, 但是 Sage 不支持自增运算符.

  增赋值支持:

增量赋值支持:+=, -=, *=, /=, %=, **=, <<=, >>=, &=, ˆ=, |=

x=0;x+=1;x
1
x=2;x**=2;x
4
x=[123,'xyz'];x+=[011];x#列表也支持增量赋值
[123, 'xyz', 9]

多重赋值指一次对多个变量自右向左赋值

x,y,z=1,2,3 print x,y,z
1 2 3
x=666;y=888; x,y=y,x;#多远赋值使得数据交换更灵活 print "x=",x print "y=",y
x= 888 y= 666

3 脚本

 Sage 的脚本可使用任意的文本编辑器书写, 一般文件扩展名为 py 或 sage. 首行添加#!/usr/bin/env sage即可添加可执行属性后直接运行. 或者在 sage 中使用 load 或 attach 方法导入sage 的控制台, 两者的区别是 load 读入脚本, 在脚本发生变化时不会修改 sage控制台内的脚本, 而 attach 当脚本发生变化后 Sage 控制台的脚本随机发生变化.

例如编写 myadd.sage 如下(在SAGE notebook下可以使用windows的编辑器编辑好以后, 选择SAGE中的data->upload or creat file...)

#!/usr/bin/env sage
x=1
x+=10
load DATA+'myadd.sage'#在notebook中需要添加文件的路径"DATA", 在cmd下只需load myadd.sage即可 x
101
attach DATA+'myadd.sage' x
101
x#执行此命令前,修改myadd.sage中的100为1000;在notebook下修改文件仅需选择Data->myadd.sage就会出现编辑界面
1001

4 冒泡排序

编写代码完成如下任务: 随机产生 10 个介于 0 到 100 的随机数, 利用冒泡排序法依据自大至小的顺序排列这 10 个随机数.

冒泡排序(Bubble Sort)是一种简单的排序算法。它重复地走访过要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来。走访数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。这个算法的名字由来是因为越小的元素会经由交换慢慢“浮”到数列的顶端。

冒泡排序算法的运作如下:

  1. 比较相邻的元素。如果第一个比第二个大,就交换他们两个。
  2. 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。
  3. 针对所有的元素重复以上的步骤,除了最后一个。
  4. 持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。

编写 bubble sort.py 如下

#!/usr/bin/env sage
n=10
x=[int(random()*100) for each in range(n)]
print "random numbers is ", x
for each in range(n):
    for k in range(n-1):
        if x[k]<x[k+1]:
            x[k],x[k+1]=x[k+1],x[k]
print "Sorted is ", x
在 Sage 中 load 该程序运行结果如下:
load DATA+'bubble sort.py'
random numbers is [25, 74, 40, 14, 25, 74, 2, 73, 13, 94] Sorted is [94, 74, 74, 73, 40, 25, 25, 14, 13, 2]

5 调用 C 语言代码

我们通过一个例子来了解 Sage 调用 C 语言代码. 编写 C 语言程序 test.c如下:

int myfactorial(int n)

{

   int y,i;

   y=1;

   for(i=2;i<=n;i++)y*=i;

   return y;

}

编写 test.spyx 如下

cdef extern from "test.c": 
 int myfactorial(int n) 
 def test(n): 
 return myfactorial(n) 
在 Sage 的命令行中调用
loda test.spyx
然后执行test(8)即可.
 
load DATA+'test.spyx'
Compiling /sagenb/servers/sage_notebook-sagenb.sagenb/home/xuepx/4/data/test.spyx...
test(8)
40320
cfile=open(DATA+'test.c') cfilelines=cfile.readlines() for eachline in cfilelines: print eachline cfile.close()
int myfactorial(int n) { int y,i; y=1; for(i=2;i<=n;i++)y*=i; return y; }
spyxfile=open(DATA+'test.spyx') spyxfilelines=spyxfile.readlines() for eachline in spyxfilelines: print eachline spyxfile.close()
cdef extern from "test.c": int myfactorial(int n) def test(n): return myfactorial(n)