Algorithm/Checkio

[Checkio] Scientific Expedition. Sum by Type

Henu 2020. 6. 17. 01:17

You have a list. Each value from that list can be either a string or an integer. Your task here is to return two values. The first one is a concatenation of all strings from the given list. The second one is a sum of all integers from the given list.

Input: An array of strings ans integers

Output: A list or tuple

 

1
2
3
4
5
6
7
8
9
def sum_by_types(items: list) -> Tuple[strint]:
    ssum = 0
    string = ''
    for e in items:
        if type(e) == str: #isinstance(e, str)
            string+=e
        elif type(e) == int: #isinstance(e, int)
            ssum += e
    return (string, ssum)
cs

어렵지 않은 문제였는데 하나 배워간게 있어서 기록한다

5, 7번째 줄 if type(e) == str 과 if type(e) == int 는

if isinstance(e, str) 과 if isinstance(e, int) 로 바꿀 수 있다

 

isinstance(object, class<type>)

object의 자료형과 비교하고자 하는 자료형이 같으면 True, 다르면 False를 반환한다