Reputation: 3057
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:]
Upvotes: 0
Views: 560
Reputation: 11300
Some code tested on 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'))
Some explanation:
code[::-1]
is a cool way to reverse a string. Stolen from hereitertools.cycle
endlessly repeats your key. So the variable key
now contains a generator which yields 2
, 1
, 2
, 1
, 2
, 1
, etcDecimal
is a datatype which can handle arbitrary precision numbers. Actually Python 3's integer numbers would be sufficient because they can handle integer numbers with arbitrary number of digits. Calling the type name as a function Decimal()
, calls the constructor of the type and as such creates a new object of that type. The Decimal()
constructor can handle one argument which is then converted into a Decimal object. In the example, the numbers_as_text
string and the integer 10
are both converted into the type Decimal
with its constructor.power
is a variable that starts with 1
is multiplied by 10
for every digit that we have worked on (counting from the right). It's basically a pointer to where we need to modify num
in the current loop iterationfor
loop header ensures we're doing one iteration for each digit in the given input text. We could also use something like for index in range(len(numbers_as_text))
but that's unnecessarily complexOf course if you want to encode text, this approach does not work. But since that wasn't in your question's spec, this is a function focused on dealing with integers.
Upvotes: 1