Python Object-Oriented Python Inheritance Instances

Matthew Hayes
Matthew Hayes
1,695 Points

Very smelly code improvements?

while writing code for this question I couldn't help but feel like I've gone along route around solving it. for example when I formated the return value and changing int/float into 'str'. I feel as though I've missed a few easy steps in simplifying my code. Can anyone critique it or suggest alternative methods? Thanks,

instances.py
def combiner(alist):
    stringjoin = ''
    str_list = []
    num_list = []
    for item in alist:
        if isinstance(item, str):
            str_list.append(item)
        elif isinstance(item, (int, float)):
            num_list.append(item)
    total = str(sum(num_list))
    str_list = stringjoin.join(str_list)
    return ("{}{}".format(str_list, total))

1 Answer

KRIS NIKOLAISEN
KRIS NIKOLAISEN
53,553 Points

Good job. You could make the code shorter by not using lists. Then the final results are handled during the iteration with no need for separate lines to sum and join the lists.

def combiner(alist):
    str_list = ''
    num_list = 0

    for item in alist:
        if isinstance(item, str):
            str_list += item
        elif isinstance(item, (int, float)):
            num_list += item

    return ("{}{}".format(str_list, str(num_list)))