填数字游戏
时间:2005-10-05 来源:bleem1998
#!/usr/bin/env python
import copy,sys,pdb
ALLDATA=range(1,10)
def printall(val):
for i in val:
for j in i:
print j,' ',
print ''
def getexist(val):
zz = []
for i in val:
if len(i) == 1:
zz.append(i[0])
return zz
def getvnexist(val, n):
zz = []
for i in val:
if len(i[n]) == 1:
zz.append(i[n][0])
return zz
def get_union(v1,v2):
zz=[]
for i in ALLDATA:
if i not in v1 and i not in v2:
zz.append(i)
return zz
def oplist(val):
for i in val:
n = 0
ln_exist = getexist(i)
while n < len(i):
if len(i[n]) != 1:
vn_exist = getvnexist(val, n)
i[n] = get_union(ln_exist, vn_exist)
n += 1
def has_repeat(val):
for i in val:
if val.count(i) != 1:
return True
return False
def is_bad(val):
if not val:
return True
for i in val:
if has_repeat(getexist(i)):
return True
for j in i:
if len(j) < 1:
return True
n = 0
val_len = len(val[0])
while n < val_len:
if has_repeat(getvnexist(val, n)):
return True
n += 1
return False
def all_ok(val):
if not val:
return False
for i in val:
for j in i:
if len(j) != 1:
return False
if i.count(j) != 1:
return False
n = 0
while n < len(val[0]):
zz = getvnexist(val, n)
for i in zz:
if zz.count(i) != 1:
return False
n += 1
return True
def guess_it(val):
if not val:
return []
elif is_bad(val):
return []
elif all_ok(val):
return val
for i in val:
indexi = val.index(i)
for j in i:
indexj = i.index(j)
lenj = len(j)
if lenj > 1:
get_copy = copy.deepcopy(val)
bakj = copy.copy(j)
nn = 0
while nn < lenj:
get_copy[indexi][indexj] = [bakj[nn]]
getit = guess_it(get_copy)
if getit:
return getit
nn += 1
return []
'''
final resault shuld be this:
L1=[[9],[6],[3],[1],[7],[4],[2],[5],[8]]
L2=[[1],[7],[8],[3],[2],[5],[6],[4],[9]]
L3=[[2],[5],[4],[6],[8],[9],[7],[3],[1]]
L4=[[8],[2],[1],[4],[3],[7],[5],[9],[6]]
L5=[[4],[9],[6],[8],[5],[2],[3],[1],[7]]
L6=[[7],[3],[5],[9],[6],[1],[8],[2],[4]]
L7=[[5],[8],[9],[7],[1],[3],[4],[6],[2]]
L8=[[3],[1],[7],[2],[4],[6],[9],[8],[5]]
L9=[[6],[4],[2],[5],[9],[8],[1],[7],[3]]
'''
L1=[[],[],[3],[1],[7],[4],[2],[5],[]]
L2=[[],[],[],[3],[2],[5],[6],[4],[9]]
L3=[[],[5],[4],[6],[],[],[7],[3],[]]
L4=[[],[2],[],[4],[],[7],[5],[9],[6]]
L5=[[],[9],[6],[8],[5],[],[3],[1],[]]
L6=[[],[3],[],[9],[6],[],[8],[2],[4]]
L7=[[],[8],[9],[7],[1],[],[4],[6],[2]]
L8=[[],[1],[7],[2],[],[],[],[8],[]]
L9=[[],[4],[2],[],[9],[8],[1],[7],[]]
Lall = [L1,L2,L3,L4,L5,L6,L7,L8,L9]
#pdb.set_trace()
print 'Before game:'
printall(Lall)
oplist(Lall)
print 'guess...'
Lall = guess_it(Lall)
if Lall:
print 'Success'
printall(Lall)
else:
print 'Failure'