如何使用累积模式而不使用len()来计算代码中的字符数?

问题描述 投票:-5回答:4

编写代码以使用累积模式对original_str中的字符数进行计数,并将答案分配给变量num_chars。不要使用len函数来解决问题(如果在处理此问题时使用它,请在以后将其注释!)

original_str = "The quick brown rhino jumped over the extremely lazy fox."
num_chars = len(original_str)
print(len(original_str))
for i in original_str:
    print(len(i))

计算机告诉我这是正确的,但是没有回答问题。我必须用另一个函数替换len。

python
4个回答
0
投票

如果无法使用len()函数,则可以编写以下类似len()的函数,该函数使用for循环遍历传入的num_characters中的字符并递增,然后根据以下内容返回变量string字符总数。我认为这就是累加器的意思吧?

total

输出:

def num_characters(string):
  total = 0
  for character in string:
    total += 1
  return total

original_string = "The quick brown rhino jumped over the extremely lazy fox."
print(f"The numbers of characters in the original string using `len` is {len(original_string)}.")
print(f"The numbers of characters in the original string using `num_characters` is {num_characters(original_string)}.")

0
投票

使用累加器模式,您有一个变量,并且在发生某些情况时将其添加到该变量中。您可以使“某物”表示“算一个特定字符”。

因此,编写一个循环遍历字符串中每个字符的循环,并且每次循环时,都将一个从零开始的变量加一个。


0
投票
The numbers of characters in the original string using `len` is 57.
The numbers of characters in the original string using `num_characters` is 57.

0
投票

original_str =“快速的棕色犀牛跳过了极为懒惰的狐狸。”计数= 0对于original_str中的w:计数=计数+1num_chars =计数打印(num_chars)

© www.soinside.com 2019 - 2024. All rights reserved.