我正在尝试创建一段代码,用于观察计数器的输出,如:
a1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30]
我希望代码能够统计总数,并告诉我遗漏了多少计数,例如,如果发生这种情况:
a1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12,13,14,15,16,17,18,19,20,21,22,23,24, 25, 26, 5, 6, 7, 8, 9, 10, 11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,1,2]
我会得到总共92个,但得到的反馈是8个缺失
我已经非常熟悉以下代码:
Blk_Tot = 0
CBN = 0
LBN = 0
x = 0
y = 0
z = 0
MissedBlocks = 0
for i in range(len(a1)):
CBN = a1[i]
if CBN - LBN <= 0:
if LBN == 30:
y = 30 - abs(CBN - LBN)
elif LBN < 30:
z = 30 - LBN
y = 30 - abs(CBN - LBN) + z
print(z)
Blk_Tot = Blk_Tot + y
else:
x = CBN - LBN
Blk_Tot = Blk_Tot + x
if x > 1:
MissedBlocks = MissedBlocks - 1 + x
LBN = CBN
print(Blk_Tot)
print(MissedBlocks)
如果我删除1到30之间的任何一个,它都能很好地工作,但是如果我删除30,比如说29,30,1,2,它就会中断。我不希望它能够连续删除30个,并且仍然能够得到一个合适的总数
有人对如何实现这一目标有什么想法吗?我觉得我错过了一个显而易见的答案:D
对不起,我想我不清楚,a1是一个来自外部设备的计数器,它从1计数到30,然后再绕到1。每个计数实际上是消息的一部分,以表明消息已被接收;比如说12 4,我知道第三条信息不见了。我想做的是找出应该收到的总数,以及从计数中漏掉多少
更新以下帖子中的想法后,另一种方法可能是:
输入:
123456
清单[1,2,3,4,5,6]
1.检查第一个输入,查看它在列表的哪个部分,然后从那里开始(如果我们不是从零开始)
2.每次接收到输入时,检查是否与数组中的下一个值匹配
3.如果没有,那么需要多少步骤才能找到该值
一般来说,如果要计算两个列表之间的差异数量,可以很容易地使用字典。另一个答案也可以,但对于稍微大一点的列表来说,它效率很低
用于检查重复序列模式中缺少元素的新代码
现在我已经更清楚地理解了你的问题,下面是代码。此代码中的假设是列表将始终按从1到30的升序排列,然后从1开始再次重复。在1和30之间可能会缺少元素,但在1和30之间的顺序将始终是升序
如果源数据如列表
a1
所示,那么代码将导致8
缺少元素其输出将为:
如果这能解决您的问题,请告诉我
比较两个列表的早期代码
不能使用
set
,因为这些项是重复的。因此,您需要sort
它们,并找出每个元素在两个列表中的次数。差额将为您提供缺少的计数。您可以在a1
中有一个元素,但在a2
中没有,反之亦然。因此,找出丢失项目的绝对计数将给出结果在下一次更新中,我将使用更好的变量更新响应
我是这样做的:
带注释的代码:
此操作的输出为:
如果您想找出缺少哪些元素,那么需要再添加几行代码
在上面的示例中,元素
27,28,29,30, 4, 5
在a2
中缺失,元素31
在a1
中缺失。所以缺失元素的总数是7
无注释代码:
如果你超过了30线,你不需要跟踪
只需与理想序列进行比较,并计算缺失的数字
不知道最后是否缺少零件
如果一个块中缺少30多个零件,则不知道
编辑
循环部分可以简单一点
相关问题 更多 >
编程相关推荐