Write function, leastChar(inputString) that takes as input a string of one or mo
ID: 3787474 • Letter: W
Question
Write function, leastChar(inputString) that takes as input a string of one or more letters (and no other characters) and prints 1) the "least" character in the string, where one character is less than another if it occurs earlier in the alphabet (thus 'a' is less than 'C' and both are less than 'y') and 2) the index of the first occurrence of that character. When comparing letters in this problem, ignore case - i.e. 'e' and 'E' should be treated as equal. However, your output should use the case of the least letter as it appears in the input. Thus, in the example below "The least char is 'b' ..." would be incorrect. Important: your function must contain exactly one loop and you must determine the index of the character within the loop (i.e. you may not use Python's min, index, or find, and you may not use any lists). You may, however, use Python's lower() function to help with string case. For example, >>> leastChar("yRrcDefxBqubSlyjYelskd") should yield: The least char is 'B' and occurs at position 8.
Explanation / Answer
PROGRAM CODE:
# function to determine the least character and its index
def leastChar(inputString):
#keeping a temp variable with all characters in lowercase
tempString = inputString.lower();
#initially making the leastchar to be the first letter in the string
#and index to be at position 0
leastChar = tempString[0];
index = 0;
#looping till the end of string
for i in range(1, len(tempString)):
#checking if the current leastchar is greater than the index from the loop
#if so, update the index and the leastchar
if leastChar > tempString[i]:
leastChar = tempString[i]
index = i;
#finally printing on screen
print(' The least char is ', inputString[index], 'and occurs at position', index);
inputString = input('Enter some string: ');
leastChar(inputString);
OUTPUT:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.