Hello guest, if you read this it means you are not registered. Click here to register in a few simple steps, you will enjoy all features of our Forum.
Bottom Page

• 0 Vote(s) - 0 Average
• 1
• 2
• 3
• 4
• 5
 Function that separates a list in two other ones eevvyy Unladen Swallow Posts: 2 Threads: 1 Joined: Nov 2017 Reputation: 0 Likes received: 0 #1 Dec-07-2017, 12:45 AM 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, test```Which for this list: `sections([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])`Returns this, which is okay: ``Output:([1, 2, 3, 4, 5, 6, 7, 8], [9, 10])``But for this list: `sections([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])`Returns this: ``Output:([1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12])``But I want this result: ``Output:([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [11, 12])``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! Quote Quote Larz60+ aetate et sapientia Posts: 3,052 Threads: 143 Joined: Sep 2016 Reputation: 91 Likes received: 462 #2 Dec-07-2017, 02:16 AM 80% of 12 is 9.6, therefore ([1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12]) is correct Quote Quote buran Posts: 1,197 Threads: 22 Joined: Sep 2016 Reputation: 64 Likes received: 320 #3 Dec-07-2017, 07:07 AM (This post was last modified: Dec-07-2017, 07:08 AM by buran. Edited 1 time in total.) (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 correct well, 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. Quote Quote Larz60+ aetate et sapientia Posts: 3,052 Threads: 143 Joined: Sep 2016 Reputation: 91 Likes received: 462 #4 Dec-07-2017, 12:26 PM then shouldn't rounding do the trick? Quote Quote eevvyy Unladen Swallow Posts: 2 Threads: 1 Joined: Nov 2017 Reputation: 0 Likes received: 0 #5 Dec-07-2017, 05:34 PM Thanks! I used round() instead of int() and it worked. I must have been too tired to even think about it :P Quote Quote « Next Oldest | Next Newest »

Top Page

 Possibly Related Threads... Thread Author Replies Views Last Post Calling a function to return a list of percentages Liquid_Ocelot 7 548 Mar-25-2017, 01:20 PM Last Post: Larz60+ define all function, interogate list, boolean blacksaber 3 433 Jan-17-2017, 12:51 PM Last Post: buran

Forum Jump:

Users browsing this thread: 1 Guest(s)