閱讀全文
1、在一條街上,有5座房子,噴了5種顏色;
2、每個房子裡住著不同國家的人;
3、每個人喝不同的飲料,抽不同牌子的香菸,養不同的寵物;
已知
1、英國人住紅色房子;
2、瑞典人養狗;
3、丹麥人喝茶;
4、綠色房子在白色房子左面;
5、綠色房子主人喝咖啡;
6、抽Pall Mall 香菸的人養鳥;
7、黃色房子主人抽Dunhill 香菸;
8、住在中間房子的人喝牛奶;
9、挪威人住第一間房;
10、 抽Blends香菸的人住在養貓的人隔壁;
11、 養馬的人住抽Dunhill 香菸的人隔壁;
12、 抽Blue Master的人喝啤酒;
13、 德國人抽Prince香菸;
14、 挪威人住藍色房子隔壁;
15、 抽Blends香菸的人有一個喝水的鄰居;
問:誰養魚?
#!/usr/bin/env python3 from enum import Enum, unique import itertools @unique class 國籍(Enum): 英國 = 1 瑞典 = 2 丹麥 = 3 德國 = 4 挪威 = 5 @unique class 房子(Enum): 紅色 = 1 白色 = 2 綠色 = 3 黃色 = 4 藍色 = 5 @unique class 香菸(Enum): PallMall= 1 Dunhill= 2 Blends= 3 BlueMaster = 4 Prince= 5 @unique class 飲料(Enum): 茶 = 1 咖啡 = 2 牛奶 = 3 啤酒 = 4 水 = 5 @unique class 寵物(Enum): 狗 = 1 鳥 = 2 貓 = 3 馬 = 4 魚 = 5 def MakeIndex(items): index = {} for i in range(0, len(items)): index[items[i]] = i return index def main(): for 國籍排列 in itertools.permutations([國籍.英國, 國籍.瑞典, 國籍.丹麥, 國籍.德國, 國籍.挪威]): # 9、 挪威人住第一間房 if 國籍排列[0] != 國籍.挪威: continue 國籍索引 = MakeIndex(國籍排列) for 房子排列 in itertools.permutations([房子.紅色, 房子.白色, 房子.綠色, 房子.黃色, 房子.藍色]): # 1、英國人住紅色房子 if 房子排列[國籍索引[國籍.英國]] != 房子.紅色: continue # 4、綠色房子在白色房子左面 房子索引 = MakeIndex(房子排列) if 房子索引[房子.白色] - 房子索引[房子.綠色] != 1: continue # 14、挪威人住藍色房子隔壁 if abs(國籍索引[國籍.挪威] - 房子索引[房子.藍色]) != 1: continue for 香菸排列 in itertools.permutations([香菸.PallMall, 香菸.Dunhill, 香菸.Blends, 香菸.BlueMaster, 香菸.Prince]): # 7、黃色房子主人抽Dunhill 香菸 if 香菸排列[房子索引[房子.黃色]] != 香菸.Dunhill: continue # 13、德國人抽Prince香菸。 if 香菸排列[國籍索引[國籍.德國]] != 香菸.Prince: continue 香菸索引 = MakeIndex(香菸排列) for 飲料排列 in itertools.permutations([飲料.茶, 飲料.咖啡, 飲料.牛奶, 飲料.啤酒, 飲料.水]): # 8、住在中間房子的人喝牛奶 if 飲料排列[2] != 飲料.牛奶: continue # 3、丹麥人喝茶 if 飲料排列[國籍索引[國籍.丹麥]] != 飲料.茶: continue # 5、綠色房子主人喝咖啡 if 飲料排列[房子索引[房子.綠色]] != 飲料.咖啡: continue # 12、抽Blue Master的人喝啤酒。 if 飲料排列[香菸索引[香菸.BlueMaster]] != 飲料.啤酒: continue 飲料索引 = MakeIndex(飲料排列) # 15、抽Blends香菸的人有一個喝水的鄰居。 if abs(香菸索引[香菸.Blends] - 飲料索引[飲料.水]) != 1: continue for 寵物排列 in itertools.permutations([寵物.狗, 寵物.鳥, 寵物.貓, 寵物.馬, 寵物.魚]): # 2、瑞典人養狗 if 寵物排列[國籍索引[國籍.瑞典]] != 寵物.狗: continue # 6、抽Pall Mall 香菸的人養鳥。 if 寵物排列[香菸索引[香菸.PallMall]] != 寵物.鳥: continue 寵物索引 = MakeIndex(寵物排列) # 10、抽Blends香菸的人住在養貓的人隔壁 if abs(香菸索引[香菸.Blends] - 寵物索引[寵物.貓]) != 1: continue # 11、養馬的人住抽Dunhill 香菸的人隔壁。 if abs(香菸索引[香菸.Dunhill] - 寵物索引[寵物.馬]) != 1: continue items = [] for i in range(0, len(國籍排列)): item = {} item['國籍'] = 國籍排列[i].name item['房子'] = 房子排列[i].name item['香菸'] = 香菸排列[i].name item['飲料'] = 飲料排列[i].name item['寵物'] = 寵物排列[i].name items.append(item) for i in range(0, len(items)): item = items[i] print('第{0}間房是{1},住著{2}人,抽{3},喝{4},養{5}'.format( i + 1, item['房子'], item['國籍'], item['香菸'], item['飲料'], item['寵物'])) if __name__ == '__main__': main()
輸出
第1間房是黃色,住著挪威人,抽Dunhill,喝水,養貓 第2間房是藍色,住著丹麥人,抽Blends,喝茶,養馬 第3間房是紅色,住著英國人,抽PallMall,喝牛奶,養鳥 第4間房是綠色,住著德國人,抽Prince,喝咖啡,養魚 第5間房是白色,住著瑞典人,抽BlueMaster,喝啤酒,養狗
thumb_up