Python any combination of the given array equals a fixed value of all solutions

Source: Internet
Author: User

Throw the question:

All solutions of a given array equal to a fixed value, such as the list L = [1, 2, 3, 4, 5], for any combination of the results of 10 of all the answers

Problem Analysis:

It is actually all permutations of the list, and then the values of each permutation are calculated, and the combined result is equal to the evaluated value.

The code implementation is the first generation and L equal length of the full 0 list, 0 means that the list of the number of positions is not taken, 1 means the list of the number of places to take, so always recursive, until the full 1

#-*-coding:utf-8-*-#Date: 2018/6/11#Author: Small mouse#all solutions of a given array equal to a fixed valuelist = [1, 2, 3, 4, 5]val= 10#generate a full 0 list of equal lengthsx = [0 forIinchRange (0,len (list))]#Recursive method x record list is not taken, I represents the current recursive position, has represents the current value of all anddefGet_val (x,i,has):ifi > Len (x)-1:        return    ifHas + list[i] = =Val:#match a condition recordX[i] = 1Print(x) x[i]=0#The current position takes execution onceX[i] = 1Get_val (X,i+1,has+List[i])#current position does not take execution onceX[i] =0 get_val (x, I+ 1, has) Get_val (x,0,0)#=========== Results =========#[1, 1, 1, 1, 0] "[1,2,3,4] 1+2+3+4=10#[1, 0, 0, 1, 1] "[1,4,5] 1+4+5=10#[0, 1, 1, 0, 1] "[2,3,5] 2+3+5=10

Python any combination of the given array equals a fixed value of all solutions

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.