2

I have the following arguments:

a = [(3, 3)]

b = [(2, 0), (1, 0), (0,1), (0,2), (1,1)]

I need to write a function that generates a list of tuples where each element is a unique summation of a and the elements of b. This is my expected result:

c = [(5, 3), (4, 3), (3, 4), (3, 5), (4, 4)]

I am having trouble writing this into a function that will work regardless of what tuple is inputted in a. I can write the code that works on one individual element via the below:

import operator

a = 3, 3
b = 2, 0
result = tuple(map(operator.add, a, b))

How can I turn this into a reproducible function? I have tried several avenues / syntax and believe I am missing something simple.

Selcuk
  • 57,004
  • 12
  • 102
  • 110
epd
  • 39
  • 4

3 Answers3

1

If a is always a list of a tuple with two elems, the following should work:

def example(a, b):
    toRet = []
    op1, op2 = a[0]
    for val1, val2 in b:
        toRet.append((val1 + op1, val2 + op2))
    return toRet


a = [(3, 3)]
b = [(2, 0), (1, 0), (0, 1), (0, 2), (1, 1)]
c = [(5, 3), (4, 3), (3, 4), (3, 5), (4, 4)]
print(f"Output correct: {example(a, b) == c}")

Output

Output correct: True

Process finished with exit code 0
Jawand S.
  • 148
  • 10
1

If a is always guaranteed to be a list of a single tuple you can use this simple list comprehension:

>>> [(a[0][0] + x, a[0][1] + y) for x, y in b]
[(5, 3), (4, 3), (3, 4), (3, 5), (4, 4)]

As a side note, generator expressions and list comprehensions are considered more pythonic when compared to map.

Selcuk
  • 57,004
  • 12
  • 102
  • 110
  • I think `map(operator.add, a, b)` is perfectly pythonic. Maps an existing function and doesn't need a `zip`, that's a pretty good use case (or at least would be if this wasn't just about 2-tuples...) – Kelly Bundy Jan 28 '22 at 00:40
  • You mean for single tuples and not for lists of tuples? Yes, it works for that case and actually feels pythonic. That's not what the question asks though. If it weren't only 2-tuples I would probably go that way too. – Selcuk Jan 28 '22 at 00:47
  • No I mean for a list, as the question asks. I reused their `map` solution in my answer, and [the equivalent genexp version](https://tio.run/##dYxBDoMgFET3nGKWkJJGZd2TGBcYbUqi8AOYoJenUOuuXU1mMu/RHl/OqpzNSs5HOJq9js4zpvFAz5WEEgMbP6WTaIQEb7/ZyPaM7lzb8mSpXHXfDMzPYVtiBeNGy8xXTfzS3/U0SSSJXQg8nccOYzEWnLyxkZ@sKLbwT5dwK1Rlq6bihyGeQinhkoaf1pzf) doesn't look more readable to me. – Kelly Bundy Jan 28 '22 at 00:49
  • I guess we are talking about different things but anyway, wee seem to mostly agree. – Selcuk Jan 28 '22 at 00:51
  • 1
    FWIW, if you unpack `a[0]` before, the comp looks a lot cleaner: `w, z = a[0]` then `[(w+x, z+y) for x, y in b]` – wjandrea Jan 28 '22 at 01:35
1

Reusing your way:

import operator

a = [(3, 3)]
b = [(2, 0), (1, 0), (0,1), (0,2), (1,1)]

x = a[0]
result = [tuple(map(operator.add, x, y)) for y in b]
Kelly Bundy
  • 23,480
  • 7
  • 29
  • 65