Getting the sums for each desired item in a list

49 Views Asked by At

I have a working code, but I was wondering if there was a better way to do it.

The function gets the sum of appearances for each specified item and returns them as a list.

def question10(ipaddresses: list[str]):
    none_count = sum(1 if x is None else 0 for x in ipaddresses)
    host_count = sum(1 if x == '129.128.1.1' else 0 for x in ipaddresses)
    target_count = sum(1 if x == '192.128.1.4' else 0 for x in ipaddresses)
    return [none_count, host_count, target_count]
2

There are 2 best solutions below

1
mdegraaff On

You could use Counter from the collections library.

It would look something like this:

from collections import Counter

def question10(ipaddresses: list[str]):
   counter = Counter(ipaddresses)
   return [counter[None], counter['129.128.1.1'], counter['192.128.1.4']]

Note that the list[str] syntax is only available in newer python versions like Python 3.9 and later.

For older versions you'd use something like:

from typing import List
from collections import Counter

def question10(ipaddresses: List[str]):
    counter = Counter(ipaddresses)
    return [counter[None], counter['129.128.1.1'], counter['192.128.1.4']]

The usecase for these, however, will remain the same. For example the list:

ipaddresses = ['192.128.1.1', '192.128.1.4', '129.128.1.1',
               '129.128.1.1', '129.128.1.4']

should output [0, 2, 1] in both cases

0
minos On

You can use the built-in count() function :

def question10(ipaddresses: list[str]):
    none_count = ipaddresses.count(None)
    host_count = ipaddresses.count('129.128.1.1')
    target_count = ipaddresses.count('192.128.1.4')    
    return [none_count, host_count, target_count]