我已经采取了问题#12从项目欧拉作为编程练习和我的(肯定不是最优的)实现在C,Python和Erlang和Haskell的比较.为了获得更高的执行时间,我搜索第一个三角形数字,其中有超过1000个除数而不是原始问题中所述的500.
结果如下:
C:
lorenzo@enzo:~/erlang$ gcc -lm -o euler12.bin euler12.c
lorenzo@enzo:~/erlang$ time ./euler12.bin
842161320
real 0m11.074s
user 0m11.070s
sys 0m0.000s
Run Code Online (Sandbox Code Playgroud)
蟒蛇:
lorenzo@enzo:~/erlang$ time ./euler12.py
842161320
real 1m16.632s
user 1m16.370s
sys 0m0.250s
Run Code Online (Sandbox Code Playgroud)
Python与PyPy:
lorenzo@enzo:~/Downloads/pypy-c-jit-43780-b590cf6de419-linux64/bin$ time ./pypy /home/lorenzo/erlang/euler12.py
842161320
real 0m13.082s
user 0m13.050s
sys 0m0.020s
Run Code Online (Sandbox Code Playgroud)
二郎:
lorenzo@enzo:~/erlang$ erlc euler12.erl
lorenzo@enzo:~/erlang$ time erl -s euler12 solve
Erlang R13B03 (erts-5.7.4) [source] [64-bit] [smp:4:4] [rq:4] [async-threads:0] [hipe] [kernel-poll:false]
Eshell V5.7.4 (abort with ^G)
1> 842161320
real 0m48.259s
user 0m48.070s
sys 0m0.020s
Run Code Online (Sandbox Code Playgroud)
哈斯克尔: …
人们常常在SO的python问题中找到这种类型的表达式.要么只是访问iterable的所有项目
for i in range(len(a)):
print(a[i])
Run Code Online (Sandbox Code Playgroud)
这只是一种繁琐的写作方式:
for e in a:
print(e)
Run Code Online (Sandbox Code Playgroud)
或者为了分配可迭代的元素:
for i in range(len(a)):
a[i] = a[i] * 2
Run Code Online (Sandbox Code Playgroud)
哪个应该是相同的:
for i, e in enumerate(a):
a[i] = e * 2
# Or if it isn't too expensive to create a new iterable
a = [e * 2 for e in a]
Run Code Online (Sandbox Code Playgroud)
或者对索引进行过滤:
for i in range(len(a)):
if i % 2 == 1: continue
print(a[i])
Run Code Online (Sandbox Code Playgroud)
可以这样表达:
for e in a [::2]:
print(e)
Run Code Online (Sandbox Code Playgroud)
或者当您只需要列表的长度而不是其内容时:
for _ in range(len(a)):
doSomethingUnrelatedToA() …
Run Code Online (Sandbox Code Playgroud) 我需要每分钟运行一个python脚本(job.py).如果该脚本已在运行,则不得启动该脚本.它的执行时间可能在10秒到几个小时之间.
所以我放入我的crontab:
* * * * * root cd /home/lorenzo/cron && python -u job.py 1>> /var/log/job/log 2>> /var/log/job/err
Run Code Online (Sandbox Code Playgroud)
为了避免在脚本运行时启动脚本,我使用flock().
这是脚本(job.py):
import fcntl
import time
import sys
def doIncrediblyImportantThings ():
for i in range (100):
sys.stdout.write ('[%s] %d.\n' % (time.strftime ('%c'), i) )
time.sleep (1)
if __name__ == '__main__':
f = open ('lock', 'w')
try: fcntl.lockf (f, fcntl.LOCK_EX | fcntl.LOCK_NB)
except:
sys.stderr.write ('[%s] Script already running.\n' % time.strftime ('%c') )
sys.exit (-1)
doIncrediblyImportantThings ()
Run Code Online (Sandbox Code Playgroud)
这种方法似乎有效.
有什么我想念的吗?我可以使用这种方法遇到任何麻烦吗?
是否有更多建议或"正确"的方法来实现这种行为?
我感谢你的任何建议.
我正在学习erlang,并且对于并行化工作是多么容易印象深刻.为了练习一点,我挖出了好的纤维Fibanocci序列.在下面的代码中,我尝试通过一次计算三个昂贵的产品来利用并行化.
-module (fib4).
-export ( [main/1] ).
main (N) ->
fib (list_to_integer (atom_to_list (hd (N) ) ) ),
halt (0).
path (1, Acc) -> Acc;
path (N, Acc) when N rem 2 =:= 0 ->
path (N - 1, [step | Acc] );
path (N, Acc) ->
path ( (N - 1) div 2, [jump | Acc] ).
fib (N) -> fib (1, 1, path (N, [] ) ).
fib (N, Nplus1, [Last] ) ->
case Last of
step -> …
Run Code Online (Sandbox Code Playgroud) 我昨天开始使用haskell,但仍然完全迷失在这个勇敢的新世界的岸边.现在我遇到了以下问题:
让我们假设我有一些函数对整数和另一个变量做了一些魔术:
makeTuple :: Int -> a -> (Int, a)
makeTuple n x = (n, x)
Run Code Online (Sandbox Code Playgroud)
现在我想将此函数应用于列表的所有元素.到目前为止没问题,因为映射是你在python(我来自哪里)的日常面包和黄油.
makeTupleList :: Int -> [a] -> [ (Int, a) ]
makeTupleList n x = map (makeTuple n) x
Run Code Online (Sandbox Code Playgroud)
据我所知,二元函数makeTuple部分应用整数n,因此成为一元函数,可以映射到x的每个元素.到目前为止,一切都很好.
但是当makeTuple函数有另一个签名时我该怎么办,例如:
makeTuple2 :: a -> Int -> (Int, a)
makeTuple2 x n = (n, x)
Run Code Online (Sandbox Code Playgroud)
许多方式导致罗马:效果是一样的,但方式是另一种.现在显然映射不再起作用了:函数需要一个Int并获得一个.
makeTupleList2 :: Int -> [a] -> [ (Int, a) ]
makeTupleList2 n x = map (makeTuple2 n) x -- boolshit
Run Code Online (Sandbox Code Playgroud)
这是可以预料的.我的-maybe太pythonic- workaround正在使用另一个函数来传递它们应该去的参数:
makeTupleList2 :: Int -> [a] -> …
Run Code Online (Sandbox Code Playgroud) 我是erlang的新手,并且在以下情况下有点头疼:
拿这个代码:
-module (so).
-export ( [foo/0] ).
bar () ->
receive
die -> ok;
Msg -> io:format ("I say ~p.~n", [Msg] )
end.
bar (Name) ->
receive
die -> ok;
Msg -> io:format ("~s says ~p.~n", [Name, Msg] )
end.
foo () ->
Bar = spawn (fun bar/0),
Bar ! "Hello",
Bar ! die,
Baz = spawn (?MODULE, bar, ["Alice"] ), % bar/1 not exported
Baz ! "Hello",
Baz ! die.
Run Code Online (Sandbox Code Playgroud)
产生的过程spawn/1
工作正常,但第二个过程产生了spawn/3
失败,因为我没有导出bar/1
,因此我得到了{undef,[{so,bar,["Alice"]}]} …
我如何用Java编写以下python行?
a = [True, False]
any (a)
all (a)
Run Code Online (Sandbox Code Playgroud)
inb4"你尝试过什么?"
在大锤的办法是写我自己all
和any
方法(和显然是一个类来承载他们):
public boolean any (boolean [] items)
{
for (boolean item: items)
if (item) return true;
return false;
}
//other way round for all
Run Code Online (Sandbox Code Playgroud)
但我不打算重新发明轮子,必须有一个简洁的方法来做到这一点......
这是对这个问题的一个后续行动.
换句话说,问题2是:是否存在以下代码(在必要的语法中)起作用的语言:
def f(): print ('f')
def g():
f()
f = 42
g()
Run Code Online (Sandbox Code Playgroud) 在容器类中,当我想迭代其项目(或其项目的变换或其项目的子集)时,我可以编写生成器(如f
)或返回生成器(如g
):
class SomeContainer:
def __init__(self):
self.data = [1, 'two', 3, 'four']
def f(self):
for e in self.data: yield e + e
def g(self):
return (e + e for e in self.data)
sc = SomeContainer()
for x in sc.f(): print(x)
for x in sc.g(): print(x)
Run Code Online (Sandbox Code Playgroud)
我不需要通过信息将信息传递给发生器send
.
显然两种方式都表现相同(在表面).
哪种方法更可取,为什么?
哪种方法可以减少开销,或者具有其他我未能发现的优势?
直到一小时前,我确信在python Foo ().bar ()
中只不过是一个简短的手,Foo.bar (Foo () )
它将实例作为第一个参数传递.在这个例子中,最后两行(显然)做同样的事情:
class Foo (object):
def bar (self): print "baz"
qux = Foo ()
qux.bar ()
Foo.bar (qux)
Run Code Online (Sandbox Code Playgroud)
但是现在我有一个类Animal,它有一个静态方法populate(),它返回man已知的所有动物的列表.此外,Animal的每个实例都有一个方法populate(),它使用随机值填充实例的属性.
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import random
animals = [ ("Bella", "cow"), ("Spike", "dog"), ("José", "iguana"), ("Tux", "penguin") ]
class Animal (object):
@staticmethod
def populate (*args): return map (lambda x: Animal (*x), animals)
def __init__ (self, name = None, species = None):
def bar (): self.name, self.species = random.choice (animals) …
Run Code Online (Sandbox Code Playgroud)