我需要用Python来解决一个问题。我可以不用代码解决这个问题,如果你搜索互联网,答案是公开的。我很难用我的代码来解决这个问题。无论如何,这里有一个问题:
史蒂夫写了数字1,2,3,4和5,顺序从左到右,形成了一个10,000位数的列表,从123451234512开始.然后他从他的名单中抹去每三位数字(即第三、第六、第九、.从左边的数字),然后从结果列表(即第4,8,12,.从左边留下的数字),然后从剩下的每五个数字中抹去一个数字。2019年、2020年、2021年的三位数之和是多少?
我已经写出了python代码,将所有的数字打印到一个列表中。我需要弄清楚如何去除每一个第9位数字。
list = []
value = 1
for i in range (10000):
list.append (value)
value = value + 1
if value == 6:
value = 1这就是写出前10,000位数字的代码。
在上一堂课中,我写了一个代码来删除每一个第n项并打印出来。该代码如下所示:
n = 3
def RemoveThirdNumber(int_list):
pos = n - 1
index = 0
len_list = (len(int_list))
while len_list > 0:
index = (pos + index) % len_list
print(int_list.pop(index))
len_list -= 1
nums = [1, 2, 3, 4]
RemoveThirdNumber(nums)
print(list)我需要帮助更改代码,所以它会在列表中删除第三个项,并打印出其余的数字。
所以这意味着,而不是输出
3
2
4
1它将是
[1,2,4]谢谢你的帮助!
发布于 2021-01-04 22:00:41
这是我想出的解决方案。我不喜欢把每个片段转换成一个元组,只需要从迭代器中消费,并且让chunk可能等同于falsey。也许有人可以看看,如果我在什么地方出了错,可以告诉我吗?或者只是建议其他可爱的itertools食谱。显然,三位数之和是10
from itertools import cycle, islice
digits = islice(cycle([1, 2, 3, 4, 5]), 10000)
def skip_nth(iterable, n):
while chunk := tuple(islice(iterable, n)):
yield from islice(chunk, n-1)
sum_of_digits = sum(islice(skip_nth(skip_nth(skip_nth(digits, 3), 4), 5), 2019, 2022))
print(sum_of_digits)输出:
10根据Matthias的建议编辑:
def skip_nth(iterable, n):
yield from (value for index, value in enumerate(iterable) if (index + 1) % n)发布于 2021-01-04 22:04:33
a = [1,2,3,4,5] * (10000//5)
a = [a[i] for i in range(len(a)) if i%3 != 2]
a = [a[i] for i in range(len(a)) if i%4 != 3]
a = [a[i] for i in range(len(a)) if i%5 != 4]
print(a[2019:2022]) # --> [2, 5, 3]
print(sum(a[2019:2022])) # --> 10发布于 2021-01-04 21:51:27
只测试了100。
bigList = []
value = 1
for i in range (100):
biglist.append(value)
value += 1
if value == 6:
value = 1# if you print here you get [1,2,3,4,5,1,2,3...]
x = 3
del biglist[x-1::x] #where x is the number of "steps" - in your case 3
# if you print here - biglist ==> 1,2,4,5,2,3 etc.. https://stackoverflow.com/questions/65570212
复制相似问题