简体   繁体   中英

smallest letter greater than target

I have written a code with the intention of returning the smallest letter after the target letter h , so in this case, it is i . However, the code below does not produce an output. Any ideas? I have a feeling the problem lies in the first if statement.

letters = [
    'a',
    'b',
    'c', 'c', 'c', 'c',
    'd',
    'e', 'e', 'e',
    'g',
    'h', 'h', 'h',
    'i',
    'j',
    'k', 'k', 'k',
    'l',
    'm',
    'n',
    'o',
    'p', 'p', 'p',
    'q',
    'r',
    's', 's',
    't'
]

target = 'h'
left = 0
right = len(letters) - 1
mid = left + (right - left) // 2

while left < right:
    if mid == target:
        for i in range(letters[mid], letters[len(letters)]):
            if letters[i] != target:
                print(letters[i])
                break

    if letters[mid] < target:
        left = mid + 1
    elif letters[mid] > target:
        right = mid - 1
letters =     ['a','b','c','c','c','c','d','e','e','e','g','h','h','h','i','j','k','k','k','l','m','n','o','p','p','p','q','r','s','s','t']

target = 'h'

# Find only after target
letters = letters[letters.index(target):]

# Remove target from list
letters = [x for x in letters if x != target]

# Sort list
letters.sort()

# Find char representation of lowest
print(letters[0])

If you like one-liner

letters[len(letters) - letters[::-1].index('h')]

The code gets the index of the first letter 'h' from the reversed list, and use it to find the first one after the letter 'h'

right = len(letters) -1
This will always return the same answer, as it always counts the number of letters in the array:

https://www.w3schools.com/python/ref_func_len.asp

Another Solution

An OrderedDict can be used to create the ordered unique list and this list can be used to get the target element index.

from collections import OrderedDict
ordered_unique_list=list(OrderedDict.fromkeys(letters))
print(ordered_unique_list[ordered_unique_list.index(target)+1])

Output

i

This would do the job;)

letters = ['a', 'b', 'c', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'g', 'h', 'h', 'h', 'i', 'j', 'k', 'k', 'k', 'l', 'm', 'n',
       'o', 'p', 'p', 'p', 'q', 'r', 's', 's', 't']

target = 'h'
left = 0
right = len(letters) - 1
mid = (left + right) // 2

while left <= right:
    if letters[mid] == target:
        for i in range(mid, len(letters)):
            if letters[i] != target:
                print(letters[i])
                break
        break

    if letters[mid] < target:
        left = mid + 1
    elif letters[mid] > target:
        right = mid - 1

    mid = (left + right) // 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM