0

How to present this code as a list comprehension:

def all_targets_hit(attempts: list) -> bool:

    for ls in range(len(attempts)):
        if not any(attempts[ls]):
            return False
    return True

attempts =([
            [True, False, False],
            [False, False, True],
            [False, False, False, False],
        ]) 

#Expected: False

3
  • 1
    That code is not right. It's only going to look at the first row, because you always return. ls will never get past 0. What do you want this to do? Commented Dec 15, 2022 at 19:21
  • @Tim Roberts Sorry, indentation error, corrected. I just need a solution in one row Commented Dec 15, 2022 at 19:34
  • 2
    return all(any(attempt) for attempt in attempts) Commented Dec 15, 2022 at 19:39

1 Answer 1

1

You could combine all with any:

def all_targets_hit(attempts: list) -> bool:
    return all([any(sublist) for sublist in attempts])

attempts =([
            [True, False, False],
            [False, False, True],
            [False, False, False, False],
        ]) 

all_targets_hit(attempts)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot! But I need smth like/ return all(any(ls) for ls in attempt for attempt in attempts) / as list comprehension. But it seems doesn`t work
Thanks for your reply! But I need smth like return all(any(ls) for ls in attempt for attempt in attempts) as list comprehension. But it doesn`t work with one list of attempts: 'bool' object is not iterable
Now all is ok, thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.