Python question. Find the smallest alphabet, the third smallest alphabet, and the most common alphabet in a given string.

Asked 2 years ago, Updated 2 years ago, 57 views

I am a student who is learning Python 3 in school class. I received my school homework, but I don't know how to start, so I post a question here.

1. Write a function, q2(inputString, minLetter), that takes as input a string of letters and returns six things: the lexicographically smallest letter (z/Z > y/Y > ... > a/A) greater or equal to minLetter, the smallest index at which that letter occurs, the third smallest letter greater than minLetter, the smallest index at which that letter occurs, the most common letter, and how many times the most common letter occurs. The third smallest letter must be distinct from the second smallest which must be distinct from the smallest. E.g. 'b' is the second smallest and 'c' is the third smallest in 'ababdc'

Ignore case during computation. E.g. 'z' and 'Z' are considered the same letter. Use lower case when returning letters.

Return None for smallest and thirdSmallest letters and corresponding indices when appropriate.

You may not assume that the input string contains at least three different characters (or even any characters at all). Make sure to recognize various situations where fewer than three different letters appear in the string, and where there is no third smallest or smallest greater than minLetter.

If two or more letters tie for most common, return the lexicographically smallest one.

For example:

>>> q2('aacyYcqyQQqyqc', 'b')
('c', 2, 'y', 3, 'q', 5)

>>> q2('aacyYcqyQQqyqc', 'r')
('y', 3, None, None, 'q', 5)

The question is this, but I don't know what to do because the school told me not to write down the list or Sort. It's my first time learning Python, so I don't know what it is, but I'm worried that it doesn't teach me well in class. Python masters, please help me.

I only made two lines of code right now, but I don't know how to approach it.

python python3

2022-09-21 12:45

1 Answers

smallest = None
smallestIdx = None
idx = 0

for c in inputString:
    if smallest == None:
        if c >= minLetter:
            smallest = c
            smallestIdx = idx
    else:
        if c > smallest:
            smallest = c
            smallestIdx = idx
    idx += 1

Let's assume that they're all lowercase letters. First of all, find the smallest one. One by one, compare it to the smallest, and if the one you took out this time is smaller, you call him the smallest.

If you understand this, it's easy to find the third little guy, just remember three and loop around.

You need to expand your thoughts a little more on counting, but it's not that different to change the counter by taking out one by one while looping around and comparing.


2022-09-21 12:45

If you have any answers or tips


© 2025 OneMinuteCode. All rights reserved.