Skip to main content
added 329 characters in body
Source Link
Nasser
  • 150.5k
  • 12
  • 161
  • 374

May be

lis = {{6,3,2,4}, {3,9,5}, {1,7,2}, {16,5,4}, {49,7}, {1,3,1}, {3, 2, 7}};
Cases[lis, {___, x_, ___, y_, ___} /; (x^2 == y || y^2 == x) :> {x, y}]

gives

{{2, 4}, {3, 9}, {16, 4}, {49, 7}, {1, 1}}

The {1,1} is from {1, 3, 1} because 1 is the square of 1

However, the above does not capture all possible n and n^2 inside the list. For example given {6, 3, 2, 4, 16}, it finds {2,4} but not also {4,16} from same list.

I assumed your list has only one pair of n and n^2 in it.

Edit

Per comment, output the whole list which contains any $n,n^2$ in it

lis = {{6,3,2,4}, {3,9,5}, {1,7,2}, {16,5,4}, {49,7}, {1,3,1}, {3, 2, 7}};
Cases[lis, {a___, x_, c___, y_, b___} /; (x^2 == y || y^2 == x) :> {a,x,c,y,b}]

gives

{{6, 3, 2, 4}, {3, 9, 5}, {16, 5, 4}, {49, 7}, {1, 3, 1}}

May be

lis = {{6,3,2,4}, {3,9,5}, {1,7,2}, {16,5,4}, {49,7}, {1,3,1}, {3, 2, 7}};
Cases[lis, {___, x_, ___, y_, ___} /; (x^2 == y || y^2 == x) :> {x, y}]

gives

{{2, 4}, {3, 9}, {16, 4}, {49, 7}, {1, 1}}

The {1,1} is from {1, 3, 1} because 1 is the square of 1

However, the above does not capture all possible n and n^2 inside the list. For example given {6, 3, 2, 4, 16}, it finds {2,4} but not also {4,16} from same list.

I assumed your list has only one pair of n and n^2 in it.

May be

lis = {{6,3,2,4}, {3,9,5}, {1,7,2}, {16,5,4}, {49,7}, {1,3,1}, {3, 2, 7}};
Cases[lis, {___, x_, ___, y_, ___} /; (x^2 == y || y^2 == x) :> {x, y}]

gives

{{2, 4}, {3, 9}, {16, 4}, {49, 7}, {1, 1}}

The {1,1} is from {1, 3, 1} because 1 is the square of 1

However, the above does not capture all possible n and n^2 inside the list. For example given {6, 3, 2, 4, 16}, it finds {2,4} but not also {4,16} from same list.

I assumed your list has only one pair of n and n^2 in it.

Edit

Per comment, output the whole list which contains any $n,n^2$ in it

lis = {{6,3,2,4}, {3,9,5}, {1,7,2}, {16,5,4}, {49,7}, {1,3,1}, {3, 2, 7}};
Cases[lis, {a___, x_, c___, y_, b___} /; (x^2 == y || y^2 == x) :> {a,x,c,y,b}]

gives

{{6, 3, 2, 4}, {3, 9, 5}, {16, 5, 4}, {49, 7}, {1, 3, 1}}
Source Link
Nasser
  • 150.5k
  • 12
  • 161
  • 374

May be

lis = {{6,3,2,4}, {3,9,5}, {1,7,2}, {16,5,4}, {49,7}, {1,3,1}, {3, 2, 7}};
Cases[lis, {___, x_, ___, y_, ___} /; (x^2 == y || y^2 == x) :> {x, y}]

gives

{{2, 4}, {3, 9}, {16, 4}, {49, 7}, {1, 1}}

The {1,1} is from {1, 3, 1} because 1 is the square of 1

However, the above does not capture all possible n and n^2 inside the list. For example given {6, 3, 2, 4, 16}, it finds {2,4} but not also {4,16} from same list.

I assumed your list has only one pair of n and n^2 in it.