Python Implementation 1-9 array form result 100 for all computational formula examples, python1-9

Source: Internet
Author: User

Python Implementation 1-9 array form result 100 for all computational formula examples, python1-9

Problem:

Write one in 1, 2 ,..., 9 (the sequence cannot be changed) insert + or-between numbers or do nothing, so that the calculation result is always 100 of the program and all possibilities are output. For example, 1 + 2 + 34-5 + 67-8 + 9 = 100.

From functools import reduce operator = {1: '+', 2: '-', 0: ''} base = ['1', '2', '3 ', '4', '5', '6', '7', '8', '9'] def isHundred (num): # convert it to an 8-digit three-digit number, obtain the array arr = [] for index in range (8): index = 7-index arr. append (num // (3 ** index) num-= (num // (3 ** index) * (3 ** index) arr = map (lambda x: operator [x], arr) # merge to obtain the formula = reduce (lambda x, y: x + y, zip (base, arr) formula = list (formula) formula. append ('9') formula = ''. join (formula) # Calculation formula result res = eval (formula) return res, formula if _ name _ = '_ main __': # All possible RESULTS total = 3 ** 8 for I in range (total): res, formula = isHundred (I) if res = 100: print (formula + '= 100 ')

Result:

/usr/bin/python3.5 /home/kang/workspace/Qt3d/test.py 123+45-67+8-9 = 100123+4-5+67-89 = 100123-45-67+89 = 100123-4-5-6-7+8-9 = 10012+3+4+5-6-7+89 = 10012+3-4+5+67+8+9 = 10012-3-4+5-6+7+89 = 1001+23-4+56+7+8+9 = 1001+23-4+5+6+78-9 = 1001+2+34-5+67-8+9 = 1001+2+3-4+5+6+78+9 = 100

In the above example of all the operators whose Python implementation result is 100 in array 1-9, I hope to give you a reference, we also hope that you can support the customer's home.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.