I have a function that let me put any string and return me the high value alphabetically. For instance, if I have a sentence like "Hello world" and we supposed that world
is bigger than hello
then we will return world
.
This high value is measured by index I set before in string_index_in_char
.
def func(string):
char = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
split_string = string.split()
i = 0
x = ""
# get letters
string = string.lower()
for s in string:
if s in char:
string_index_in_char = char.index(s) + 1
else:
string_index_in_char = 0
x += str(string_index_in_char)
split_any_char_not_letters = x.split("0")
# convert string into interger in list
for i in range(0, len(split_any_char_not_letters)):
split_any_char_not_letters[i] = int(split_any_char_not_letters[i])
convert_to_int = split_any_char_not_letters
# (split_string, convert_to_int) comparison
n = convert_to_int.index(max(convert_to_int))
my_string = split_string[n]
print("%s -> %s" %(string, my_string.lower()))
#func("This Is my home")
func("Hello wOrld")
I get this error:
Traceback (most recent call last):
File "D:\courses\udacity-python\python\Exam\alphabet\alphabet 5.py", line 27, in <module>
func("This Is my home")
File "D:\courses\udacity-python\python\Exam\alphabet\alphabet 5.py", line 23, in func
my_string = split_string[n]
IndexError: list index out of range
No problem appears with me just when I type any other words like "man i need a taxi up to Ubud"
or some words. So why it get this error despite it not sending me this error when I type "hello world"?
Updated as suggested by @Parakiwi:
The problem occurs when you split the zero
, in your example: this is my home, t is at position 20
since you split by 0
it affects the code by adding extra value to the split list causing the error. Changing to any arbitrary number apart from those of char index like <<carefully chosen split criteria>>
will work:
Change:
if s in char:
string_index_in_char = char.index(s) + 1
print(string_index_in_char)
else:
string_index_in_char = "^"
x += str(string_index_in_char)
split_any_char_not_letters = x.split("^")
Before:
if s in char:
string_index_in_char = char.index(s) + 1
else:
string_index_in_char = 0
x += str(string_index_in_char)
split_any_char_not_letters = x.split("0")
However, you would need to handle the case of an equality of two words.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments