Reputation: 19
How can I rewrite this piece of code so that it works faster? Currently the execution time is more than 10 seconds.
def mostActive(customers):
initial = sorted(list(set(customers)))
filter_object = filter(lambda s: customers.count(s)/len(customers) >= 0.05, initial)
return filter_object
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
customers_count = int(input().strip())
customers = []
for _ in range(customers_count):
customers_item = input()
customers.append(customers_item)
result = mostActive(customers)
fptr.write('\n'.join(result))
fptr.write('\n')
fptr.close()
Upvotes: 1
Views: 12302
Reputation: 1
def mostActive(customers):
n=len(customers)
res=dict()
for i in customers:
if i not in res:
res[i]=1
else:
res[i]+=1
perc=dict()
for i in res:
perc[i]= (res[i]/n)*100
b=[]
for i in perc:
if perc[i]>=5:
b.append(i)
return(sorted(b))
Upvotes: 0
Reputation: 663
A Java 7 solution (without lambdas)
public static List<String> mostActive(List<String> customers) {
int size = customers.size();
Map<String, Integer> map = new HashMap<>();
for (String customer : customers) {
if (map.containsKey(customer)) {
map.put(customer, map.get(customer) + 1);
} else {
map.put(customer, 1);
}
}
List<String> result = new ArrayList<>();
for (String key : map.keySet()) {
double currentCustomerPercent = (double) (map.get(key)) / (double) size;
if (currentCustomerPercent * 100 >= 5.0) {
result.add(key);
}
}
Collections.sort(result);
return result;
}
Upvotes: 0
Reputation: 1
public static List<string> mostActive(List<string> customers)
{
List<string> res = new List<string>();
foreach (var c in customers)
{
double count = customers.Count(a => a.Contains(c));
double per = (count / customers.Count()) * 100;
if (!res.Contains(c) && per>=5)
{
res.Add(c);
}
}
return res.OrderBy(r=>r).ToList();
}
Upvotes: 0
Reputation: 1005
def mostActive(customers):
store=dict()
res=[]
for i in customers:
for i in store:
store[i]+=1
else:
store[i]=1
for i in store.items():
if(i[1]/len(customers))*100>5 or (len(customers)*5)/100>=5:
if(1[1]/len(customers))*100 >=(len(customers)*5)/100>=5 or (1[1]/len(customers))*100>=5:
res.append(i[0])
return sorted (res)
Upvotes: 1