求解数组任务python

2024-09-30 01:30:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我在下面有一个数组,包含每天奶牛的总产量。你知道吗

[5, 3, 7, 9, 3, 3, 7, 108, 66, 16, 5, 3, 7, 3]

牛群中有两头奶牛,它们一天挤奶两次,因此我的数组中有14个元素,每个元素代表一天的总产奶量,因此每个元素有7个元素对应7天的总产奶量。你知道吗

我的数组的格式是。你知道吗

[Cow1Day1, Cow1Day2, Cow1Day3, Cow1Day4, Cow1Day5, Cow1Day6, Cow1Day7, Cow2Day1, Cow2Day2, Cow2Day3, Cow2Day4, Cow2Day5, Cow2Day6, Cow2Day7]

我需要找出哪头牛在4天或更长的时间里产量低于12升。我该怎么做?你知道吗

注意:我甚至可以在我的牛群中拥有更多的牛,这取决于用户的输入。你知道吗


Tags: 元素格式代表数组奶牛总产量产奶量cow1day2
2条回答

试试这个:

yields = [5, 3, 7, 9, 3, 3, 7, 108, 66, 16, 5, 3, 7, 3]
numOfCows = int(len(yields) / 7)       ## /7 as there are 7 days in a week

for i in range(numOfCows):   ## For every cow
    for j in range(4):       ## There are four possible spans to be checked
        span = yields[ (i * 7) + j  :  (i * 7) + j + 4 ]    ## Get the four-day period
        if sum(span) < 12:   ## If the sum of the span is smaller than 12 litres
            print("Cow " + str(i + 1))    ## Print the cow number
data = [5, 3, 7, 9, 3, 3, 7, 108, 66, 16, 5, 3, 7, 3]

首先分割你的奶牛数据,得到每头奶牛每周产量的单独列表,如下所示:

cows = [data[x:x+7] for x in range(0, len(data), 7)]

输出:

[[5, 3, 7, 9, 3, 3, 7], [108, 66, 16, 5, 3, 7, 3]]

现在,对于每头母牛,计算出任何4天窗口的总和是否小于12:

bad_yields = [any([sum(cow[n:4+n])<12 for n in range(len(cow)-4+1)]) for cow in cows]

输出:

[False, False]

最后,打印出产量低于12头的奶牛

for idx, ylt12 in enumerate(bad_yields):
    if ylt12:
        print("Yield less than 12 for cow %d" % (idx + 1))

相关问题 更多 >

    热门问题