
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to reduce list by given operation and find smallest remaining number in Python
Suppose we have a list of positive numbers called nums. Now consider an operation where we remove any two values a and b where a ≤ b and if a < b is valid, then insert back b-a into the list nums. If we can perform any number of operations, we have to find the smallest remaining number we can get. If the list becomes empty, then simply return 0.
So, if the input is like nums = [2, 4, 5], then the output will be 1, because, we can select 4 and 5 then insert back 1 to get [2, 1]. Now pick 2 and 1 to get [1].
To solve this, we will follow these steps −
- s := sum of all elements present in nums
- Define a function f() . This will take i, s
- if i >= size of nums , then
- return s
- n := nums[i]
- if s - 2 * n < 0, then
- return f(i + 1, s)
- return minimum of f(i + 1, s - 2 * n) and f(i + 1, s)
- from the main method return f(0, s)
Example
Let us see the following implementation to get better understanding −
def solve(nums): s = sum(nums) def f(i, s): if i >= len(nums): return s n = nums[i] if s - 2 * n < 0: return f(i + 1, s) return min(f(i + 1, s - 2 * n), f(i + 1, s)) return f(0, s) nums = [2, 4, 5] print(solve(nums))
Input
[2, 4, 5]
Output
1
- Related Articles
- Python program to find the smallest number in a list
- Program to find nth smallest number from a given matrix in Python
- Python program to find Largest, Smallest, Second Largest, and Second Smallest in a List?
- Program to perform given operation with each element of a list and given value in Python
- C++ Program to find the smallest digit in a given number
- Program to make all elements equal by performing given operation in Python
- Program to find minimum cost to reduce a list into one integer in Python
- Program to find smallest string with a given numeric value in Python
- Find the smallest number formed by inserting a given digit
- Reduce a number to 1 by performing given operations in C++
- Python program to find largest number in a list
- Program to find folded list from a given linked list in Python
- Python Program for Smallest K digit number divisible by X
- C# program to find Largest, Smallest, Second Largest, Second Smallest in a List
- 8085 Program to find the smallest number

Advertisements