DEV

codeIQをやってみた

The Essence of Programming 結城 浩さんからのアルゴリズムの問題をやってみました。簡単だと思ったのですが、アルゴリズムとかまだ勉強できてないので合ってるのか分かりません。ミスしてる可能性もあります。一応確認したら出来てる感じでしたが。ただ、やっぱりアルゴリズムの問題はクイズ的だし面白いので、もっと勉強しようと思いました。codeIQにはこういうのが色々あるようなので色々見てみたいと思いました。

合ってなかったら残念です。

# -*- coding: utf-8 -*-
f = open('blendlist.txt', 'r')
blends = [] #[[a,[b,c,d]],[b,[d,e,f]]]
curryA = []
curryB = []
#blendsの作成
for blend in f:
spices = blend.split() #[a,b]
flag = False
for spice in spices:
if len(blends) > 0:
for b in blends:
if spice == b[0]:
flag = True
break
if not flag: blends.append([spice,[]])
flag = False
for idxS in range(len(spices)):
for idxB in range(len(blends)):
if spices[idxS] == blends[idxB][0]:
if idxS == 0: idxAdd = 1
else: idxAdd = 0
if not spices[idxAdd] in blends[idxB][1]:
blends[idxB][1].append(spices[idxAdd])
f.close()
#curryA,Bの作成
cntA = 0
cntB = 0
for blend in blends:
if not curryA and not curryB:
curryA += [blend[0]] + blend[1]
for b in blends:
if not b[0] in curryA: curryB += [b[0]]
else:
for idx in range(len(blend[1])):
if blend[1][idx] in curryA: cntA += 1
else: cntB += 1
if cntA > cntB:
if not blend[0] in curryA:
curryB.remove(blend[0])
curryA.append(blend[0])
elif cntA < cntB:
if not blend[0] in curryB:
curryA.remove(blend[0])
curryB.append(blend[0])
cntA = 0
cntB = 0
#得点の計算
pntA = 0
pntB = 0
for blend in blends:
if blend[0] in curryA:
for spice in blend[1]:
if spice in curryA: pntA += 1
for idxBlends in range(len(blends)):
if blends[idxBlends][0] == spice:
blends[idxBlends][1].remove(blend[0])
else:
for spice in blend[1]:
if spice in curryB: pntB += 1
for idxBlends in range(len(blends)):
if blends[idxBlends][0] == spice:
blends[idxBlends][1].remove(blend[0])
#Answerの作成
answer = ''
if pntA > pntB:
curryA.sort()
for spice in curryA: answer += spice + ' '
else:
curryB.sort()
for spice in curryB: answer += spice + ' '
answer = answer.rstrip()
answer += 'nn■得点n'
answer += 'CurryA: ' + str(pntA) + '点n'
answer += 'CurryB: ' + str(pntB) + '点n'
answer += '------------------------------n'
answer += '合計 : ' + str(pntA + pntB) + '点nn■ソースコードn'
f = open('curry.py','r')
answer += f.read()
f.close()
#answerの書き込み
f = open('answer.txt', 'w')
f.write(answer)
f.close()