Python 中的自定义 len() 函数

pythonserver side programmingprogramming

让我们看看如何在 Python 中实现自定义 len() 函数。请先按照以下步骤自行尝试。

步骤

  • 从用户字符串/列表/元组中获取迭代器。

  • 定义一个具有自定义名称的函数,并通过传递迭代器来调用它。

    • 将计数初始化为 0。
    • 运行循环,直到到达末尾。
      • 将计数增加 1
    • 返回计数。

示例

## 函数用于计算迭代器的长度
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

相关文章