IT

프로그래머스 lv0 - 조건에 맞게 수열 변환하기 1

규동이이 2023. 7. 2. 11:59

문제 설명

정수 배열 arr가 주어집니다. arr의 각 원소에 대해 값이 50보다 크거나 같은 짝수라면 2로 나누고, 50보다 작은 홀수라면 2를 곱합니다. 그 결과인 정수 배열을 return 하는 solution 함수를 완성해 주세요.

def solution(arr):
    answer = []
    for i in arr:
        if i>=50 and i%2==0:
            i/=2
        elif i<50 and i%2==1:
            i*=2
        print(arr)
    return arr

파이썬 for in 문에서 꺼내진 각 원소 i는 copy 된 원소라서, 해당 원소를 modify 해도 원 배열에는 영향이 가지 않는다.

추가로, i/2=2를 하기 전 후에 id(i)를 print 해보면 다른 걸 알 수 있음.

만약 전후 모두 id(i)가 같은 경우는 cpython은 short integer를 pool로 만들어 cache 같은 곳에 저장시켜 놓기 때문이다.

참고 : https://stackoverflow.com/questions/20688324/why-doesnt-assigning-to-the-loop-variable-modify-the-original-list-how-can-i-a

 

Why doesn't assigning to the loop variable modify the original list? How can I assign back to the list in a loop?

When I try this code: bar = [1,2,3] print(bar) for foo in bar: print(id(foo)) foo = 0 print(id(foo)) print(bar) I get this result: [1, 2, 3] 5169664 5169676 5169652 5169676 5169640 516...

stackoverflow.com