Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

James Dunn
James Dunn
3,041 Points

isinstance code challenge

So I've tried several methods of achieving the answer including

print(s,n)

however, I have not been able to figure out what I'm doing wrong.

Help would be much appreciated.

Thank you.

instances.py
def combiner(self, l_input[]):
    i = 0
    s = ""
    n = 0

    for x in l_input:
        if isinstance(x, str):
            s += x
        elif isinstanc(x, int):
            n += x

    print(s+n)

1 Answer

Ben Slivinn
Ben Slivinn
10,156 Points

Hi, Check my code:

def combiner(stdin: list):
    sum = float()
    full_str = str()
    for item in stdin:
        if isinstance(item, int) or isinstance(item, float):
            sum = sum + item
        else:
            full_str = full_str + item
    return full_str + str(sum)

Self explanatory, but the function accept one argument (stdin) of list type. The I declare 2 variables, one of total sum of numbers and one for the strings. I iterate over stdin (list) and check if each item isinstance of integer or floating point number, if it is I add to the total sum, if the item is not instance of number, I assume it's a string (it's can be list or object but the challenge dosen't pass a list inside a list ect...) and add them too. At the end I add the total number sum as str to the full strings.

BTW,

  1. At the challenge you should not pass self as first argument becouse it's a function not a class method.
  2. You check only for integers not floating point numbers.

Cheers