返回数组中数字的总和,但忽略以6开头并扩展到下一个7的数字部分(每6个字符后至少跟7个数字)。没有数字则返回0。
def sum67(nums):
for i in range(len(nums)):
if nums[i] == 6:
nums[i] = 0
for j in range(len(nums)):
if nums[j] == 7:
nums[j] =0
nums[i:j+1] = 0
return sum(nums)
答案 0 :(得分:0)
def sum67(nums):
result = 0
skip = False
for num in nums:
if not skip:
if num == 6:
skip = True
else:
result += num
elif skip and num == 7:
skip = False
return result
if __name__ == '__main__':
assert sum67([1, 2, 2]) == 5
assert sum67([1, 2, 2, 6, 99, 99, 7]) == 5
assert sum67([1, 1, 6, 7, 2]) == 4
assert sum67([1, 6, 2, 2, 7, 1, 6, 99, 99, 7]) == 2
assert sum67([1, 6, 2, 6, 2, 7, 1, 6, 99, 99, 7]) == 2
assert sum67([2, 7, 6, 2, 6, 7, 2, 7]) == 18
assert sum67([2, 7, 6, 2, 6, 2, 7]) == 9
assert sum67([1, 6, 7, 7]) == 8
assert sum67([6, 7, 1, 6, 7, 7]) == 8
assert sum67([6, 8, 1, 6, 7]) == 0
assert sum67([]) == 0
assert sum67([6, 7, 11]) == 11
assert sum67([11, 6, 7, 11]) == 22
assert sum67([2, 2, 6, 7, 7]) == 11
答案 1 :(得分:0)
我刚刚开始学习编程。这就是我如何解决您分享的问题。
def sum67(nums):
sum = 0
pos6 = []
pos7 = []
if len(nums) == 0:
return 0
elif len(nums) == 1:
return nums[0]
else:
# first identifying the positions of 6s and 7s in the array "nums"
for i in range(len(nums)):
if nums[i] == 6:
pos6 = pos6 + [i]
for i in range(len(nums)):
if nums[i] == 7:
pos7 = pos7 + [i]
# ignoring the 7s that appears before the 1st 6 (To be added to final sum)
if len(pos6) > 0:
for i in range(len(pos7)):
if pos6[0] > pos7[0]:
pos7 = pos7[1:]
# ignoring the 7s that are not pairable with any 6
if len(pos7) > len(pos6):
pos7 = pos7[:len(pos6)]
# replacing every digit between 6 and 7 (including 6 & 7) with 0
for i in range(len(pos6)):
var1 = 0
while var1 <= (pos7[i]-pos6[i]):
nums[pos6[i] + var1] = 0
var1 += 1
# adding all the values within the array
for i in range(len(nums)):
sum = sum + nums[i]
return sum