강의

멘토링

로드맵

Inflearn Community Q&A

mmmpapi934182's profile image
mmmpapi934182

asked

Introduction to Python Algorithm Problem Solving (Coding Test Preparation)

1. Binary output using recursive function

파이썬에서 전역변수는 어떻게 쓰나요?

Written on

·

498

0

  • import sys
    sys.stdin = open("input.txt", "rt")
    res = ''

    def dfs(x):
        if x == 0:
            return
        div, mod = divmod(x, 2)
        dfs(div)
        res+=str(mod)


    if __name__ == "__main__":
        n = int(input())
        dfs(n)
        print(res)

     

저는 위처럼 코드를 짰는데요, res=''로 처음에 초기화하고, 여기에 나머지 값을 str으로 바꿔서 더해주는 방식인데,

res가 초기화되지 않았다고 나오네요.. 

맨 상단에 두면 전역변수로 두는게 아닌가요?

코테 준비 같이 해요! python

Quiz

재귀 함수에서 print 문을 재귀 호출 뒤에 두면 출력이 역순으로 되는 이유가 무엇일까요?

전역 변수 충돌 때문에

종료 조건이 없어서

스택에 쌓였다가 역순으로 처리돼서

지역 변수 우선순위 때문에

Answer 1

0

함수 내에 global을 선언해주시면 될 것 같아요

mmmpapi934182's profile image
mmmpapi934182

asked

Ask a question