我有一个家庭作业,要求不使用内置函数进行字符串长度计算。
我的想法是使用柜台:
s = 0
while name[s] != "":
s += 1
但是我仍然坚持如何解决string index out of range
错误......或者实际上是否存在其他方式?
答案 0 :(得分:3)
你有两个简单的选择:
添加try/except
子句:
s = 0
try:
while(name[s]):
s += 1
except IndexError:
pass
print(s)
或使用迭代器:
s = 0
for _ in name:
s += 1
print(s)
答案 1 :(得分:1)
试试这个,
counter = 0
st = 'ABCDEF'
for i in st:
counter += 1
print('Length of String is : ', str(counter))
答案 2 :(得分:0)
因此,字符串基本上是一系列字符。例如:
'hello' = ['h', 'e', 'l', 'l', 'o']
因此,如果您只是遍历此数组并在每个循环中将1
添加到length
变量,那么您将得到长度:
string = "hello"
length = 0
for character in string:
length = length + 1
print(length)
这样,您甚至不必担心处理异常:)
在线试用
进一步阅读
答案 3 :(得分:0)
有一个替代#34;愚蠢"通过为每个字符添加一个来计数:
带测试部分的代码:
def is_valid_index(s, i):
'''Returns True, if i is a valid index of string s, and False otherwise.'''
try:
s[i]
return True
except IndexError:
return False
def string_length(s):
'''Returns the length of string s without built-ins.'''
# Test for empty string (needed for the invariant
# of the following exponential search.)
if not is_valid_index(s, 0):
return 0
# Exponential search with low as inclusive lower bound
# and high as exclusive upper bound.
# Invariant for the loop: low is a valid index.
low = 0
high = 1
while True:
if is_valid_index(s, high):
low = high
high *= 2
continue
break
# Binary search inside the found range
while True:
if low + 1 == high:
return high
middle = (low + high) // 2
if is_valid_index(s, middle):
low = middle
else:
high = middle
# Test section
print(string_length('hello'))
# Test the first thousand string lengths
for i in range(1000):
s = 'x' * i
if len(s) != string_length(s):
print('Error for {}: {}'.format(i, string_length(s)))
# Test quite a large string
s = 'x' * 1234567890
print(string_length(s))
结果:
5
1234567890
答案 4 :(得分:-1)
字符串具有属性__len__
,该函数返回字符串的长度。因此,以下解决方案不使用内置函数,但计算是微不足道的(没有计算操作,因此,它可能不是作业的意图):
def get_string_length(s):
return s.__len__()
测试:
print(get_string_length('hello'))
结果:
5