def sum_except_between_6_and_9(sequence):
"""
:param sequence: a list of numbers
:return: the sum of numbers excluding those between 6 and 9
"""
if 6 not in sequence or 9 not in sequence:
# 如果数列中没有6或9,直接返回所有数字之和
return sum(sequence)
# 找到6和9第一次出现的位置
start_index = sequence.index(6)
end_index = sequence.index(9)
# 判断6和9的位置关系
if start_index < end_index:
# 如果6在9前面,删除6到9之间的数
del sequence[start_index:end_index+1]
else:
# 如果9在6前面,则需要反转数列,再做同样的操作
sequence.reverse()
start_index = sequence.index(6)
end_index = sequence.index(9)
del sequence[start_index:end_index+1]
sequence.reverse()
# 计算除6和9之间的数字之和
return sum(sequence)
示例:
>>> sum_except_between_6_and_9([1, 2, 3, 4, 5, 6, 7, 8, 9])
15
>>> sum_except_between_6_and_9([1, 2, 3, 4, 5, 7, 8, 9])
29
>>> sum_except_between_6_and_9([1, 2, 3, 6, 7, 9, 4, 5, 8])
15
>>> sum_except_between_6_and_9([1, 2, 6, 3, 4, 5, 7, 8, 9])
6