程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[computer test questions (implementation language: python3)] 24 point game algorithm ---- recursion

編輯:Python

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


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved