这件事有点牵扯。是否有更简单的方法在基本python中实现这个前缀代码,我现有的代码在下面,但是任何修改或审查的帮助都是有帮助的。
# Lagged fibonacci numbers the sequence starts: 1,2,3,5,8,11
def fibonacci(n):
a = 1
b = 1
out = []
for i in range(n):
out.append(a)
a,b = a+b,a
return out
# There has to be a better way to do this, right?
# Go through the list for the first few fibonacci numbers from greatest to
# make a list of fibonacci numbers that add up to each code number (1,2,3...)
# The code is then the indexes of those fibonacci numbers, with leading zeroes
# removed, reversed, with an additional "1" at the end.
def makeCodebook(decode=False):
F = fibonacci(10)
F.reverse()
codes = []
for x in range(1,27):
while x != 0:
code = []
for f in F:
if f <= x:
code.append("1")
x = x-f
else:
code.append("0")
while code[0] == "0":
code.pop(0)
code.reverse()
code.append("1")
codes.append("".join(code))
# Matchup codes with letters
D = {}
alpha = "ETAOINSRHLDCUMFPGWYBVKXJQZ"
if decode == False:
for a,b in zip(alpha,codes):
D[a] = b
if decode == True:
for a,b in zip(alpha,codes):
D[b] = a
return D
def prefixCode(text,decode=False):
# Build the codebook
D = makeCodebook(decode=decode)
# When encoding we simply translate each letter to its code
if decode == False:
out = []
for letter in text:
out.append(D[letter])
return "".join(out)发布于 2019-01-08 22:37:45
您的fibonacci不需要变量a和b;out已经在跟踪它们。
def fibonacci(n):
out = [1,2]
for i in range(n-2):
out.append(out[i]+out[i+1])
return out您应该同时构建编码和编码代码本,这样您就不必运行相同的函数两次才能得到这两种代码。
您可以在找到代码时构建代码本:
def makeCodebook():
alpha = "ETAOINSRHLDCUMFPGWYBVKXJQZ"
F = fibonacci(10)
F.reverse()
D = {}
E = {}
for x,letter in enumerate(alpha,1):
while x != 0:
code = []
for f in F:
if f <= x:
code.append("1")
x = x-f
else:
code.append("0")
while code[0] == "0":
code.pop(0)
code.reverse()
code.append("1")
D[code] = letter
E[letter] = code
return D,E注意,这消除了保留codes列表的需要。
那你就可以
def prefixCode(text,decode=False):
D, E = makeCodebook(decode=decode)
if not decode:
return "".join([E[letter] for letter in text])https://codereview.stackexchange.com/questions/211098
复制相似问题