Making a sublist from a list

  • Python
  • Thread starter joshmccraney
  • Start date
  • #1
joshmccraney
Gold Member
2,253
143
Hello PF!

Initializing with an empty list [], how would we perform the operations [[1]] and then [[1,2]] then [[1,2,3]] then [[1,2,3],[2]] then [[1,2,3], [2,4]] then [[1,2,3],[2,4],[1]] and so on. I'm trying to do this iteratively, so within a for-loop. Basically, given a list of numbers [1,2,3,2,4,1] add them to a sublist until the sum of values of that sublist exceeds a threshold, in which case create a new sublist. I've no clue how to do this, and have googled but to no avail
 

Answers and Replies

  • #2
jack action
Science Advisor
Insights Author
Gold Member
2,710
5,638
You didn't specified a language, but in PHP:

PHP:
<?php
function makeList($numbers, $threshold){
    $list = [];
    $sublist = [];
    $total = 0;

    foreach($numbers as $number){
        $sublist[] = $number;
        $total += $number;
    
        if($total > $threshold){
            $list[] = $sublist;
            $total = 0;
            $sublist = [];       
        }
    }

    if(!empty($sublist)){
        $list[] = $sublist;
    }
    
    return $list;
}

$numbers = [1,2,3,2,4,1];
$threshold = 5;

var_dump(makeList($numbers, $threshold));

Output:

Code:
array(3) {
  [0]=>
  array(3) {
    [0]=>
    int(1)
    [1]=>
    int(2)
    [2]=>
    int(3)
  }
  [1]=>
  array(2) {
    [0]=>
    int(2)
    [1]=>
    int(4)
  }
  [2]=>
  array(1) {
    [0]=>
    int(1)
  }
}
 
  • #3
36,871
8,916
You didn't specified a language
It's in the thread title -- Python.
 
  • Like
Likes jack action
  • #4
jack action
Science Advisor
Insights Author
Gold Member
2,710
5,638
It's in the thread title -- Python.
Then it will be left as an exercise for the OP to convert it!
 
  • #5
14,289
8,318
Then it will be left as an exercise for the OP to convert it!
I wonder how many teachers have gotten that response from their students.
 
  • Like
Likes jack action
  • #6
joshmccraney
Gold Member
2,253
143
Got it, thanks for the suggestion!
 

Suggested for: Making a sublist from a list

  • Last Post
Replies
2
Views
420
Replies
43
Views
2K
Replies
1
Views
440
Replies
27
Views
495
  • Last Post
Replies
6
Views
525
Replies
1
Views
559
  • Last Post
Replies
15
Views
1K
Top