Using Python3
For a given array of transactions, group all of the transactions by item name. Return an array of string where each string contains the item name followed by a space and the number of associated transactions.
Note: Sort the array descending by transaction count, then ascending alphabetically by item name for items with matching transaction counts.
Example
transactions = ['notebook', 'notebook', 'mouse', 'keyboard', 'mouse']
There are two items with 2 transactions each: 'notebook' and 'mouse'. In alphabetical order, they are 'mouse', 'notebook'. There is one item with 1 transaction: 'keyboard'. The return array sorted as required is ['mouse 2', 'notebook 2', 'keyboard 1']
What I've got
def get_trans(lst):
ans = {}
for i in lst:
ans[i] = ans.get(i, 0) 1
return ans
dictionary = get_trans(transactions)
print(dictionary)
{'notebook' : 2, 'mouse' : 2, 'keyboard' : 1}
data = list(dictionary.items())
an_array = np.array(data)
print(an_array)
Current output: 'notebook' comes before 'mouse', separate strings for word/count
[['notebook' '2']
['mouse' '2']
['keyboard' '1']]
Desired output: 'notebook' alphabetically ordered after 'mouse', word/count is one string
['mouse 2', 'notebook 2', 'keyboard 1']
CodePudding user response:
Your function is almost correct, only you need to pass the key first and a default value second to the get
method. Then you can use the sorted
function to sort the tuples of key-value pairs in dictionary
with counts in descending order and item names in ascending order:
def get_trans(lst):
ans = {}
for i in lst:
ans[i] = ans.get(i, 0) 1
return ans
out = [' '.join([t[0],str(t[1])]) for t in sorted(get_trans(transactions).items(), key=lambda x:(-x[1],x[0]))]
Output:
['mouse 2', 'notebook 2', 'keyboard 1']
CodePudding user response:
Manlai A provided the correct answer. I've converted it to a function:
def get_trans(lst):
ans = {}
for i in lst:
ans[i] = ans.get(i, 0) 1
return ans
# A function using get_trans() function with Manlai A's answer
def grouping(lst):
out = sorted(get_trans(lst).items(), key=lambda x:(-x[1],x[0]))
out = [' '.join([t[0],str(t[1])]) for t in out]
return out
# Passing transactions list into the new function
grouping(transactions)
Output:
['mouse 2', 'notebook 2', 'keyboard 1']