Python Sudoku Solver Tutorial with Backtracking p.2

  Рет қаралды 144,830

Tech With Tim

Tech With Tim

Күн бұрын

Пікірлер: 320
@ashwinbabu1426
@ashwinbabu1426 4 жыл бұрын
For anyone who is confused with the valid function (as I and many others were), wait until he creates the solve function and actually uses it. Then, it makes a lot more sense.
@henryash413
@henryash413 4 жыл бұрын
I watched this video last year over and over but couldnt get my head around it, I finally clicked to watch it again today determined to succeed, and satisfyingly, I did just that! Thanks Tim
@asdfasdfasdf383
@asdfasdfasdf383 4 жыл бұрын
Beautiful. Simply put. This is the best video I ve found for Sudoku backtracking. Its also amazing how little space you need for the whole code.
@amirfirdaus3573
@amirfirdaus3573 4 жыл бұрын
8:34 Tim : to do this, it is actually very straightforward Me : oh okay Tim : we're gonna do it recursively Me : (°-° )
@langrock74
@langrock74 4 жыл бұрын
I would start with implementing a solver using the method you would use when solving a sudoku by hand. You'd first look at fields for which there can only be a single valid number. Once you implement this, you can solve easy and medium-hard sudokus. After that, look again at what Tim is doing with the back-tracking algorithm and it may make more sense.
@user-wc1sm8cj8s
@user-wc1sm8cj8s 3 жыл бұрын
LOL That got me
@theomichail9818
@theomichail9818 2 жыл бұрын
@@langrock74 Sorry to revive this a year later but what you're talking about is heuristics which would be the next step in making this even faster than what it is currently
@ThatControlUser
@ThatControlUser Жыл бұрын
​@@theomichail9818here I am, a year later, could you please tell me more about how that would improve the speed os this algorithm?
@saisreekarsunku4140
@saisreekarsunku4140 Жыл бұрын
🤣🤣🤣🤣🤣🤣😂
@nktslp3650
@nktslp3650 4 жыл бұрын
Confusing moment when I did understand how x/y is handled here. Damn that was painful to go through in the valid() function part! This is brillant! Thanks !
@surajvijay1937
@surajvijay1937 4 жыл бұрын
Ya he could have used x for rows and y for columns
@besllu8116
@besllu8116 4 жыл бұрын
When I came here I didn't know how to use backtracking really, and even less I know how to play Sudoku. Now I know both, after taking apart your code I can say it is brilliant example. Subscribed.
@flamexc
@flamexc Жыл бұрын
I did find bits confusing and poorly explained (lines 17-20 for example) but overall you explained the concept of backtracking pretty well and this gave me good insight into what it is. Thanks!
@andrewm6788
@andrewm6788 5 жыл бұрын
Could you do one more episode of this where you make a gui of this
@eutog
@eutog 2 жыл бұрын
Dude one year have passed and i came back here to do this algorithm translating him do c# and damn this still pretty awesome. thank u a lot
@minimationsinc.6100
@minimationsinc.6100 5 жыл бұрын
Really cool! I've been pondering over solving the sudoku solver problem for a long time and did not think of recursion as an option! Thanks for making this video...
@baphnie
@baphnie Жыл бұрын
Really good tutorials! @2:20 isn't necessary, since we haven't written the selected number to the blank cell yet at this point. The code works with or without this second condition.
@Davidsito44
@Davidsito44 Жыл бұрын
Yeah! That was confusing and after running and debugging I found that is not necessary.
@Lafret17
@Lafret17 4 жыл бұрын
i cannot express how legendary you are for these vids. thank you man
@josenordenflycht6517
@josenordenflycht6517 Жыл бұрын
Bro, you just saved my advanced programming homework, i had to do a board similar to sudoku and i didnt know how to do it, your video saved my life :)
@HealthInspectorz
@HealthInspectorz 4 жыл бұрын
Thanks mate! Its fun to code these algorithms because i remember coding a maze algorithm with recursive algorithm and memories begin flashing my eyes.
@davidjimenezlopez
@davidjimenezlopez 4 жыл бұрын
Hi Tim, First, great job. I enjoyed the videos. It is easy to understand for beginners, short code. For fun I am doing a sudoku module, and yes, it does have more bells and whistles. But just the bactracking and my sudoku grid object takes about a hundred lines of python code more than yours. I do see one single problem with your solution: Your code can find if a grid has no solution or has a solution, but it does not figure out if the solution is unique. That is an important part of a puzzle. On the other hand, like you, I have a grid that I use to test. I found it randomly online, I cannot even tell you exactly where. But with that grid, your code is not as immediate. You can try it. In my machine (2017 laptop with i5 processor) it took 15 seconds to find a single solution. About half the time it took my code to find that it was the only solution. I post the matrix here. grid = np.array([ (6, 0, 0, 0, 0, 0, 0, 5, 1), (0, 0, 0, 3, 0, 0, 9, 0, 0), (0, 0, 8, 0, 0, 0, 0, 0, 0), (0, 4, 0, 7, 0, 0, 5, 0, 0), (0, 0, 0, 0, 9, 0, 8, 0, 0), (0, 0, 1, 8, 5, 0, 0, 3, 7), (5, 0, 2, 6, 0 ,0, 0, 0, 4), (3, 0, 0, 0, 0, 7, 0, 2, 9), (0, 0, 4, 0, 0, 0, 0, 0, 0) ]) Again, even with this comment, great job. Once you graduate, you should teach. You are good at it. Believe me, I am a college professor.
@braxtonec
@braxtonec 4 жыл бұрын
Love the code. Integer division great trick. Thanks for sharing! Inspired me to write my own and try for less than 100 lines before watching this seeing what you did!
@alexb2773
@alexb2773 4 жыл бұрын
I came here to learn more about backtracking, and I did. I knew of the channel before, but now I'm a subscriber - please make more videos like this. Thank you!
@TheJChrest
@TheJChrest 5 жыл бұрын
Keep up the content bro, i'm learning a lot!
@nnhh9211
@nnhh9211 4 жыл бұрын
Thanks a lot. The recursion bit was a bit hectic but this was a really good explanation especially for self-taught developers who don't know some of this concepts from a classroom.
@harold3802
@harold3802 4 жыл бұрын
Couldn’t wrap my head around 2D arrays until this, thanks 🙏🏽
@kylejames2126
@kylejames2126 2 жыл бұрын
Spends a week trying to make a back tracking algo by myself* Finds this video, follows along, everything makes sense, and finishes a project in 20 minutes* Man I love programming :')
@niloofarsahebalzamani7934
@niloofarsahebalzamani7934 3 жыл бұрын
Thank you Tim, it was so nice. I just want to say if you print out every part to see what happen, it was so understandable for me which is beginner.
@eutog
@eutog 3 жыл бұрын
hey tim, i got to say: your content is pretty awesome. i'm here from brazil learning a lot with your videos, dude. this video is from a some time ago but i keep following you every day. a great hug man
@andrew77359
@andrew77359 3 жыл бұрын
The explanation is very straightforward to the point where it is unbelievable!
@snoxxer_5552
@snoxxer_5552 4 жыл бұрын
5:33 3//3 is 1.
@mkay7800
@mkay7800 4 жыл бұрын
Its awesome to watch how easy things can be Easy if taught by great teachers, Hats off to you !!
@michaelantoun9353
@michaelantoun9353 4 жыл бұрын
Since you traverse the board in a particular order, then you can check if the board is full by checking only the bottom-right value. The solution you have now is O(n^2) where n is the length of the board for every call to solve, just to check if the board is full.
@sarthak2482
@sarthak2482 2 жыл бұрын
Just a question (I'm not sure if this is right). If we only check the bottom right value, we won't be able to get the coordinates of the first occurrence of an empty cell. So isn't it true that what he is doing (checking full length of board) has dual purpose of 1) checking if game is solved or not and 2) if it isn't solved, what is the position of '0'
@DennisZIyanChen
@DennisZIyanChen 3 жыл бұрын
@Tech With Tim your video is a good step by step guide but to truly distinguish yourself from the dozens other sites with a lot more content and more experienced teachers, you have to help answer the question "how can I come up with the same thought process that Tim did in his video". You are teaching what to think and do, but not how you came up with the what in the first place. What if you can draw a mindmap of your entire thought process without ever showing the code? The recursion step is perfect for some visual illustration, maybe starting with the last 3 numbers to be filled in, a trivial board state.
@saisreekarsunku4140
@saisreekarsunku4140 Жыл бұрын
super explanation and marvelous code you made it short i tried box with definingeach and every position in thew box array
@big123lak
@big123lak 9 ай бұрын
edit: im pretty sure I figured it out, this should help any beginners understand and answer anything not understood. its calling the functions wether they are true or not, so everytime we make it to if solve it basically goes into a new solve, but once we reach when valid is false it goes to a return false for solve, which ends the current solve then goes back to the last called solve function and continues to set it to 0 but then how does it recall solve from there, someone said it continues the loop so if the loop was at 5 originally it will set it to 0 and the for loop picks it back up, but this doesnt work if the loop is already at 9 it would just end, but it then could go back to previous one again until it find a loop it can continue , so the only way it would fail is if the starting loop ends up at a 9 and the next loop needed to be reset which shouldn't happen if it runs thru each one from 0 and only back tracks when needed and when it back tracks it starts at the number it left off and if it fails completely at 9 begins the previous function which can happen as many times as needed so only the very first number can only be changed 9 times and once its at the correct number it should never have to be changed as every other number would get changed first and run thru every possibility so theres no way for a false positive to cause a change, so every number except the first number can be reset from 0 multiple times and since its a sodoku puzzle its set with correct numbers so once you find a correct number in the beginning its impossible to fail
@220SouthlandAve
@220SouthlandAve 6 ай бұрын
Pretty simple when you break it down like this!
@langrock74
@langrock74 4 жыл бұрын
Fun fact. If you precede the backtracking algorithm by one that fills in all the 'obvious' choices, the fields for which there is only a single possible number, you can speed the code up by over a factor of 15 for 'hard' sudokus. This preconditioning algorithm will actually also solve 'easy' and 'medium' hard sudokus without the recursive backtracking algorithm. For those interested in coding a solver, start with that one instead of the back-tracking one.
@delbandtaha5539
@delbandtaha5539 5 жыл бұрын
Good stuff! The only thing that was not clear is why you used the len of the first row in the find_empty function. for j in range(len(bo[0])) You could have done this... for j in range(len(bo[i])) which would have made a little more sense. I know the length does not change from row to row.
@TechWithTim
@TechWithTim 5 жыл бұрын
Ya you’re right, oversight on my part but really not an issue as we know the length of each is the same.
@delbandtaha5539
@delbandtaha5539 5 жыл бұрын
@@TechWithTim thanks again for taking the time to put this together. Keep up the great work.
@JonasAmidu
@JonasAmidu 5 жыл бұрын
Continually impressed by your videos ! Your explanation make coding simple. Keep up the good work
@Molenkof
@Molenkof 3 жыл бұрын
function solve(bo) doesn't return the board.... how is the global variable 'board' being modified?
@theauthenticdhamma
@theauthenticdhamma 11 ай бұрын
The idea of backtracking is very clear and obvious, what is not clear and obvious at all is how that process is fulfilled by the presented form of recursion. Now I know that when you start thinking about recursion too much, your brain starts to hurt, however if someone could find a better way to explain how recursion is actually implementing backtracking here that would be really helpful. What is somewhat puzzling to me as well is why the output of the solve_sudoku() function is True or False, instead of simply the solution to the sudoku puzzle. A fun fact: adding a guess number counter and trying to solve an "extreme" level sudoku (from among levels: easy, medium, hard, expert and extreme), the code needed to make about 80 mil guesses and took about 7 minutes to solve. When I altered the initial board a bit to make the puzzle unsolvable, the number of guesses increased to 180 mil and the time required was 12 min.
@big123lak
@big123lak 9 ай бұрын
ye im confused to, its calling the functions wether they are true or not, so everytime we make it to if solve it basically goes into a new solve, but once we reach when valid is false it goes to a return false for solve, which ends the current solve then goes back to the last called solve function and continues to set it to 0 but then how does it recall solve from there, this is the only way I can understand recursion but then leaves me wondering how solve restarts from there and if the functions just starts going backwards that doesnt make sense either
@theauthenticdhamma
@theauthenticdhamma 9 ай бұрын
@@big123lak I wonder who is the actual author of the code. This same form of recursion to solve Sudoku appears in a number of tutorials, but is never properly explained. I would think if Tim himself actually came up with the code he should be able to explain what kind of thought-process led him to it, and then we would understand how the recursion works in this case better. However I do not think he is the actual author. Anyway, since no one of those geniuses out there offered any real explanation, I tried out Google's Bard and finally received an explanation that made it a lot clearer. Here is the relevant part of it: BARD: In essence, the recursion allows the function to explore different possibilities systematically, while backtracking ensures it can recover from incorrect guesses and try alternative paths until a valid solution is reached. QUESTION: I wonder whether you could provide a more detailed explanation of the last paragraph. The given code looks extremely simple yet what it is doing is rather complex, i.e. it somehow has to remember what guesses have been made so far at different single empty cells of the sudoku and it always has to determine how far back it needs to backtrack when it hits a dead end. Now, how this is happening is rather difficult to understand. BARD I'll provide a more detailed explanation of how the code remembers guesses and determines backtracking: 1. Recursion as Implicit Memory: Each recursive call of solve_sudoku(puzzle) represents a decision point. The function doesn't explicitly store guesses in a separate data structure. Instead, the nested nature of recursive calls implicitly stores the state of the puzzle and the guesses made so far. Each recursive call has its own local scope, along with its own version of puzzle. This means changes made to puzzle within a call don't affect previous calls. 2. Backtracking Through Function Returns: When a guess fails (either invalid or doesn't lead to a solution): The function returns False to the previous call, signaling a dead end. The previous call then backtracks by trying a different guess for the cell it was working on. This process repeats until a valid solution is found or all possibilities are exhausted. Illustrative Example: Imagine the function calls itself recursively three times: solve_sudoku(puzzle) solve_sudoku(puzzle) (within the first call) solve_sudoku(puzzle) (within the second call) If the third call encounters a dead end, it returns False to the second call. The second call then tries a different guess for its cell. If all guesses in the second call fail, it returns False to the first call, and so on. Remember: Backtracking is a depth-first search approach. It explores one path fully before backtracking and trying another. The recursive calls and their return values implicitly manage the search and backtracking process, eliminating the need for explicit memory structures. I thought what Google's AI produced here was remarkably good.
@rxlvnd3397
@rxlvnd3397 4 жыл бұрын
Thanks Tim! This helps me a lot to understand logic in coding
@xandermichels8336
@xandermichels8336 4 жыл бұрын
hmmm, i don’t think i can use this on my cv anymore, i was close to the solution by myself but i think this might have helped too much, curse your excellent explaining :(
@hamad87ad
@hamad87ad 5 жыл бұрын
Thanks, it was so helpful I, ll go through each line of code and try to learn it. Good job sir
@Vibertex
@Vibertex 4 жыл бұрын
literally so well explained bro. Nice job
@nursultansulaymanov
@nursultansulaymanov 3 жыл бұрын
You helped me a lot to understand the recursion and baCKTRACKING! aWESOME VIDEO ! tHANK U BUDDY
@martin-xq7te
@martin-xq7te 5 жыл бұрын
Great set of training videos. Well done Tim
@Toga333T
@Toga333T 5 жыл бұрын
The video is great, but I recommend you to read "clean code" book. It's a beautiful help to you and to us !
@merover99
@merover99 5 жыл бұрын
I have read that book and I agree with you. The algorithm gets cleaner if, for example, you use "row" and "col" as variable names instead of i and j. But I really like the video. Good explanations.
@HealthInspectorz
@HealthInspectorz 4 жыл бұрын
@@merover99 oh thats what i did. It makes it easier to read. I learned that in my days where i coded in python.
@jaylynnemuzik
@jaylynnemuzik 4 жыл бұрын
Robert Martin or Jim Lewis ...which "clean code" book?
@Toga333T
@Toga333T 3 жыл бұрын
@@jaylynnemuzik The uncle bob, Robert Martin
@zacharyhoppock674
@zacharyhoppock674 2 жыл бұрын
Very impressive work here, Tim
@oscar33212
@oscar33212 4 жыл бұрын
Have you tried solving larger grids? I.e. 16x16, 25x25, 36x36. They get more challenging as you recursive function call stack is limited.
@langrock74
@langrock74 4 жыл бұрын
Even more important to then precondition the board by iteratively filling in the fields with only a single valid solution before calling the recursive algorithm.
@sachinloecher5780
@sachinloecher5780 4 жыл бұрын
Really helped. Would love to see more in the future
@minhnguyenquang6248
@minhnguyenquang6248 2 жыл бұрын
Thank you bro, i have learnt a bunch of great and interesting thing from you.
@MrEmanuelFeijo
@MrEmanuelFeijo 4 жыл бұрын
Thank you very much for the ideia and explanation, i did it java because i'm trying to be fluent that language and works spectular. Keep making good content :)
@codeme1529
@codeme1529 3 жыл бұрын
Thank you Tim! I have a question though. In the script, we iterate over the number for a give "0" (any) and once it is legit, we go further. However, what I cannot quite get is how come python goes back to the previously assigned value (i) and changes it if the current loop over len(1, 10) is False. In other words: let's say that the current attempt to fill in "0" spot with value from the len() is not possible. How python goes back to the previously made decision and changes it (example: from 5 to 3)? You did not write the specific explanation to into the script. From what I saw I expected your code to run a backtracking algorithm to the current "0" position. But what I cannot understand (because there is no explanation in the script) is how it changes the previous one. If you can explain, it would be amazing! I should say that your explanation so far was perfect! (The only missing part is above)) Many thanks in advance!
@hossumquat
@hossumquat 3 жыл бұрын
It happens automatically with the magic of recursion. Every time you call solve() again, it creates a whole new variable space, so you can have different values in your variables from the parent instance. So each new call to solve() tries to fill in another cell. If we reach a dead-end where nothing will work, it returns false, which tells the parent call that it was a dead end and it has to try the next value. Each call of solve() has it's own value for find_empty(), which is the cell it is attempting to solve. That is how each call of solve() knows what cell to change back. You probably just need a more solid understanding of stacks and how they work and you'll likely understand what's happening.
@khechog
@khechog 2 жыл бұрын
In the solve(bo) function there is a for loop, so when it recursively returns to the same stack, we assign 0 to that value (bo[row][col] = 0) so that we can change it to another valid value using the for loop (range 1, 10).
@abhijitprajapati3764
@abhijitprajapati3764 3 жыл бұрын
this is an amazing video! i hope you hit one million subscribers in the future
@Danielagostinho21
@Danielagostinho21 5 жыл бұрын
Nice algorithm, I like particularly how you just make the first spot and then make it recursive, really clever. Could this be implemented on making schools timetables? For classrooms, teachers and students?
@TechWithTim
@TechWithTim 5 жыл бұрын
Probably!
@peschebichsu
@peschebichsu 3 жыл бұрын
Really like the video, just as I do all of your content! Would be cool to see a tutorial of something like a chess AI of you :)
@sriyashsinghania8420
@sriyashsinghania8420 4 жыл бұрын
what is pos[1] and pos[0] in the above code? Please explain. Thanky you!
@langrock74
@langrock74 4 жыл бұрын
'pos' is a tuple returned from the find_valid() function. Hence pos[0] is the first element and pos[1] is the first element of that tuple, referring to row and column indices.
@victoriae3253
@victoriae3253 2 жыл бұрын
@@langrock74 @Techwithtim I guess you mean find_empty function, pos[0] is the first element of what? is it the list of tuples returned from the find empty() function or what? please could you clarify, Also pos[1] assuming you have a tuple (2,6) do you mean pos[ 1 ] would be 2 please i would appreciate it if you could use an example
@xianlongzeng860
@xianlongzeng860 3 жыл бұрын
So clear. Genius
@muddyexport5639
@muddyexport5639 3 жыл бұрын
Excellent & Elegant solution & code
@RE-yp5bz
@RE-yp5bz 3 жыл бұрын
Thanks 💓 . Please do more like this
@charlesbamelis4237
@charlesbamelis4237 Жыл бұрын
Thanks bro you explain it very well!!
@vigneshrajendiran8384
@vigneshrajendiran8384 4 жыл бұрын
Tim you could have mentioned about DFS similarity and have given some algo base too.
@user-hd6xc1xn9d
@user-hd6xc1xn9d 4 жыл бұрын
I don't understand anything in this tutorial. how does the valid() function work, also what is pos[]?
@j3m1llp___54
@j3m1llp___54 4 жыл бұрын
so its kinda like recursion and inception, solve function would be ran inside itself until the last cell is filled or there are no more valid numbers, then it would return false and backtrack until it finds a valid number???
@ruggeropiazza2157
@ruggeropiazza2157 4 жыл бұрын
I noticed that the algorithm only returns correct solutions with a certain number of entries to start with: if the sudoku board to solve has between 25 to 30 numbers to start with, it produce a correct solution, but if you pass a board with less than that it returns wrong solutions. Does anyone know why? Thanks for any reply and congrats for your channel man, love it!!!!
@cbt121314
@cbt121314 4 жыл бұрын
I'm late but in case it helps someone else I'd make sure to change the line that says "for i in range(1,10)" to put the size of the rows u're using... like for an 8*8 sudoku that would be " for i in range(1,9)" to go through 8 columns and not 9
@kevinsee1671
@kevinsee1671 3 жыл бұрын
great video! may I ask why you used return False at the end of the solve() function? From the way I see it, it would work just fine without it still. Thanks
@sagarmehla2102
@sagarmehla2102 3 жыл бұрын
awesome teaching style.
@arrievandervliet7361
@arrievandervliet7361 2 жыл бұрын
Hi Tim! Great video and very clean code. The given code will find the first valid solution. Challenge: how would we change the code to find all solutions. I've been wondering about this and I think what is necessary is to keep looping and backtracking until we've tried all values in each free cell, i.e. all counters have are at 9, instead of the first value that yields a valid board.
@sbalogh53
@sbalogh53 2 жыл бұрын
Yes. If you don't stop after finding a solution the backtracking method will find all others as well.
@aihuachen3568
@aihuachen3568 4 жыл бұрын
Could you explain: when solve function return false, and the bo[row][col] is reset to 0, how does the program know next try it should use a different number than what it was used before that did not pass the valid function? How does the program avoid trapping itself in a infinite loop without any solution at all? Thank you very much!
@vamsikrishna4960
@vamsikrishna4960 4 жыл бұрын
bo[row][col] = 0 is inside the for loop for iterating 1 to 10. So lets say 1 failed, then the for loop tries 2 to 10
@mp-ng
@mp-ng 4 жыл бұрын
Before the program backtracks, it actually tries to solve further squares recursively. Therefore the square tried this time would be different from previous ones (not the same call for function solve). It would only be caught in a "loop" if that is the only empty square remaining, which would only happen if there is a fault with the actual puzzle.
@henryash413
@henryash413 4 жыл бұрын
The for loop continues from where it left off. If 5 didnt work and it has backtracked to this loop again, the loop will next try 6 (if 6 is valid).
@subigyashrestha4956
@subigyashrestha4956 4 жыл бұрын
I understood it this way as the row and column is inside the solve function they are different variables every time function gets called . Lets take an example suppose if we go on solving solve for 1st empty 2nd empty and reach 3rd empty where we cant find a value that so the solve function returns false it traces back to the if statement of 2nd empty where the row and col are that of the 2nd empty space and sets it to zero and the for loop continues form where it left off and so on...
@cheeyuanng853
@cheeyuanng853 3 жыл бұрын
@@mp-ng I don't quite see the recursion and the backtracking. for i in range(1,10): if valid(bo, i, (row, col)): bo[row][col] = i if solve(bo): return True bo[row][col] = 0 does the if statement calls solve(bo) instead of just checking if "solve(bo)'s boolean state is True? and when it calls solve, it goes into the next level of recursion? Edit: Looks like someone answered it below. Thanks.
@Heck-ed6sr
@Heck-ed6sr 4 жыл бұрын
For the solve(bo) function, it is possible to indent the 'bo [row] [col] = 0' line equally as much as the 'return False' statement (outside of the for loop)?
@shahzaib-5802
@shahzaib-5802 3 жыл бұрын
Sorry but I'm new to python, I need some insights that will this code be useful to make a program quite similar to this; calcudoko? or can i somehow alter the code and make that program? P.S You're a LEGEND GUY Tim, an inspiration.
@capy_can_code
@capy_can_code 4 жыл бұрын
love this one! good job bro
@bukkalapraneeth7177
@bukkalapraneeth7177 4 жыл бұрын
super bro,very good solution.
@deeraj3069
@deeraj3069 5 жыл бұрын
Thanks for the video. Can you please make a series of hard problems of LeetCode
@paraglide01
@paraglide01 3 жыл бұрын
Thanks,Tim, your are a great inspiration to go to advanced python programming for us beginners.
@cripi5636
@cripi5636 2 жыл бұрын
Fara tine aveam restanta asa ca iti multumesc uwu
@Vorturo
@Vorturo 4 жыл бұрын
10:48 find_empty returns none anyways, there is no need to write it.. or am I wrong??
@krishnans2006
@krishnans2006 4 жыл бұрын
Vorturo, you are correct. There is no need to write "return None" in the function, since by default if there is no return statement, it returns None. However, it is a good coding practice is that you add a "return None" statement to the function if you are going to use that value. For example, if you are just calling a function to print text to the console, and you are not going to use the returned value from the function, there is no need for a return statement. But, if you are going to use the None value returned from a function, then it is recommended to add a return None statement. This is mainly for good code readability.
@wanderingfido
@wanderingfido 3 жыл бұрын
Why hasn't anyone bothered to improve the backtracking algo with set theory? You could further filter the available elements of choice rather than blindly (or naively) decrementing or incrementing through 1 to 9. Each empty cell could be the resultant set _R = U - (H + V + B)_ where _U = {1 to 9} H = {h | all known horizontal numbers} V = {v | all known vertical numbers} B = { b | all known numbers in the box}_
@gopihosur
@gopihosur 4 жыл бұрын
fantastic video, very useful please make more projects!!!!!!!!!!!!
@antonigolos1406
@antonigolos1406 5 жыл бұрын
Good work! I will try to do this in C++, cause i dont know python :/
@davideettori3226
@davideettori3226 5 жыл бұрын
Great video, keep doing this kind of problem
@wearecode9199
@wearecode9199 3 жыл бұрын
Looks very good - now try do this in C++ using a stack :) :) :)
@kiralight4212
@kiralight4212 2 жыл бұрын
Why do I print out two boards that are identitical(unsolved) rather than one on the top being unsolved and the one at the bottom being solved? I used the exact code.
@saikrishnamaddali1659
@saikrishnamaddali1659 5 жыл бұрын
You are Genius bro
@moesparc
@moesparc 2 жыл бұрын
This code works without the check box, function. I do not understand why it's necessary if you are already checking the rows and columns.
@ssfgvvh
@ssfgvvh 3 жыл бұрын
It helped a lot. Thanks.
@sainco3036
@sainco3036 5 жыл бұрын
thanks.
@avinababanerjee9087
@avinababanerjee9087 4 жыл бұрын
You are the best ! Thanks a lot !!
@jananni123456789
@jananni123456789 3 жыл бұрын
If you wanted to make a pygame gui would you have to convert this into a while loop?
@rushisheth2582
@rushisheth2582 4 жыл бұрын
For the valid function, why did you divide and multiply the position by three? When you could have just used the positions as they were to begin with.
@hossumquat
@hossumquat 3 жыл бұрын
It is integer division, so the remainder gets dropped, then multiply. So it essentially rounds the number off to a multiple of 3. So not quite back where it began.
@mariuskunauskas1297
@mariuskunauskas1297 3 жыл бұрын
What I'm really confused about is the valid function's and pos != i part. Why would we be concerned about this exception if we loop through it only once. I mean, once we confirm that the valid function returns True, we insert the number into our specified spot and then we call a brand new valid function where the 0 is in the next spot. Long story short, I deleted all three "and pos !=" statements from all three valid function's parts and am still getting the same solutions.
@victorsamsonov4942
@victorsamsonov4942 4 жыл бұрын
how does line 29 bo[row][col] = 0 execute if there is an if statement before it that is constantly being checked?
@newtonphile
@newtonphile 3 жыл бұрын
Would if the board has more than one valid solution. How would you modify this to find all valid solutions?
@boicey
@boicey 5 жыл бұрын
Could you make another video perhaps expanding on testing? Possibly a good sample size?
@TechWithTim
@TechWithTim 5 жыл бұрын
Ya maybe
@boicey
@boicey 5 жыл бұрын
@@TechWithTim How easy would it be to take this program and generate a GUI for it allowing users to enter a puzzle rather than going through the code?
@octavian3033
@octavian3033 4 жыл бұрын
"To do that is very straight forward." Dude, for newbies none of this is straight forward.
@enochayodele6121
@enochayodele6121 3 жыл бұрын
Likeeeeeeeeeee! 😭
@X_x_kingfisher_x_X
@X_x_kingfisher_x_X Жыл бұрын
Hey Tim what if the board has more than one solutions? How to get that in python?
@gunjanshellar1987
@gunjanshellar1987 3 жыл бұрын
what if i wanted to get a board from a csv file? how can i do it? will it still work? cause you just gave pre made board to the solver whereas i want to give the solver some other values like from a dataset or so.
@vyasyash8157
@vyasyash8157 4 жыл бұрын
Amazing video very helpful
@CompsciChronicles
@CompsciChronicles 4 жыл бұрын
Superb one 👌
@suyashneelambugg
@suyashneelambugg 2 жыл бұрын
Can we not write : if valid(bo, i, (row, col)): bo[row][col] = i if solve(bo): return True bo[row][col] = 0 as : if valid(bo, i, (row, col)): bo[row][col] = i else: solve(bo) bo[row][col] = 0 ??
@ankitwankhede2982
@ankitwankhede2982 4 жыл бұрын
i had a question , why would it try next value while backtracking instead of the same one ? like if the solution is like 4567 and it backtracks to 6 what stops it from choosing 6 again ?
@Ashenfyre
@Ashenfyre 2 жыл бұрын
It’s kinda hard to understand at first, but it keeps track of the number it was at. Pretty much it starts at the very end and makes it way to the top. So let’s say 6 wasn’t the right digit 3 square later, well it goes back to that to the recursion it was in when it chose 6 and will try 7, since it was at 6 back then. Kinda hard to explain, but that’s how it works. Pretty much, it already knows whats gonna work and whats not.
@ankitwankhede2982
@ankitwankhede2982 4 жыл бұрын
Also RecursionError: maximum recursion depth exceeded in comparison , why ?
@wangrobbie6867
@wangrobbie6867 4 жыл бұрын
Thx for sharing!
@user-hd6xc1xn9d
@user-hd6xc1xn9d 4 жыл бұрын
What is if bo[i][j]? what is i and j?
@langrock74
@langrock74 4 жыл бұрын
'bo' is the name for the board inside the function. It's a list of lists of integers representing the sudoku. The 'i' and 'j' are the row and column indices.
Python Sudoku Solver Tutorial with Backtracking p.1
17:31
Tech With Tim
Рет қаралды 285 М.
An Introduction to Software Design - With Python
34:05
Tech With Tim
Рет қаралды 518 М.
ЛУЧШИЙ ФОКУС + секрет! #shorts
00:12
Роман Magic
Рет қаралды 21 МЛН
Каха и лужа  #непосредственнокаха
00:15
UFC 308 : Уиттакер VS Чимаев
01:54
Setanta Sports UFC
Рет қаралды 910 М.
Sudoku Solver in Python (using 10 different solving strategies)
18:22
Games Computers Play
Рет қаралды 37 М.
Backtracking (Think Like a Programmer)
13:02
V. Anton Spraul
Рет қаралды 337 М.
Python Sudoku Solver - Computerphile
10:53
Computerphile
Рет қаралды 1,2 МЛН
How to Build an Algorithm to Solve ANY Sudoku Puzzle
10:05
Jack Tech
Рет қаралды 9 М.
Create a Sudoku Solver In Java In 20 Minutes - Full Tutorial
20:25
Coding with John
Рет қаралды 323 М.
C++ vs Rust: which is faster?
21:15
fasterthanlime
Рет қаралды 400 М.
Pygame in 90 Minutes - For Beginners
1:35:22
Tech With Tim
Рет қаралды 1,1 МЛН
This Is Why Python Data Classes Are Awesome
22:19
ArjanCodes
Рет қаралды 812 М.
Sudoku Solver in Python
19:22
NeuralNine
Рет қаралды 42 М.