2013-03-23 128 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。