Тёмный
No video :(

Coding a Sudoku solver in Python using recursion/backtracking 

Kylie Ying
Подписаться 74 тыс.
Просмотров 80 тыс.
50% 1

Learn how to code a Sudoku puzzle solver in Python! In this tutorial, I explain how recursion/backtracking work in order to solve a Sudoku puzzle input.
Code: github.com/kyi...
- sudoku_empty.py: empty template with optional helper functions and comments in the code for the steps
- sudoku.py: my solution from the video!
In this video, I go over the steps necessary to use recursion to solve the input. Basically, the steps we need to follow are: determine where the next guess should go, place a guess between 1-9, then attempt to solve by recursively calling the mutating function. If the function solves the puzzle, then we are done. Otherwise, we reset our guess and guess another number.
At the end, we've literally tried every single combination of numbers on the board, through the backtracking process, so if we haven't reached a solution, then we know that our puzzle is unsolvable.
Of course, this is not a very "intelligent" solution in the sense that we have to try all the various combinations. There is probably a more optimized solution out there that can solve the problem in fewer steps. This is a good exercise to try! If you think your solution is good, you can make a pull request on github or just DM me your solution. I might include it in the github (with credits to you ofc).
Check out this wiki page for some more info about sudoku algorithms that are more intelligent than just backtracking: en.wikipedia.o...
Feel free to leave any questions.
Please consider subscribing if you liked this video: www.youtube.co...
Thanks for watching everyone!
~~~~~~~~~~~~~~~~~~~~~~~~
Follow me on Instagram: / kylieyying
Follow me on Twitter: / kylieyying
Check out my website: www.kylieying.com

Опубликовано:

 

25 авг 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 104   
@KylieYYing
@KylieYYing 3 года назад
Code: github.com/kying18/sudoku If you want to take it a step further, try coming up with an algorithm to solve the sudoku more intelligently (basically right now we're iterating through every combination til we find one that works. but there are definitely better ways that would require less time/steps). Send your solution to me/make a pull request if you've found one, and I may feature it on github! Subscribe and follow me on insta/twitter: @kylieyying :)
@seabunni9957
@seabunni9957 3 года назад
I don't have the code for it or anything, but what if instead of filling in the empty cells in order, we first filled in all 9 1's, then all 9 2's, and so on? My claim is that this would cause the algorithm to fail (and therefore backtrack) as fast as possible. This may be inconsequential for a sudoku of size n=3, but for larger n I suspect this would shave magnitudes off the runtime.
@KylieYYing
@KylieYYing 3 года назад
Yeah that could potentially work.. I was also thinking maybe doing some type of check for the blank space that has the most information at each recursive step, instead of grabbing the first point we see... that help decrease the top level iterations
@spike_wav
@spike_wav 3 года назад
@@KylieYYing ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-G_UYXzGuqvM.html
@pratyushvatsa7490
@pratyushvatsa7490 3 года назад
@@KylieYYing Is there a way to be sure whether the puzzle given by user is solvable?
@smallfryskilledge1550
@smallfryskilledge1550 2 года назад
Sort sub groups into a group list, with 9 rows, then the 9 columns, then the 9 blocks. Makes iterating and unitetesting easier as each file appears exactly 3 times.
@alexanderpoplawski577
@alexanderpoplawski577 3 года назад
This is one of the best videos on this topic. I like that you use x in list for validation and list comprehension for building the columns. For some Sudokus you could continue after the first solution. There might be others, but that's considered a weak Sudoku.
@sergiobost4891
@sergiobost4891 2 года назад
Best explanation of sudoku recursive backtracking I've seen.. and I've been searching!
@Blubb5000
@Blubb5000 Месяц назад
Well... I just ran across another video explaining the backtracking method. The video is 5 minutes long and the code fits on the screen. Just saying...
@MrEdwardCollins
@MrEdwardCollins 2 года назад
When I spend my day off watching, and enjoying, videos like this, I suspect that confirms what I've always known... I'm a nerd. I wouldn't want it any other way. :) Thanks Kylie.
@abhinavl999
@abhinavl999 Год назад
Great explanation!! I was thinking for lines 32 to 34, where a check is being made for a number guess being repeated in a column, that for loop could be used to check every column value. This way, no extra space has to be allocated. Considering that the number of rows and columns is fixed in this case, I think the current code is alright. Otherwise, I highly appreciate your sharing of understanding and please continue to do so.
@softwareengineer8923
@softwareengineer8923 2 месяца назад
Such a well detailed and lucid explanation, thanks a lot
@LordTails
@LordTails 3 года назад
Thanks for the video! I'm working on a sudoku generator but kept getting infinite loops. After a lot of digging, I realized Python was making impossible puzzles and got stuck halfway while making them since it had no way of determining if the puzzles were solvable.
@codedoctor3265
@codedoctor3265 3 года назад
Wow , you got a nicest way to explain source code :)
@saqibraja4410
@saqibraja4410 2 года назад
my version ''' Define the isValid() function, which checks if num can be place in the cell indicated by row and col ''' def isValid( board, row, col, num): #check row for i in range(9): if board[row][i] == num: return False #check col for j in range(9): if board[i][col] == num: return False #get top-left corner c_row = row - row % 3 c_col = col - col % 3 #check 3x3 square for i in range(c_row, c_row+3): for j in range(c_col, c_col+3): if board[i][j] == num: return False #return True if none of the cases above returns False return True ''' Define the solveBoard() function, which solves the sudoku board recursively ''' def solveBoard(board): for i in range(9): for j in range(9): if board[i][j] == 0: for num in range(1,10): if isValid(board,i,j,num): board[i][j] = num result = solveBoard(board) if result: return True else: board[i][j]= 0 return False return True #no empty cell found mylist = [] for i in range(9): mylist.append(str(input("Please input first " +str(i)+ " row of board: "))) if solveBoard(mylist): print("Yes") else: print("No")
@zchamdawala
@zchamdawala 3 года назад
I recognize the new set up. Love the way you explain the concepts. Looking forward for new and *quick* posts. 😅❤️❤️
@neo3669
@neo3669 3 года назад
Great video, the explenation was great, keep it up!
@alanz2423
@alanz2423 2 года назад
Thanks for making this fantastic tutorial video! Learned a lot and appreciate your efforts! Just a small thing. When the program reaches the Step 6 (if none of the numbers that we try work...), it does not mean the puzzle is unsolvable. It means all numbers tried won't work for this cell. In this case the program will recursively go back to the previous state and continue. This can be seen by put a print statement right before the "return False" statement.
@jharvey1012
@jharvey1012 2 года назад
Best sudoku backtracking video, really nice work.
@samersabri6068
@samersabri6068 3 года назад
Very nicely explained! Great job this should have a ton more views please keep up the great work!!
@mohgawsih6958
@mohgawsih6958 3 года назад
Hey you . . . we need more . . . get it!!!!! mooooore . . . the pace and attitude are great . . . I am learning and enjoying 🥰😘😍😎🤩
@Gthefray
@Gthefray 3 года назад
this is perfect 👌 you explain it really well! i‘ve been meaning to get back into working with python and this was perfect timing plus who doesn‘t love sudoku!
@glansingColt
@glansingColt Год назад
Her thought process makes me feel like i still have a long way to go
@leoalex331
@leoalex331 3 года назад
Your video is so easy to understand.
@nolanbock5076
@nolanbock5076 3 года назад
Best video of all time imo
@dikshyantthapa3367
@dikshyantthapa3367 3 года назад
most underrated tut on sudoku..was crying all day imao !! thanks!!!
@anshuman8650
@anshuman8650 3 года назад
It's easily understandable
@saxpete
@saxpete 3 года назад
nice channel, directed here from your freecodecamp vid on the 12 projects, looking forward to learn some practical python stuff..thx
@eitamr
@eitamr 2 года назад
I'm no programmer in any way but I have an idea to possibly speed up the run time. As first stage filling each square on the board with 1-9 as "available guesses", then to check for each col/row/3x3 if there are any repetitions in available guesses. if there is non, then you have found a positive correct for sure. now, you need this to go back and check the board from the beginning until "board before last check" = "board after". so you have utilized all of the "simple information". That way you are left with way fewer options for the resource intensive "dumb guessing" you are left with at the end. (I hope it's explained sort of well, the logic is the most basic "human solving method", but I tried to somewhat translate to computer logic in words. It's probably way more complex to write but it might be faster. unfortunately currently I don't have the tools to check myself)
@chakmadeveloper5192
@chakmadeveloper5192 2 года назад
Please make a course on "Professional data structure and algorithm" I want to learn more about it
@neilkumar3626
@neilkumar3626 2 года назад
Joma Tech also did the same exact thing
@mohithkankanala8336
@mohithkankanala8336 3 года назад
Amazing explanation! Thank you!
@mehmethankaya9974
@mehmethankaya9974 3 года назад
i love this channel. very helpful!
@priyalorha4412
@priyalorha4412 3 года назад
pretty neat, and lucid!
@mehdismaeili3743
@mehdismaeili3743 Год назад
Excellent. great as always.
@asdasd-iq2mv
@asdasd-iq2mv 2 года назад
U got a subscriber from 🇹🇷
@stringtra4531
@stringtra4531 3 года назад
Love your videos ....👍👌👌
@fmtuby
@fmtuby Год назад
Hi Kylie, v nice!, is this DFS backtracking?
@MrPetzold123
@MrPetzold123 3 года назад
That was excellent, I followed your lead and implemented this in Rust (I am a terrible Rust programmer, but finally got it to work :-). Thank you !
@OmniAshley
@OmniAshley 3 года назад
Thank you so much Kylie ♥
@tomisinabiodun243
@tomisinabiodun243 3 года назад
This is awesome!!!!
@sofunny7984
@sofunny7984 2 года назад
How do we call does blue lines on left side
@raghavkaushal6383
@raghavkaushal6383 3 года назад
This was helpful !! Thanks :)
@CollosalTrollge
@CollosalTrollge Год назад
Going to give this a try, but not sure if this is ideal for a beginner at Python.
@X_x_kingfisher_x_X
@X_x_kingfisher_x_X Год назад
But if we return only true how to get the result? How to grab the puzzle?
@joefreundt
@joefreundt 2 года назад
Great video... I just don't get why the value of "example_puzzle" changes so that when it's printed on the last line of the code it shows the solved puzzle.
@gikisTSB
@gikisTSB 3 года назад
Hello! Could you please tell me what terminal/interface is this? I am completely green in coding and when I download newest Python, it opens up as command prompt only. Thank you!
@gustavofaraco27
@gustavofaraco27 3 года назад
It's called VS Code, you can know more about it here: Visual Studio Code - code.visualstudio.com I think this is a great tutorial to get stated with it: VSCode Tutorial For Beginners - ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-ORrELERGIHs.html
@surters
@surters Год назад
Nice backtracking example.
@prog8123
@prog8123 2 месяца назад
How long was it running? O(9^81) is not promising
@aasemelshahat6780
@aasemelshahat6780 3 года назад
YOU ARE THE BEST!
@chaks2432
@chaks2432 3 года назад
What level of complexity would this algorithm be?
@gnzz_24
@gnzz_24 3 года назад
Both space and time will be O(n^2)
@Munax.
@Munax. 3 года назад
Hey nice tutorial! Thank you for your work. But I need to ask question. what's that if __name__ = "main"? what does it do and why you needed it? I removed that part and it still works.
@KylieYYing
@KylieYYing 3 года назад
yep, it'll still work. that if statement is good practice for when you start building projects with multiple files. i explain this here: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-G8ns2HxpM0U.html
@cameronlee6367
@cameronlee6367 3 года назад
This is a great explanation!
@jpillstream
@jpillstream 3 года назад
7:17 how is that technique called in Python?, thanks
@KylieYYing
@KylieYYing 3 года назад
List comprehension
@paulm6084
@paulm6084 2 года назад
Fine job!!!
@scfog90
@scfog90 3 года назад
Getting the triangles could be also done with Mod und compare only the starting points where mod3==0
@AK-mg5rh
@AK-mg5rh 2 года назад
Hi I liked the video, can I ask you how did you learn python ? school or books or online ? Thanks
@cooperdayz6959
@cooperdayz6959 Год назад
I copied this and ran it and it doesn't seem to work
@Alex_1408.
@Alex_1408. 3 года назад
Love you from India
@keving2013
@keving2013 2 года назад
why this code isn't working on expert level?
@md.asifhasan6224
@md.asifhasan6224 2 года назад
can u plz explain why in line 8 we r checking the empty cell with "-1"??
@danpost5651
@danpost5651 3 года назад
Must be a valid puzzle -- plus, "with one unique solution" (should probably have been clarified). However, you could save the solution and continue the recursion beyond that point; and, if another solution arises, let the program inform that such solution is not unique.
@GaadhiMahendra
@GaadhiMahendra 2 года назад
I love you !
@chaks2432
@chaks2432 3 года назад
Thanks! This really helped me get a better understanding of this topic. Hopefully it'll be enough for finals tomorrow
@plush1993
@plush1993 14 дней назад
What a cool fuckin program dude nice job
@twixerty6399
@twixerty6399 2 года назад
How would you change this to make it valid for a 2x3 sudoku puzzle?
@TheOlegLviv
@TheOlegLviv 3 года назад
If possible can you recomend top python books for beginners. Thanks
@ricj9594
@ricj9594 3 года назад
thank you Mulann!!!
@rheintochter7367
@rheintochter7367 3 года назад
would converting the puzzle to a matrix make it easier?
@procode6881
@procode6881 3 года назад
Wow thanks a ton
@SomeGuy-tz8dz
@SomeGuy-tz8dz 3 года назад
Yor explaination is quite nice! Just one thing how do enter that code into the computer while your hands are off of the keyboard as you explain things???😉😉😉
@differentperspectives
@differentperspectives Год назад
Kylie first recoreded herself writing out the suduko solver code without any sound, then, as she replayed her recording she is then able to talk without any distractions such as, trying to talk and type on her keyboard. Add in some clever editing and you have what you see in her video.
@aquinino
@aquinino 3 года назад
Thank!
@aldonbobed7484
@aldonbobed7484 3 года назад
It doesn't work with me
@vitelspring
@vitelspring 3 года назад
I don't get how THAT recursion call works, it's hurting my brain quite a bit, but how does 'if solve_sudoku(puzzle): return True' recursively call the solve puzzle function? and how do you know where to indent your backtracking line?
@FreakFolkerify
@FreakFolkerify 3 года назад
Beauty
@spike_wav
@spike_wav 3 года назад
she is so cute that at minute 2:30 she can write code without using her hands
@ayman4490
@ayman4490 3 года назад
She's recorded it before and is teaching us again.
@spike_wav
@spike_wav 3 года назад
@@ayman4490 ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-G_UYXzGuqvM.html
@thorbag8695
@thorbag8695 3 года назад
Hmm...u copy Joma or Joma copy u?
@shilashm5691
@shilashm5691 2 года назад
Change the name of the video🙃🙃, it should be valid sudoku instead of sudoku solver
@41oe80
@41oe80 2 года назад
すごい
@DS-nr9zc
@DS-nr9zc 3 года назад
yo recursion does make your brain hurt!
@KylieYYing
@KylieYYing 3 года назад
How I feel about recursion sometimes: 🥴🥴🥴
@arm9180
@arm9180 3 года назад
I just did this, except I used java
@georgeprout42
@georgeprout42 3 года назад
Me too, except half the desktops had the wrong client version and it failed.
@piyushparadkar3779
@piyushparadkar3779 3 года назад
Will you b my friend
@so8907
@so8907 3 года назад
Love the video. You are clearly very intelligent (and cute :P). one thing that kinda bugged me was the amount of comments you have... Its too much and makes the code harder to read. While comments are useful there shouldn't be more comments than code imo. I'm Nitpicking otherwise a great video
@thixunguyen2023
@thixunguyen2023 6 месяцев назад
Hello my wealing girls friends ?
@TheGuitarRiot
@TheGuitarRiot 3 года назад
The most unintelligent method of solving a sudoku is "trying all of possible combinations and then choosing the right one". That's crap. That's not really fun.
@KylieYYing
@KylieYYing 3 года назад
Thanks for letting me know. I think in this video, I really wanted to teach recursion. It's pretty difficult to incorporate much more logic from there. In addition, if you think about it, humans playing sudoku also pretty much try all the combos in their head, but just make the combinations fail faster so they end up trying less.
@TheGuitarRiot
@TheGuitarRiot 3 года назад
@@KylieYYing yes, you're probably right. Sorry for my angry remark earlier. Just been thinking about writing the sudoku solving code in Python myself. Pretty much via "guess" function, trying to go without recursion. But still haven't finished it, really. So, been rather annoyed at myself. Thanks for your answer.
@alexanderpoplawski577
@alexanderpoplawski577 3 года назад
I think you don't understand this solution. It actually finds a path to the solution and reroutes at any obstacle. It does not try all possible combinations with multiple violations of the puzzle.
@ryanchen2412
@ryanchen2412 3 года назад
Backtracking woohoooo😌
Далее
Python Sudoku Solver - Computerphile
10:53
Просмотров 1,2 млн
Коротко о моей жизни:
01:00
Просмотров 244 тыс.
УГАДАЙ ЕДУ ПО ЭМОДЗИ! #shorts
00:57
Просмотров 251 тыс.
Please Master These 10 Python Functions…
22:17
Просмотров 139 тыс.
Create Sudoku Solver with Python in 20 minutes
19:47
Просмотров 65 тыс.
Sudoku Solver in Python
19:22
Просмотров 40 тыс.
Solving Wordle using information theory
30:38
Просмотров 10 млн
5 years of MIT in 20 minutes
21:45
Просмотров 195 тыс.
5 Simple Steps for Solving Any Recursive Problem
21:03
The SAT Question Everyone Got Wrong
18:25
Просмотров 12 млн
Python Sudoku Solver Tutorial with Backtracking p.1
17:31