简单的Python消息编码器/解码器问题

时间:2014-01-22 14:32:55

标签: python

我是Python的新手,只是在玩一些代码。我正在尝试构建一个“秘密消息生成器”,它接受一个字符串(例如“1234567890”)并根据一个简单的模式(例如“1357924680”)输出它。我让编码器工作90%(目前它无法处理撇号),但解码器给我带来了很多麻烦。对于超过6个字符的任何内容,都没有问题。输入“1357924680”输出“1234567890”。但是,对于较短的奇数编号的字符串(例如“Hello”),它不显示最后一个字符(例如,它输出“Hell”)。我的代码如下。可能有一种更简单的方法来编写它,但由于我自己构建它,我很感激使用我的代码而不是重写它。那么,如何解决?

#simple decoder

def decode(s2):
    oddlist = []
    evenlist = []
    final = []
    s2 = s2.lower() #makes a string lowercase
    size = len(s2) #gets the string size
    print "Size " + str(size) #test print
    half = size / 2
    print "Half " + str(half)
    i = 0
    while i < half:
        if size % 2 == 0: #checks if it is even
            split = size / 2 #splits it
            oddlist.append(s2[0:split]) #makes a list of the first half
            evenlist.append(s2[split:]) #makes a list of the second half
            joinodd = ''.join(oddlist) #list -> string
            joineven = ''.join(evenlist) #list -> string
        else:
            split = (size / 2) + 1
            print split
            oddlist.append(s2[0:split]) #makes a list of the first half
            evenlist.append(s2[split:]) #makes a list of the second half
            joinodd = ''.join(oddlist) #list -> string
            joineven = ''.join(evenlist) #list -> string
        string = joinodd[i] + joineven[i]
        final.append(string)
        i = i + 1
    decoded = ''.join(final)
    print final
    return decoded

print decode("hello")

2 个答案:

答案 0 :(得分:1)

也许另一个答案会在你的代码中给你错误但是我想给你一个推荐,如果你使用的是python切片表示法,请全部使用它!这是一个如何以更加pythonic的方式做你想做的事情的例子:

import itertools

def encode(s):
    return s[::2] + s[1::2]

def decode(s):
    lim = (len(s)+1)/2
    return ''.join([odd + even for odd,even in itertools.izip_longest(s[:lim], s[lim:],fillvalue="")])


def test(s):
    print "enc:",encode(s)
    print "dec:",decode(encode(s))
    print "orig:",s
    print 

test("")
test("1")
test("123")
test("1234")
test("1234567890")
test("123456789")
test("Hello")

输出:

enc: 
dec: 
orig: 

enc: 1
dec: 1
orig: 1

enc: 132
dec: 123
orig: 123

enc: 1324
dec: 1234
orig: 1234

enc: 1357924680
dec: 1234567890
orig: 1234567890

enc: 135792468
dec: 123456789
orig: 123456789

enc: Hloel
dec: Hello
orig: Hello

答案 1 :(得分:0)

您的代码将文本拆分为两个一组。

这对奇数长度的单词不起作用。所以你要么用

跳过一个
while i < half:
> ['hl', 'eo']

或者您确保使用以下内容获取所有值:

while i <= half:

> ['hl', 'eo', 'll']

虽然这会为输出添加一个额外的字母,因为它在技术上添加了另一对。您可能需要重新考虑该算法。