我是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")
也许另一个答案会告诉您代码中的错误,但我想给您一个建议,如果您使用python切片表示法,请全部使用它!这是一个例子,告诉你如何以一种更具Python式的方式做你想做的事情:
输出:
^{pr2}$你的代码将文本分成两组。在
对于长度奇数的单词来说,这是行不通的。所以你要么跳过一个
或者,您要确保您获得的所有值都符合以下条件:
^{pr2}$虽然这会在输出中增加一个额外的字母,因为它在技术上是在添加另一个对。你可能需要重新考虑这个算法。在
相关问题 更多 >
编程相关推荐