![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if is possible to get given sum from a given set of elements in Python
Suppose we have an array called nums and another value sum. We have to check whether it is possible to get sum by adding elements present in nums, we may pick a single element multiple times.
So, if the input is like nums = [2, 3, 5] sum = 28, then the output will be True as we can get 26 by using 5 + 5 + 5 + 5 + 3 + 3 + 2
To solve this, we will follow these steps −
- MAX := 1000
- table := an array of size MAX ad fill with 0
- Define a function util() . This will take nums
- table[0] := 1
- sort the list nums
- for i in range 0 to size of nums - 1, do
- val := nums[i]
- if table[val] is non-zero, then
- go for next iteration
- for j in range 0 to MAX - val - 1, do
- if table[j] is non-zero, then
- table[j + val] := 1
- if table[j] is non-zero, then
- From the main method do the following −
- util(nums)
- if table[sum] is non-zero, then
- return True
- return False
Let us see the following implementation to get better understanding −
Example
MAX = 1000 table = [0] * MAX def util(nums): table[0] = 1 nums.sort() for i in range(len(nums)): val = nums[i] if table[val]: continue for j in range(MAX - val): if table[j]: table[j + val] = 1 def solve(nums, sum): util(nums) if table[sum]: return True return False nums = [2, 3, 5] sum = 28 print (solve(nums, sum))
Input
[2, 3, 5], 28
Output
True
Advertisements