0

Does anyone know how to form a random partition of 2 lists (List1 and List2) in python? The lists do not have to have the same size. For example:

S = [1,2,3,4,5,6,7]
List1=[3,6,1,2]
List2=[5,4,7]

or

List1 =[3,5]
List2=[1,2,4,7,6]
user02
  • 281
  • 3
  • 10
  • 1
    Have you tried anything? – Julien Apr 04 '17 at 01:00
  • Hi. I have not. I'm very new to Python. I am trying to form a random initial solution for solving minimum cut problem using simulated annealing. – user02 Apr 04 '17 at 01:03
  • Sorry, we are not here to write code for you or give you a personal training. Please try something first, read tutorials etc... and come back when you have so code to show. – Julien Apr 04 '17 at 01:06

3 Answers3

6

I'm not sure what your rules are around randomness and partitioning, but this should get you started:

import random

s = [1,2,3,4,5,6,7]

random.shuffle(s)

cut = random.randint(0, len(s))
list_1 = s[:cut]
list_2 = s[cut:]

print list_1
print list_2
Chris Curvey
  • 9,738
  • 10
  • 48
  • 70
3

I would recommend:

  1. Shuffle or randomly rearrange the list
  2. Then choose the random index at which to break up the list

Code:

import random

S = [1,2,3,4,5,6,7]
random.shuffle(S)
index = random.randint(0, len(S))
List1 = S[index:]
List2 = S[:index]
Neil
  • 14,063
  • 3
  • 30
  • 51
0

Not sure what modules you have but this is a function that does what you want.

import random
def split(S): 
    x = random.randint(0,len(S))
    y = len(S)-x
    S1 = S[0:x]
    S2 = []
    for i in range(len(S)):
        if S[i] not in S1:
           S2.append(S[i])
    return S1,S2
Adam Warner
  • 1,334
  • 2
  • 14
  • 30
  • thank you!! Do you know how to modify the code if I want the first element is always in list 1 and the last element is always in list 2? – user02 Apr 08 '17 at 22:08