Say we have a function that translates the morse symbols:
.
->-.
-
->...-
如果我们两次行使这一职能,我们就取得了以下成果:
<代码> ->->。 ->
...-.
Given an input string and a number of repetitions, want to know the length of the final string. (Problem 1 from the Flemish Programming Contest VPW, taken from these slides which provide a solution in Haskell).
参考书
4
. 4
.- 2
-- 2
--... 50
我们期待解决办法。
44
16
20
34028664377246354505728
由于我不知道Haskell,这是我在Sharma的令人厌恶的解决办法,我收到了:
def encode(msg, repetition, morse={ . : -. , - : ...- }):
if isinstance(repetition, str):
repetition = eval(repetition)
while repetition > 0:
newmsg = .join(morse[c] for c in msg)
return encode(newmsg, repetition-1)
return len(msg)
def problem1(fn):
with open(fn) as f:
f.next()
for line in f:
print encode(*line.split())
用于头三个投入的工作,但最后一项投入的记忆有误。
你们如何以更有效的方式来重新制定这一标准?
<><>Edit>>
根据所发表的评论意见:
def encode(p, s, repetition):
while repetition > 0:
p,s = p + 3*s, p + s
return encode(p, s, repetition-1)
return p + s
def problem1(fn):
with open(fn) as f:
f.next()
for line in f:
msg, repetition = line.split()
print encode(msg.count( . ), msg.count( - ), int(repetition))
关于风格和进一步改进的评论仍然值得欢迎。