本文介绍了其他说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 以下是我在语言的最后几周收集的一些问题和建议(请注意,其中一些(大多数?) 可能是错误/无用/愚蠢的,但我已经看到这样的笔记对我有帮助 了解很多东西并找到我的弱点。) 1)我已经看到pop / append列表被分摊到它的尾部,但不是因为 它的头部。为此,有deque。但我认为动态数组可以是头部和尾部都有一些缓冲区(但是你需要保留一个 索引S来跳过头部缓冲区而你必须使用此索引每个 访问列表的元素)。我认为Python内置数据类型中最重要的设计目标是灵活性(和安全性), 而不仅仅是速度(但字典很快^ _ ^ ),那么为什么 是deques而不是带有摊销尾部和尾部操作的列表? (我的假设:保持列表实现更简单,避免 浪费头缓冲区的内存,并保持它们更快一点, 避免使用跳过索引S)。 2)I通常更喜欢明确的详细语法,而不是神秘的符号 (像装饰器语法),但我喜欢中缀Pascal语法.. 指定一个整数或字母的闭合间隔(一个元组?)(这个 语法并不意味着弃用范围函数)。它提醒我 ....语法有时用于数学定义序列。 例子: 断言1 .9 ==元组(范围(1,10))对于i在1..12中的:对于a中的c,传递 。 z":传递 3)我认为它可以用来定义中缀函数,比如这个 想象的装饰器语法: @infix def interval(x,y):返回范围(x,y + 1)#2所需参数 这可能允许: 断言5间隔9 ==间隔(5,9) 4)printf风格的格式很强大,但我仍然认为它是 对于通常的目的而言非常复杂,我通常必须在文档中查看其语法 。我认为Pascal语法很好而且更容易记住 (特别是对于有一点Pascal / Delphi经验的人^ _ ^),它 使用两个: ;格式化浮点数(第二个:数字 是可选的)。例如这个Delphi程序: {$ APPTYPE CONSOLE} const a = -12345.67890; 开始 writeln(a); writeln(a:2:0); writeln(a:4:2); writeln(a:4:20); writeln(a:12:2); 结束。 给: -1.23456789000000E + 0004 -12346 -12345.68 -12345.67890000000000000000 -12345.68 (最后一行以3个空格开头) 5)关于回合的文档: 值四舍五入到10的最大倍数减去n; 如果两个倍数相等,则舍入远离0(所以。 例如,round(0.5)是1.0和圆(-0.5)是-1.0)。 例如: a = [0.05 + x / 10.0,范围内的x(10)] b str(round(x,1)) for x in a:print x, print for x in a: print str(round(x,1))+ ", 给: 0.05 0.15 0.25 0.35 0.45 0.55 0.65 0.75 0.85 0.95 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 如果数字紧靠最后一个sig的右边。图。比你更多的是b $ b,你可以向上看。 如果数字紧靠最后一个sig的右边。图。比你少了5美元,你向下舍入。 如果数字紧靠最后一个sig的右边。图。等于 5,如果最后一个sig,你会向上舍入。图。很奇怪。如果 最后一个sig,你向下舍入。图。甚至。如果5后跟非零 数字,则向上舍入,无论最后一个sig。图。是奇数还是偶数。 http:// www。 towson.edu/~ladon/roundo~1.html http://mathforum.org/library/drmath/view/58972.html http://mathforum.org/library/drmath/view/58961.html 6)map(功能,列表, ...)将函数应用于列表的每个项目,并且 返回结果列表。如果list是嵌套数据结构,则map 仅将函数应用于上层对象。 在Mathematica中,还有另一个参数来指定level。 适用。 所以: map(str,[[1,[2]],3]) ==> [''[1,[2]]'',''3''] 假设级别(默认级别= 1,它给出正常的 Python地图): map(str,[[1,[2] ],3],等级= 1) ==> [''[1,[2]]'',''3''] map(str,[[1,[2]],3],level = 2) ==> ['''',''[2]'',''3''] 我认为这种语义可以扩展: level = 0意味着地图执行到叶子(0表示无限,这不是很好,但它可能很有用因为我认为Python 不不包含内置无限。 level = -1表示地图执行到 离开之前的等级。 等级= -n表示地图在离开之前的n个级别执行。 7)也许它对于拓展有用nded reload(module)语义: reload(module [,recurse = False]) 如果recurse = True,它会重新加载模块并递归所有模块 它导入。 8)为什么重载是一个函数而导入是一个声明? (那么为什么不是重新加载一个语句,或两个函数?) 9)没有返回语句的函数返回无: def foo(x):print x 我认为编译器/解释器可以提供编译警告。其中 这样的功能结果分配给某些东西: y = foo(x) (我知道有些情况不能在编译时间, 但其他情况也很有用。) 我不知道PyChecker是否已经这样做了。一般来说,我希望看到一些内置在普通翻译中的支票。 说明如下: open ="你好 合法,但可能是汇编警告在这里也很有用 (如果设置了详细标志,甚至可能是运行时警告)。 10)def语句之间可能存在中间内容 lambda。例如,它可以被称为有趣。 (或者它可以被称为 def仍然)。有了它可能def和lambdas都不是必需的再次。示例: cube = fun x: 返回x ** 3 (最后一行缩进) > 排序(数据,有趣x,y:返回xy) (可能现在几乎不可能用语言修改它。) 11)对于在函数内指定 全局变量的替代语法,这只是一个疯狂的想法。来自: def foo(x): 全球y y = y + 2 (最后两行是缩进的) 要: def foo(x):global.y = global.y + 2 除了global.y之外,也许它可以存在像upper.y或 caller.y这样的语法,这意味着在上层语境中的名称y。 upper.upper.y等 12)Mathematica的交互式IDE建议可能的拼写错误; 此功能通常很有用,也适用于内置名称功能, 它可以关闭。 在[1]中:= sin2 = N [Sin [2]] Out [1] = 0.909297 在[2]中:= sina2 一般::" spell1":"可能的拼写错误:新符号名称" sina2" 类似于现有符号sin2。 Out [2] = sina2 我不知道是否一些Python IDE(或IPython)已经这样做了,但是它可以在Pythonwin中使用。 13)在Mathematica语言中,=具有与Python相同的含义,但是 :=不同: lhs:= rhs将rhs指定为lhs的延迟值。 rhs是以未评估的形式维持的。当lhs出现时,它会被 rhs取代,每次重新评估。 我不知道这是否有用... ------------------ 14)在我最后一封笔记的电子邮件中,我'我试图解释Mathematica的 模式匹配编程范例。 Josiah Carlson 回答我: http://groups-beta.google.com/group/...5600094cb281c1 在C / C ++世界中,即称为多态。你可以用Python做多态,装饰者可以把它变成 更容易...... 这种编程就像在函数参数上使用一种正则表达式 。以下是一些快速操作符,来自 (受版权保护的)在线帮助: _或Blank []是一个模式对象,可以代表任何Mathematica 表达式。 例如这个信息来自: http://documents.wolfram.com/mathema...unctions/Blank 这用于函数定义中的示例: f [x_]:= x ^ 2 __(两个_字符)或BlankSequence []是一个模式对象,可以 代表一个或多个Mathematica表达式的任何序列。 ___(三个_字符)或BlankNullSequence []是一个模式对象 可以站立对于任何零或多个Mathematica 表达式的序列。 ___h或BlankNullSequence [h]可代表任何表达式序列, all of有头h。 p1 | p2 | ...是一个模式对象,代表任何模式 pi s:obj代表模式对象obj,分配名称为s。当使用 转换规则时,右侧*手 侧的任何出现都会被左侧匹配的任何表达式替换为* 方。运营商:优先级相对较低。表达式 x:_ + _因此被解释为x:(_ + _),而不是(x:_)+ _。 p:v是模式对象,表示形式为p的表达式,如果省略,则应替换为v。可选用于指定 " optional arguments"在由模式表示的函数中。模式 对象p给出了参数应该具有的形式(如果存在)。 表达式v给出默认值。如果参数是缺席则使用。示例:模式f [x_,y_:1]与f [a]匹配,x 取值a,y取值1.它也可以匹配 f [a,b],y取值b。 p ..是一个模式对象,表示一个或多个序列 表达式,每个匹配p。 p ...是一个模式对象,表示零个或多个 表达式的序列,每个匹配p。 patt /; test是一种模式,只有当测试的评估结果为真时才会匹配。 示例:f [x_]:= fp [x] /; x> 1在a的情况下定义了一个函数。 lhs:= Module [{vars},rhs /; test]允许在test和rhs之间共享局部变量 。您可以使用与Block相同的构造和 With。 p?test是一个模式对象,代表任何匹配的表达式 p,测试的应用程序给出了True。例如: p1 [x_?NumberQ]:= Sqrt [x] p2 [x_?NumericQ]:= Sqr [x] Verbatim [expr]表示模式匹配中的expr,要求expr 与它看起来完全匹配,没有替换空格或 其他变换。 Verbatim [x_]只匹配实际的 表达式x_。 Verbatim在设置转换其他转换规则的规则时非常有用。 HoldPattern [expr]相当于模式匹配的expr,但是 以未评估的形式维护expr。 无序是一个属性,可以分配给符号f到 表示元素a in形式为f [e1,e2,...] 的表达式应自动按规范顺序排序。这个属性是模式匹配中的。 Flat是一个属性,可以分配给符号f表示 所有涉及嵌套函数f的表达式都应该被展平 out。这个属性在模式匹配中被考虑。 OneIdentity是一个属性,可以分配给符号f到 表示f [x],f [f [x]]等等等等于模式匹配的 目的。 默认[f],如果已定义,则给出使用_获得的 函数f的参数的默认值。模式对象。 默认[f,i]给出_时使用的默认值。显示为f的 i-th参数。 个案[{e1,e2,...},pattern]给出一个a的列表符合 模式。 个案[{e1,e2,...},模式 - > rhs]给出了对应于与模式匹配的ei的rhs 的值列表。 位置[expr,pattern]给出了一个列表对象 匹配模式的位置出现在expr中。 选择[list,crit]选择列表的所有元素列表[ei] 是真的。 DeleteCases [expr,pattern]删除所有符合 模式的expr元素。 DeleteCases [expr,pattern,levspec]删除levspec指定的级别上的expr的所有部分。匹配模式。 示例:DeleteCases [{1,a, 2,b},_Integer] ==> {a,b} Count [list,pattern]给出列表中符合 模式的元素数量。 如果模式表单与expr匹配,则MatchQ [expr,form]返回True,否则 返回False。 它可能看起来很奇怪,但是专家甚至可以使用它来编写小型的完整的b $ b程序...但通常它们只在必要时使用。 注意我不是建议添加那些(全部)进入python。 ------------------ 15) NetLogo是一种源自StarLogo的徽标,用 Java实现。 http://ccl.northwestern.edu/netlogo/ 我认为它包含一些对Python也有用的想法。 - 它内置了一些高级数据结构,比如通常的海龟 (但通常你会同时使用大量的海龟), 和拍拍ch(可编程细胞自动机层,每个细胞可以编程并且可以与附近的细胞或附近的海龟互动) - 它包含内置图形,因为它'对于开始编程的人来说,它通常很有用,而且它对很多其他东西都很有用。在 Python中,它可以是一个小而简单的快速的用途。图形库 (也可以使用Tkinter,但更简单的东西可以用于某些 快速和肮脏的图形。也许这个库也可以比 Tkinter像素绘图和像素矩阵可视化。 - 它包含几种类型的内置图形来绘制变量等等(对于 python有许多外部绘图仪。) - 它的内置小部件非常易于使用(它们在内部定义了 NetLogo和StarLogo源代码),但它们看起来也很可能非常类似于玩具的 用于Python程序... - 这种语言包含许多其他好主意。其中一些 可能看起来太像玩具了,还有一些例子: http://ccl.northwestern.edu/netlogo/models/ 显示这种语言只是部分玩具,它可能很有用 这是一个来源,通常是它的一些部分(如小部件定位和 $ b) $ b参数)由IDE管理: http://ccl.northwestern.edu/netlogo/...logy/Fur.nlogo 再见, 熊抱, Bearophile 解决方案 APPTYPE CONSOLE} const a = - 12345.67890; 开始 writeln(a); writeln(a:2:0); writeln (a:4:2); writeln(a:4:20); writeln(a:12:2); 结束。 给: -1.23456789000000E + 0004 -12346 -12345.68 -12345.67890000000000000000 -12345.68 (最后一个行以3个空格开头) 5)关于回合的文档: 将值四舍五入到10的最接近倍数到幂减去n; 如果两个倍数相等,则舍入远离0(所以。 例如,round(0.5)为1.0,round(-0.5)为-1.0)。 例如: a = [0.05 + x / 10.0 for x in range(10)] b str(round(x,1)) for x in a:print x, print for x in a:print str(round(x,1))+" ", 给: 0.05 0.15 0.25 0.35 0.45 0.55 0.65 0.75 0.85 0.95 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 如果数字紧靠最后一个sig的右边。图。比你更多的是b $ b,你可以向上看。 如果数字紧靠最后一个sig的右边。图。比你少了5美元,你向下舍入。 如果数字紧靠最后一个sig的右边。图。等于 5,如果最后一个sig,你会向上舍入。图。很奇怪。如果 最后一个sig,你向下舍入。图。甚至。如果5后跟非零 数字,则向上舍入,无论最后一个sig。图。是奇数还是偶数。 http:// www。 towson.edu/~ladon/roundo~1.html http://mathforum.org/library/drmath/view/58972.html http://mathforum.org/library/drmath/view/58961.html 6)map(功能,列表, ...)将函数应用于列表的每个项目,并且 返回结果列表。如果list是嵌套数据结构,则map 仅将函数应用于上层对象。 在Mathematica中,还有另一个参数来指定level。 适用。 所以: map(str,[[1,[2]],3]) ==> [''[1,[2]]'',''3''] 假设级别(默认级别= 1,它给出正常的 Python地图): map(str,[[1,[2] ],3],等级= 1) ==> [''[1,[2]]'',''3''] map(str,[[1,[2]],3],level = 2) ==> ['''',''[2]'',''3''] 我认为这种语义可以扩展: level = 0意味着地图执行到叶子(0表示无限,这不是很好,但它可能很有用因为我认为Python 不不包含内置无限。 level = -1表示地图执行到 离开之前的等级。 等级= -n表示地图在离开之前的n个级别执行。 7)也许它对于拓展有用nded reload(module)语义: reload(module [,recurse = False]) 如果recurse = True,它会重新加载模块并递归所有模块 它导入。 8)为什么重载是一个函数而导入是一个声明? (那么为什么不是重新加载一个语句,或两个函数?) 9)没有返回语句的函数返回无: def foo(x):print x 我认为编译器/解释器可以提供编译警告。其中 这样的功能结果分配给某些东西: y = foo(x) (我知道有些情况不能在编译时间, 但其他情况也很有用。) 我不知道PyChecker是否已经这样做了。一般来说,我希望看到一些内置在普通翻译中的支票。 说明如下: open ="你好 合法,但可能是汇编警告在这里也很有用 (如果设置了详细标志,甚至可能是运行时警告)。 10)def语句之间可能存在中间内容 lambda。例如,它可以被称为有趣。 (或者它可以被称为 def仍然)。有了它可能def和lambdas都不是必需的再次。示例: cube = fun x: 返回x ** 3 (最后一行缩进) > 排序(数据,有趣x,y:返回xy) (可能现在几乎不可能用语言修改它。) 11)对于在函数内指定 全局变量的替代语法,这只是一个疯狂的想法。来自: def foo(x): 全球y y = y + 2 (最后两行是缩进的) 要: def foo(x):global.y = global.y + 2 除了global.y之外,也许它可以存在像upper.y或 caller.y这样的语法,这意味着在上层语境中的名称y。 upper.upper.y等 12)Mathematica的交互式IDE建议可能的拼写错误; 此功能通常很有用,也适用于内置名称功能, 它可以关闭。 在[1]中:= sin2 = N [Sin [2]] Out [1] = 0.909297 在[2]中:= sina2 一般::" spell1":"可能的拼写错误:新符号名称" sina2" 类似于现有符号sin2。 Out [2] = sina2 我不知道是否一些Python IDE(或IPython)已经这样做了,但是它可以在Pythonwin中使用。 13)在Mathematica语言中,=具有与Python相同的含义,但是 :=不同: lhs:= rhs将rhs指定为lhs的延迟值。 rhs是以未评估的形式维持的。当lhs出现时,它会被 rhs取代,每次重新评估。 我不知道这是否有用... ------------------ 14)在我最后一封笔记的电子邮件中,我'我试图解释Mathematica的 模式匹配编程范例。 Josiah Carlson 回答我: http://groups-beta.google.com/group/...5600094cb281c1 在C / C ++世界中,即称为多态。你可以用Python做多态,装饰者可以把它变成 更容易...... 这种编程就像在函数参数上使用一种正则表达式 。以下是一些快速操作符,来自 (受版权保护的)在线帮助: _或Blank []是一个模式对象,可以代表任何Mathematica 表达式。 例如这个信息来自: http://documents.wolfram.com/mathema...unctions/Blank 这用于函数定义中的示例: f [x_]:= x ^ 2 __(两个_字符)或BlankSequence []是一个模式对象,可以 代表一个或多个Mathematica表达式的任何序列。 ___(三个_字符)或BlankNullSequence []是一个模式对象 可以站立对于任何零或多个Mathematica 表达式的序列。 ___h或BlankNullSequence [h]可代表任何表达式序列, all of有头h。 p1 | p2 | ...是一个模式对象,代表任何模式 pi s:obj代表模式对象obj,分配名称为s。当使用 转换规则时,右侧*手 侧的任何出现都会被左侧匹配的任何表达式替换为* 方。运营商:优先级相对较低。表达式 x:_ + _因此被解释为x:(_ + _),而不是(x:_)+ _。 p:v是模式对象,表示形式为p的表达式,如果省略,则应替换为v。可选用于指定 " optional arguments"在由模式表示的函数中。模式 对象p给出了参数应该具有的形式(如果存在)。 表达式v给出默认值。如果参数是缺席则使用。示例:模式f [x_,y_:1]与f [a]匹配,x 取值a,y取值1.它也可以匹配 f [a,b],y取值b。 p ..是一个模式对象,表示一个或多个序列 表达式,每个匹配p。 p ...是一个模式对象,表示零个或多个 表达式的序列,每个匹配p。 patt /; test是一种模式,只有当测试的评估结果为真时才会匹配。 示例:f [x_]:= fp [x] /; x> 1在a的情况下定义了一个函数。 lhs:= Module [{vars},rhs /; test]允许在test和rhs之间共享局部变量 。您可以使用与Block相同的构造和 With。 p?test是一个模式对象,代表任何匹配的表达式 p,测试的应用程序给出了True。例如: p1 [x_?NumberQ]:= Sqrt [x] p2 [x_?NumericQ]:= Sqr [x] Verbatim [expr]表示模式匹配中的expr,要求expr 与它看起来完全匹配,没有替换空格或 其他变换。 Verbatim [x_]只匹配实际的 表达式x_。 Verbatim在设置转换其他转换规则的规则时非常有用。 HoldPattern [expr]相当于模式匹配的expr,但是 以未评估的形式维护expr。 无序是一个属性,可以分配给符号f到 表示元素a in形式为f [e1,e2,...] 的表达式应自动按规范顺序排序。这个属性是模式匹配中的。 Flat是一个属性,可以分配给符号f表示 所有涉及嵌套函数f的表达式都应该被展平 out。这个属性在模式匹配中被考虑。 OneIdentity是一个属性,可以分配给符号f到 表示f [x],f [f [x]]等等等等于模式匹配的 目的。 默认[f],如果已定义,则给出使用_获得的 函数f的参数的默认值。模式对象。 默认[f,i]给出_时使用的默认值。显示为f的 i-th参数。 个案[{e1,e2,...},pattern]给出一个a的列表符合 模式。 个案[{e1,e2,...},模式 - > rhs]给出了对应于与模式匹配的ei的rhs 的值列表。 位置[expr,pattern]给出了一个列表对象 匹配模式的位置出现在expr中。 选择[list,crit]选择列表的所有元素列表[ei] 是真的。 DeleteCases [expr,pattern]删除所有符合 模式的expr元素。 DeleteCases [expr,pattern,levspec]删除levspec指定的级别上的expr的所有部分。匹配模式。 示例:DeleteCases [{1,a, 2,b},_Integer] ==> {a,b} Count [list,pattern]给出列表中符合 模式的元素数量。 如果模式表单与expr匹配,则MatchQ [expr,form]返回True,否则 返回False。 它可能看起来很奇怪,但是专家甚至可以使用它来编写小型的完整的b $ b程序...但通常它们只在必要时使用。 注意我不是建议添加那些(全部)进入python。 ------------------ 15) NetLogo是一种源自StarLogo的徽标,用 Java实现。 http://ccl.northwestern.edu/netlogo/ I think it contains some ideas that can be useful for Python too. $b$ b - It has built-in some hi-level data structures, like the usual turtle (but usually you use LOTS of turtles at the same time, in parallel), $b$ b and the pat ch (programmable cellular automata layers, each cell can be programmed and it can interact with nearby cells or nearby turtles) - It contains built-in graphics, because it’’s often useful for people that starts to program, and it’’s useful for lots of other things. In Python it can be useful a tiny and easy "fast" graphics library (Tkinter too can be used, but something simpler can be useful for some quick&dirty graphics. Maybe this library can also be faster than the Tkinter pixel plotting and the pixel matrix visualisation). - It contains few types of built-in graphs to plot variables, etc. (for python there are many external plotters). - Its built-in widgets are really easy to use (they are defined inside NetLogo and StarLogo source), but they probably look too much toy-like for Python programs... - This language contains lots of other nice ideas. Some of them probably look too much toy-like, still some examples: http://ccl.northwestern.edu/netlogo/models/ Show that this language is only partially a toy, and it can be useful to understand and learn nonlinear dynamics of many systems. This is a source, usually some parts of it (like widget positioning and parameters) are managed by the IDE: http://ccl.northwestern.edu/netlogo/...logy/Fur.nlogo Bye, bear hugs, Bearophile be************@lycos.com wrote: for i in 1..12: pass for c in "a".."z": pass ..... @inf ix def interval(x, y): return range(x, y+1) # 2 parameters needed assert 5 interval 9 == interval(5,9) ..... 10) There can be something in the middle between the def statement and the lambda. These will likely not appear in CPython standard, but Livelogix runs on top of the CPython VM and supports ".." sequences and custom infix operators: http://logix.livelogix.com/tutorial/...ard-Logix.html 11) This is just a wild idea for an alternative syntax to specify a global variable inside a function. From: def foo(x): global y y = y + 2 (the last two lines are indented) To: def foo(x): global.y = global.y + 2 Beside the global.y, maybe it can exist a syntax like upper.y or caller.y that means the name y in the upper context. upper.upper.y etc. This will also likely never appear in Python. I like your idea though. I implemented the same exact thing a couple months ago. One difference though, you only need to type out the full "global.y" if you want to differentiate it from a local variable with the same name. 15) NetLogo is a kind of logo derived from StarLogo, implemented in Java. Show that this language is only partially a toy, and it can be useful to understand and learn nonlinear dynamics of many systems. If you want to do something like Netlogo but using Python instead of Logo, see: http://repast.sourceforge.net/ You can script repast in jython or you can script repast.net. Also, you might request the NetLogo and StarLogo developers to support Jython (in addition to Logo) scripting in their next version (which is already in development and supports 3D).bearophileHUGS: [on Python’’s O(n) list insertion/deletion) at any place other than tail (My hypothesis: to keep list implementation a bit simpler, to avoid wasting memory for the head buffer, and to keep them a little faster, avoiding the use of the skip index S). Add its relative infrequent need. 2) I usually prefer explicit verbose syntax, instead of cryptic symbols (like decorator syntax), but I like the infix Pascal syntax ".." to specify a closed interval (a tuple?) of integers or letters assert 1..9 == tuple(range(1,10)) for i in 1..12: pass for c in "a".."z": pass It’’s been proposed several times. I thought there was a PEP but I can’’t find it. One problem with it; what does for x in 1 .. "a": do? (BTW, it needs to be 1 .. 12 not 1..12 because 1. will be interpreted as the floating point value "1.0".) What does a = MyClass() b = AnotherClass() for x in a .. b: print x do? That is, what’’s the generic protocol? In Pascal it works because you also specify the type and Pascal has an incr while Python doesn’’t. 3) I think it can be useful a way to define infix functions, like this imaginary decorator syntax: @infix def interval(x, y): return range(x, y+1) # 2 parameters needed This may allow: assert 5 interval 9 == interval(5,9) Maybe you could give an example of when you need this in real life? What does 1 + 2 * 3 interval 9 / 3 - 7 do? That is, what’’s the precedence? Does this only work for binary or is there a way to allow unary or other n-ary (including 0-ary?) functions? 4) The printf-style formatting is powerful, but I still think it’’s quite complex for usual purposes, and I usually have to look its syntax in the docs. I think the Pascal syntax is nice and simpler to remember (especially for someone with a little Pascal/Delphi experience ^_^), But to someone with C experience or any language which derives its formatting string from C, Python’’s is easier to understand than your Pascal one. A Python view is that there should be only one obvious way to do a task. Supporting both C and Pascal style format strings breaks that. Then again, having both the old % and the new PEP 292 string templates means there’’s already two different ways to do string formatting. For example this Delphi program: ... const a = -12345.67890; ... writeln(a:4:20); ... Gives: ... -12345.67890000000000000000 Python says that’’s "%.20f" % -12345.67890 ’’-12345.67890000000079453457’’ I don’’t think Pascal is IEEE enough. note also that the Pascal-style formatting strings are less capable than Python’’s, though few people use features like "% 2.3f" % -12.34 ’’-12.340’’ "% 2.3f" % 12.34 ’’ 12.340’’ 5) From the docs about round: ... But to avoid a bias toward rounding up there is another way do this: There are even more ways than that. See http://www.python.org/peps/pep-0327....ing-algorithms The solution chosen was not to change ’’round’’ but to provide a new data type -- Decimal. This is in Python 2.4. 6) map( function, list, ...) applies function to every item of list and return a list of the results. If list is a nested data structure, map applies function to just the upper level objects. In Mathematica there is another parameter to specify the "level" of the apply. .. I think this semantic can be extended: A real-life example would also be helpful here. What does map(len, "Blah", level = 200) return? In general, most people prefer to not use map and instead use list comprehensions and (with 2.4) generator comprehensions. level=0 means that the map is performed up to the leaves (0 means infinitum, this isn’’t nice, but it can be useful because I think Python doesn’’t contain a built-in Infinite). You need to learn more about the Pythonic way of thinking of things. The usual solution for this is to have "level = None". 7) Maybe it can be useful to extended the reload(module) semantic: reload(module [, recurse=False]) If recurse=True it reloads the module and recursively all the modules that it imports. It isn’’t that simple. Reloading modules isn’’t sufficient. Consider import spam a = spam.Eggs() reload(spam) print isinstance(a, spam.Eggs) This will print False because a contains a reference to the old Eggs which contains a reference to the old spam module. As I recall, Twisted has some super-reload code that may be what you want. See http://twistedmatrix.com/documents/c...n.rebuild.html 8) Why reload is a function and import is a statement? (So why isn’’t reload a statement too, or both functions?) import uses the underlying __import__ function. Consider using the __import__ function directly math = __import__("math") The double use of the name "math" is annoying and error prone. It’’s more complicated with module hierarchies. xml = __import__("xml.sax.handler") xml.sax.handler <module ’’xml.sax.handler’’ from ’’/sw/lib/python2.3/xml/sax/handler.pyc’’> xml.sax.saxutils Traceback (most recent call last): File "<stdin>", line 1, in ? AttributeError: ’’module’’ object has no attribute ’’saxutils’’ __import__("xml.sax.saxutils") <module ’’xml’’ from ’’/sw/lib/python2.3/xml/__init__.pyc’’> xml.sax.saxutils <module ’’xml.sax.saxutils’’ from ’’/sw/lib/python2.3/xml/sax/saxutils.pyc’’> Reload takes a reference to the module to reload. Consider import UserString x = UserString reload(x) This reloads UserString. It could be a statement but there’’s no advantage to doing so. 9) Functions without a return statement return None: def foo(x): print x I think the compiler/interpreter can give a "compilation warning" where such function results are assigned to something: y = foo(x) You might think so but you’’ld be wrong. Consider def vikings(): pass def f(): global vikings def vikings(): print "Spammity spam!" return 1.0 if random.random() > 0.5: f() x = vikings() More realistically I’’ve done class DebugCall: def __init__(self, obj): self.__obj = obj def __call__(self, *args, **kwargs): print "Calling", self.__obj, "with", args, kwargs x = self.__obj(*args, **kwargs) print "Returned with", x return x from wherever import f f = DebugCall(f) I don’’t want it generating a warning for those cases where the implicit None is returned. A more useful (IMHO) is to have PyChecker check for cases where both explicit and implicit returns can occur in the same function. Don’’t know if it does that already. Why haven’’t you looked at PyChecker to see what it does? (I know that some of such cases cannot be spotted at compilation time, but the other cases can be useful too). I don’’t know if PyChecker does this already. Generally speaking I’’d like to see some of those checks built into the normal interpreter. Instructions like: open = "hello" Are legal, but maybe a "compilation warning" can be useful here too (and maybe even a runtime warning if a Verbose flag is set). There’’s a PEP for that. See http://www.python.org/peps/pep-0329.html Given your questions it would be appropriate for you to read all the PEPs. 10) There can be something in the middle between the def statement and the lambda. For example it can be called "fun" (or it can be called "def" still). With it maybe both def and lambdas aren’’t necessary anymore. Examples: cube = fun x: return x**3 (the last line is indented) sorted(data, fun x,y: return x-y) (Probably now it’’s almost impossible to modify this in the language.) It’’s been talked about. Problems are: - how is it written? - how big is the region between a lambda an a def? Try giving real world examples of when you would use this ’’fun’’ and compare it to lambda and def forms. you’’ll find there’’s at most one extra line of code needed. That doesn’’t seem worthwhile. 11) This is just a wild idea for an alternative syntax to specify a global variable inside a function. From: def foo(x): global y y = y + 2 (the last two lines are indented) To: def foo(x): global.y = global.y + 2 Beside the global.y, maybe it can exist a syntax like upper.y or caller.y that means the name y in the upper context. upper.upper.y etc. It does have the advantage of being explicit rather than implicit. 12) Mathematica’’s interactive IDE suggests possible spelling errors; I don’’t know anything about the IDEs. I have enabled the tab-complete in my interactive Python session which is nice. I believe IPython is the closest to giving a Mathematica-like feel. There’’s also tmPython. 13) In Mathematica language the = has the same meaning of Python, but := is different: lhs := rhs assigns rhs to be the delayed value of lhs. rhs is maintained in an unevaluated form. When lhs appears, it is replaced by rhs, evaluated afresh each time. I don’’t know if this can be useful... Could you explain why it might be useful? 14) In one of my last emails of notes, I’’ve tried to explain the Pattern Matching programming paradigm of Mathematica. Josiah Carlson answered me: Was there a question in all that? You are proposing Python include a Prolog-style (or CLIPS or Linda or ..) programming idiom, yes? Could you also suggest a case when one would use it? 15) NetLogo is a kind of logo derived from StarLogo, implemented in Java. How about the "turtle" standard library? I must say it’’s getting pretty annoying to say things like "when would this be useful?" and "have you read the documentation?" for your statements. Maybe this library can also be faster than the Tkinter pixel plotting and the pixel matrix visualisation). See also matplotlib, chaco, and other libraries that work hard to make this simple. Have you done any research on what Python can do or do you think ... no, sorry, I’’m getting snippy. Andrew da***@dalkescientific.com Here are some questions and suggestions of mine that I''ve collected inthe last weeks on the language (please note that some (most?) of themare probably wrong/useless/silly, but I''ve seen that such notes help meunderstand a lot of things and to find my weak spots.) 1) I''ve seen that list pop/append is amortised to its tail, but not forits head. For this there is deque. But I think dynamical arrays can bemade with some buffer at both head and tail (but you need to keep anindex S to skip the head buffer and you have to use this index everyaccess to the elements of the list). I think that the most importantdesign goal in Python built-in data types is flexibility (and safety),instead of just speed (but dictionaries are speedy ^_^), so why thereare deques instead of lists with both amortised tail&tail operations?(My hypothesis: to keep list implementation a bit simpler, to avoidwasting memory for the head buffer, and to keep them a little faster,avoiding the use of the skip index S).2) I usually prefer explicit verbose syntax, instead of cryptic symbols(like decorator syntax), but I like the infix Pascal syntax ".." tospecify a closed interval (a tuple?) of integers or letters (thissyntax doesn''t mean to deprecate the range function). It reminds me the.... syntax sometimes used in mathematics to define a sequence.Examples: assert 1..9 == tuple(range(1,10))for i in 1..12: passfor c in "a".."z": pass3) I think it can be useful a way to define infix functions, like thisimaginary decorator syntax: @infixdef interval(x, y): return range(x, y+1) # 2 parameters needed This may allow:assert 5 interval 9 == interval(5,9)4) The printf-style formatting is powerful, but I still think it''squite complex for usual purposes, and I usually have to look its syntaxin the docs. I think the Pascal syntax is nice and simpler to remember(especially for someone with a little Pascal/Delphi experience ^_^), ituses two ":" to format the floating point numbers (the second :numberis optional). For example this Delphi program: {$APPTYPE CONSOLE}const a = -12345.67890;beginwriteln(a);writeln(a:2:0);writeln(a:4:2);writeln(a:4:20);writeln(a:12:2);end. Gives:-1.23456789000000E+0004-12346-12345.68-12345.67890000000000000000-12345.68(The last line starts with 3 spaces)5) From the docs about round:Values are rounded to the closest multiple of 10 to the power minus n;if two multiples are equally close, rounding is done away from 0 (so.for example, round(0.5) is 1.0 and round(-0.5) is -1.0).Example:a = [0.05 + x/10.0 for x in range(10)]b str(round(x, 1))for x in a: print x,printfor x in a: print str(round(x, 1)) + " ", Gives:0.05 0.15 0.25 0.35 0.45 0.55 0.65 0.75 0.85 0.950.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 But to avoid a bias toward rounding up there is another way do this:If the digit immediately to the right of the last sig. fig. is morethan 5, you round up.If the digit immediately to the right of the last sig. fig. is lessthan 5, you round down.If the digit immediately to the right of the last sig. fig. is equal to5, you round up if the last sig. fig. is odd. You round down if thelast sig. fig. is even. You round up if 5 is followed by nonzerodigits, regardless of whether the last sig. fig. is odd or even. http://www.towson.edu/~ladon/roundo~1.html http://mathforum.org/library/drmath/view/58972.html http://mathforum.org/library/drmath/view/58961.html6) map( function, list, ...) applies function to every item of list andreturn a list of the results. If list is a nested data structure, mapapplies function to just the upper level objects.In Mathematica there is another parameter to specify the "level" of theapply. So:map(str, [[1,[2]], 3])==>[''[1, [2]]'', ''3''] With a hypothetical level (default level = 1, it gives the normalPython map): map(str, [[1,[2]], 3], level=1)==>[''[1, [2]]'', ''3''] map(str, [[1,[2]], 3], level=2)==>[''1'', ''[2]'', ''3''] I think this semantic can be extended:level=0 means that the map is performed up to the leaves (0 meansinfinitum, this isn''t nice, but it can be useful because I think Pythondoesn''t contain a built-in Infinite).level=-1 means that the map is performed to the level just before theleaves.Level=-n means that the map is performed n levels before the leaves.7) Maybe it can be useful to extended the reload(module) semantic:reload(module [, recurse=False])If recurse=True it reloads the module and recursively all the modulesthat it imports.8) Why reload is a function and import is a statement? (So why isn''treload a statement too, or both functions?)9) Functions without a return statement return None:def foo(x): print xI think the compiler/interpreter can give a "compilation warning" wheresuch function results are assigned to something:y = foo(x)(I know that some of such cases cannot be spotted at compilation time,but the other cases can be useful too).I don''t know if PyChecker does this already. Generally speaking I''dlike to see some of those checks built into the normal interpreter.Instructions like:open = "hello"Are legal, but maybe a "compilation warning" can be useful here too(and maybe even a runtime warning if a Verbose flag is set).10) There can be something in the middle between the def statement andthe lambda. For example it can be called "fun" (or it can be called"def" still). With it maybe both def and lambdas aren''t necessaryanymore. Examples:cube = fun x:return x**3(the last line is indented) sorted(data, fun x,y: return x-y)(Probably now it''s almost impossible to modify this in the language.)11) This is just a wild idea for an alternative syntax to specify aglobal variable inside a function. From: def foo(x):global yy = y + 2(the last two lines are indented) To: def foo(x): global.y = global.y + 2 Beside the global.y, maybe it can exist a syntax like upper.y orcaller.y that means the name y in the upper context. upper.upper.y etc.12) Mathematica''s interactive IDE suggests possible spelling errors;this feature is often useful, works with builtin name functions too,and it can be switched off.In[1]:= sin2 = N[Sin[2]]Out[1]= 0.909297 In[2]:= sina2General::"spell1": "Possible spelling error: new symbol name "sina2"is similar to existing symbol "sin2".Out[2]= sina2 I don''t know if some Python IDEs (or IPython) do this already, but itcan be useful in Pythonwin.13) In Mathematica language the = has the same meaning of Python, but:= is different: lhs := rhs assigns rhs to be the delayed value of lhs. rhs ismaintained in an unevaluated form. When lhs appears, it is replaced byrhs, evaluated afresh each time. I don''t know if this can be useful...------------------ 14) In one of my last emails of notes, I''ve tried to explain thePattern Matching programming paradigm of Mathematica. Josiah Carlsonanswered me: http://groups-beta.google.com/group/...5600094cb281c1 In the C/C++ world, that is called polymorphism. You can do polymorphism with Python, and decorators may make iteasier... This kind of programming is like the use of a kind regular expressionon the parameters of functions. Here are some fast operators, from the(copyrighted) online help: _ or Blank[ ] is a pattern object that can stand for any Mathematicaexpression.For example this info comes from: http://documents.wolfram.com/mathema...unctions/BlankThis is used for example in the definition of functions:f[x_] := x^2 __ (two _ characters) or BlankSequence[ ] is a pattern object that canstand for any sequence of one or more Mathematica expressions. ___ (three _ characters) or BlankNullSequence[ ] is a pattern objectthat can stand for any sequence of zero or more Mathematicaexpressions.___h or BlankNullSequence[h] can stand for any sequence of expressions,all of which have head h. p1 | p2 | ... is a pattern object which represents any of the patternspi s:obj represents the pattern object obj, assigned the name s. When atransformation rule is used, any occurrence of s on the right*handside is replaced by whatever expression it matched on the left*handside. The operator : has a comparatively low precedence. The expressionx:_+_ is thus interpreted as x:(_+_), not (x:_)+_. p:v is a pattern object which represents an expression of the form p,which, if omitted, should be replaced by v. Optional is used to specify"optional arguments" in functions represented by patterns. The patternobject p gives the form the argument should have, if it is present. Theexpression v gives the "default value" to use if the argument isabsent. Example: the pattern f[x_, y_:1] is matched by f[a], with xtaking the value a, and y taking the value 1. It can also be matched byf[a, b], with y taking the value b. p.. is a pattern object which represents a sequence of one or moreexpressions, each matching p. p... is a pattern object which represents a sequence of zero or moreexpressions, each matching p. patt /; test is a pattern which matches only if the evaluation of testyields True.Example: f[x_] := fp[x] /; x > 1 defines a function in the case when a.lhs := Module[{vars}, rhs /; test] allows local variables to be sharedbetween test and rhs. You can use the same construction with Block andWith. p?test is a pattern object that stands for any expression which matchesp, and on which the application of test gives True. Ex:p1[x_?NumberQ] := Sqrt[x]p2[x_?NumericQ] := Sqr[x] Verbatim[expr] represents expr in pattern matching, requiring that exprbe matched exactly as it appears, with no substitutions for blanks orother transformations. Verbatim[x_] will match only the actualexpression x_. Verbatim is useful in setting up rules for transformingother transformation rules. HoldPattern[expr] is equivalent to expr for pattern matching, butmaintains expr in an unevaluated form. Orderless is an attribute that can be assigned to a symbol f toindicate that the elements a in expressions of the form f[e1, e2, ...]should automatically be sorted into canonical order. This property isaccounted for in pattern matching. Flat is an attribute that can be assigned to a symbol f to indicatethat all expressions involving nested functions f should be flattenedout. This property is accounted for in pattern matching. OneIdentity is an attribute that can be assigned to a symbol f toindicate that f[x], f[f[x]], etc. are all equivalent to x for thepurpose of pattern matching. Default[f], if defined, gives the default value for arguments of thefunction f obtained with a _. pattern object.Default[f, i] gives the default value to use when _. appears as thei-th argument of f. Cases[{e1, e2, ...}, pattern] gives a list of the a that match thepattern.Cases[{e1, e2, ...}, pattern -> rhs] gives a list of the values of rhscorresponding to the ei that match the pattern. Position[expr, pattern] gives a list of the positions at which objectsmatching pattern appear in expr. Select[list, crit] picks out all elements a of list for which crit[ei]is True. DeleteCases[expr, pattern] removes all elements of expr which matchpattern.DeleteCases[expr, pattern, levspec] removes all parts of expr on levelsspecified by levspec which match pattern.Example : DeleteCases[{1, a, 2, b}, _Integer] ==> {a, b} Count[list, pattern] gives the number of elements in list that matchpattern. MatchQ[expr, form] returns True if the pattern form matches expr, andreturns False otherwise. It may look strange, but an expert can even use it to write small fullprograms... But usually they are used just when necessary.Note that I''m not suggesting to add those (all) into python. ------------------ 15) NetLogo is a kind of logo derived from StarLogo, implemented inJava. http://ccl.northwestern.edu/netlogo/I think it contains some ideas that can be useful for Python too.- It has built-in some hi-level data structures, like the usual turtle(but usually you use LOTS of turtles at the same time, in parallel),and the patch (programmable cellular automata layers, each cell can beprogrammed and it can interact with nearby cells or nearby turtles)- It contains built-in graphics, because it''s often useful for peoplethat starts to program, and it''s useful for lots of other things. InPython it can be useful a tiny and easy "fast" graphics library(Tkinter too can be used, but something simpler can be useful for somequick&dirty graphics. Maybe this library can also be faster than theTkinter pixel plotting and the pixel matrix visualisation).- It contains few types of built-in graphs to plot variables, etc. (forpython there are many external plotters).- Its built-in widgets are really easy to use (they are defined insideNetLogo and StarLogo source), but they probably look too much toy-likefor Python programs...- This language contains lots of other nice ideas. Some of themprobably look too much toy-like, still some examples: http://ccl.northwestern.edu/netlogo/models/Show that this language is only partially a toy, and it can be usefulto understand and learn nonlinear dynamics of many systems. This is a source, usually some parts of it (like widget positioning andparameters) are managed by the IDE: http://ccl.northwestern.edu/netlogo/...logy/Fur.nlogoBye,bear hugs,Bearophile 解决方案 APPTYPE CONSOLE}const a = -12345.67890;beginwriteln(a);writeln(a:2:0);writeln(a:4:2);writeln(a:4:20);writeln(a:12:2);end. Gives:-1.23456789000000E+0004-12346-12345.68-12345.67890000000000000000-12345.68(The last line starts with 3 spaces)5) From the docs about round:Values are rounded to the closest multiple of 10 to the power minus n;if two multiples are equally close, rounding is done away from 0 (so.for example, round(0.5) is 1.0 and round(-0.5) is -1.0).Example:a = [0.05 + x/10.0 for x in range(10)]b str(round(x, 1))for x in a: print x,printfor x in a: print str(round(x, 1)) + " ", Gives:0.05 0.15 0.25 0.35 0.45 0.55 0.65 0.75 0.85 0.950.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 But to avoid a bias toward rounding up there is another way do this:If the digit immediately to the right of the last sig. fig. is morethan 5, you round up.If the digit immediately to the right of the last sig. fig. is lessthan 5, you round down.If the digit immediately to the right of the last sig. fig. is equal to5, you round up if the last sig. fig. is odd. You round down if thelast sig. fig. is even. You round up if 5 is followed by nonzerodigits, regardless of whether the last sig. fig. is odd or even. http://www.towson.edu/~ladon/roundo~1.html http://mathforum.org/library/drmath/view/58972.html http://mathforum.org/library/drmath/view/58961.html6) map( function, list, ...) applies function to every item of list andreturn a list of the results. If list is a nested data structure, mapapplies function to just the upper level objects.In Mathematica there is another parameter to specify the "level" of theapply. So:map(str, [[1,[2]], 3])==>[''[1, [2]]'', ''3''] With a hypothetical level (default level = 1, it gives the normalPython map): map(str, [[1,[2]], 3], level=1)==>[''[1, [2]]'', ''3''] map(str, [[1,[2]], 3], level=2)==>[''1'', ''[2]'', ''3''] I think this semantic can be extended:level=0 means that the map is performed up to the leaves (0 meansinfinitum, this isn''t nice, but it can be useful because I think Pythondoesn''t contain a built-in Infinite).level=-1 means that the map is performed to the level just before theleaves.Level=-n means that the map is performed n levels before the leaves.7) Maybe it can be useful to extended the reload(module) semantic:reload(module [, recurse=False])If recurse=True it reloads the module and recursively all the modulesthat it imports.8) Why reload is a function and import is a statement? (So why isn''treload a statement too, or both functions?)9) Functions without a return statement return None:def foo(x): print xI think the compiler/interpreter can give a "compilation warning" wheresuch function results are assigned to something:y = foo(x)(I know that some of such cases cannot be spotted at compilation time,but the other cases can be useful too).I don''t know if PyChecker does this already. Generally speaking I''dlike to see some of those checks built into the normal interpreter.Instructions like:open = "hello"Are legal, but maybe a "compilation warning" can be useful here too(and maybe even a runtime warning if a Verbose flag is set).10) There can be something in the middle between the def statement andthe lambda. For example it can be called "fun" (or it can be called"def" still). With it maybe both def and lambdas aren''t necessaryanymore. Examples:cube = fun x:return x**3(the last line is indented) sorted(data, fun x,y: return x-y)(Probably now it''s almost impossible to modify this in the language.)11) This is just a wild idea for an alternative syntax to specify aglobal variable inside a function. From: def foo(x):global yy = y + 2(the last two lines are indented) To: def foo(x): global.y = global.y + 2 Beside the global.y, maybe it can exist a syntax like upper.y orcaller.y that means the name y in the upper context. upper.upper.y etc.12) Mathematica''s interactive IDE suggests possible spelling errors;this feature is often useful, works with builtin name functions too,and it can be switched off.In[1]:= sin2 = N[Sin[2]]Out[1]= 0.909297 In[2]:= sina2General::"spell1": "Possible spelling error: new symbol name "sina2"is similar to existing symbol "sin2".Out[2]= sina2 I don''t know if some Python IDEs (or IPython) do this already, but itcan be useful in Pythonwin.13) In Mathematica language the = has the same meaning of Python, but:= is different: lhs := rhs assigns rhs to be the delayed value of lhs. rhs ismaintained in an unevaluated form. When lhs appears, it is replaced byrhs, evaluated afresh each time. I don''t know if this can be useful...------------------ 14) In one of my last emails of notes, I''ve tried to explain thePattern Matching programming paradigm of Mathematica. Josiah Carlsonanswered me: http://groups-beta.google.com/group/...5600094cb281c1 In the C/C++ world, that is called polymorphism. You can do polymorphism with Python, and decorators may make iteasier... This kind of programming is like the use of a kind regular expressionon the parameters of functions. Here are some fast operators, from the(copyrighted) online help: _ or Blank[ ] is a pattern object that can stand for any Mathematicaexpression.For example this info comes from: http://documents.wolfram.com/mathema...unctions/BlankThis is used for example in the definition of functions:f[x_] := x^2 __ (two _ characters) or BlankSequence[ ] is a pattern object that canstand for any sequence of one or more Mathematica expressions. ___ (three _ characters) or BlankNullSequence[ ] is a pattern objectthat can stand for any sequence of zero or more Mathematicaexpressions.___h or BlankNullSequence[h] can stand for any sequence of expressions,all of which have head h. p1 | p2 | ... is a pattern object which represents any of the patternspi s:obj represents the pattern object obj, assigned the name s. When atransformation rule is used, any occurrence of s on the right*handside is replaced by whatever expression it matched on the left*handside. The operator : has a comparatively low precedence. The expressionx:_+_ is thus interpreted as x:(_+_), not (x:_)+_. p:v is a pattern object which represents an expression of the form p,which, if omitted, should be replaced by v. Optional is used to specify"optional arguments" in functions represented by patterns. The patternobject p gives the form the argument should have, if it is present. Theexpression v gives the "default value" to use if the argument isabsent. Example: the pattern f[x_, y_:1] is matched by f[a], with xtaking the value a, and y taking the value 1. It can also be matched byf[a, b], with y taking the value b. p.. is a pattern object which represents a sequence of one or moreexpressions, each matching p. p... is a pattern object which represents a sequence of zero or moreexpressions, each matching p. patt /; test is a pattern which matches only if the evaluation of testyields True.Example: f[x_] := fp[x] /; x > 1 defines a function in the case when a.lhs := Module[{vars}, rhs /; test] allows local variables to be sharedbetween test and rhs. You can use the same construction with Block andWith. p?test is a pattern object that stands for any expression which matchesp, and on which the application of test gives True. Ex:p1[x_?NumberQ] := Sqrt[x]p2[x_?NumericQ] := Sqr[x] Verbatim[expr] represents expr in pattern matching, requiring that exprbe matched exactly as it appears, with no substitutions for blanks orother transformations. Verbatim[x_] will match only the actualexpression x_. Verbatim is useful in setting up rules for transformingother transformation rules. HoldPattern[expr] is equivalent to expr for pattern matching, butmaintains expr in an unevaluated form. Orderless is an attribute that can be assigned to a symbol f toindicate that the elements a in expressions of the form f[e1, e2, ...]should automatically be sorted into canonical order. This property isaccounted for in pattern matching. Flat is an attribute that can be assigned to a symbol f to indicatethat all expressions involving nested functions f should be flattenedout. This property is accounted for in pattern matching. OneIdentity is an attribute that can be assigned to a symbol f toindicate that f[x], f[f[x]], etc. are all equivalent to x for thepurpose of pattern matching. Default[f], if defined, gives the default value for arguments of thefunction f obtained with a _. pattern object.Default[f, i] gives the default value to use when _. appears as thei-th argument of f. Cases[{e1, e2, ...}, pattern] gives a list of the a that match thepattern.Cases[{e1, e2, ...}, pattern -> rhs] gives a list of the values of rhscorresponding to the ei that match the pattern. Position[expr, pattern] gives a list of the positions at which objectsmatching pattern appear in expr. Select[list, crit] picks out all elements a of list for which crit[ei]is True. DeleteCases[expr, pattern] removes all elements of expr which matchpattern.DeleteCases[expr, pattern, levspec] removes all parts of expr on levelsspecified by levspec which match pattern.Example : DeleteCases[{1, a, 2, b}, _Integer] ==> {a, b} Count[list, pattern] gives the number of elements in list that matchpattern. MatchQ[expr, form] returns True if the pattern form matches expr, andreturns False otherwise. It may look strange, but an expert can even use it to write small fullprograms... But usually they are used just when necessary.Note that I''m not suggesting to add those (all) into python. ------------------ 15) NetLogo is a kind of logo derived from StarLogo, implemented inJava. http://ccl.northwestern.edu/netlogo/I think it contains some ideas that can be useful for Python too.- It has built-in some hi-level data structures, like the usual turtle(but usually you use LOTS of turtles at the same time, in parallel),and the patch (programmable cellular automata layers, each cell can beprogrammed and it can interact with nearby cells or nearby turtles)- It contains built-in graphics, because it''s often useful for peoplethat starts to program, and it''s useful for lots of other things. InPython it can be useful a tiny and easy "fast" graphics library(Tkinter too can be used, but something simpler can be useful for somequick&dirty graphics. Maybe this library can also be faster than theTkinter pixel plotting and the pixel matrix visualisation).- It contains few types of built-in graphs to plot variables, etc. (forpython there are many external plotters).- Its built-in widgets are really easy to use (they are defined insideNetLogo and StarLogo source), but they probably look too much toy-likefor Python programs...- This language contains lots of other nice ideas. Some of themprobably look too much toy-like, still some examples: http://ccl.northwestern.edu/netlogo/models/Show that this language is only partially a toy, and it can be usefulto understand and learn nonlinear dynamics of many systems. This is a source, usually some parts of it (like widget positioning andparameters) are managed by the IDE: http://ccl.northwestern.edu/netlogo/...logy/Fur.nlogoBye,bear hugs,Bearophile be************@lycos.com wrote: for i in 1..12: pass for c in "a".."z": pass..... @infix def interval(x, y): return range(x, y+1) # 2 parameters needed assert 5 interval 9 == interval(5,9)..... 10) There can be something in the middle between the def statement and the lambda.These will likely not appear in CPython standard, but Livelogix runs ontop of the CPython VM and supports ".." sequences and custom infixoperators: http://logix.livelogix.com/tutorial/...ard-Logix.html 11) This is just a wild idea for an alternative syntax to specify a global variable inside a function. From: def foo(x): global y y = y + 2 (the last two lines are indented) To: def foo(x): global.y = global.y + 2 Beside the global.y, maybe it can exist a syntax like upper.y or caller.y that means the name y in the upper context. upper.upper.y etc.This will also likely never appear in Python. I like your idea though.I implemented the same exact thing a couple months ago. Onedifference though, you only need to type out the full "global.y" if youwant to differentiate it from a local variable with the same name. 15) NetLogo is a kind of logo derived from StarLogo, implemented in Java. Show that this language is only partially a toy, and it can be useful to understand and learn nonlinear dynamics of many systems. If you want to do something like Netlogo but using Python instead ofLogo, see: http://repast.sourceforge.net/You can script repast in jython or you can script repast.net. Also, you might request the NetLogo and StarLogo developers to supportJython (in addition to Logo) scripting in their next version (which isalready in development and supports 3D).bearophileHUGS:[on Python''s O(n) list insertion/deletion) at any place other than tail (My hypothesis: to keep list implementation a bit simpler, to avoid wasting memory for the head buffer, and to keep them a little faster, avoiding the use of the skip index S).Add its relative infrequent need. 2) I usually prefer explicit verbose syntax, instead of cryptic symbols (like decorator syntax), but I like the infix Pascal syntax ".." to specify a closed interval (a tuple?) of integers or letters assert 1..9 == tuple(range(1,10)) for i in 1..12: pass for c in "a".."z": passIt''s been proposed several times. I thought there was a PEPbut I can''t find it. One problem with it; what does for x in 1 .. "a": do? (BTW, it needs to be 1 .. 12 not 1..12 because 1. will beinterpreted as the floating point value "1.0".) What doesa = MyClass()b = AnotherClass()for x in a .. b:print x do? That is, what''s the generic protocol? In Pascal itworks because you also specify the type and Pascal hasan incr while Python doesn''t. 3) I think it can be useful a way to define infix functions, like this imaginary decorator syntax: @infix def interval(x, y): return range(x, y+1) # 2 parameters needed This may allow: assert 5 interval 9 == interval(5,9)Maybe you could give an example of when you need this inreal life? What does 1 + 2 * 3 interval 9 / 3 - 7 do? That is, what''s the precedence? Does this only workfor binary or is there a way to allow unary or othern-ary (including 0-ary?) functions? 4) The printf-style formatting is powerful, but I still think it''s quite complex for usual purposes, and I usually have to look its syntax in the docs. I think the Pascal syntax is nice and simpler to remember (especially for someone with a little Pascal/Delphi experience ^_^),But to someone with C experience or any language which derivesits formatting string from C, Python''s is easier to understand thanyour Pascal one. A Python view is that there should be only one obvious way to doa task. Supporting both C and Pascal style format strings breaksthat. Then again, having both the old % and the new PEP 292 stringtemplates means there''s already two different ways to do stringformatting. For example this Delphi program:... const a = -12345.67890;... writeln(a:4:20);... Gives:... -12345.67890000000000000000Python says that''s "%.20f" % -12345.67890''-12345.67890000000079453457'' I don''t think Pascal is IEEE enough. note also that the Pascal-style formatting strings are lesscapable than Python''s, though few people use features like "% 2.3f" % -12.34''-12.340'' "% 2.3f" % 12.34'' 12.340'' 5) From the docs about round:... But to avoid a bias toward rounding up there is another way do this:There are even more ways than that. See http://www.python.org/peps/pep-0327....ing-algorithms The solution chosen was not to change ''round'' but to providea new data type -- Decimal. This is in Python 2.4. 6) map( function, list, ...) applies function to every item of list and return a list of the results. If list is a nested data structure, map applies function to just the upper level objects. In Mathematica there is another parameter to specify the "level" of the apply... I think this semantic can be extended:A real-life example would also be helpful here. What doesmap(len, "Blah", level = 200)return? In general, most people prefer to not use map and insteaduse list comprehensions and (with 2.4) generator comprehensions. level=0 means that the map is performed up to the leaves (0 means infinitum, this isn''t nice, but it can be useful because I think Python doesn''t contain a built-in Infinite).You need to learn more about the Pythonic way of thinkingof things. The usual solution for this is to have "level = None". 7) Maybe it can be useful to extended the reload(module) semantic: reload(module [, recurse=False]) If recurse=True it reloads the module and recursively all the modules that it imports.It isn''t that simple. Reloading modules isn''t sufficient.Consider import spama = spam.Eggs()reload(spam)print isinstance(a, spam.Eggs) This will print False because a contains a reference tothe old Eggs which contains a reference to the old spam module. As I recall, Twisted has some super-reload code that may bewhat you want. See http://twistedmatrix.com/documents/c...n.rebuild.html 8) Why reload is a function and import is a statement? (So why isn''t reload a statement too, or both functions?)import uses the underlying __import__ function. Consider using the __import__ function directly math = __import__("math") The double use of the name "math" is annoying and error prone. It''s more complicated with module hierarchies. xml = __import__("xml.sax.handler") xml.sax.handler<module ''xml.sax.handler'' from ''/sw/lib/python2.3/xml/sax/handler.pyc''> xml.sax.saxutilsTraceback (most recent call last):File "<stdin>", line 1, in ?AttributeError: ''module'' object has no attribute ''saxutils'' __import__("xml.sax.saxutils")<module ''xml'' from ''/sw/lib/python2.3/xml/__init__.pyc''> xml.sax.saxutils<module ''xml.sax.saxutils'' from ''/sw/lib/python2.3/xml/sax/saxutils.pyc''>Reload takes a reference to the module to reload. Considerimport UserStringx = UserStringreload(x) This reloads UserString. It could be a statement but there''sno advantage to doing so. 9) Functions without a return statement return None: def foo(x): print x I think the compiler/interpreter can give a "compilation warning" where such function results are assigned to something: y = foo(x)You might think so but you''ld be wrong. Consider def vikings():pass def f():global vikingsdef vikings():print "Spammity spam!"return 1.0 if random.random() > 0.5:f() x = vikings() More realistically I''ve done class DebugCall:def __init__(self, obj):self.__obj = objdef __call__(self, *args, **kwargs):print "Calling", self.__obj, "with", args, kwargsx = self.__obj(*args, **kwargs)print "Returned with", xreturn x from wherever import ff = DebugCall(f) I don''t want it generating a warning for those cases wherethe implicit None is returned. A more useful (IMHO) is to have PyChecker check for caseswhere both explicit and implicit returns can occur in thesame function. Don''t know if it does that already. Why haven''t you looked at PyChecker to see what it does? (I know that some of such cases cannot be spotted at compilation time, but the other cases can be useful too). I don''t know if PyChecker does this already. Generally speaking I''d like to see some of those checks built into the normal interpreter. Instructions like: open = "hello" Are legal, but maybe a "compilation warning" can be useful here too (and maybe even a runtime warning if a Verbose flag is set).There''s a PEP for that. See http://www.python.org/peps/pep-0329.html Given your questions it would be appropriate for you to read all thePEPs. 10) There can be something in the middle between the def statement and the lambda. For example it can be called "fun" (or it can be called "def" still). With it maybe both def and lambdas aren''t necessary anymore. Examples: cube = fun x: return x**3 (the last line is indented) sorted(data, fun x,y: return x-y) (Probably now it''s almost impossible to modify this in the language.)It''s been talked about. Problems are:- how is it written?- how big is the region between a lambda an a def? Try giving real world examples of when you woulduse this ''fun'' and compare it to lambda and def forms.you''ll find there''s at most one extra line of codeneeded. That doesn''t seem worthwhile. 11) This is just a wild idea for an alternative syntax to specify a global variable inside a function. From: def foo(x): global y y = y + 2 (the last two lines are indented) To: def foo(x): global.y = global.y + 2 Beside the global.y, maybe it can exist a syntax like upper.y or caller.y that means the name y in the upper context. upper.upper.y etc.It does have the advantage of being explicit rather thanimplicit. 12) Mathematica''s interactive IDE suggests possible spelling errors;I don''t know anything about the IDEs. I have enabled thetab-complete in my interactive Python session which is nice. I believe IPython is the closest to giving a Mathematica-like feel.There''s also tmPython. 13) In Mathematica language the = has the same meaning of Python, but := is different: lhs := rhs assigns rhs to be the delayed value of lhs. rhs is maintained in an unevaluated form. When lhs appears, it is replaced by rhs, evaluated afresh each time. I don''t know if this can be useful...Could you explain why it might be useful? 14) In one of my last emails of notes, I''ve tried to explain the Pattern Matching programming paradigm of Mathematica. Josiah Carlson answered me:Was there a question in all that? You are proposing Python include a Prolog-style (orCLIPS or Linda or ..) programming idiom, yes? Could youalso suggest a case when one would use it? 15) NetLogo is a kind of logo derived from StarLogo, implemented in Java.How about the "turtle" standard library? I must say it''s getting pretty annoying to say things like"when would this be useful?" and "have you read the documentation?"for your statements. Maybe this library can also be faster than the Tkinter pixel plotting and the pixel matrix visualisation). See also matplotlib, chaco, and other libraries that work hardto make this simple. Have you done any research on what Pythoncan do or do you think ... no, sorry, I''m getting snippy. Andrew da***@dalkescientific.com 这篇关于其他说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-23 01:49