본문 바로가기

Python_Matter/[Check_IO]Home

All the Same

Quiz>

We have prepared a set of Editor's Choice Solutions.

You will see them first after you solve the mission.

In order to see all other solutions you should change the filter.

In this mission you should check if all elements in the given list are equal.

 

Input:

List.

 

Output:

Bool.

 

Example:

all_the_same([1, 1, 1]) == True
all_the_same([1, 2, 1]) == False
all_the_same(['a', 'a', 'a']) == True
all_the_same([]) == True

 

The idea for this mission was found on Python Tricks series by Dan Bader

 

Precondition:

all elements of the input list are hashable

 

from typing import List, Any


def all_the_same(elements: List[Any]) -> bool:
    # your code here
    return True


if __name__ == '__main__':
    print("Example:")
    print(all_the_same([1, 1, 1]))
    
    # These "asserts" are used for self-checking and not for an auto-testing
    assert all_the_same([1, 1, 1]) == True
    assert all_the_same([1, 2, 1]) == False
    assert all_the_same(['a', 'a', 'a']) == True
    assert all_the_same([]) == True
    assert all_the_same([1]) == True
    print("Coding complete? Click 'Check' to earn cool rewards!")

 

Solve>

1. 순환 참조 에러 방지를 위한 모듈 임포트

from typing import List, Any

 

2. set은 중복 허용이 안되는 특징을 가졌다.

   중복이 안되므로 값이 같다는 걸 의미한다.

   elements를 set으로 만드면 중복은 삭제 되고 그 갯수를 세어 1개 이하이면 모든 값이 같는것을 의미한다.

def all_the_same(elements: List[Any]):
    return len(set(elements)) <= 1

 

Code>

def all_the_same(elements: List[Any]):
    return len(set(elements)) <= 1

 

Example>

if __name__ == '__main__':
    print("Example:")
    print(all_the_same([1, 1, 1]))

    # These "asserts" are used for self-checking and not for an auto-testing
    assert all_the_same([1, 1, 1]) == True
    assert all_the_same([1, 2, 1]) == False
    assert all_the_same(['a', 'a', 'a']) == True
    assert all_the_same([]) == True
    assert all_the_same([1]) == True
    print("Coding complete? Click 'Check' to earn cool rewards!")

 

Result>

Example:

True

Coding complete? Click 'Check' to earn cool rewards!

'Python_Matter > [Check_IO]Home' 카테고리의 다른 글

Find Quotes  (0) 2020.04.15
Count Digits  (0) 2020.04.15
All the Same  (0) 2020.04.15
Non-unique Elements  (0) 2020.04.15
Popular Words  (0) 2020.04.15
Sort Array by Element Frequency  (0) 2020.04.15