How to list all solutions in 24 game using Python - python

Recently I created a 24 game solver with python
Read this website if you do not know what the 24 game is:
https://www.pagat.com/adders/24.html
Here is the code:
from itertools import permutations, product, chain, zip_longest
from fractions import Fraction as F
solutions = []
def ask4():
num1 = input("Enter First Number: ")
num2 = input("Enter Second Number: ")
num3 = input("Enter Third Number: ")
num4 = input("Enter Fourth Number: ")
digits = [num1, num2, num3, num4]
return list(digits)
def solve(digits, solutions):
digit_length = len(digits)
expr_length = 2 * digit_length - 1
digit_perm = sorted(set(permutations(digits)))
op_comb = list(product('+-*/', repeat=digit_length-1))
brackets = ([()] + [(x,y)
for x in range(0, expr_length, 2)
for y in range(x+4, expr_length+2, 2)
if (x,y) != (0,expr_length+1)]
+ [(0, 3+1, 4+2, 7+3)])
for d in digit_perm:
for ops in op_comb:
if '/' in ops:
d2 = [('F(%s)' % i) for i in d]
else:
d2 = d
ex = list(chain.from_iterable(zip_longest(d2, ops, fillvalue='')))
for b in brackets:
exp = ex[::]
for insert_point, bracket in zip(b, '()'*(len(b)//2)):
exp.insert(insert_point, bracket)
txt = ''.join(exp)
try:
num = eval(txt)
except ZeroDivisionError:
continue
if num == 24:
if '/' in ops:
exp = [(term if not term.startswith('F(') else term[2])
for term in exp]
ans = ' '.join(exp).rstrip()
print("Solution found:", ans)
solutions.extend(ans)
return ans
print("No solution found for:", ' '.join(digits))
def main():
digits = ask4()
solve(digits, solutions)
print(len(solutions))
print("Bye")
main()
Right now, my code only shows one solution for the numbers given, even when there are clearly more solutions.
So if someone knows how to do this please help me
Thanks

You're not allowing the code to finish it's task before all of the solutions have been calculated and listed. Better to save the solutions in a list/array instead of returning it straight away.

Your function is returning as soon as it finds a solution. Delete the return statement. After the loop, you can return the list of all solutions if desired. To check if there were none, see if the length of the list is zero (so you know when to say there are no solutions).
I would also suggest making solutions local to solve, instead of global.

Related

Reversing 32bit integer

I was trying out a question which asked me to reverse a 32bit signed integer, I created this python program
input1=int(input("Enter the number: "))
binary=bin(input1).replace('0b','')
result=binary.zfill(32)
num=list(result)
num=num[::-1]
result=''.join(num)
ans=int(result,2)
print(ans)
This code passed one test case when the value of input1 was 2 but failed in second testcase, when the value of input1 was 1
Expected answer = -2147483648
My answer = 2147483648
What changes should I make in the code to make it pass second testcase ?
You need to look at the sign bit of the binary version of your number. You can do that by looking at the 0-indexed value of either your num variable or result.
input1 = int(input("Enter the number: "))
binary = bin(input1).replace('0b', '')
result = binary.zfill(32)
num = list(result)
num = num[::-1]
result = ''.join(num)
if num[0] == '0':
ans = int(result, 2)
else:
# flip the sign
ans = -int(result, 2)
print(ans)
input1 = int(input("Enter the number: "))
binary = bin(input1 ).replace("0b","").zfill(32)
reverse = binary[::-1]
result = int(reverse,2)
print(result if reverse[0] == "0" else -result)

To find if the input given is lucky or not

My aim: Two inputs will be given.
purchase date and number on plate.
My code should add all numbers of purchase date till single digit is reached and compare it with the similar addition of plate number.
If the both the numbers turn out to be same , it should return lucky otherwise it should display dare.
This is what I tried:
def lucky_dare():
input1=input("enter ; ")
input2=input("enter:")
s=str(input1)
p1=int(s[0])
p2=int(s[1])
p3=int(s[2])
sty=[]
ma=max([p1,p2,p3])
while ma>0:
if p1>0 and p2>0 and p3>0:
sty.append(input1)
elif p1<1 and p2<0 and p3>0:
sty.append(int(s[2]))
elif p1<1 and p2>0 and p3<1:
sty.append(int(s[1]+"0"))
elif p1<1 and p2>0 and p3>0:
sty.append(int(s[1]+s[2]))
elif p1>0 and p2<1 and p3<1:
sty.append(int(s[0]+"0"+"0"))
elif p1>0 and p2<1 and p3>0:
sty.append(int(s[0]+"0"+s[2]))
elif p1>0 and p2>0 and p3<1:
sty.append(int(s[0]+s[1]+"0"))
else:
pass
p1-=1
p2-=1
p3-=1
ma-=1
print(sum(sty))
lucky_dare()
But I am getting several errors. So I couldn't display what errors I got here. Where am I going wrong? Can someone please help. Thanks in advance for your time and help:)
Here is a nicer, simpler and cleaner way to solve your problem:
import re
def recursive_sum(text):
while (len(text) > 1):
numbers = re.findall(r'\d', text)
_sum = sum(map(int, numbers))
text = str(_sum)
return text
def luck_dare():
input1= input("enter ; ")
input2=input("enter:")
return recursive_sum(input1) == recursive_sum(input2)
I don't really understand your code, but it can be done much simpler. Here is my attempt, but it can still be optimized:
def lucky_dare():
dop = sum([int(i) for i in input("enter date of purchase: ").split('/')])
# 23/05/1998
while dop > 9:
dop = sum([int(i) for i in str(dop)])
pn = int(input("enter plate number: ")) # 2345
while pn > 9:
pn = sum([int(i) for i in str(pn)])
print('lucky' if dop == pn else 'dare')
# print(dop, pn)
lucky_dare()
def lucky_dare():
input1=input("enter date: ")
input2=input("enter car number:")
# Evaluating date
s = input1.split('/')
a = [int(num) for num in s]
b = sum(a)
c = [int(i) for i in str(b)]
d=(sum(c))
single_digit_dt = str(d)[0]
# Evaluating car number
y = [int(num) for num in input2]
x= sum(y)
single_digit_platenumber =str(x)[0]
# Comparing both the numbers
print(single_digit_dt, single_digit_platenumber)
if single_digit_dt ==single_digit_platenumber:
print('Lucky')
else:
print('Dare')
lucky_dare()

calculate the sum of the digits of any three digit no(in my code loop is running every time help in correction)

my problem is i have to calculate the the sum of digits of given number and that no is between 100 to 999 where 100 and 999 can also be include
output is coming in this pattern
if i take a=123 then out put is coming total=3,total=5 and total=6 i only want output total=6
this is the problem
there is logical error in program .Help in resolving it`
this is the complete detail of my program
i have tried it in this way
**********python**********
while(1):
a=int(input("Enter any three digit no"))
if(a<100 or a>999):
print("enter no again")
else:
s = 0
while(a>0):
k = a%10
a = a // 10
s = s + k
print("total",s)
there is no error message in the program because it has logical error in the program like i need output on giving the value of a=123
total=6 but i m getting total=3 then total=5 and in last total=6 one line of output is coming in three lines
If you need to ensure the verification of a 3 digit value and perform that validation, it may be useful to employ Regular Expressions.
import re
while True:
num = input("Enter number: ")
match = re.match(r"^\d{3}$, num)
if match:
numList = list(num)
sum = 0
for each_number in numList:
sum += int(each_number)
print("Total:", sum)
else:
print("Invalid input!")
Additionally, you can verify via exception handling, and implementing that math you had instead.
while True:
try:
num = int(input("Enter number: "))
if num in range(100, 1000):
firstDigit = num // 10
secondDigit = (num // 10) % 10
thirdDigit = num % 10
sum = firstDigit + secondDigit + thirdDigit
print("Total:", sum)
else:
print("Invalid number!")
except ValueError:
print("Invalid input!")
Method two utilizes a range() function to check, rather than the RegEx.
Indentation problem dude, remove a tab from last line.
Also, a bit of python hint/tip. Try it. :)
a=123
print(sum([int(x) for x in str(a)]))

Python Basic Input Confusion

So I am trying to teach myself python and I am having some problems accomplishing this task. I am trying to read in two integers from the keyboard, but the problem is that they can either be read in on the same line or on two different lines.
Example Inputs:
23 45
or
23
45
Each number should go to its own variable.
Im pretty sure I should make use of the strip/split functions, but what else am I missing? I just really dont know how to go about this... Thanks.
Here is what Im working with, but obviously this version takes the numbers one on each line.
def main():
num1 = int(input())
num2 = int(input())
numSum = num1 + num2
numProduct = num1 * num2
print("sum = ",numSum)
print("product = ",numProduct)
main()
the input terminates on new line (more percisely, the sys.stdin flushes on new line), so you get the entire line. To split it use:
inputs = input("Enter something").split() # read input and split it
print inputs
applying to your code, it would look like this:
# helper function to keep the code DRY
def get_numbers(message):
try:
# this is called list comprehension
return [int(x) for x in input(message).split()]
except:
# input can produce errors such as casting non-ints
print("Error while reading numbers")
return []
def main():
# 1: create the list - wait for at least two numbers
nums = []
while len(nums) < 2:
nums.extend(get_numbers("Enter numbers please: "))
# only keep two first numbers, this is called slicing
nums = nums[:2]
# summarize using the built-in standard 'sum' function
numSum = sum(nums)
numProduct = nums[0] * nums[1]
print("sum = ",numSum)
print("product = ",numProduct)
main()
Notes on what's used here:
You can use list comprehension to construct lists from iterable objects.
You can use sum from the standard library functions to summarize lists.
You can slice lists if you only want a part of the list.
Here I have modified your code.
def main():
num1 = int(input("Enter first number : "))
num2 = int(input("\nEnter second number : "))
if(num1<=0 or num2<=0):
print("Enter valid number")
else:
numSum = num1 + num2
numProduct = num1 * num2
print("sum of the given numbers is = ",numSum)
print("product of the given numbers is = ",numProduct)
main()
If you enter invalid number it prints message Enter valid number.

Taking apart strings in Python

So I am making a quick calculator script in Python, and I need to take apart a short string. The program first displays a short welcome message, then a prompt asks What they want to do calculate, and shows them the correct format. The functionality is there to do the calculation but unfortunately, I can not get the string dissecting bit working.
Here's my code
print ("--------------------------------------")
print (" ")
print ("Advanced Quick Calculator")
print ("By Max M, licenced under GPLv3")
print (" ")
print ("--------------------------------------")
statement = raw_input ("Please enter your mathematical statement [3 3 plus minus times divide]: ")
strnum1 = statement[:1]
print ("strnum1 : " + strnum1)
#num1 = int (strnum1)
strnum2 = statement[:4]
print ("strnum2 : " + strnum2)
#num2 = int (strnum2)
operation = statement[5:11]
print ("operation : " + operation)
#if operation == "+":
# ans = num1 + num2
#if operation == "-":
# ans = num1 - num2
#if operation == "*":
# ans = num1 * num2
#if operation == "/":
# ans = num1 / num2
#print ("The answer is : "), ans
This looks like a job for regular expressions:
>>> import re
>>> match = re.search(r'(\d+)\s*([+*/-])\s*(\d+)', '42 + 7')
>>> match.group(1) # <-- num1
'42'
>>> match.group(2) # <-- operation
'+'
>>> match.group(3) # <-- num2
'7'
Slicing the input like you're currently doing is probably not a good idea as it greatly restricts the allowed formats. For instance, what if the user accidentally precedes his input with a couple of spaces? Regular expressions can handle such cases well.
I'm not going to do your homework for you, but I will point you to the answer to your question (hint: it looks like you're trying to split on spaces instead of comma's like in the link, so adjust the code accordingly).
How to read formatted input in python?

Categories

Resources