Why is the first Phonkemon question correct?

Asked 1 years ago, Updated 1 years ago, 342 views

def solution(nums):
    answer = 0
    l = int(len(nums) / 2)
    nums_set = len(set(nums))
    if l < nums_set:
        answer = l
    elif l > nums_set:
        answer = nums_set
    else:
        answer = l            
    return answer

This is Phonkemon, question number 1 of the coding test Python. In the example, the number of nums and the number of Pokémon to choose from Only the small ones are printed out, so I wrote it like that. It passed. Why did it pass?

python coding-test

2023-02-18 16:13

1 Answers

This is a question of finding the way to select the most number of phonemes out of the N/2 phonemes. If the number of phonemes that can be selected is greater than N/2, you cannot select all kinds of phonemes when selecting N/2; therefore, the maximum number of phonemes that can be selected is N/2.

On the other hand, if the number of phoneme types you can choose is less than N/2, you can select any type of phoneme when you select N/2 so the maximum number of phoneme types you can choose is the number of phoneme types you can choose.

Therefore, in the code you wrote, the number of phonkemon types that can be selected is divided into cases that are less than and larger than N/2, and if the same is the case, select N/2. This code would have allowed the example case to return the correct result and would have passed the test.

However, there is a simple way to solve this code using the set() function in counting the number of phonkemon types that can be selected. Since the set() function removes duplicate values and returns set objects with only unique values, you can calculate the number of phonkemon types with set(nums). And if this number is less than N/2, you can select any type of ponkemon, so the length of set(nums) is the maximum number of types you can select.

Therefore, you can easily modify the code as shown below.

def solution(nums):
    answer = 0
    n = len(nums) // 2
    unique_nums = len(set(nums))
    answer = unique_nums if unique_nums < n else n
    return answer


2023-02-19 01:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.