'Can you help me with a solution of hackerrank active traders problem?
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()
Solution 1:[1]
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)
Solution 2:[2]
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();
}
Solution 3:[3]
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;
}
Solution 4:[4]
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))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Hvaandres |
Solution 2 | user3283325 |
Solution 3 | marcelv3612 |
Solution 4 | Sita |