Python에서 사용자 정의 len() 함수를 구현하는 방법을 살펴보겠습니다. 다음 단계에 따라 먼저 직접 시도해 보세요.
단계
-
사용자 문자열/목록/튜플에서 반복자를 가져옵니다.
-
원하는 대로 사용자 정의 이름으로 함수를 정의하고 반복자를 전달하여 호출합니다.
- 카운트를 0으로 초기화합니다.
- 끝에 도달할 때까지 루프를 실행합니다.
- 카운트를 1 증가
- 카운트를 반환합니다.
예시
## function to calculate lenght of the iterator
def length(iterator):
## initializing the count to 0
count = 0
## iterating through the iterator
for item in iterator:
## incrementing count
count += 1
## returning the length of the iterator
return count
if __name__ == "__main__":
## getting input from the user
iterator = input("Enter a string:- ")
## invoking the length function with 'iterator'
print(f"Length of {iterator} is {length(iterator)}")입니다. 위의 프로그램을 실행하면 다음과 같은 결과를 얻을 수 있습니다.
출력
Enter a string:- tutorialspoint Length of tutorialspoint is 14