Grill it!

 https://www.codewars.com/kata/grill-it/train/python

Introduction

A grille cipher was a technique for encrypting a plaintext by writing it onto a sheet of paper through a pierced sheet (of paper or cardboard or similar). The earliest known description is due to the polymath Girolamo Cardano in 1550. His proposal was for a rectangular stencil allowing single letters, syllables, or words to be written, then later read, through its various apertures. The written fragments of the plaintext could be further disguised by filling the gaps between the fragments with anodyne words or letters. This variant is also an example of steganography, as are many of the grille ciphers. Wikipedia Link

Grill it!_第1张图片 Grill it!_第2张图片

Task

Write a function that accepts two inputs: message and code and returns hidden message decrypted from message using the code.
The code is a nonnegative integer and it decrypts in binary the message.

Grille("abcdef", 5)  => "df"

message : abcdef
code    : 000101
----------------
result  : df

 

 题目:

通过将数字变成二进制数,101010,再将消息从右到左对应上,看看是1的就保存下来,其他的舍去,最后拼起来就是真正要表达的意思。

如:字符串 'abcdef' ,与 000101 对应上,最后只剩下 df

测试用例:

test.assert_equals(grille("abcdef", 5), "df")
test.assert_equals(grille("", 5), "")
test.assert_equals(grille("abcd", 1), "d")
test.assert_equals(grille("0abc", 2), "b")   
test.assert_equals(grille("ab", 255), "ab")      
test.assert_equals(grille("ab", 256), "")
test.assert_equals(grille("abcde", 32), "")
test.assert_equals(grille("tcddoadepwweasresd", 77098), "codewars")

我的算法:

def grille(message, code):
    # 先将数字转换为二进制数,再转换为字符串
    code = bin(code)[2:]
    # 获取message和二进制数之间的最小长度
    min_len = len(code) if len(code)

大神1的算法:

def grille(msg, code):
    return ''.join(msg[-1-i] for i,c in enumerate(bin(code)[::-1]) if c == '1' and i < len(msg))[::-1]

大神1很巧妙的用倒着输出的思想避免了判断message和code的长度

 

 大神2的算法:

def grille(message, code):
    binary = bin(code)[2:][-len(message):].zfill(len(message))
    return ''.join(char for char, code in zip(message, binary) if code == '1')

大神2用了zfill和zip函数

你可能感兴趣的:(python,菜鸟练习,kata)