So I'm trying to find the least/smallest char in a string. The program is suppose to compare each character to each other and finds the smallest char. Should look like this when calling.

``least("rcDefxB")The least char is B``

this is the code that i have so far

``def least(inputS):for i in range(len(inputS)-1):current = inputS[i]nextt = inputS[i+1]if current > nextt:current = nexttnextt = inputS[i+2]print('The least char is',current)``

but the output that i get is this:

``least("rcDefxB")CDIndexError: string index out of rangein line least nextt = inputS[i+2]``

I probably incremented the wrong way or compared my characters the wrong way. I feel like i have the right setup, let me know where i missed up in my code.

You could just use :

``````min("rcDefxB")
``````

If you really want to write it on your own, you could use :

``````def leastChar(inputString):
min_char = inputString[0]
for char in inputString:
if char < min_char:
min_char = char
print 'The leastchar is %s' % min_char
``````

Both methods require a non-empty string.

Eric Duminil solution is better, but if you want your code works properly you should modify it as follows:

``````inputString = "rcDefxB"
index = 0
while index < len(inputString) - 1:
currentChar = inputString[index]
nextChar = inputString[index + 1]
if currentChar > nextChar:
currentChar = nextChar
index += 1
print('The leastchar is',currentChar)
``````

if by smallest you mean the ASCII code position just:

``````>>> s = "aBCdefg"
>>> min(s)
'B'
``````

but if you mean the alphabet position ignore the upper or lower case:

``````>>> min(s, key=lambda x: x.upper())
'a'
``````

``````def least(inputString):
leastChar = min(list(inputString))
print('The leastchar is', leastChar)
``````

After running `least("rcDefxB")`, you'll have:

``````The leastchar is B
``````

Well you are not actually finding the lowest char in string. You are only comparing adjacent chars. Your code will show the error whenever last char of your string is smaller then second last char.

Top