Python Forum

Full Version: Help needed for Understanding this code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I saw this code for solving sudoku using python on the internet, and I was reading it. I am a beginner python-er, so I don't quite understand some of these lines. If someone could please write an explanation for each line that would be great! Thanks!

Code:

import sys

def same_row(i,j): return (i/9 == j/9) # Can someone explain how this math 
                                      #proves that they are in the same?
def same_col(i,j): return (i-j) % 9 == 0
def same_block(i,j): return (i/27 == j/27 and i%9/3 == j%9/3)

def r(a):
  i = a.find('0')
  if i == -1:
    sys.exit(a)

  excluded_numbers = set()
  for j in range(81):
    if same_row(i,j) or same_col(i,j) or same_block(i,j):
      excluded_numbers.add(a[j])

  for m in '123456789':
    if m not in excluded_numbers:
      r(a[:i]+m+a[i+1:]) # I really need help with this line which I don't get at all.

if __name__ == '__main__':
  if len(sys.argv) == 2 and len(sys.argv[1]) == 81:
    r(sys.argv[1])# I also don't get the use of len(sys.argv) here
  else:
    print 'Usage: python sudoku.py puzzle'
    print '  where puzzle is an 81 character string 
             representing the puzzle read left-to-right,
             top-to-bottom, and 0 is a blank'
this is terrible code, so non-pythonic...
1. lines 3-6, function definitions on single line
2. use of one-char variable names
3. use of one-char function name

also it is python2 code and as new to python you should use python3
anyway, pizzle is entered as 81-chars string. chars on positions 0-8 are first row, 9-17 - second row, etc. in python2 / is floor division, so in floor division every index from 0 to 8 (first 9 indexes) will return 0, 9-17 floor division by 9 will return 1, etc.
Python 2.7.12 (default, Dec  4 2017, 14:50:18) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 9/9
1
>>> 17/9
1
>>> 
len(sys.argv) is the number of arguments supplied when run the script from command line. the first element in sys.argv, i.e. sys.argv[0] is always the script name and in this case sys.argv[1] is the puzzle, as string

a is 81-char string, i.e. 81 digits as string. a[:i]+m+a[i+1:] will replace the char (digit on index i) with m
Ahh thank you!
I post by mistake after explaining the first lines. in the meantime I updated the post. check my updated post
(Apr-03-2018, 06:49 PM)buran Wrote: [ -> ]a is 81-char string, i.e. 81 digits as string. a[:i]+m+a[i+1:] will replace the char (digit on index i) with m
that is not 100% precise
r(a[:i]+m+a[i+1:]) is calling function r with a string that is derived from a, but the char (digit) on index i is replaced with m