def closest(s, queries):
for query in queries:
c = s[query]
for i in s[query:]:
if s[i] == c:
return i
else:
return -1
在上面的代码中,我有一个字符串s
=“ abcaccba”(例如),并且我有一个索引数组,查询= [1, 3, 2]
。我正在尝试在这些索引处找到最接近的字符。
例如:s[1] = b
,第二个b出现的最接近的索引是6。当我尝试运行上面的代码时,出现此错误:
File "solution.py", line 23, in closest
if s[i] == c:
TypeError: string indices must be integers
我在这里做什么错了?
答案 0 :(得分:0)
i
已经是字符串中的字符。您只需要将s[i]
更改为i
并计算字符的位置即可。
def closest(s, queries):
for query in queries:
c = s[query]
for i in s[query:]:
if i == c: # i is a char , i = s[position]
print( i,(s[query+1:].index(i)+query+1) )
break
else:
pass
s = "abcaccba"
queries = [1, 3, 2]
closest(s, queries)
答案 1 :(得分:0)
您遇到的错误是因为i
是string
,但是索引必须是integers
。 (这应该从错误消息中清除)。将段if s[i] ==c:
更改为if i == c:
可以使您的代码运行,但是我认为它不会给您真正想要的答案。
由于您希望使用字符与查询索引相同的最接近索引,因此我认为您应该获得结果列表,该列表的长度应等于您的len
gth queries
。以下是一些可以帮助您实现该目标的代码。我还扩展了您的示例,以增进理解。
s = "abcaccba"
queries = [1,3,2,0, 5]
def closest(s, queries):
print('String: ', s)
print('Query: ', queries)
results = []
for query in queries:
c = s[query]
if s[query] in s[query+1 :]:
results.append(('query = {}'.format(query), 'character = {}'.format(c), 'index of next occurrence = {}'.format(1+query+s[query+1 :].index(c))))
#results.append((query, c, 1+query+s[query+1 :].index(c)))
else:
results.append(('query = {}'.format(query), 'character = {}'.format(c), 'index of next occurrence = {}'.format(-1)))
#results.append((query, c, -1))
return results
closest(s = s, queries = queries)
这是输出
String: 'abcaccba'
Query: [1, 3, 2, 0, 5]
[('query = 1', 'character = b', 'index of next occurrence = 6'),
('query = 3', 'character = a', 'index of next occurrence = 7'),
('query = 2', 'character = c', 'index of next occurrence = 4'),
('query = 0', 'character = a', 'index of next occurrence = 3'),
('query = 5', 'character = c', 'index of next occurrence = -1')]
答案 2 :(得分:0)
您可以使用find()
字符串方法来查找字符串中的字符位置。
查看每个query
索引字符前面和后面的字符串段。然后使用它们的相对位置来确定它们在s
中的真实索引。
s = "abcaccbaz"
queries = [1, 3, 2, 0, 5, 6, 8]
closest = []
for q in queries:
char = s[q]
pre = s[:q][::-1] # reversed, so nearest character to char is first
post = s[q+1:]
pre_dist = pre.find(char)
pre_found = pre_dist >= 0
post_dist = post.find(char)
post_found = post_dist >= 0
if post_found and (post_dist <= pre_dist or not pre_found):
closest.append(post_dist + len(pre) + 1)
elif pre_found and (pre_dist <= post_dist or not post_found):
closest.append(q - pre_dist - 1)
else:
closest.append(None)
closest
# [6, 0, 4, 3, 4, 1, None]
我添加了一个额外的大写字母z
,以涵盖该字符没有其他实例的情况。在这种情况下,过程将返回None
。