rStorms
rStorms

Reputation: 1115

Check type in Python

I am currently doing my first Python course and got the following exercise:

# THREE GOLD STARS

# Sudoku [http://en.wikipedia.org/wiki/Sudoku]
# is a logic puzzle where a game
# is defined by a partially filled
# 9 x 9 square of digits where each square
# contains one of the digits 1,2,3,4,5,6,7,8,9.
# For this question we will generalize
# and simplify the game.

# Define a procedure, check_sudoku,
# that takes as input a square list
# of lists representing an n x n
# sudoku puzzle solution and returns the boolean
# True if the input is a valid
# sudoku square and returns the boolean False
# otherwise.

# A valid sudoku square satisfies these
# two properties:

#   1. Each column of the square contains
#       each of the whole numbers from 1 to n exactly once.

#   2. Each row of the square contains each
#       of the whole numbers from 1 to n exactly once.

# You may assume the the input is square and contains at
# least one row and column.

correct = [[1,2,3],
           [2,3,1],
           [3,1,2]]

incorrect = [[1,2,3,4],
             [2,3,1,3],
             [3,1,2,3],
             [4,4,4,4]]

incorrect2 = [[1,2,3,4],
             [2,3,1,4],
             [4,1,2,3],
             [3,4,1,2]]

incorrect3 = [[1,2,3,4,5],
              [2,3,1,5,6],
              [4,5,2,1,3],
              [3,4,5,2,1],
              [5,6,4,3,2]]

incorrect4 = [['a','b','c'],
              ['b','c','a'],
              ['c','a','b']]

incorrect5 = [ [1, 1.5],
               [1.5, 1]]

def check_sudoku():


#print check_sudoku(incorrect)
#>>> False

#print check_sudoku(correct)
#>>> True

#print check_sudoku(incorrect2)
#>>> False

#print check_sudoku(incorrect3)
#>>> False

#print check_sudoku(incorrect4)
#>>> False

#print check_sudoku(incorrect5)
#>>> False

My idea was to solve this by doing the following:

  1. First I need to append all columns to the list
  2. Then I can create an index starting from and check each element in sudoku as nested for loop with if soduko.count(index) != 1 --> return false

However, one sudoku is made up of letters in a string. I can't figure out what to do with that. I could convert each element in the list to ASCII with ord() and start the index from the ASCII code, in case of a = 97. This gives an error for numbers though. So before that I have to check if a list is either numbers or strings. How can I do that?

Thanks!

Upvotes: 1

Views: 210

Answers (4)

mehr
mehr

Reputation: 103

def check_sudoku( grid ):
    '''
    list of lists -> boolean

    Return True for a valid sudoku square and False otherwise.
    '''

    for row in grid:        
        for elem in row:
            if type(elem) is not int:
                return False # as we are only interested in wholes 
            # continue with your solution

Upvotes: 0

micromoses
micromoses

Reputation: 7507

If items are strings, you can use the isdigit() and isalpha() methods. You'll have to verify that they are strings, otherwise you'll get an exception:

if all([isinstance(x, int) for x in my_list]):
    # All items are ints
elif all([isinstance(x, str) for x in my_list]):
    if all([x.isdigit() for x in my_list]):
        # all items are numerical strings
    elif all([x.isalpha() for x in my_list]):
        # all items are letters' strings (or characters, no digits)
    else:
        raise TypeError("type mismatch in item list")
else:
    raise TypeError("items must be of type int or str")

Upvotes: 1

kojiro
kojiro

Reputation: 77187

As far as I understand it, if the input contains an element that is not an integer, you can be sure it's not a valid Sudoku square. So you don't need type checking:

def isValidSudokuSquare(inp):
  try:
    # .. validation that assumes elements are integers
  except TypeError:
    return False

(Aside/Hint: You can implement the rest of this validation in about two very readable lines of Python if you use sets.)

Upvotes: 1

Bunny Rabbit
Bunny Rabbit

Reputation: 8411

You can use

type('a') is str

or

isinstance('a', str)

Upvotes: 1

Related Questions