蟒2 - 239个 211 210字节
感谢@ mbomb007和@Cyoce为这个解决方案提供了更多帮助!
def r(s):
t=[]
for x in s.split("AND"):
if"T"in x:a=map(int,x.split("TO"));b=2*(a[0]<a[1])-1;t+=range(a[0],a[1]+b,b)
else:t+=int(x),
return t
lambda p,v:[(['']+p+['']*max(map(abs,r(v))))[x]for x in r(v)]
直截了当的方法。尝试了生成器和递归版本,但是它们无法在每个循环中都超越简单性。我是一个高尔夫菜鸟,所以很有可能会有所改善。而且,此代码段的主要缺陷在于,每次从字符数组中检索元素时,都会再次计算作为列表对象的范围(请参阅最后一行,列表理解)。这意味着r(s)
执行len(r(s)) + 1
时间。
取消程式码:
def find_range(string):
result = []
# Split at each AND and look at each element separately
for element in string.split("AND"):
# Element is just a number, so add that number to the result list
if "TO" not in string:
result += [int(string)]
# Generate a list with all the values in between the boundaries
# (and the boundaries themselves, of course) and append it to the result list
else:
boundaries = map(int, string.split("TO"))
ascending = boundaries[0] < boundaries[1]
# range(start, stop, step) returns [start, ..., stop - 1], so extend the stop value accordingly
# range(8, 3, 1) returns just [], so choose respective step (negative for a descending sequence)
result += range(boundaries[0], boundaries[1] + (1 if ascending else -1), 1 if ascending else -1)
# Make the char array 1-indexed by appending an empty char in 0th position
# Add enough empty chars at the end so too large and negative values won't wrap around
interpret = lambda chars, range_expr: [(['']+chars+['']*max(map(abs, find_range(range_expr))))[x] for x in find_range(range_expr)]
测试用例:
c = list("Hello World")
print interpret(c, "1 TO 3")
print interpret(c, "5")
print interpret(c, "-10 TO 10")
print interpret(c, "0 AND 2 AND 4")
print interpret(c, "8 TO 3")
print interpret(c, "-300 AND 300")
输出:
['H', 'e', 'l']
['o']
['', '', '', '', '', '', '', '', '', '', '', 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l']
['', 'e', 'l']
['o', 'W', ' ', 'o', 'l', 'l']
['', '']
"0 TO 2"
=>{'H', 'e', 'l'}
?