0

Using python to print pairs(x,y) which add up to a certain number. Like if user inputs n=5 as,then we should get the output as [[1,4],[2,3],[3,2]]

n= int(input())
a=[[i,j] for i in range(1,m+1) if i+j=m]
print(a)

Please let me know where my snippet goes wrong. I want to try it using list comprehension only.

Bill Hileman
  • 2,798
  • 2
  • 17
  • 24
Ankit
  • 11
  • 1
  • `x=list(range(1,10)); m=5; [t for sl in [[(i,j) for i,j in zip([e]*len(x),x) if i+j==m] for e in x] for t in sl]` – dawg May 02 '22 at 13:42
  • Or, with a Cartesian product: `[(i,j) for i in range(1,10) for j in range(1,10) if i+j==m]` – dawg May 02 '22 at 14:35
  • @dawg Can you please explain the part "for t in sl" in `x=list(range(1,10)); m=5; [t for sl in [[(i,j) for i,j in zip([e]*len(x),x) if i+j==m] for e in x] for t in sl]` – Ankit May 02 '22 at 16:36
  • The second one I posted is better, but the `[t for sl in ... for t in sl]` is flattening the list of tuples produced by `zip`. [See Here](https://stackoverflow.com/a/952952/298607) – dawg May 02 '22 at 18:07
  • @dawg or just `[(i,m-i) for i in range(1,m)]`? O(n) instead of O(n**2). – CDJB May 03 '22 at 12:44
  • @CDJB: Not a complete set of pairs. For example, it only produces the pair `i==j` iff m is even and only the single pair for `i/2==j/2` – dawg May 03 '22 at 14:54
  • @dawg seems to produce the same output as your example in all cases? If m was odd then there wouldn't be a valid pair i==j where m=i+j=2i? Maybe I'm missing something... – CDJB May 03 '22 at 15:07
  • Try `{(i,j) for i in range(1,m) for j in range(1,m)}` vs `{(i,m-i) for i in range(1,m)}` for any value of `m>2` – dawg May 03 '22 at 15:12
  • @dawg sure, but those aren't equivalent sets, that's just the cartesian product and you haven't included the if statement. Try `{(i,j) for i in range(1,m) for j in range(1,m) if i+j==m}` vs `{(i,m-i) for i in range(1,m)}` – CDJB May 04 '22 at 07:35
  • I guess the proof is the question does the set represented by `{(i,m-i) for i in range(1,m)}` include all possible pairs adding up to `m`. If it does (which I doubt) then that is a way faster approach. I know that the cartesian product does include all possible combinations but that may be intellectually lazy to see a faster way I grant. ;-) – dawg May 04 '22 at 12:40

0 Answers0