Python Cote Question

Asked 1 years ago, Updated 1 years ago, 334 views

def solution(n):
    answer = []


    # First, pull out all the mineral water, and then leave only the few of the mineral water.
    for i in range(2,n+1):
        if n%i == 0:
            answer.append(i)


    for i in answer:
        cnt = 0
        for j in range(1,i+1):
            if i % j == 0:
                cnt += 1
            if cnt >= 3 :
                answer.remove(i)
                break


    return answer

In the stomach lining, we made an answer a list of mineral water I'd like to test the mineral water one by one at the bottom of the cloth to remove the synthetic water, but the result is

Test 1
Input value > 12
Expectations > [2, 3]
Run Results> The run result value [2,3,6] is different from the expected value [2,3].

Test 2
Input value > 17
Expectations > [17]
Run Results > Test Passed.

Test 3
Input value> 420
Expectations > [2, 3, 5, 7]
Run Results> The run result value [2,3,5,7,12,15,21,30,42,70,105,210] is different from the expected value [2,3,5,7].

It comes out like this.

I don't know why some are removed and some are not. For example, in Te1, If you turn the door below to 6, the cnt should be removed over 3, but it doesn't work.

python coding-test

2022-10-18 09:00

1 Answers

for i in answer:
     # Change answer

In this way, an error occurs that is difficult to predictable.

It's a very simple example.

>>> lst = [ 1, 2, 3, 4, 5 ]
>>> for i in lst:
    print(i, lst)
    lst.remove(i)


1 [1, 2, 3, 4, 5]
3 [2, 3, 4, 5]
5 [2, 4, 5]
>>> lst
[2, 4]

You need to filter that leaves only the conditions in the list compliance, or you need to copy and use a new answer instead of an answer.

>>> lst = [ 1, 2, 3, 4, 5 ]
>>> for i in lst[:]:
    print(i, lst)
    lst.remove(i)


1 [1, 2, 3, 4, 5]
2 [2, 3, 4, 5]
3 [3, 4, 5]
4 [4, 5]
5 [5]
>>> lst
[]


2022-10-18 09:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.