- # tips = []
- # dic = {}
- # N = None
- # while True:
- # try:
- # N = int(input('共有多少個已知條件?請輸入:'))
- # break
- # except TypeError:
- # print('輸入錯誤!')
- # for n in range(N):
- # print('\n已知條件 %d'%(n+1))
- # while True:
- # try:
- # num = tuple(map(int, str(input('已知條件號碼是?請輸入:'))))
- # break
- # except TypeError:
- # print('輸入錯誤!')
- # while True:
- # try:
- # code = int(input('有多少個數字是正確數字?請輸入:'))
- # break
- # except TypeError:
- # print('輸入錯誤!')
- # if code > 0:
- # while True:
- # try:
- # index = int(input('有多少個數字位置是正確的?請輸入:'))
- # break
- # except TypeError:
- # print('輸入錯誤!')
- # else: print('因為沒有數字正確,所以沒有位置正確!')
- # dic['code'] = code
- # dic['index'] = index
- # tips.append([dic, num])
- # notches = len(tips[0][1])
- # combination = 10**notches
- # -----------------------------------------------------------------------------------------------------------------------
- # 以下是根據題目所給的 5 個已知條件,如果想自己定義輸入,可以運用以上代碼,方便輸入
- N = 5
- notches = 3
- combination = []
- for digit in range(10):
- temp = []
- for position in range(notches):
- temp.append(digit)
- combination.append(temp)
- # code 代表正確數字有多少? index 代表正確位置有多少? 後面是題給的提示號碼
- tips = [
- [{'code': 1, 'index': 1}, (6, 8, 2)],
- [{'code': 1, 'index': 0}, (6, 1, 4)],
- [{'code': 2, 'index': 0}, (2, 0, 6)],
- [{'code': 0, 'index': 0}, (7, 3, 8)],
- [{'code': 1, 'index': 0}, (8, 7, 0)],
- ]
- for i in range(N):
- # 數字正確,位置也正確
- if tips[i][0]['code'] > 0 and tips[i][0]['index'] > 0:
- A = list(tips[i][1])
- for n, i in enumerate(A):
- for j in range(notches):
- if n != j:
- combination[i][j] = 'X'
- # 數字正確,位置不正確
- elif tips[i][0]['code'] > 0 and tips[i][0]['index'] == 0:
- A = list(tips[i][1])
- for n, i in enumerate(A):
- for j in range(notches):
- if n == j:
- combination[i][j] = 'X'
- # 全部不正確
- elif tips[i][0]['code'] == 0 and tips[i][0]['index'] == 0:
- A = list(tips[i][1])
- for n, i in enumerate(A):
- for j in range(notches):
- combination[i][j] = 'X'
- # ans 為默認等下輸出答案,flag 為肯定答案不存在數字
- ans = ['X']*notches
- flag = []
- for n, i in enumerate(combination):
- count = 0
- for j in i:
- if j == 'X':
- count += 1
- if count == len(i)-1:
- ans[n] = n
- flag.append(n)
- elif count == len(i):
- flag.append(n)
- elif count == 0:
- flag.append(n)
- # 這裡 ans = [0, 'X', 2],因為 0 和 2 已確定位置,剩下找出中間位置數字
- for n, i in enumerate(combination):
- if n not in flag:
- if combination[n].index('X') != ans.index('X'):
- for j in range(notches):
- if ans[j] == 'X':
- ans[j] = n
- print('answer: '.title(), tuple(ans))
- # 以上代碼還不夠完善,只針對題目給出的函數,如果有特別案例比如:2個號碼正確,1個位置正確,另一個號碼不正確等,這些不確定因素不能用以上代碼
- # 希望有大神可以完善代碼,感恩
复制代码 |