def sudoku(size): import time start_time=time.time() import sys import random as rn grid = {} n = 0 print('started calculating') while len(grid) < 9: n += 1 x = range(1, size+1) testlist = rn.sample(x, len(x)) isgood = True for dictid,savedlist in grid.items(): if isgood == False: break for v in savedlist: if testlist[savedlist.index(v)] == v: isgood = False break if isgood == True: isgoodafterduplicatecheck = True mod = len(grid) % 3 dsavedlists = {} dtestlists = {} dcombindedlists = {} for a in range(1,mod + 1): savedlist = grid[len(grid) - a] for v1 in savedlist: modsavedlists = (savedlist.index(v1) / 3) % 3 dsavedlists[len(dsavedlists)] = [modsavedlists,v1] for t1 in testlist: modtestlists = (testlist.index(t1) / 3) % 3 dtestlists[len(dtestlists)] = [modtestlists,t1] for k,v2 in dsavedlists.items(): dcombindedlists[len(dcombindedlists)] = v2 dcombindedlists[len(dcombindedlists)] = dtestlists[k] vsave = 0 lst1 = [] for k, vx in dcombindedlists.items(): vnew = vx[0] if not vnew == vsave: lst1 = [] lst1.append(vx[1]) else: if vx[1] in lst1: isgoodafterduplicatecheck = False break else: lst1.append(vx[1]) vsave = vnew if isgoodafterduplicatecheck == True: grid[len(grid)] = testlist print('success found'), len(grid), 'row' print(' finished calculating.') total_time = time.time()-start_time return grid, n, total_time return_dict, total_tries, amount_of_time = sudoku(9) print ('') print ('~printing output:') print (' ') for n,v in return_dict.items(): print (n,v) print(' ') print ('process took',total_tries,'tries in', round(amount_of_time,2), 'seconds') print ('------------------------')
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question