Ask your own question, for FREE!
MIT 6.00 Intro Computer Science (OCW) 16 Online
OpenStudy (anonymous):

can somebode help me with this python question please. Define a function called shuffle() which repeatedly splits a list in half, then interleaves the two resulting lists together. Your function should also take an additional integer parameter to control the number of split/interleave steps

OpenStudy (anonymous):

We had to do something similar for a genetic algorithm. What do you have so far?

OpenStudy (anonymous):

I imagine you should make a midpoint. So first make 2 empty lists,L1 and L2. Then find the midpoint of the parameter list by dividing the length by 2. This resulting midpoint should be the index you use to split up the given list.

OpenStudy (anonymous):

Hmm, this could be taken a few ways. Does it do all the splits first and then interleaves them back together kind of like a merge sort. Example: shuffle([1,2,3,4,5,6,7,8],2) first split [1,2,3,4] and [5,6,7,8] second split [1,2] [3,4] and [5,6] [7,8] Now I guess we interleave the first two and then second two [1,3,2,4] and [5,7,6,8] And then the last interleave [1,5,3,7,2,6,4,8] Or maybe you do split and interleave at each step and never have more than 2 lists. Example: shuffle([1,2,3,4,5,6,7,8],2) first split [1,2,3,4] [5,6,78] first interleave [1,5,2,6,3,7,4,8] second split [1,5,2,6] [3,7,4,8] second interleave [1,3,5,7,2,4,6,8] The second option is a little easier. Different output but it depends what is needed.

OpenStudy (anonymous):

i already wrote the split and interleave function jus dnt know how to use them to make the shuffle

OpenStudy (anonymous):

@shamincy how'd you do it? want to post your solution? http://dpaste.com/1058613/

OpenStudy (anonymous):

def split(lst): x= int(len(lst)/2) lst1=lst[:x] lst2=lst[x:] return lst1 lst2 def interleave(lst1,lst2): if len(lst1)==0 and len(lst2)==0: return [] if len(lst1)==0: return lst2 if len(lst2)==0: return lst1 y =[lst1[0],lst2[0]] return y + interleave(lst1[1:],lst2[1:])

OpenStudy (anonymous):

do you kno how to write it using the functions i wrote?

OpenStudy (anonymous):

split produces a syntax error without a comma in line "return lst1, lst2" Using my second option described above and your functions here is a shuffle that does that. def shuffle(n, lst): for i in range(n): lst1, lst2 = split(lst) lst = interleave(lst1, lst2) return lst >>> shuffle(2,[1,2,3,4,5,6,7,8]) [1, 3, 5, 7, 2, 4, 6, 8]

OpenStudy (anonymous):

yeah it was a typo i already correct it thx,

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!