0

A = [[[1,2,3],[4]],[[1,4],[2,3]]]

Here I want to find lists in A which sum of all sublists in list not grater than 5.

Which the result should be [[1,4],[2,3]]

I tried a long time to solve this problem in python. But I still can't figure out the right solution, which I stuck at loop out multiple loops. My code as follows, but its obviously wrong, how to correct it?

A = [[[1,2,3],[4]],[[1,4],[2,3]]] z = [] for l in A: for list in l: sum = 0 while sum < 5: for i in list: sum+=i else: break else: z.append(l) print z 

Asking for help~

3
  • 6
    what did you try already? Commented Apr 26, 2017 at 9:32
  • Your more likely to get help if you post some code, preferably a minimal reproducible example. That shows us that you've tried to solve this problem yourself, and we can point out why your code doesn't do what you want it to do. Commented Apr 26, 2017 at 9:34
  • 4
    First of all the premise of this question is not very clear. What kind of input do you expect? Are the lists nested to only 3 levels? Commented Apr 26, 2017 at 9:35

4 Answers 4

2

Simplification of @KindStranger method in a one-liner:

>> [sub for x in A for sub in x if max(sum(sub) for sub in x) <= 5] [[1, 4], [2, 3]] 
Sign up to request clarification or add additional context in comments.

Comments

0

A simple solution which you can think of would be like this -

A = [[[1,2,3],[4]],[[1,4],[2,3]]] r = [] # this will be our result for list in A: # Iterate through each item in A f = True # This is a flag we set for a favorable sublist for item in list: # Here we iterate through each list in the sublist if sum(item) > 5: # If the sum is greater than 5 in any of them, set flag to false f = False if f: # If the flag is set, it means this is a favorable sublist r.append(list) print r 

But I'm assuming the nesting level would be the same. http://ideone.com/hhr9uq

3 Comments

Thanks. This is exactly what I am looking for.
@GauravOjha, Instead of the boolean f you can use a Else Clauses on Loop Statements to do exactly the same thing. Please have a look at the link.
Thanks for noticing.
0

This should work for your problem:

>>> for alist in A: ... if max(sum(sublist) for sublist in alist) <= 5: ... print(alist) ... [[1, 4], [2, 3]] 

Comments

0

The one with all()

[t for item in A for t in item if all(sum(t)<=5 for t in item)] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.