how to fix 'ValueError: math domain error' in Python - python

def distinctIntegers(n):
board = [n]
lenBoard = 0
while lenBoard != len(board):
lenBoard = len(board)
for num in board:
temp = num - 1
for i in range(2, int(math.sqrt(temp)) + 1):
if temp % i == 0:
if i not in board:
board.append(i)
if temp / i not in board:
board.append(temp / i)
return len(board)
it's fine for now.
i wanted put that (if temp not in board : board.append(temp)) in first for loop. 'ValueError: math domain error in Python' occured after putting that .
def distinctIntegers(n):
board = [n]
lenBoard = 0
while lenBoard != len(board):
lenBoard = len(board)
for num in board:
temp = num - 1
if temp not in board:
board.append(temp)
for i in range(2, int(math.sqrt(temp)) + 1):
if temp % i == 0:
if i not in board:
board.append(i)
if temp / i not in board:
board.append(temp / i)
return len(board)
this and
def distinctIntegers(n):
board = [n]
lenBoard = 0
while lenBoard != len(board):
lenBoard = len(board)
for num in board:
temp = num - 1
for i in range(2, int(math.sqrt(temp)) + 1):
if temp % i == 0:
if i not in board:
board.append(i)
if temp / i not in board:
board.append(temp / i)
if temp not in board:
board.append(temp)
return len(board)
this, both of them didn't work
i changed the location and put 'num - 1' instead of temp..
but still doesn't works. I dont know why..

Related

Python program to print alphabet A from star pattern using nested loops [duplicate]

I've written these two functions to return a letters 'A' and 'H' as a stars pattern. Is there any way to print them next each other or should I rewrite the code to print them as one pattern?
rows = 8
cols = 8
sym = '*'
thick = 2
def A(rows, cols, sym, thick):
tmp = ''
for i in range(rows):
for j in range(cols):
if (i == 0 or i == 1) and j != 1 and j != 0:
tmp += sym
elif i > 1 and j == 0 or j == cols - 1:
tmp += sym * thick
elif i == 3 or i == 4:
tmp += sym
else:
tmp += ' '
tmp += '\n'
return tmp
def H(rows, cols, sym, thick):
tmp = ''
for i in range(rows):
for j in range(cols):
if j == 0 or j == 7:
tmp += sym * thick
if i != 3 and (i != 4):
tmp += ' '
elif (i == 3 and j != 7) or (i == 4 and j != 7):
tmp += sym
tmp += '\n'
return tmp
str = H(rows, cols, sym, thick)
str += A(rows, cols, sym, thick)
print(str)
The output is:
There are 3 general solutions:
Add logic to split the returned strings in to lines, than recombine them
Add logic to print the returned strings line by line
Use the pycurses module to create a separate window for each character and print them there.
I will demonstrate method #1 here as it is the simplest:
#you need this if you plan on letters of different height
from itertools import zip_longest
rows = 8
cols = 8
sym = '*'
thick = 2
def A(rows, cols, sym, thick):
tmp = ''
for i in range(rows):
for j in range(cols):
if (i == 0 or i == 1) and j != 1 and j != 0:
tmp += sym
elif i > 1 and j == 0 or j == cols - 1:
tmp += sym * thick
elif i == 3 or i == 4:
tmp += sym
else:
tmp += ' '
tmp += '\n'
return tmp
def H(rows, cols, sym, thick):
tmp = ''
for i in range(rows):
for j in range(cols):
if j == 0 or j == 7:
tmp += sym * thick
if i != 3 and (i != 4):
tmp += ' '
elif (i == 3 and j != 7) or (i == 4 and j != 7):
tmp += sym
tmp += '\n'
return tmp
h = H(rows, cols, sym, thick)
a = A(rows, cols, sym, thick)
s = ""
#if your letters are guaranteed to be same height, you can use regular zip
for line in zip_longest(h.split('\n'), a.split('\n'), fillvalue=''):
s += line[0] + ' ' + line[1] + '\n'
print(s)
Notice I changed your str var to s because str is a built in function in Python and you should not use it for your own variable names!
Also, all lines in "H" except middle to have a space at the end.
This is a bug in your H function, but should be easy to fix for you.
Here is alternative solution:
from operator import add
h = H(rows, cols, sym, thick)
a = A(rows, cols, sym, thick)
# horizontal join
res = '\n'.join(map(add, h.split('\n'), a.split('\n')))
print(res)
which yields:
** ** ******
** ** ******
** ** ** **
*********************
*********************
** ** ** **
** ** ** **
** ** ** **
The inconsistencies in spacing come from the fact, that you add no padding to the H bar.

why is this recursive sudoku code not working?

im learning python, I wanted the sudoku numbers to be read from a csv file and to be reconstructed. that part works. but it does not solve the sudoku. it just prints the same input again.
Can somebody please help me? Any idea why?
Question number 2: Any Tipps how i could modify this code to give the number of possible sudoku solutions? In case, there are multiple solutions possible.
Thank you so much in Advanced! :)
import csv
with open('sudoko.csv') as f:
board = list(csv.reader(f,delimiter=';'))
def solve(bo):
find = find_empty(bo)
if not find:
return True
else:
row, col = find
for num in range(1,10):
if valid(bo, num, (row, col)):
bo[row][col] = num
if solve(bo):
return True
bo[row][col] = 0
return False
def valid(bo, num, pos):
# Check row
for field in range(len(bo[0])):
if bo[pos[0]][field] == num and pos[1] != field:
return False
# Check column
for line in range(len(bo)):
if bo[line][pos[1]] == num and pos[0] != line:
return False
# Check box
box_x = pos[1] // 3
box_y = pos[0] // 3
for i in range(box_y*3, box_y*3 + 3):
for j in range(box_x * 3, box_x*3 + 3):
if bo[i][j] == num and (i,j) != pos:
return False
return True
def print_board(bo):
for i in range(len(bo)):
if i % 3 == 0 and i != 0:
print("- - - - - - - - - - - - - ")
for j in range(len(bo[0])):
if j % 3 == 0 and j != 0:
print(" | ", end="")
if j == 8:
print(bo[i][j])
else:
print(str(bo[i][j]) + " ", end="")
def find_empty(bo):
for i in range(len(bo)):
for j in range(len(bo[0])):
if bo[i][j] == 0:
return (i, j) # row, col
return None
if __name__ == "__main__":
print_board(board)
solve(board)
print("___________________")
print("")
print_board(board)

Sudoku Solver Python backtracking input

For school, we should program a sudoku solver and I just followed a tutorial to program one and it works:
board = [
[7,8,0,4,0,0,1,2,0],
[6,0,0,0,7,5,0,0,9],
[0,0,0,6,0,1,0,7,8],
[0,0,7,0,4,0,2,6,0],
[0,0,1,0,5,0,9,3,0],
[9,0,4,0,6,0,0,0,5],
[0,7,0,3,0,0,0,1,2],
[1,2,0,0,0,7,4,0,0],
[0,4,9,2,0,6,0,0,7]
]
def solve(bo):
find = find_empty(bo)
if not find:
return True
else:
row, col = find
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
return False
def valid(bo, num, pos):
# Check row
for i in range(len(bo[0])):
if bo[pos[0]][i] == num and pos[1] != i:
return False
# Check column
for i in range(len(bo)):
if bo[i][pos[1]] == num and pos[0] != i:
return False
# Check box
box_x = pos[1] // 3
box_y = pos[0] // 3
for i in range(box_y*3, box_y*3 + 3):
for j in range(box_x * 3, box_x*3 + 3):
if bo[i][j] == num and (i,j) != pos:
return False
return True
def print_board(bo):
for i in range(len(bo)):
if i % 3 == 0 and i != 0:
print("- - - - - - - - - - - - - ")
for j in range(len(bo[0])):
if j % 3 == 0 and j != 0:
print(" | ", end="")
if j == 8:
print(bo[i][j])
else:
print(str(bo[i][j]) + " ", end="")
def find_empty(bo):
for i in range(len(bo)):
for j in range(len(bo[0])):
if bo[i][j] == 0:
return (i, j) # row, col
return None
print_board(board)
solve(board)
print("___________________")
print_board(board)
But my problem is we have to handle strings like:
003020600
900305000
001806400
008102900
700000008
006708200
002609500
800203009
005010300
and couldn't separate them with a comma. Do you have an idea how to fix the problem?
You can transform a multiline string to a 2d-list of integers like:
s = """003020600
900305000
001806400
008102900
700000008
006708200
002609500
800203009
005010300"""
board = [[*map(int, line)] for line in s.splitlines()]
Or, if you are reading these lines as input from stdin:
board = []
for _ in range(9):
board.append([*map(int, input())])

Is there a way such that I can refresh a board on the screen instead of having it pile on and on in the console?

I've just completed a Connect Four game and now I'm wondering how I can keep the board in one place without having it refresh over and over again in the console. I've searched far and wide on the web for any solutions but couldn't find anything.
Below is my full code. Feel free to run it on your IDEs. Any help would be greatly appreciated!
import random
import ast
def winner(board):
"""This function accepts the Connect Four board as a parameter.
If there is no winner, the function will return the empty string "".
If the user has won, it will return 'X', and if the computer has
won it will return 'O'."""
row = 0
while row <= len(board) - 1:
count = 0
last = ''
col = 0
while col <= len(board[0]) - 1:
row_win = board[row][col]
if row_win == " ":
count = 0
col += 1
continue
if row_win == last:
count += 1
else:
count = 1
if count >= 4:
return row_win
last = row_win
col += 1
row += 1
col = 0
while col <= len(board[0]) - 1:
count = 0
last = ''
row = 0
while row <= len(board) - 1:
col_win = board[row][col]
if col_win == " ":
count = 0
row += 1
continue
if col_win == last:
count += 1
else:
count = 1
if count >= 4:
return col_win
last = col_win
row += 1
col += 1
row = 0
while row <= len(board) - 1:
col = 0
while col <= len(board[0]) - 1:
try:
if (board[row][col] == board[row + 1][col + 1] and board[row + 1][col + 1] == board[row + 2][
col + 2] and
board[row + 2][col + 2] == board[row + 3][col + 3]) and (
board[row][col] != " " or board[row + 1][col + 1] != " " or board[row + 2][col + 2] != " " or
board[row + 3][col + 3] != " "):
return board[row][col]
except:
IndexError
col += 1
row += 1
row = 0
while row <= len(board) - 1:
col = 0
while col <= len(board[0]) - 1:
try:
if (board[row][col] == board[row + 1][col - 1] and board[row + 1][col - 1] == board[row + 2][
col - 2] and
board[row + 2][col - 2] == board[row + 3][col - 3]) and (
board[row][col] != " " or board[row + 1][col - 1] != " " or board[row + 2][col - 2] != " " or
board[row + 3][col - 3] != " "):
return board[row][col]
except:
IndexError
col += 1
row += 1
# No winner: return the empty string
return ""
def display_board(board):
"""This function accepts the Connect Four board as a parameter.
It will print the Connect Four board grid (using ASCII characters)
and show the positions of any X's and O's. It also displays
the column numbers on top of the board to help
the user figure out the coordinates of their next move.
This function does not return anything."""
header = " "
i = 1
while i < len(board[0]):
header = header + str(i) + " "
i += 1
header = header + str(i)
print(header)
separator = "+---+"
i = 1
while i < len(board[0]):
separator = separator + "---+"
i += 1
print(separator)
for row in board:
print(" ", " | ".join(row))
separator = "+---+"
i = 1
while i < len(board[0]):
separator = separator + "---+"
i += 1
print(separator)
print()
def make_user_move(board):
"""This function accepts the Connect Four board as a parameter.
It will ask the user for a row and column. If the row and
column are each within the range of 1 and 7, and that square
is not already occupied, then it will place an 'X' in that square."""
valid_move = False
while not valid_move:
try:
col_num = "What col would you like to move to (1 - " + str(len(board[0])) + ")? "
col = int(input(col_num))
if board[0][col - 1] != ' ':
print("Sorry, that column is full. Please try again!\n")
else:
col = col - 1
for row in range(len(board) - 1, -1, -1):
if board[row][col] == ' ' and not valid_move:
board[row][col] = 'X'
valid_move = True
except:
ValueError
print("Please enter a valid option! ")
return board
def make_computer_move(board):
"""This function accepts the Connect Four board as a parameter.
It will randomly pick row and column values between 0 and 6.
If that square is not already occupied it will place an 'O'
in that square. Otherwise, another random row and column
will be generated."""
computer_valid_move = False
while not computer_valid_move:
col = random.randint(0, len(board) - 1)
if board[0][col] != ' ':
print("Sorry, that column is full. Please try again!\n")
else:
for row in range(len(board) - 1, -1, -1):
if board[row][col] == ' ' and not computer_valid_move:
board[row][col] = 'O'
computer_valid_move = True
return board
def main():
"""The Main Game Loop:"""
cf_board = []
row = int(input("How many rows do you want your game to have? "))
col = int(input("How many columns do you want your game to have? "))
move_order = input("Would you like to move first? (y/n) ")
while move_order.lower() != "y" and move_order.lower() != "n":
print("Invalid input! Please choose y (yes) or n (no) - case insensitive. ")
move_order = input("Would you like to move first? (y/n) ")
if move_order.lower() == "y":
users_turn = True
elif move_order.lower() == "n":
users_turn = False
free_cells = col * row
row_str = "\" \""
board_str = "\" \""
i = 0
j = 0
while i < col - 1:
row_str = row_str + "," + "\" \""
i += 1
board_list = [row_str]
while j < row - 1:
board_list.append(row_str)
j += 1
cf_board = [list(ast.literal_eval(x)) for x in board_list]
# for i in range(row-1):
# cf_board.append(row_str)
while not winner(cf_board) and (free_cells > 0):
display_board(cf_board)
if users_turn:
cf_board = make_user_move(cf_board)
users_turn = not users_turn
else:
cf_board = make_computer_move(cf_board)
users_turn = not users_turn
free_cells -= 1
display_board(cf_board)
if (winner(cf_board) == 'X'):
print("Y O U W O N !")
elif (winner(cf_board) == 'O'):
print("T H E C O M P U T E R W O N !")
elif free_cells == 0:
print("S T A L E M A T E !")
print("\n*** GAME OVER ***\n")
# Start the game!
main()
I guess the idea you want to implement is similar to make a terminal based progress bar;
For example on unix/linux systems you can update a progress bar or a simple sentence in one place with "\r" character instead of "\n" which used on print() function by default:
from sys import stdout
from time import sleep
def realtime_sentence():
name = 0
while name <= 100:
stdout.write("\r My name is {}".format(name))
name += 1
sleep(0.2)
def realtime_progress_bar():
progress = 0
while progress <= 100:
stdout.write("\r Progress: {} {}%".format(progress*"#", progress))
progress += 1
sleep(0.2)
realtime_sentence()
realtime_progress_bar()
Also check this question:
Rewrite multiple lines in the console

Invalid Syntax ; probably simple to fix

This is the part of my code which doesn't work. It says "there's an error in your code: invalid syntax."
edit: this is the part of code that is broken: for i in range(0, len(marks)):
def histogram(data):
def getFrequency(marks):
freqList = []
for i in range(0,101):
freqList.append(0)
for i in range(0, 101):
starsList = []
for i in range(0, data[i]):
starsList.append("*")
pad
if data[i] < 10:
pad = " "
elif data[i] < 100:
stars = "" .join(starsList)
print("%d | %s %d" %(i, starsList)
for i in range(0, len(marks)):
mark = marks[i]
freqList[mark] += 1
return freqList
freq = getFrequency(marks)
mode = maximum(freq)
#print (freq)
this is the rest of the code (which is above the part with the error). It may or may not be riddled with errors. I put it here in case it is relevant.
import random
def bubbleSort(data):
count = 0
for i in range(0,len(data) - 1):
for j in range(0, len(data) - 1):
count += 1
if data[j] > data[j+1]:
#swap
temp = data[j]
data[j] = data[j + 1]
data[j + 1] = temp
print(count)
return data
data = [5,4,3,2,1]
data = bubbleSort(data)
print(data)
def getData():
data = []
for i in range(0, 100):
data.append(random.randint(0,100))
return data
def mean(data):
total = 0
for i in range (0, len(data)):
#add data[i]
total = total + data[i]
return total/ len(data)
def maximum(data):
maximum = data[0]
for i in range(0, len(data)):
if maximum < data[i]:
maximum = data[i]
return maximum
def minimum(data):
minimum = data[0]
for i in range(0, len(data)):
if minimum > data[i]:
minimum = data[i]
return minimum
#def mode(data):
marks = getData()
You're simply missing a right parenthesis here:
print("%d | %s %d" %(i, starsList)
You have to add a parenthesis in print line, inside for cicle:
for i in range(0, len(marks)):
....
print("%d | %s %d" %(i, starsList))

Categories

Resources