Python: Tallying the number of unique sizes in a list

Question:

Word Problem:

Pant Sizes

A store marketing manager has a chronological list of pant sizes sold to customers for a particular style of pant sold during a promotion. A tally of each unique size is required. Write and test a function that given a list of sizes, returns a new list with each size followed by its tally (total number sold).

Function Definition

def tally(sizes: list) -> list:

Example input:

a = [30, 34, 30, 20, 34]

print(tally(a))

Example output:

[30, 2, 34, 2, 20, 1]

So far I created a function that returns a new list with the unique values and I need help including the tally beside the value. I was thinking about creating a accumulator but I don’t know the number of unique values in a list

sizes = [30, 34, 30, 20, 34]

unique = []
for i in sizes:
    if i not in unique:
        unique.append(i)
        
print(unique)
Asked By: Underleague

||

Answers:

If you want to stick to using only lists, then you could keep track of the tally in a separate list and then merge the two lists at the end.

sizes = [30, 34, 30, 20, 34]

unique = []
tally = []
for i in sizes:
    if i not in unique:
        unique.append(i)
        tally.append(1)
    else:
        idx = unique.index(i)
        tally[idx] += 1
result = []
for i in range(len(unique)):
    result.append(unique[i])
    result.append(tally[i])

print(result) # [30, 2, 34, 2, 20, 1]

if you are okay with using a dictionary which is the better/more efficient way then you could do something like this:

sizes = [30, 34, 30, 20, 34]

unique = {}
for i in sizes:
    if i in unique:
       unique[i] += 1
    else:
       unique[i] = 1
result = [j for i in unique.items() for j in i]  
print(result) #  [30, 2, 34, 2, 20, 1]
Answered By: Alexander

If you want to learn python, learn how to use the builtin modules.

Here using collections.Counter and a list comprehension.

def tally(l):
    from collections import Counter
    return [x for t in Counter(l).items() for x in t]

tally([30, 34, 30, 20, 34])
# [30, 2, 34, 2, 20, 1]

If you don’t want to use a module, you can code your own Counter (quite easy for a simple count).

Answered By: mozway
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.