-6

I have a complete matching in the form:

M=[(1,3),(2,4),(5,6)]

I want to perform a simple transposition on it.

Function si(M) should swap the positions of numbers i and i+1.

For instance s2(M) should swap the positions of numbers 2 and 3:

s2(M) should return:

[(1,2),(3,4),(5,6)]

Preferably written in python3 code.

Kshitij Saraogi
  • 6,821
  • 8
  • 41
  • 71
Shoogiebaba
  • 81
  • 10
  • 6
    SO is not a place to ask random people to do your work for you.. please try to code it yourself and if you encounter any problems ask about them. – Ronen Ness Jul 13 '15 at 07:01
  • 1
    That's very good. So, write some code, and if you run into problems, write an on-topic question and post it here. – juanchopanza Jul 13 '15 at 07:02
  • Please post your own attempt at writing this function & we'll help you fix it. Tuples aren't really suitable for this since they're immutable. Your transpose function should take two arguments: the list you want to transpose, and the index. – PM 2Ring Jul 13 '15 at 07:06
  • 1
    @Alex Gain One method is to first convert **list of tuples** to **list of lists** then swap the values you want by using index of the elements in the list of lists; generally let us assume your list of list is L. You can use L[i][j] for the index of elements and swapping where **i** will vary from 0 to length of your list and **j** will vary from 0 to 1. – Tanmaya Meher Jul 13 '15 at 07:20
  • This is an extremely small part of what I'm working on and is quite similar in nature to a lot of other questions involving functions on data structures. Thank you for the feedback, though. – Shoogiebaba Jul 13 '15 at 07:28
  • 1
    Thank you for the pseudocode, very much appreciated. @TanmayaMeher – Shoogiebaba Jul 13 '15 at 07:32
  • @AlexGain You will get some idea here http://stackoverflow.com/questions/14831830/convert-a-list-of-tuples-to-a-list-of-lists and for finding index of numbers in here http://stackoverflow.com/questions/9553638/python-find-the-index-of-an-item-in-a-list-of-lists – Tanmaya Meher Jul 13 '15 at 08:24

1 Answers1

1

For anyone curious, I quickly wrote a function for it. First off, the complete matching is written as a 2D list.

The following function is needed before writing the main one:

def index_2d(myList, v): #Returns tuple containing the position of v in the 2D list
  for i, x in enumerate(myList):
     if v in x:
        return (i, x.index(v))

eg. If the complete matching is M=[[1,2],[3,4],[5,6]], index_2d(M, 4) would return (1,1).

Next, the simple transposition function:

def s(M,n):
   a=index_2d(M,n)
   b=index_2d(M,n+1)
   M[a[0]][a[1]], M[b[0]][b[1]] = M[b[0]][b[1]], M[a[0]][a[1]]
   return M

I wasn't concerned with efficiency, so perhaps there is more efficient code than this.

Shoogiebaba
  • 81
  • 10