首页 > 解决方案 > 优化python代码以避免运行时错误

问题描述

给定一个可能多次出现相同字符的字符串,返回字符串中任何指定字符的最接近的相同字符。

给定查询的字符串sn数量。在每个查询中,您都会获得一个字符的索引a(where 0 <= a <= |s|),并且您需要打印壁橱相同字符的索引。如果有多个答案,请打印最小的一个。否则,打印-1.

例如,字符串s = 'youyouy',对于给定的查询3:在索引 0 和 6 处有两个匹配字符,每个字符相距 3,我们选择最小的一个,即 0。

这是我的计划:我将字符串放在字典中,键是字符串中不同的字母,值是字母对应的索引。当给定查询时,在字典中找到对应的字母并返回最接近查询的值。

def closest(s, queries):
    res = []
    dict2={}

     #dict2 - letter - indexs
    for i in range(len(s)):
       if s[i] not in dict2:
           dict2[s[i]]=[i]
       else:
           dict2[s[i]].append(i)

    for num in queries:
         #closet- denotes closet letter index
        closet = math.inf
        #num is out of range , append -1
        if num > (len(s)-1):
            res.append(-1)
            continue
        #this is the only one letter, append -1 
        letter=s[num]
        if len(dict2[letter])==1:
            res.append(-1)
            continue
        #temp = list for that letters    
        temp=dict2[s[num]]
        index=temp.index(num) . #in the list, letter index's index in list

        if index==0:
            closet=temp[1]
        elif index==(len(temp)-1):
            closet=temp[index-1]
        else:
            distance1=num-temp[index-1] .   #left
            distance2=temp[index+1]-num .   #right
            if distance1 <= distance2:
                closet=temp[index-1]
            else:
                closet=temp[index+1]

        if closet == math.inf:
            res.append(-1)
        else:
            res.append(closet)
    return res  

我有两个运行时错误。我想知道您是否可以帮助我减少一些运行时间?

另外,我正在寻找其他建议!我用 Python 有一段时间了,正在找工作(大学应届毕业生)。java通常比Python运行得快吗?我应该切换到Java吗?

标签: pythonarraysstringalgorithmdictionary

解决方案


我试着做尽可能简单,但我看起来有点复杂。尽管您的问题是避免运行时错误,但我想提出我的想法

s='oooyyouoy'
k='0123456789'
def cloest(string,pos):
    c = string[pos]
    p1 , p2 = s[:pos] , s[pos+1:]

    # reserve left part and find the closet one , add 1 because len(p1)=final_position + 1
    l = len(p1) - (p1[::-1].find(c) + 1) 
    # find without reserve and add 1 because s[pos+1:]
    r = (p2.find(c) + 1) + pos 

    # judge which one is closer if same chose left one
    result = l if (pos - l) <= (r - pos) else r 
    if result == pos:
        return -1
    else:
        return result

print(cloest(s,4))

推荐阅读