Title Description
Problem description : give 4 individual 1-10 The number of , By addition, subtraction, multiplication and division , Get the number as 24 Even if we win
Input :
4 individual 1-10 The number of .[ The number allows repetition , But each number is only allowed to be used once , Test cases guarantee no abnormal numbers .
Output :
true or false
This question contains several groups of sample input .
Input description :
Input 4 individual int Integers
Output description :
Return whether you can get 24 spot , Can output true, No output false
Example 1
Input
7 2 1 10
Output
true
The code implementation is as follows
import sys
def func(nums, tar):
if len(nums) == 1: return nums[0] == tar
#print("========nums:",nums,"tar:",tar)
# Note that various calculation sequences should be considered
for i in range(len(nums)):
nums = nums[1:] + [nums[0]]
#print("nums:",nums)
if func(nums[1:], tar+nums[0]) or func(nums[1:], tar-nums[0]) or func(nums[1:], tar*nums[0]) or func(nums[1:], tar/nums[0]):
return True
return False
for line in sys.stdin:
nums = list(map(int, line.strip().split()))
print(str(func(nums, 24)).lower())
Implementation mode II :
import sys
import itertools
def func(cards):
for nums in itertools.permutations(cards): # Four numbers
for ops in itertools.product('+-*/', repeat=3): # Three operators ( repeatable !)
# Construct three infix expressions (bsd)
bds1 = '({0}{4}{1}){5}({2}{6}{3})'.format(*nums, *ops) # (a+b)*(c-d)
bds2 = '(({0}{4}{1}){5}{2}){6}{3}'.format(*nums, *ops) # (a+b)*c-d
bds3 = '{0}{4}({1}{5}({2}{6}{3}))'.format(*nums, *ops) # a/(b-(c/d))
for bds in [bds1, bds2, bds3]: # Traverse
try:
if abs(eval(bds) - 24.0) < 1e-10: # eval function
return 'true'
except ZeroDivisionError: # Zero division error !
continue
return 'false'
for line in sys.stdin:
nums = list(map(int, line.strip().split()))
print(str(func(nums)).lower())
expand :
understand itertools