gpt4 book ai didi

Python 数组中数字的总和,忽略特定数字的部分

转载 作者:行者123 更新时间:2023-12-01 00:29:09 50 4
gpt4 key购买 nike

我对 Python 非常陌生,并且已经阅读了多个教程来变得更好。

我曾被一个难题困扰并找到了解决方案。但感觉,工作起来很像新手。我认为我已经对其进行了定制以回答特定问题。

所以问题是:

SUMMER OF '69:返回数组中数字的总和,但忽略以 6 开头并延伸到下一个 9 的数字部分(每个 6 后面至少有一个 9)。如果没有数字则返回 0。

summer_69([1, 3, 5]) --> 9
summer_69([4, 5, 6, 7, 8, 9]) --> 9
summer_69([2, 1, 6, 9, 11]) --> 14

我解决这个问题的代码是:

def summer_69(arr):
list1 = arr
summ = int()
for i in range(0, len(arr)):
if 6 in list1:
listOfRange = range(list1.index(6), list1.index(9) + 1)
for index in listOfRange:
print(listOfRange)
arr[index] = 0
if 6 != arr[i]:
summ += arr[i]
else:
continue
else:
summ += arr[i]
return summ

这是一个非常基本的问题,我非常警惕,我已经在类似的问题上苦苦挣扎了。

最佳答案

短 O(n) 解决方案,使用迭代器和 in 运算符来搜索(从而跳至)每个 6 之后的 9:

def summer_69(lst):
it = iter(lst)
return sum(x for x in it
if x != 6 or 9 not in it)

密度较低的版本:

def summer_69(lst):
it = iter(lst)
total = 0
for x in it:
if x == 6:
9 in it
else:
total += x
return total

正确性检查(随机测试用例)和基准(使用 [1] * 5000 + [6, 9] * 2500)使用接受的答案的解决方案(需要 O(n2)):

30 out of 30 tests correct

303045 us 303714 us 304335 us 306007 us 309986 us summer_69_Accepted
444 us 446 us 464 us 478 us 527 us summer_69_Kelly1
442 us 448 us 453 us 465 us 500 us summer_69_Kelly2

代码(Try it online!):

from timeit import repeat

def summer_69_Accepted(lst):
copyoflist = lst[:] # makes shallow copy of list
while True:
if 6 not in copyoflist:
return sum(copyoflist)

indexof6 = copyoflist.index(6)
indexof9 = copyoflist.index(9, indexof6+1) # begin search for 9 after 6
del copyoflist[indexof6:indexof9+1]

def summer_69_Kelly1(lst):
it = iter(lst)
return sum(x for x in it
if x != 6 or 9 not in it)

def summer_69_Kelly2(lst):
it = iter(lst)
total = 0
for x in it:
if x == 6:
9 in it
else:
total += x
return total

funcs = summer_69_Accepted, summer_69_Kelly1, summer_69_Kelly2

from random import randrange, choices

def testcase():
def others():
return choices([0, 1, 2, 3, 4, 5, 7, 8], k=randrange(10))
lst = others()
for _ in range(10):
lst += [6, *others(), 9, *others()]
return lst

tests = correct = 0
for _ in range(10):
lst = testcase()
expect = funcs[0](lst.copy())
for func in funcs:
result = func(lst.copy())
correct += result == expect
tests += 1
print(correct, 'out of', tests, 'tests correct')
print()

lst = [1] * 5000 + [6, 9] * 2500
for func in funcs:
times = repeat(lambda: func(lst), number=1)
print(*('%6d us ' % (t * 1e6) for t in sorted(times)), func.__name__)

关于Python 数组中数字的总和,忽略特定数字的部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58325254/

50 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com