2013-03-09 42 views
-2

这里是我到目前为止的代码:Python的编码键,再减去一个字符,如果太长

def code_block(text, key): 
    itext = int(text) 
    rkey = int(key) 
    res= itext + rkey 
    def last(): 
     return res[-1:] 
    if res>=11111111: 
     last() 
    return res 

这里是我已经设定的任务:

Now we need a function to take a block of code and a key as input, where both are assumed to be 8 digits long, and encrypts each digit of the number with the corresponding digit of the key:

>>> code_block('12341234','12121212') 
'24462446' 

>>> code_block('66554433','44556677') 
'00000000' 

我要去哪里错了?你能指出我的方向是否正确,并告诉我我错了吗?

+0

你想用'最后做什么( )'?你只是丢弃结果。你的代码现在也出错了,因为'res'是一个整数,而不是一个字符串('TypeError:'int'object'没有属性'__getitem __'')。 – 2013-03-09 18:20:15

+0

而你的引号是无效的Python引号;为你自己做了一些“自动更正”的东西,或者你是用手来打这些东西的? – 2013-03-09 18:21:58

+0

With last() 如果代码长度超过8个字符,那么它会删除最后一个字符。 – user2151912 2013-03-09 18:27:14

回答

0

你正在走这个错误的路。通过文字把这个角色:

def code_block(text, key): 
    res = [str(int(c) + int(k))[-1:] for c, k in zip(text, key)] 
    return ''.join(res) 

这给了我:

>>> code_block('12341234','12121212') 
'24462446' 
>>> code_block('66554433','44556677') 
'00000000' 

代码总结每个字符分开,把它放回一个字符串,并只使用的最后一个字符结果; 9 + 9是18,但结果是'8'

您的代码将总结整个数字,但是这将导致:

>>> 66554433 + 44556677 
111111110 

这是不正确的结果。无论你有没有把你和回字符串了,所以你的代码,试图通过切片它来治疗之结果为一个字符串,给了一个例外:

>>> code_block('12341234', '12121212') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "<stdin>", line 8, in code_block 
    File "<stdin>", line 6, in last 
TypeError: 'int' object has no attribute '__getitem__'