perl,python和ruby的对比

perl,python和ruby的对比 (2012-05-19 11:00:13)[编辑][删除]转载▼
标签: it
看到这篇文章挺好,所以转来,以防将来找不到了.
转:http://danvk.org/josephus.html

The Josephus Problem
What is the Josephus problem? To quote from Concepts, Techniques, and Models of Computer Programming (a daunting title if ever there was one):
Flavius Josephus was a roman historian of Jewish origin. During the Jewish-Roman wars of the first century AD, he was in a cave with fellow soldiers, 40 men in all, surrounded by enemy Roman troops. They decided to commit suicide by standing in a ring and counting off each third man. Each man so designated was to commit suicide...Josephus, not wanting to die, managed to place himself in the position of the last survivor.
In the general version of the problem, there are n soldiers numbered from 1 to n and each k-th soldier will be eliminated. The count starts from the first soldier. What is the number of the last survivor?
I decided to model this situation using objects in three different scripting languages, Perl, Ruby, and Python. The solution in each of the languages is similar. A Person class is defined, which knows whether it is alive or dead, who the next person in the circle is, and what position number it is in. There are methods to pass along a kill signal, and to create a chain of people. Either of these could have been implemented using iteration, but I wanted to give recursion a whirl, since it's tougher on the languages. Here are my results.

Perl
package Person;
use overload q("") => \&to_s;

# Create a new, living Person with the given position
sub new {
my $invocant = shift;
my $class = ref($invocant) || $invocant;
my $pos = shift;
my $self = { "position" => $pos,
"alive" => 1,
"succ" => undef };
return bless($self,$class);
}

# Getter/Setter for successor
sub succ : lvalue {
my $self = shift;
$self->{succ}
}

# Create a chain of people
sub createChain {
my $self = shift;
my $n = shift;
return $self unless $n;

my $succ = Person->new($self->{position}+1);
$self->succ = $succ;
$succ->createChain($n-1)
}

# Pass on the killing message
sub circularKill {
my $self = shift;
my ($pos,$nth,$remaining)=@_;

return $self->{succ}->circularKill($pos, $nth, $remaining)
unless $self->{alive};
return $self unless $remaining > 1;

if ($pos == $nth) {
$self->{alive} = 0;
$pos = 0;
$remaining--;
}
$self->{succ}->circularKill($pos+1, $nth, $remaining)
}

# Print descriptive information
sub to_s{
my $self = shift;
"Person #".$self->{position}.", ".($self->{alive} ? "alive" : "dead")
}

# Circle of $n people, kill every one out of every $m
$m = 3;
$n = 40;

$first = new Person(1);
$last = $first->createChain($n-1);
$last->succ = $first;

$winner = $first->circularKill(1,$m,$n);
print "Winner: ", $winner, "\n";



What's good:
Support for statement modifiers (ie, the 'if' or 'unless' after a line
Last evaluated expression is assumed to be the return value (look at sub succ)
Once the class is actually defined, everything seems fairly clean
It runs, quickly, and gets the right answer
What's bad:
It looks ugly as hell, and feels like a hack. Look at the new routine! Without the help of Programming Perl (aka The Camel), I would have been clueless how to write this.
Also under the "it's a hack" heading, I don't like how each subroutine begins by shifting $self off of the arguments stack. This seems unnatural.
Overloading the "stringification" operator was a little roundabout (look at the use overload line. Again, this felt unnatural, and I wouldn't have had a clue how to do it without The Camel.

So, in conclusion, defining classes in Perl is decidedly inelegant, and unintuitive. If I were to do it often, I'd have to cut and paste that new routine wherever I went. That's a BIG stumbling block, and it would probably be enough to keep me from using OO in Perl. In fact, it has been for the past several years.
I wanted to do some OO however, so I checked out Python and Ruby. Here's the same problem coded using each of them.
Ruby
class Person
attr_reader :position, :succ, :alive
attr_writer :position, :succ, :alive

# Everyone is alive, initially
def initialize(pos)
@position = pos
@alive = true
end

# For creating a linked chain of people
def createChain(n)
return self unless n>0
@succ = Person.new(@position + 1)
@succ.createChain(n-1)
end

# Kill every nth person
# Current position in the cycle is pos
# there are remaining people remaining
# Stop killing if we're the last one.
def kill(pos,nth,remaining)
return @succ.kill(pos,nth,remaining) if !@alive
return self if (remaining == 1)

if pos == nth
@alive = false
puts self
pos = 0
remaining-=1
end
@succ.kill(pos+1,nth,remaining)
end

# Information about this person
def to_s
"Person \##@position, #{@alive ? 'alive' : 'dead'}"
end
end

# Set n to anything much higher (like 10, say)
# And the program hangs, or has an "Illegal Instruction"
n = 7

first = Person.new(1)
last = first.createChain(n-1)
last.succ = first

winner = first.kill(1,3,n)
# If I use puts "Winner: " + winner, I get an error:
# in `+': failed to convert Person into String (TypeError)
#puts "Winner: " + winner
puts "Winner: ", winner


What's good:
Since this was my first Ruby script, I can't claim to have written good, idiomatic code, but it sure looks nice to me. It's far more elegant than the Perl mess, and significantly shorter as well.
I like the attr_reader and attr_writer shortcuts.
"stringification" overloading was pretty simple, especially since this is done frequently in the online reference.
As in Perl, there are statement modifiers and the last statement is the return value, a fact which I used in most of these routines.
I like the flexible interpolation via #{}
What's bad:
While the code looks great, the execution sucks. Ruby's limit on stack depth seems to be set somewhere around 60, which is absurdly low. This clearly prevents setting n particularly high. While n=40 worked in both Perl and Python, Ruby gives an "Illegal Instruction" error or just hangs, which I eventually figured out was its way of saying that the depth limit had been reached. There may be some way around it, but this limitation seems pretty atrocious.
When there's an error in a Ruby program, the error messages tend to be pretty useless, usually along the lines of "There's an error in line x", if that. When I had n set at 40, I'd just get an "Illegal Instruction" error, which was incredibly misleading. Setting the --debug flag didn't help in this department.
Also, and I may just be missing something here, puts "Winner: " + winner told me that it couldn't convert a Person into a String, which it clearly could, since puts winner worked fine.

So in conclusion, I really liked coding in Ruby, but the execution just wasn't there. If there are any Ruby fans out there who know how to fix the problems I mentioned, I'd be thrilled to hear from you.
Python
class Person:
def __init__(self,pos):
self.pos = pos
self.alive = 1
def __str__(self):
return "Person #%d, %s" % (self.pos, self.alive)

# Creates a chain of linked people
# Returns the last one in the chain
def createChain(self,n):
if n>0:
self.succ = Person(self.pos+1)
return self.succ.createChain(n-1)
else:
return self

# Kills in a circle, getting every nth living person
# When there is only one remaining, the lone survivor is returned
def kill(self,pos,nth,remaining):
if self.alive == 0: return self.succ.kill(pos,nth,remaining)
if remaining == 1: return self
if pos == nth:
self.alive = 0
pos=0
remaining-=1
return self.succ.kill(pos+1,nth,remaining)

# n people in a circle
# kill every mth person
n = 40
m = 3

first = Person(1)
last = first.createChain(n-1)
last.succ = first

print "In a circle of %d people, killing number %d" % (n,m)
winner = first.kill(1,m,n)
print "Winner: ", winner


What's good:
It's very compact (shortest of the three), mostly because of the lack of lines to end blocks (ie, "end" in Ruby or "}" in Perl). Not having these lines does feel a little weird, but I think I could get used to it.
I like the printf-style formatting via the % operator. I can't say whether I like it more than the direct interpolation in Ruby and Perl, however.
Unlike in Ruby, the program ran without a hitch, and got the right answer.
What's bad:
__init__ and __str__? This seems ugly, though that may be part of the "never touch anything starting with __" credo coming in from my C background.
Passing self as the first parameter of every routine makes Python's OO seem almost as hackish as Perl's or PHP's. I much prefer Ruby's system of using @ to indicate an instance variable, rather than "self.".
I wish I could use tabs instead of four spaces to indicate indentation.
No statement modifiers, and there has to be an explicit return statement. These aren't major drawbacks, but I'd rather have them than not.
Python isn't quite as clean as Ruby, though it certainly trounces Perl. It would be hard not to trounce Perl. The performance was much better than in Ruby, however: Python ran the script for n=40 without any hitches. In the debugging department, syntax errors included helpful information, including where in the line the error occured.
Now for the comparison. First of all, I'll throw Perl right out. I love the language, but not for object-oriented programming. To write a purely procedural program I'd take it over both Ruby and Python any day of the week, but not for OO.
If I had my choice in the matter, I would use Ruby. It's syntax seems cleaner, and it's object orientation doesn't seem hackish in the least. It's performance, however, left a lot to be desired. Granted, deep recursion probably isn't the most widely used technique, but there's no reason it shouldn't work. For a different sort of problem, I'd likely choose Ruby, though I'm worried I might have to switch over to Python if I ran into similar problems.
And that brings us to the aforementioned beast. It seems to present the middle ground in this problem. It's syntax is fairly clean though, as I mentioned, I'd rather not have to type "self." all the time. But on the plus side, it could actually solve the problem without crashing.
So for this round, the winner is Python, though I really wish it had been Ruby. For most problems, I'll go with Ruby. It's more enjoyable to code in, and that's what I'm coding for--enjoyment.
FFmpeg流媒体开发避坑指南:avformat_open_input超时设置的那些坑 本文深入剖析了FFmpeg流媒体开发中avformat_open_input函数的超时设置难题。针对默认阻塞行为、无效的timeout参数以及不稳定的线程取消方案等常见误区,文章详细解读了官方推荐的interrupt_callback机制,并提供了健壮的超时控制器实现方案与最佳实践,帮助开发者构建稳定可靠的流媒体应用。 阅读详情

相关推荐

已解决-Parallels Desktop 16 网络初始化失败:您的虚拟机将继续正常运作,但将无法连接网络

我是月球挖掘机,相信不少打工人为了尝鲜已经更新了MacOS 11 Big Sur,当然,苹果每次的系统大更新,都会给我们软件的功能无法使用惊喜,这次的也不例外。 这个问题是我在更新macOS Big Sur之后,Parallels Desktop打开虚拟机后,提示: 报错信息 网络初始化失败:您的虚拟机将继续正常运作,但将无法连接网络 这是我的软件版本: 起初我以为是我的虚拟机坏了,结果重装了一遍虚拟机,没有任何用处。我开始在网上找方法,只能找到那个使用命令行打开软件的命令,除此之外没有了

月球挖掘机 5万+

perl,ruby,python 个人看法(内部讨论)

 那天时间有点晚了,说的多,大家可能也没有听完整 现在书也到了,大家有时间可以看看 下面是动态语言我的个人评价 仅供参考,写的有点乱,大家见谅 perl,ruby,python三者运行效率都差不多,只是各有侧重而已,毕竟要效率就用c了 功能也差不多,不存在谁能做谁不能做的问题 从纯粹语法设计的角度,比如代码书写规范,数据结构的设计,算法控制和设计的一致性ruby是最好的,

suningrass的博客 7095

从零开始:用Neo4j构建你的第一个知识图谱(附完整代码示例)

本文提供了一份从零开始的Neo4j知识图谱构建实战指南。通过一个“经典科幻电影宇宙”的具体案例,手把手教你安装环境、设计图谱模式,并使用Cypher查询语言完成节点与关系的创建、数据查询及可视化,帮助你快速掌握自下而上构建知识图谱的核心技能。

weixin_29053073的博客 480

JSP,PHP,Python,Ruby,Perl概要及各自特点

互联网技术日新月异,编程的语言层出不穷,原本稍微平静了几年的网络编程技术又不断出现新的东西,涤荡着整个网络世界,ruby,Python等技术使我们原本比较老板的编程理念和概念产生了混淆和动荡。他们有什么区别和联系?怎么定义这些新生的事物?抹去额头因为生疏而津津的汗滴,从头Google一下吧。 [table] | 用户 |...

wang_159369的专栏 472

Nangate 45nm FreePDK开源工艺库:从RTL到GDSII全流程实战

在数字IC设计中,标准单元库是连接逻辑综合与物理实现的基石,它定义了每个单元的逻辑功能、时序延迟与物理尺寸。开源EDA工具链的成熟,使得个人也能借助免费工艺套件完整跑通芯片设计流程。Nangate 45nm FreePDK作为一套经典的开源工艺库,凭借结构清晰、配套完善的特性,成为学习数字后端和时序收敛的理想训练场。从综合工具Yosys读取Liberty文件进行逻辑映射,到OpenROAD执行布局布线与时钟树综合,再到使用OpenSTA分析关键路径延迟,这套流程涵盖了数字设计最核心的环节。通过亲手操作,开发

weixin_29168393的博客 298

实现AI Agent的多Agent协作能力

在当今复杂的计算环境和应用场景中,单个AI Agent的能力往往受到限制。实现AI Agent的多Agent协作能力的目的在于通过多个Agent之间的协同工作,充分发挥各自的优势,提高整体系统的性能和效率,以解决更为复杂的问题。本文章的范围涵盖了多Agent协作的核心概念、算法原理、数学模型、项目实战以及实际应用场景等方面,旨在为读者提供全面且深入的技术指导。本文将按照以下结构进行阐述:首先介绍多Agent协作的背景知识,包括目的范围、预期读者和文档结构等;

AI Python 编程之道的博客 1489

python ruby perl技术特点各有什么不同

编程语言是程序员手中的工具,不同的语言有着各自独特的优势和适用场景。Python、Ruby和Perl这三种语言在脚本编写、Web开发等领域都有着广泛的应用。然而,它们各自的技术特点有何不同?选择哪一种更适合你的项目?本文将从语法风格、应用场景、生态系统等多个维度进行深入剖析,帮助你更好地理解这三种语言的特点,并为你的技术选型提供参考。

yjq125931902的博客 1161

168、运动控制中的标定:编码器零点标定

文章摘要 运动控制系统中的编码器零点标定是确保精确控制的关键基础步骤。文章通过实际案例说明,即使0.3度的零点偏移也会导致电机异常抖动。详细介绍了三种标定方法:反电动势法(需示波器)、电流注入法(适合量产)和霍尔传感器法(粗标定),并指出常见陷阱如忽略极对数、Z脉冲重复性问题和温度漂移。提供了基于STM32的嵌入式实现代码片段,强调标定后的静态、动态和负载验证的重要性。作者建议量产产品设置自动标定工位,研发样机采用更精确的方法,并强调标定数据应与电机序列号绑定。

m0_50546716的博客 149

一段小程序(Perl vs. Ruby)

读《Perl语言入门》(第四版,我买的书,网上有个翻译质量很高的电子版)的第10章的习题,人见人爱的猜数游戏,用perl写出来大概这样: $num=int(1+rand100);print"Ihaveanumber,guessit?:\n";while(<>) { chomp; nextunless/\...

weixin_34082789的博客 153

[RK3568 Android11] 教程之原厂SDK源码适配AIO-3568J板子跑起来

目录 一、前提 二、修改dts设备树 三、适配板子的dts 四、编译系统烧入固件验证 一、前提 因源码是直接使用原厂的SDK,没有使用firefly配套的SDK源码,所以手上这块firefly aio-3568j板子在硬件设计上与原厂使用的板子会有些差异;就是因为这些差异会导致新固件烧入后,debug串口打印许多错误信息,可能的话,系统还会崩溃掉,跑不起来; 主要差异在哪里呢?比如: ● DDR类型和品牌多样性; ...

~未来可期~ 1749

5步上手Quartz.NetUI:.NET Core定时任务的开箱即用解决方案

Quartz.NetUI是一个基于.NET Core + Quartz.NET + Vue + IView的开箱即用的定时任务UI解决方案。它结合了Quartz.NET的强大功能和Vue.js的易用性,提供了一个不依赖数据库、只需在界面进行简单配置即可使用的定时任务管理系统。通过上述步骤,你已经学会了如何使用Quartz.NetUI在.NET Core项目中实现定时任务。Quartz.NetUI不仅功能强大,而且使用简单,非常适合那些需要快速实现定时任务管理的开发者。

java专栏 2414

perl与python性能_哪种脚本语言在vs perl vs python vs ruby中性能更好?

到目前为止,我一直在用Perl编写程序。我决定尝试一下python,发现了一些不同之处。虽然perl内置了ARGV、regex等,但必须用python导入它们。我认为这给了python一个性能优势,因为您只需要加载真正需要的内容。所以,我用每种语言编写了一个演示程序来测试它的性能。Perl#!/usr/bin/perlexit(1) if $ARGV[-1] ne 'test';print "Te...

weixin_39902085的博客 283

WQ7033开发指南(应用篇)之2.1 主函数详解(1)

整个系列文章查看: ​​​​​​WQ7033开发指南汇总 目录 1.函数模块位置 2.函数main_chip_init()解析 2.1 cal_data_ana_load() 2.2 函数iot_cache_restore_register()解析 3.函数iot_soc_chip_init()解析 3.1 soc芯片初始化的低功耗使能 3.2 分支预设功能使能 3.3 数据异常中止使能 3.4 外围低速总线访问路径使能 3.5 1.8V DCDC功能配置 3.6 ADC配..

心跳包的博客 816

PHP, Perl, Python, Ruby语言对比

原文 http://hyperpolyglot.org/scripting Hyperpolyglot Interpreted Languages: PHP, Perl, Python, Ruby (Sheet One) a side-by-side reference sheet sheet one: variables and expressions |ari

魔神翼 4404

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

perl python ruby_perl,lua,python,ruby的对比(3) -- lambda,closure,proper tail function call

今天的题目是函数,先看一下匿名函数。Perl里是这样的$f = sub{ return $_[0]+$_[1]+$_[2];};print &$f(1,2,3)."\n";lua里是这样的f = function(x,y,z) return x+y+z endprint (f(1,2,3))python里使用了lambda概念,实现是这样的,也可以通过全局函数apply调用任意的函数f =...

weixin_39908985的博客 344

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

Perl vs. Python vs. Ruby

I’m evaluating Python and Ruby as replacements for Perl . I’ve been using Perl for several years and am very comfortable with it, although I’m definitely not an expert. Perl is a powerful langu...

CURSED! 194

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

Ruby和其它类似语言的比较

Smalltalk 和smalltalk一样,Ruby也是动态的纯面向对象的语言。你不需要静态的指定数据类型,所有东西都是对象。而且,两者都有垃圾收集机制。在Smalltalk中,流程控制语句也都是通过给对象发送消息来完成的,但有时候这使得程序难以阅读理解。而Ruby中的控制流程结构就显得保守一些,而且也就自然、容易理解一些。说实话,Smalltalk为何物,我一无所知。以上废话全

Ruby语言 6843

Python, Ruby和Perl

在最近的一两个月工作中,自己做了一些工具,还有一些测试的自动化脚本。大量地使用了Python,总的来说,我觉得Python是一门值得学习的脚本语言。         先说说我使用这三门脚本语言的认识历史和程度。我最早听过的脚本语言是Perl,那时候我买了一本叫做《24小时精通Perl》的书,不过可惜了,因为我没有翻到第三章。第二个接触的语言是Python,那大概是在2002年我读大三的时候,买...

AnkyHe's Blog 511

【转】Perl、PHP、Python、Java和Ruby的比较

感觉写得不错,特转载于此。地址:《Perl、PHP、Python、Java和Ruby的比较》预览 ◆ 语言的发展趋势一定是动静结合、刚柔并济 ◆ Perl凝练晦涩,Python优雅明晰,Ruby精巧灵动,PHP简明单纯 ◆ 或许优雅正是来自对细节和规范的重视 ◆ (RoR)与Ruby结合之后,便如一只猱身而上灵猫,立刻衬托出Java和.NET大象般的身影 提问 ◆ Perl、Python、Ruby

our2848884的专栏 2729

转载:Perl、Java、Ruby、Python的IO性能比较

原文:http://www.simplelife.cn/blog/post/1/721前几天测试了Perl和Shell的IO状况,结论是Perl大概比Shell快10倍。今天,加入了Java和Ruby,看看测试结果:分别用Perl(5.8.5)、Ruby(1.8.6)、Java(1.5.0_01)、Python(2.3.4)逐行读一个241M的文本文件,并写入另一文件,测试花费的时间。

5534

Perl、PHP、Python、Java和Ruby的比较

预览 ◆ 语言的发展趋势一定是动静结合、刚柔并济 ◆ Perl凝练晦涩,Python优雅明晰,Ruby精巧灵动,PHP简明单纯 ◆ 或许优雅正是来自对细节和规范的重视 ◆ (RoR)与Ruby结合之后,便如一只猱身而上灵猫,立刻衬托出Java和.NET大象般的身影 提问 ◆ Perl、Python、Ruby和PHP各自有何特点? ◆ 为什么动态语言多作为轻

snrnjhna的博客 623

Perl,Python,Ruby,Javascript 四种脚本语言比较

为了选择一个合适的脚本语言学习,今天查了不少有关Perl,Python,Ruby,Javascript的东西,可是发现各大阵营的人都在吹捧自己喜欢的语言,不过最没有争议的应该是Javascript现阶段还不适合用来做独立开发,它的天下还是在web应用上。我主要是想做数据挖掘算法的研究,应该会处理大量的文本。提到文本处理,相信大部分人都会说应该用Perl。的确,Perl的文本处理很强大,但是它的

lee576的专栏 1万+

Perl,PHP,Python,Ruby概要及各自特点

http://run-wang.iteye.com/blog/1290061 互联网技术日新月异,编程的语言层出不穷,原本稍微平静了几年的网络编程技术又不断出现新的东西,涤荡着整个网络世界,ruby,Python等技术使我们原本比较老板的编程理念和概念产生了混淆和动荡。他们有什么区别和联系?怎么定义这些新生的事物?抹去额头因为生疏而津津的汗滴,从头Google一下吧。

weiyastory的博客 4675

Perl、PHP、Python、Java和Rub之间的异同比较

◆ 语言的发展趋势一定是动静结合、刚柔并济◆ Perl凝练晦涩,Python优雅明晰,Ruby精巧灵动,PHP简明单纯◆ 或许优雅正是来自对细节和规范的重视◆ (RoR)与Ruby结合之后,便如一只猱身而上灵猫,立刻衬托出Java和.NET大象般的身影提问◆ Perl、Python、Ruby和PHP各自有何特点?◆ 为什么动态语言多作为轻量级的解决方案?◆ LAMP为什么受欢迎?◆ Ruby on

zgp3297299的专栏 1261
下一篇: perl,python和ruby的对比
kingwmj78
博客等级 码龄17年 34粉丝 2原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值