find-num-1.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. """
  4. Q:
  5. 给函数传递一个正整数的列表alist和一个正整数T,假装它等于[1,3,6,4,2,7],给出alist里所有相加等于T的元素的list,
  6. 每个数只用一次。比如T=7,列表里3+4=7,7=7,1+6=7。你的函数就要返回[[3,4],[7],[1,6]]
  7. A:
  8. 1. 如果列表里面每个数字不可以重复,解法利用哈希标记,这是k-num算法在面对2元数据时的思想
  9. 2. 如果列表里面每个数字可以重复,就在find_num里dict的标记,把True和False改为剩余没有用过的个数
  10. """
  11. def find_num(alist, T):
  12. mark = {}
  13. for v in alist:
  14. mark[v] = True
  15. result = []
  16. for v in alist:
  17. if not mark[v]:
  18. continue
  19. if v == T:
  20. result.append([v])
  21. mark[v] = False
  22. continue
  23. if mark.__contains__(T-v) and mark[T - v]:
  24. result.append([v, T - v])
  25. mark[v] = False
  26. mark[T - v] = False
  27. return result
  28. if __name__ == '__main__':
  29. n = 0
  30. T = 0
  31. while True:
  32. print("input T:")
  33. T = int(input())
  34. print('input data length:')
  35. n = int(input())
  36. print('input digits: ')
  37. alist = []
  38. for i in range(0, n):
  39. digit = int(input())
  40. alist.append(digit)
  41. result = find_num(alist, T)
  42. print(result)