I was given the following task:
Richard likes to ask his classmates questions like the following:
4 x 4 x 3 = 13
In order to solve this task, his classmates have to fill in the missing arithemtic operators (+, -, *, /) that the created equation is true. For this example the correct solution would be 4 * 4 - 3. Write a piece of code that creates similar questions to the one above. It should comply the following rules:
The riddles should only have one solution (e.g. not 3 x 4 x 3 = 15, which has two solutions)
The operands are numbers between 1-9
The solution is a positive integer
Point before dashes is taken into account (e.g. 1 + 3 * 4 = 13)
Every interim result is an integer (e.g. not 3 / 2 * 4 = 6)
Create riddles up to 15 arithmetic operands, which follow these rules.
My progress so far:
import random
import time
import sys
add = lambda a, b: a + b
sub = lambda a, b: a - b
mul = lambda a, b: a * b
div = lambda a, b: a / b if a % b == 0 else 0 / 0
operations = [(add, '+'),
(sub, '-'),
(mul, '*'),
(div, '/')]
operations_mul = [(mul, '*'),
(add, '+'),
(sub, '-'),
(div, '/')]
res = []
def ReprStack(stack):
reps = [str(item) if type(item) is int else item[1] for item in stack]
return ''.join(reps)
def Solve(target, numbers):
counter = 0
def Recurse(stack, nums):
global res
nonlocal counter
valid = True
end = False
for n in range(len(nums)):
stack.append(nums[n])
remaining = nums[:n] + nums[n + 1:]
pos = [position for position, char in enumerate(stack) if char == operations[3]]
for j in pos:
if stack[j - 1] % stack[j + 1] != 0:
valid = False
if valid:
if len(remaining) == 0:
# Überprüfung, ob Stack == target
solution_string = str(ReprStack(stack))
if eval(solution_string) == target:
if not check_float_division(solution_string)[0]:
counter += 1
res.append(solution_string)
if counter > 1:
res = []
values(number_ops)
target_new, numbers_list_new = values(number_ops)
Solve(target_new, numbers_list_new)
else:
for op in operations_mul:
stack.append(op)
stack = Recurse(stack, remaining)
stack = stack[:-1]
else:
if len(pos) * 2 + 1 == len(stack):
end = True
if counter == 1 and end:
print(print_solution(target))
sys.exit()
stack = stack[:-1]
return stack
Recurse([], numbers)
def simplify_multiplication(solution_string):
for i in range(len(solution_string)):
pos_mul = [position for position, char in enumerate(solution_string) if char == '*']
if solution_string[i] == '*' and len(pos_mul) > 0:
ersatz = int(solution_string[i - 1]) * int(solution_string[i + 1])
solution_string_new = solution_string[:i - 1] + solution_string[i + 1:]
solution_string_new_list = list(solution_string_new)
solution_string_new_list[i - 1] = str(ersatz)
solution_string = ''.join(str(x) for x in solution_string_new_list)
else:
return solution_string
return solution_string
def check_float_division(solution_string):
pos_div = []
solution_string = simplify_multiplication(solution_string)
if len(solution_string) > 0:
for i in range(len(solution_string)):
pos_div = [position for position, char in enumerate(solution_string) if char == '/']
if len(pos_div) == 0:
return False, pos_div
for j in pos_div:
if int(solution_string[j - 1]) % int(solution_string[j + 1]) != 0:
# Float division
return True, pos_div
else:
# No float division
return False, pos_div
def new_equation(number_ops):
equation = []
operators = ['+', '-', '*', '/']
ops = ""
if number_ops > 1:
for i in range(number_ops):
ops = ''.join(random.choices(operators, weights=(4, 4, 4, 4), k=1))
const = random.randint(1, 9)
equation.append(const)
equation.append(ops)
del equation[-1]
pos = check_float_division(equation)[1]
if check_float_division(equation):
if len(pos) == 0:
return equation
for i in pos:
equation[i] = ops
else:
'''for i in pos:
if equation[i+1] < equation[i-1]:
while equation[i-1] % equation[i+1] != 0:
equation[i+1] += 1'''
new_equation(number_ops)
else:
print("No solution with only one operand")
sys.exit()
return equation
def values(number_ops):
target = 0
equation = ''
while target < 1:
equation = ''.join(str(e) for e in new_equation(number_ops))
target = eval(equation)
numbers_list = list(
map(int, equation.replace('+', ' ').replace('-', ' ').replace('*', ' ').replace('/', ' ').split()))
return target, numbers_list
def print_solution(target):
equation_encrypted_sol = ''.join(res).replace('+', '○').replace('-', '○').replace('*', '○').replace('/', '○')
print("Try to find the correct operators " + str(equation_encrypted_sol) + " die Zahl " + str(
target))
end_time = time.time()
print("Duration: ", end_time - start_time)
input(
"Press random button and after that "ENTER" in order to generate result")
print(''.join(res))
if __name__ == '__main__':
number_ops = int(input("Number of arithmetic operators: "))
# number_ops = 10
target, numbers_list = values(number_ops)
# target = 590
# numbers_list = [9, 3, 5, 3, 5, 2, 6, 3, 4, 7]
start_time = time.time()
Solve(target, numbers_list)
Basically it's all about the "Solve(target, numbers)" method, which returns the correct solution. It uses Brute-Force in order to find that solution. It receives an equation and the corresponding result as an input, which has been generated in the "new_equation(number_ops)" method before. This part is working fine and not a big deal. My main issue is the "Solve(target, numbers)" method, which finds the correct solution using a stack. My aim is to make that program as fast as possible. Currently it takes about two hours until an arithmetic task with 15 operators has been found, which follows the rules above. Is there any way to make it faster or maybe another approach to the problem besides Brute-Force? I would really appreciate your help :)
This is mostly brute force but it only takes a few seconds for a 15 operation formula.
In order to check the result, I first made a solve function (recursive iterator) that will produce the solutions:
def multiplyDivide(numbers):
if len(numbers) == 1: # only one number, output it directly
yield numbers[0],numbers
return
product,n,*numbers = numbers
if product % n == 0: # can use division.
for value,ops in multiplyDivide([product//n]+numbers):
yield value, [product,"/",n] + ops[1:]
for value,ops in multiplyDivide([product*n]+numbers):
yield value, [product,"*",n] + ops[1:]
def solve(target,numbers,canGroup=True):
*others,last = numbers
if not others: # only one number
if last == target: # output it if it matches target
yield [last]
return
yield from ( sol + ["+",last] for sol in solve(target-last,others)) # additions
yield from ( sol + ["-",last] for sol in solve(target+last,others)) # subtractions
if not canGroup: return
for size in range(2,len(numbers)+1):
for value,ops in multiplyDivide(numbers[-size:]): # multiplicative groups
for sol in solve(target,numbers[:-size]+[value],canGroup=False):
yield sol[:-1] + ops # combined multipicative with rest
The solve function recurses through the numbers building an addition or subtraction with the last number and recursing to solve a smaller problem with the adjusted target and one less number.
In addition to the additions and subtraction, the solve function groups the numbers (from the end) into consecutive multiplications/divisions and processes them (recursing into solve) using the resulting value that will have calculation precedence over additions/subtractions.
The multiplyDivide function (also a recursive generator) combines the group of numbers it is given with multiplications and divisions performed from left to right. Divisions are only added when the current product divided by the additional number produces an integer intermediate result.
Using the solve iterator, we can find a first solution and know if there are more by iterating one additional time:
def findOper(S):
expression,target = S.split("=")
target = int(target.strip())
numbers = [ int(n.strip()) for n in expression.split("x") ]
iSolve = solve(target,numbers)
solution = next(iSolve,["no solution"])
more = " and more" * bool(next(iSolve,False))
return " ".join(map(str,solution+ ["=",target])) + more
Output:
print(findOper("10 x 5 = 2"))
# 10 / 5 = 2
print(findOper("10 x 5 x 3 = 6"))
# 10 / 5 * 3 = 6
print(findOper("4 x 4 x 3 = 13"))
# 4 * 4 - 3 = 13
print(findOper("1 x 3 x 4 = 13"))
# 1 + 3 * 4 = 13
print(findOper("3 x 3 x 4 x 4 = 25"))
# 3 * 3 + 4 * 4 = 25
print(findOper("2 x 6 x 2 x 4 x 4 = 40"))
# 2 * 6 * 2 + 4 * 4 = 40 and more
print(findOper("7 x 6 x 2 x 4 = 10"))
# 7 + 6 * 2 / 4 = 10
print(findOper("2 x 2 x 3 x 4 x 5 x 6 x 3 = 129"))
# 2 * 2 * 3 + 4 * 5 * 6 - 3 = 129
print(findOper("1 x 2 x 3 x 4 x 5 x 6 = 44"))
# 1 * 2 + 3 * 4 + 5 * 6 = 44
print(findOper("1 x 2 x 3 x 4 x 5 x 6 x 7 x 8 x 9 x 8 x 7 x 6 x 5 x 4 x 1= 1001"))
# 1 - 2 - 3 + 4 * 5 * 6 * 7 / 8 * 9 + 8 * 7 - 6 + 5 + 4 + 1 = 1001 and more
print(findOper("1 x 2 x 3 x 4 x 5 x 6 x 7 x 8 x 9 x 8 x 7 x 6 x 5 x 4 x 1= 90101"))
# no solution = 90101 (15 seconds, worst case is not finding any solution)
In order to create a single solution riddle, the solve function can be converted to a result generator (genResult) that will produce all possible computation results. This will allow us to find a result that only has one combination of operations for a given list of random numbers. Given that the multiplication of all numbers is very likely to be a unique result, this will converge rapidly without having to go through too many random lists:
import random
def genResult(numbers,canGroup=True):
*others,last = numbers
if not others:
yield last
return
for result in genResult(others):
yield result - last
yield result + last
if not canGroup: return
for size in range(2,len(numbers)+1):
for value,_ in multiplyDivide(numbers[-size:]):
yield from genResult(numbers[:-size]+[value],canGroup=False)
def makeRiddle(size=5):
singleSol = []
while not singleSol:
counts = dict()
numbers = [random.randint(1,9) for _ in range(size)]
for final in genResult(numbers):
if final < 0 : continue
counts[final] = counts.get(final,0) + 1
singleSol = [n for n,c in counts.items() if c==1]
return " x ".join(map(str,numbers)) + " = " + str(random.choice(singleSol))
The reason we have to loop for singleSol (single solution results) is that there are some cases where even the product of all numbers is not a unique solution. For example: 1 x 2 x 3 = 6 could be the product 1 * 2 * 3 = 6 but could also be the sum 1 + 2 + 3 = 6. There aren't too many of those cases but it's still a possibility, hence the loop. In a test generating 1000 riddles with 5 operators, this occurred 4 times (e.g. 4 x 1 x 1 x 4 x 2 has no unique solution). As you increase the size of the riddle, the occurrence of these no-unique-solution patterns becomes more frequent (e.g. 6 times generating 20 riddles with 15 operators).
output:
S = makeRiddle(15) # 7 seconds
print(S)
# 1 x 5 x 2 x 5 x 8 x 2 x 3 x 4 x 1 x 2 x 8 x 9 x 7 x 3 x 2 = 9715
print(findOper(S)) # confirms that there is only one solution
# 1 * 5 * 2 * 5 * 8 * 2 * 3 * 4 - 1 + 2 + 8 * 9 + 7 * 3 * 2 = 9715
I've been struggling to find the right logic for my sudoku solver. So far I've created a function to take (x,y) coordinates and the number and check if it is a legal move.
Though I don't understand how I can iterate through the grid replacing every 0 with a legal number, then go back and fix numbers that make the solve incorrect.
For example sometimes I will be left with 0's on the grid because some numbers can no longer be played. I took a deeper look at it and realized that numbers played previously in the same row were legal but ruined the puzzle. Instead, if those numbers were a bit higher the puzzle would be solved.
I understand backtracking would be my friend here but, I have no clue on how to implement it. So far here is what I have.
solve.py
import numpy as np
import time
class sodoku:
def __init__(self,grid,boxRange):
self.grid = grid
self.boxRange = boxRange
def show(self):
for row in self.grid:
print(row)
def solve(self):
def possible(num,x,y):
def box(x,y):
board = np.array(self.grid)
result = {}
size = 3
for i in range(len(board) // size):
for j in range(len(board) // size):
values = board[j * size:(j + 1) * size, i * size:(i + 1) * size]
result[i * size + j + 1] = values.flatten()
if y <= 2 and x <= 2:
squareBox = result[1]
if (y <= 5 and y > 2) and x <= 2:
squareBox = result[2]
if (y <= 8 and y > 5) and x <= 2:
squareBox = result[3]
if (y <= 2 ) and (x <= 5 and x > 2):
squareBox = result[4]
if (y <= 5 and y > 2)and (x <= 5 and x > 2):
squareBox = result[5]
if (y <= 8 and y > 5)and (x <= 5 and x > 2):
squareBox = result[6]
if (y <= 2) and (x <= 8 and x > 5):
squareBox = result[7]
if (y <= 5 and y > 2)and (x <= 8 and x > 5):
squareBox = result[8]
if (y <= 8 and y > 5)and (x <= 8 and x > 5):
squareBox = result[9]
return squareBox
row = self.grid[y]
column= [r[x] for r in self.grid]
square = box(x,y)
if (num not in row) and (num not in column) and (num not in square):
return True
else:
return False
y = 0
for row in self.grid:
x = 0
for number in row:
if number == 0:
for i in range(1,10):
if possible(i,x,y):
row[x] = i
elif i == 9 and possible(i,x,y) == False: pass
#what would I do here now
x += 1
y += 1
boxRange = "3x3"
bxd = []
with open('board.txt', 'r') as f:
for line in f:
line = line.strip()
line = line.split(' ')
bLine = [int(x) for x in line]
bxd.append(bLine)
# brd = [[3,0,0,2],[0,4,1,0],[0,3,2,0],[4,0,0,1]]
brd = sodoku(bxd,boxRange)
brd.show()
brd.solve()
print('-----Solved------')
brd.show()
board.txt
5 3 0 0 7 0 1 0 0
6 0 0 1 9 5 0 0 0
0 9 8 0 0 0 0 6 0
8 0 0 0 6 0 0 0 3
4 0 0 8 0 3 0 0 1
7 0 0 0 2 0 0 0 6
0 6 0 0 0 0 2 8 0
0 0 0 4 1 9 0 0 5
0 0 0 0 8 0 0 7 9
Recursive pseudocode backtracing sudoku solver:
#solve will return a solved board, or None if it fails
def solve(board):
#case 1: board is solved
if board.is_solved: #simple check for leftover empty spaces
return board #board is solved. unzip the call stack
pos = board.next_empty_space()
valid = [i for i in range(1,10) if board.is_valid(pos, i)]
#case 2: not solved and no more valid moves
if not valid:
return None #no valid moves left
new_board = copy(board) #don't step on the original data in case this isn't the solution
for value in valid:
new_board[pos] = value
result = solve(new_board)
#case 3: one of the valid moves led to a valid solution
if result is not None: #we found a fully solved board
return result #here's where we unzip the call stack
#case 4: none of the valid moves led to a valid solution
return None #none of the valid moves panned out
Basically you consider each empty space on the board as a branch in a tree, and sub-branches from each branch you insert a new number which is currently valid at that point in the tree. If you get to the end of a branch, and there are no more valid moves left (sub-branches) you have either successfully filled in all the blank spaces or one of the numbers is wrong. When None gets returned, and execution goes back to the caller (up a frame in the call stack), the local position in the for loop going over valid moves is what "remembers" where you're at, and what the next possible valid move should be. It's basically a depth-first tree search algorithm for a correct board state.
How do I include the user input value in the very first place in the output?
here is my code below:
seq = []
n = int(input("\nEnter a number (greater than 1): "))
while (n > 1):
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
seq.append(n)
print()
print(*seq)
So when I entered 6, it was printed like this:
3 10 5 16 8 4 2 1
My entered value (which MUST be included) is missing.
Please help!
In your current code, you add n to seq at the end of every iteration. To add the initial value of n, simply do seq.append(n) before entering the while loop:
seq = []
n = int(input("\nEnter a number (greater than 1): "))
seq.append(n) # this is the addition you need
while (n > 1):
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
seq.append(n)
print()
print(*seq)
There are several ways you can do this. I believe the most logical way is to move your seq.append(n) statement to the first line of your while loop to capture your input. The issue will then be that 1 will be dropped off the end of the list. To fix that, you change your while loop condition to capture the one and add a condition to break out of the while loop:
seq = []
n = int(input("\nEnter a number (greater than 1): "))
while (n > 0):
seq.append(n)
if n == 1:
break
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
print()
print(*seq)
#output:
Enter a number (greater than 1): 6
6 3 10 5 16 8 4 2 1
I am trying to make a decimal to binary converter, however, I noticed that some values are being ignored and the last value is not being entered into the list I created.
#Here we create a new empty list.
binary = []
n = int(input("Enter number: "))
while n > 1:
n = n//2
m = n%2
binary.append(m)
binary.reverse()
print( " ".join( repr(e) for e in binary ))
This is your code after correction :
binary = []
n = int(input("Enter number: "))
while n > 0:
m = n%2
n = n//2
binary.append(m)
if len(binary)==0:
binary.append(0)
binary.reverse()
print( " ".join( repr(e) for e in binary ))
Your question is duplicate to this stackoverflow question check the link too.
good luck :)
As PM 2Ring suggested a tuple assignment may be the way to go. Makes your code shorter too :-) ... also changed n > 1 to n >= 1
binary = []
n = int(input("Enter number: "))
while n >= 1:
n, m = n // 2, n % 2
binary.append(m)
binary.reverse()
print( " ".join( repr(e) for e in binary ))
n = int(input("Enter number: "))
print("{0:0b}".format(n)) # one-line alternate solution
if n == 0: # original code with bugs fixed
binary = [0]
else:
binary = []
while n > 0:
m = n%2
n = n//2
binary.append(m)
binary.reverse()
print("".join( repr(e) for e in binary ))
Your algorithm is close, but you need to save the remainder before you perform the division. And you also need to change the while condition, and to do special handling if the input value of n is zero.
I've fixed your code & put it in a loop to make it easier to test.
for n in range(16):
old_n = n
#Here we create a new empty list.
binary = []
while n:
m = n % 2
n = n // 2
binary.append(m)
# If the binary list is empty, the original n must have been zero
if not binary:
binary.append(0)
binary.reverse()
print(old_n, " ".join(repr(e) for e in binary))
output
0 0
1 1
2 1 0
3 1 1
4 1 0 0
5 1 0 1
6 1 1 0
7 1 1 1
8 1 0 0 0
9 1 0 0 1
10 1 0 1 0
11 1 0 1 1
12 1 1 0 0
13 1 1 0 1
14 1 1 1 0
15 1 1 1 1
As Blckknght mentions in the comments, there's a standard function that can give you the quotient and remainder in one step
n, m = divmod(n, 2)
It can be convenient, but it doesn't really provide much benefit apart from making the code a little more readable. Another option is to use a tuple assignment to perform the operations in parallel:
n, m = n // 2, n % 2
It's a good practice, especially when you're new to coding, to work through your algorithm on paper to get a feel for what it's doing. And if your code doesn't give the expected output it's a good idea to add a few print calls in strategic places to check that the values of your variables are what you expect them to be. Or learn to use a proper debugger. ;)
This code executes primes upto a given number. It works correctly as far as the prime generation is concerned but the output is painfully repetitive.
The code is:
numP = 1
x = 3
y = int(input('Enter number of primes to be found: '))
while numP<=y:
for n in range(2, x):
for b in range(2, n):
if n % b == 0:
break
else:
# loop fell through without finding a factor
print (n)
x += 2
numP += 1
The output is like (e.g. for y=4):
2
2
3
2
3
5
2
3
5
7
I want to avoid repetition and obtain output like:
2
3
5
7
How should the code be modified?
If you store the data in a set, you will avoid repetitions
There's no reason to loop n from 2..x. Get rid of that loop, and replace all references to 'n' with 'x'. I.e.:
def find_primes(y):
x = 3
numP = 0
while True:
for b in range(2, x):
if x % b == 0:
break
else:
# loop fell through without finding a factor
print (x)
numP += 1
if numP >= y:
return
x += 2