编写代码以使用累积模式计算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。
答案 0 :(得分:0)
在累加器模式下,您有一个变量,在发生某些情况时将其添加到变量中。您可以使“某物”表示“算一个特定字符”。
因此,编写一个循环遍历字符串中每个字符的循环,每次遍历该循环时,请将变量从零开始加一个。
答案 1 :(得分:0)
如果无法使用len()
函数,则可以编写下面的num_characters
之类的函数,该函数使用for循环遍历传入的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)}.")
输出:
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.
答案 2 :(得分:0)
original_str = "The quick brown rhino jumped over the extremely lazy fox."
num_chars = original_str.count('') - 1
print (num_chars)
答案 3 :(得分:0)
original_str = "The quick brown rhino jumped over the extremely lazy fox."
count = 0
for w in original_str:
count = count + 1
num_chars = count
print(num_chars)
答案 4 :(得分:-1)
exec "$@"