[Solved] Check whether sum of two list members can be found in another list [closed]


If I understood well this is what you you’re looking for:

This is not the most elegant solution, but one that is rather easy to understand
and doesn’t require knowledge of any other python modules.

you just try out all combinations of two dice, calculate the sum and if you can find a sum, you return True (and stop looking for other solutions)
otherwise (if you have tried all combinations and you found nothing)
you return False)

Now you can use this function in your code to check whether you want to ask the user which dice to choose or whether to immediately continue the loop

def can_remove_a_number(thrown_dice, remaining_numbers):
    """
    checks whether the sum of two dice out of thrown_dice
    can be found in remaining_numbers
    """
    for idx1 in range(len(thrown_dice) - 1):
        for idx2 in range(idx1 + 1,  len(thrown_dice)):
            # next line for debugging only
            print("trying die %d and die %d" % (idx1, idx2))
            sum_ = thrown_dice[idx1] + thrown_dice[idx2]
            # next line for debugging only
            print("sum = ", sum_)
            if sum_ in remaining_numbers:
                return True
    return False

and for testing:

print("*" * 30)
print(can_remove_a_number([1,2,2], [5,6,7]))
print("*" * 30)
print(can_remove_a_number([1,2,2], [4,5,6,7]))
print("*" * 30)

# or if you want to write a test
# assert <expression> breaks if expression is not True
assert not can_remove_a_number([1,2,2], [5,6,7])
print("*" * 30)

assert can_remove_a_number([1,2,2], [4,5,6,7])
print("*" * 30)

In fact now a less manual solution.
Just use https://docs.python.org/3.8/library/itertools.html#itertools.combinations

from itertools import combinations

def can_remove_a_number(thrown_dice, remaining_numbers):
    for dice in combinations(thrown_dice, 2):
        sum_ = sum(dice)
        if sum_ in remaining_numbers:
            return True
    return False

Or if you heard about list comprehensions / comprehensions ( https://python-3-patterns-idioms-test.readthedocs.io/en/latest/Comprehensions.html ) :

def can_remove_a_number(thrown_dice, remaining_numbers):
    for sum_ in (sum(dice) for dice in combinations(thrown_dice, 2)):
        if sum_ in remaining_numbers:
            return True
    return False

or with another comprehension

def can_remove_a_number(thrown_dice, remaining_numbers):
    for found in (sum(dice) in remaining_numbers 
                  for dice in combinations(thrown_dice, 2)):
        if found:
            return True
    return False

or you combine with the any function ( https://docs.python.org/3.8/library/functions.html#any )

def can_remove_a_number(thrown_dice, remaining_numbers):
    return any(sum(dice) in remaining_numbers 
               for dice in combinations(thrown_dice, 2))

11

solved Check whether sum of two list members can be found in another list [closed]