標籤:

用python寫一個程序,找出數組中差值為K的數共有幾對

用python寫一個程序,找出數組中差值為K的數共有幾對

article/index.md at master · pythonpeixun/article · GitHub有人問「用python寫一個程序,找出數組中差值為K的數共有幾對」

#coding:utf-8n"""nn用python寫一個程序,找出數組中差值為K的數共有幾對nnnn示例:nn差值k=4 and 數組是[7, 6, 23,19,10,11, 9, 3, 15]nn這樣的結果是(7,11) (7,3) (6,10) (19,23) (15,19) (15,11) 共6對nnnn從標準輸入讀入兩行數據nn5 2nn1 5 3 4 2nnnn第一行代表N和K, N是數組是一共有多少數字,K是所要求的差值nn第二是數組,空白分格nnnn輸出到標準輸出nnnnnnSample Input #00:nn5 2nn1 5 3 4 2nnSample Output #00:nn3nnSample Input #01:nn10 1nn363374326 364147530 61825163 1073065718 1281246024 1399469912 428047635 491595254 879792181 1069262793nnSample Output #01:nn0nn"""nnnndef diff_of_element_list(lst, k):nn """黃哥python遠程視頻培訓班nn https://github.com/pythonpeixun/article/blob/master/index.mdnnnn 黃哥python培訓試看視頻播放地址nn https://github.com/pythonpeixun/article/blob/master/python_shiping.mdnn """nn newlst = [i + k for i in lst]nn return len(set(lst) & set(newlst))nnnnif __name__ == __main__:nn lst = [7, 6, 23,19,10,11, 9, 3, 15]nn k = 4nn print(diff_of_element_list(lst, k))nn lst = [1,5, 3, 4, 2]nn k = 2nn print(diff_of_element_list(lst, k))nnnn n, k = input("please input n and k:n").split()nn lst = input("plesae input {0} number:n".format(n)).split()nn lst = [int(i) for i in lst]nn print(diff_of_element_list(lst, int(k)))n

推薦閱讀:

NumPy和MATLAB哪個強大,Numpy能替代MATLAB嗎?
Python編程(bbb二):Python進程、線程那點事兒
在 Python 中如何判斷輸入數字是實數(整型數字或者浮點型數字)?
python 能否print到console固定一行?
pymongo 查詢時,顯示循環不同,為何效率相差百倍?

TAG:Python |