简体   繁体   English

如何在python中优化for循环?

[英]How to optimize for loop in python?

I was trying to roll the character string in python Example : s='abz' roll=[3,2,1]我试图在 python 中滚动字符串示例:s='abz' roll=[3,2,1]

  1. roll[0]=abz become bca roll[0]=abz 变成 bca
  2. roll[1]= bca becomes cda roll[1]= bca 变成 cda
  3. roll[2]= cda becomes dda I want to return dda roll[2]= cda 变成 dda 我要返回 dda
for i in roll:           
     s = ''.join([letters[(letters.index(c)+1)%len(letters)] for c in s[:i]]) + s[i:]
    
 return s

few test cases are failing on hackerrank due to time constraints, could someone please help me in optimizing this code.由于时间限制,很少有测试用例在hackerrank上失败,有人可以帮助我优化此代码。

I think you want ord() , which is the inverse of chr() ;我想你想要ord() ,它是chr()的倒数; once your char is a number, it's easier to +1 (don't forget to wrap)一旦你的字符是一个数字,就更容易+1(不要忘记换行)

then use a method to process each string (call this fn in a loop - once per word):然后使用一种方法来处理每个字符串(在循环中调用这个 fn - 每个单词一次):

def increment(in_str):
  # loop over each letter
  for idx in range(0,len(in_str)):
    # convert to a number
    char_val = ord(in_str[idx])
    if char_val == ord("z"):
      # if 'z' - replace with 'a'
      in_str[idx] = chr("a")
    else:
      # otherwise +1 and convert back to char
      in_str[idx] = chr(char_val + 1)

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

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