Home > front end >  Creating a New List Using a Percent Amount of a Pre-existing One - Python
Creating a New List Using a Percent Amount of a Pre-existing One - Python

Time:12-06

Essentially, I have to take a pre-existing list and a percentage and return a new list with the given percentage of items from the first list in a new list. I have what follows:

def select_stop_words(percent, list):
    possible_stop_words = []
    l = len(list)
    new_words_list = l//(percent/100)
    x = int(new_words_list - 1)
    possible_stop_words = [:x]
    return possible_stop_words

But this always yields the same results as the first. Help??

CodePudding user response:

Replace

new_words_list = l//(percent/100)

with

new_words_list = l * percent/100

Given percent <=100, new_words_list >= len(lst) right now.

CodePudding user response:

You might want to multiply l to percent / 100:

def select_stop_words(percent, lst):
    return lst[:len(lst) * percent // 100]

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(select_stop_words(50, lst)) # [1, 2, 3, 4, 5]
print(select_stop_words(20, lst)) # [1, 2]
print(select_stop_words(99, lst)) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(select_stop_words(100, lst)) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  • Related