codewars -- Rail Fence Cipher: Encoding and Decoding (python)

14 篇文章 0 订阅
13 篇文章 0 订阅

Rail Fence Cipher: Encoding and Decoding

难度系数:3kyu

本质为一个编码解码的过程,参考 Blind4Basics https://www.codewars.com/users/Blind4Basics ,解法十分巧妙!我对此进行了详细分析,值得学习,分享给大家!

题目:
Create two functions to encode and then decode a string using the Rail Fence Cipher. This cipher is used to encode a string by placing each character successively in a diagonal along a set of “rails”. First start off moving diagonally and down. When you reach the bottom, reverse direction and move diagonally and up until you reach the top rail. Continue until you reach the end of the string. Each “rail” is then read left to right to derive the encoded string. You can optionally include or dis-include punctuation.

For example, the string “WEAREDISCOVEREDFLEEATONCE” could be represented in a three rail system as follows:

W      E     C     R      L      T       E
 E   R  D  S  O  E  E   F   E  A   O   C  
   A     I     V      D      E      N

The encoded string would be:

WECRLTEERDSOEEFEAOCAIVDEN

Write a function/method that takes 2 arguments, a string and the number of rails, and returns the ENCODED string.

Write a second function/method that takes 2 arguments, an encoded string and the number of rails, and returns the DECODED string.

For both encoding and decoding, assume number of rails >= 2 and that passing an empty string will return an empty string.

Note that the example above excludes the punctuation and spaces just for simplicity. There are, however, tests that include punctuation. Don’t filter out the punctuation as they are a part of the string.

解题思路:

from itertools import chain
def fencer(string, n):
    ## 分别保存
    save = [[] for _ in range(n)]
    ## 判断处于哪个列表就添加到哪个列表
    list_i = 0 #初始为第0个列表
    change = 1 #每次移动一次
    for c in string:
        save[list_i].append(c)
        # 判断依据为 当处于最后一个列表,并且change为1时,应转变方向,
        # 同理,当处于第0个列表,并且change为-1时,又得转变方向,
        if (list_i==n-1 and change>0) or (list_i==0 and change<0):
            change *= -1
        list_i += change
    return chain.from_iterable(save) #衔接元素,必须为字符串
def encode_rail_fence_cipher(s, n): 
    return ''.join(fencer(s,n))

# 解码,也就是只要将字符串变为数字,经过一次编码就可以知道,每个字符串的检索位置
# 相应的将值插入到检索位置即可  
def decode_rail_fence_cipher(s, n):
    save = ['']*len(s)
    for c,i in zip(s, fencer(range(len(s)),n)):
        save[i] = c
    return ''.join(save)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值