0

So I'm trying to work to create a program which can take two inputs such as

encrypt('12345','12')

and it will return

'33557'

where the code ('12345') and been incremented by the key ('12'), working from right to left.

I have already created one which will work for when the code and key are both 8 long, but I cannot work out how to do this should the code be allowed to be any size, possibly with nested for statments?

Here is the one i did early so you can see better what i am trying to do

def code_block(char,charBlock):
    if len(char) == 8 and len(charBlock) == 8:    #Check to make sure both are 8 didgets.
        c = char
        cB = charBlock
        line = ""
        for i in range(0,8):
            getDidget = code_char2(front(c),front(cB))
            c = last(c)
            cB = str(last(cB))
            line =line + getDidget
        print(line)
    else:
        print("Make sure two inputs are 8 didgets long")

def front(word):
    return word[:+1]

def last(word):
    return word[+1:]
4

1 回答 1

1

在 Python 3.2 上测试的一些代码:

from decimal import Decimal
import itertools

def encrypt(numbers_as_text, code):
    key = itertools.cycle(code[::-1])

    num = Decimal(numbers_as_text)

    power = 1
    for _ in numbers_as_text:
        num += power * int(next(key))
        power *= Decimal(10)

    return num



if __name__ == "__main__":
    print(encrypt('12345','12'))

一些解释:

  • code[::-1]是反转字符串的一种很酷的方法。从这里偷来的
  • itertools.cycle无休止地重复你的钥匙。所以变量key现在包含一个生成器,它产生2, 1, 2, 1, 2, 1, 等等
  • Decimal是一种可以处理任意精度数的数据类型。实际上 Python 3 的整数就足够了,因为它们可以处理任意位数的整数。将类型名称作为函数Decimal()调用,调用该类型的构造函数,从而创建该类型的新对象。构造Decimal()函数可以处理一个参数,然后将其转换为 Decimal 对象。在示例中,numbers_as_text字符串和整数10Decimal通过其构造函数转换为类型。
  • power是一个变量,以我们处理的每个数字(从右数)1相乘。10它基本上是一个指针,指向我们需要num在当前循环迭代中修改的地方
  • for循环标头确保我们对给定输入文本中的每个数字进行一次迭代。我们也可以使用类似的东西,for index in range(len(numbers_as_text))但这太复杂了

当然,如果你想对文本进行编码,这种方法是行不通的。但由于这不在您的问题规范中,因此这是一个专注于处理整数的函数。

于 2013-03-08T14:27:50.600 回答