2013-03-23 141 views
-4

我仍然在学习pascal,我试图找出一种方法来获得这个工作,但现在我在Python中找到了一个例子,但我不知道Python如何工作,而且我需要将我的但是这是它的一个重要组成部分,当我没有它时,我可能会失败 - 你能否向我解释它在帕斯卡​​中的工作原理?需要说明,请

def checkIDCode(code): 
     if len(code) != 11 or not code.isdigit(): 
       return False 

     c = map(int,code) 
     w1 = [1,2,3,4,5,6,7,8,9,1] 
     w2 = [3,4,5,6,7,8,9,1,2,3] 

     s1 = sum(map(lambda x,y: x*y, c[:-1], w1))%11 
     s2 = (sum(map(lambda x,y: x*y, c[:-1], w2))%11)%10 

     return s1 == c[-1] or s1 == 10 and s2 == c[-1] 
+0

它如何在帕斯卡工作?根本不是,因为它是一个Python代码。您只是想将此代码翻译成Pascal或解释此代码的作用。 [我不是downvoter,但这个问题并没有显示任何研究工作] – TLama 2013-03-23 18:49:51

+2

请不要只是重新发布您的问题,如果它被关闭。您可以*编辑*您的旧问题。改进那个,然后重新打开它。 – 2013-03-23 18:50:01

+0

我知道它做了什么,但我不明白哪些操作和功能需要在帕斯卡中做到这一点。这是我的程序的第四部分,但我无法弄清楚,哪些功能需要在pascal中完成。 – BeginnerPascal 2013-03-23 18:50:55

回答

1

让我们来看看代码。

if len(code) != 11 or not code.isdigit(): 
    return False 

这就告诉你,code必须是十位的名单,或十一位字符串:

In [1]: code = [str(i) for i in range(1,12)] 

In [2]: len(code) 
Out[2]: 11 

In [3]: code2 = '12345678912' 

In [4]: code2.isdigit() 
Out[4]: True 

下一页:

c = map(int,code) 

这种转换code到列表整数。

In [3]: code 
Out[3]: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11'] 

In [4]: map(int,code) 
Out[4]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] 

In [5]: code2 = '12345678912' 

In [6]: map(int,code2) 
Out[6]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2] 

w1w2是号码清单。

s1 = sum(map(lambda x,y: x*y, c[:-1], w1))%11 

现在来了棘手的位。

slicing语法返回列表中的部分副本:

In [19]: c 
Out[19]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] 

In [20]: c[:-1] 
Out[20]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 

map功能应用匿名函数。在这种情况下,它将乘以c[:-1]w1

In [21]: map(lambda x,y: x*y, c[:-1], w1) 
Out[21]: [1, 4, 9, 16, 25, 36, 49, 64, 81, 10] 

sum函数做了明显的事情。

In [22]: sum(map(lambda x,y: x*y, c[:-1], w1)) 
Out[22]: 295 

%算子不带余除法:

In [23]: sum(map(lambda x,y: x*y, c[:-1], w1))%11 
Out[23]: 9 

In [24]: 295/11 
Out[24]: 26 

In [25]: 295-11*26 
Out[25]: 9 

您现在应该能够了解以下内容:

s2 = (sum(map(lambda x,y: x*y, c[:-1], w2))%11)%10 

最后一行:

return s1 == c[-1] or s1 == 10 and s2 == c[-1] 

它说;如果s1等于c中的最后一个元素,或者s1是10并且s2等于c中的最后一个元素,则返回True。否则返回False。