Python implements 1-9 arrays to form all expressions with a result of 100

Source: Internet
Author: User

Problem:

Write a program that inserts + or-or nothing between 1,2,...,9 (the order cannot be changed), so that the result of the calculation is always 100 and outputs all the possibilities. For example: 1 + 2 + 34–5 + 67–8 + 9 = 100.

From functools Import reduceoperator = {    1: ' + ',    2: '-',    0: '}base = [' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ']def ishundred (num):    #转化为8位3进制数, get an array of operators    arr = [] for    Index in range (8):        index = 7-index        Arr.app End (num//(3 * index))        num-= (num/(3 * * index)) * (3 * * index)    arr = map (lambda x:operator[x], arr)    #合 And get the op-    formula = reduce (lambda x, y:x + y, zip (base, arr))    formula = List (Formula)    formula.append (' 9 ') 
   formula = ". Join (Formula)    #计算运算式结果    res = eval (Formula)    return res, formulaif __name__ = = ' __main__ ':    #所有可能的结果 Total    = 3 * * 8    for I in range:        res, formula = ishundred (i)        if res = =:            p Rint (formula+ ' = 100 ')
Results:
/usr/bin/python3.5/home/kang/workspace/qt3d/test.py123+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

Python implements 1-9 arrays to form all expressions with a result of 100

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.