简体   繁体   English

用它后面的第一个更大的字符替换每个字符

[英]replace each character with the first greater character after it

I am trying to replace each character with the next greater character after it and if there is no greater character after it then replace it by '#'我试图用它后面的下一个更大的字符替换每个字符,如果它后面没有更大的字符,那么用'#'替换它

if I have a circular list of characters [K, M, Y, R, E, J, A] the output should be [M, Y, #, Y, J, K, K]如果我有一个循环的字符列表[K, M, Y, R, E, J, A] output 应该是[M, Y, #, Y, J, K, K]

'M is greater than k so replace K with M and Y is greater than M so replace M with Y and so one ( greater here means comes after it )' 'M 大于 k,所以用 M 替换 K,Y 大于 M,所以用 Y 替换 M,所以 1(这里更大的意思是在它之后)'

this is the code that I have tried but it gives wrong output这是我尝试过的代码,但它给出了错误的 output

def que1(input_list):
for i in range (len (input_list)-1) :
    j=i+1
    for j in range (len(input_list)-1):
        
     if input_list[i]<input_list[j]:
        input_list[i]=input_list[j]
        
        
     if input_list[i]>input_list[j]:
         input_list[i]='@'

return input_list

    

The following code should do what you want.下面的代码应该做你想做的事。

def que1(input_list):
output_list = []

# loop through the input list with index
for index, c in enumerate(input_list):

    # split list at c and create new list
    # [all greater characters after c, all greater character before c]
    tmp = [i for i in input_list[index:] if i > c] + [i for i in input_list[:index] if i > c]

    # if list empty there is no greater character
    if len(tmp) == 0:
        output_list.append('#')
    # else choose the first greater character
    else:
        output_list.append(tmp[0])

return output_list

Input: ['K', 'M', 'Y', 'R', 'E', 'J', 'A']输入:['K', 'M', 'Y', 'R', 'E', 'J', 'A']

Output: ['M', 'Y', '#', 'Y', 'J', 'K', 'K'] Output:['M','Y','#','Y','J','K','K']

Another way to do it:另一种方法:

def que1(i_list):
    input_list=i_list*2
    output_list=[]

    for i in range (len (i_list)) :
        found=False
        for j in range (i+1,len(input_list)-1):
            if input_list[i]<input_list[j]:
                output_list.append(input_list[j])
                found=True
                break      
              
        if not found:
            output_list.append('#')

    return output_list

output: output:

['M', 'Y', '#', 'Y', 'J', 'K', 'K']

Here is another way to do it.这是另一种方法。

def next_greatest(data):
    out = []
    for idx in range(len(data)):
        char = data[idx]
        cs = iter(data[idx + 1:] + data[:idx])
        while True:
            try:
                curr = next(cs)
            except StopIteration:
                out.append("#")
                break
            if curr > char:
                out.append(curr)
                break
    return out

next_greatest(chars)
>> ['M', 'Y', '#', 'Y', 'J', 'K', 'K']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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