【问题标题】:Optimize python code to avoid runtime error优化python代码以避免运行时错误
【发布时间】:2019-04-07 16:15:14
【问题描述】:

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

给定字符串sn 的查询数。在每个查询中,您都会获得一个字符的索引a(其中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吗?

【问题讨论】:

  • 您的运行时错误是什么?
  • @HåkenLid 。他们只是告诉我由于运行时错误而终止,没有其他任何东西
  • @Robin 我不是说你要进一步缩短变量名;而是给他们起真正意味着某事的名字。你能发布squeries 来测试函数吗?
  • @Robin 可读名称不会立即解决您正在寻找的错误,但它们帮助您和其他人了解您的想法和代码,从而使其他人更容易帮助您。让可理解的标识符成为您永远不会打破的习惯,即使是最脆弱的任务也不例外。
  • 我很好奇:是什么让您得出它可能与速度有关的结论? “运行时错误”确实指向执行时间,它指向您没有想出的输入值的错误。

标签: python arrays string algorithm dictionary


【解决方案1】:

我正在尝试尽可能简单,但我看起来有点复杂。虽然你的问题是避免运行时错误,但我想提出我的想法

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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-22
    • 2013-04-06
    • 2014-09-20
    • 2010-11-14
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多