Kumar
Kumar

Reputation: 175

Finding subset List of Python List based on an input integer

I want a subset list from input List based on input integer value.

For Example:

Input List: [3,7,9,11,12]
Input Value: 2
Output List: [1,7,9,11,12]
# 2 is subtracted from first element of list

Input List: [3,7,9,11,12]
Input Value: 5
Output List: [5,9,11,12]
#5 is subtracted from list in sequence manner, first 3 is subtracted then remaining 2 is subtracted from 7 hence output is [5,9,11,12]

Upvotes: 2

Views: 285

Answers (3)

Mark Moretto
Mark Moretto

Reputation: 2348

Another solution:

# First set of test variables
list1 = [3,7,9,11,12]
input1 = 2

# Second set of test variables
list2 = [3,7,9,11,12]
input2 = 5

def eval_list(input_value, iterable, output = None):
    if output is None:
        output = []

    for i, v in enumerate(iterable):
        current = iterable[i]
        if input_value > 0:
            if v <= input_value:
                input_value -= current
            else:
                current -= input_value
                input_value = 0
                output.append(current)
        else:
            output.append(current)

    return output

Run for each data set and output results:

res1 = eval_list(input1, list1)
res2 = eval_list(input2, list2)

print(f"Set 1: {res1}")
print(f"Set 2: {res2}")

Output:

Set 1: [1, 7, 9, 11, 12]
Set 2: [5, 9, 11, 12]

Upvotes: 1

Scott Hunter
Scott Hunter

Reputation: 49848

Recursive solution:

def subfrom( lst, n ):
    if n<=0 or lst == []:
        # No change necessary
        return lst
    if lst[0] <= n:
        # First element gets removed
        # Return the list you get by removing the leftover from the rest of the list
        return subfrom( lst[1:], n-lst[0] )
    # Reducde first element
    return [lst[0]-n] + lst[1:]

Upvotes: 2

Vicrobot
Vicrobot

Reputation: 3988

Use numpy.cumsum() if modules are allowed:

import numpy as np
input_list = np.asarray([3, 7, 9, 11, 12])
input_integer = 5
output_list = input_list[input_list.cumsum() > input_integer]
output_list[0] -= input_integer - input_list[input_list.cumsum() <= input_integer].sum()
print(output_list)

Output:

[ 5  9 11 12]

What i did there:

Since total sum is to be subtracted from starting, using cumulated sum will tell you where to crop the list from.

Then set the first element = first elem - (input_integer - cropped list's sum)

Upvotes: 2

Related Questions