Function that separates a list in two other ones - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: Function that separates a list in two other ones (/thread-6775.html) |
Function that separates a list in two other ones - eevvyy - Dec-07-2017 Hi, I have an assignment in which I have to write a function that takes a list, separates it in two other lists and return them into a tuple. One list has to consist of 80% of the original one, and the other 20%. My function should be able to take a list of any length, not just one that can be divided by 10, and separate in a similar ratio. So far, my code looks like this: def sections(liste): test = [] for i in range(int((len(liste) / 100) * 80) , len(liste)): test.append(liste[i]) train = [x for x in liste if x not in test] return train, testWhich for this list: sections([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])Returns this, which is okay: But for this list:sections([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])Returns this: But I want this result: I don't really know what to add to my code to make it work like it should, maybe an if statement regarding the length of the list?Thanks! RE: Function that separates a list in two other ones - Larz60+ - Dec-07-2017 80% of 12 is 9.6, therefore ([1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12]) is correct RE: Function that separates a list in two other ones - buran - Dec-07-2017 (Dec-07-2017, 02:16 AM)Larz60+ Wrote: 80% of 12 is 9.6, therefore ([1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12]) is correctwell, under all math rules 9.6 would round to 10 and i guess that is why OP expects list with len 10 :-) I also guess OP is using pythin2 thus / is actually floor division. RE: Function that separates a list in two other ones - Larz60+ - Dec-07-2017 then shouldn't rounding do the trick? RE: Function that separates a list in two other ones - eevvyy - Dec-07-2017 Thanks! I used round() instead of int() and it worked. I must have been too tired to even think about it :P |