Manually calculate string length
So, a string is basically a sequence of characters. For example:
'hello' = ['h', 'e', 'l', 'l', 'o']
So, if you just loop through this array and add each loop 1
to the variable length
, you get the length:
string = "hello"
length = 0
for character in string:
length = length + 1
print(length)
This way you don't even have to worry about handling exceptions :)
Try online
additional literature
source to share
There is an alternative to "silly" calculations, adding one for each character:
- Exponential search finds a range of string length.
- Binary search concatenates the length of the string starting from the range found in the previous step.
Test section code:
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))
Result:
5 1234567890
source to share
The string has an attribute __len__
, a function that returns the length of the string. So the following solution does not use built-in modules, but the computation is trivial (no computation of operations, hence this might not be the goal of homework):
def get_string_length(s):
return s.__len__()
Test:
print(get_string_length('hello'))
Result:
5
source to share