使用简单数组进行全周期和半周期计算



我的程序接受随机数组输入,其中数组具有0-n的整数值和字母";M〃;其代表标记。基于这个数组,我必须确定数组中有多少个循环。输入为

[M,1,2,3,4,5,6]=半周期

[M,1,2,3,4,5,6,M]=一个全周期

[1,2,3,4,5,M]=半周期

[1,2,3,4]=半周期

[M,1,2,3,4]=半周期

[M,1,2,3,4,M,6]=一个完整和一个半周期

[M,1,2,3,4,M,6,7,8,M]=两个完整周期

[M,1,2,3,4,M,6,7,8,M,M,9]=两个完整周期和一个半周期

如何为这种逻辑编写代码?

要回答这个问题,你需要构建你的想法。让我们先把你的单子重新整理一下。

首先不要看"一个半周期"组。

[M,1,2,3,4,5,6] = One half cycle
[1,2,3,4,5,M] = One half cycle
[1,2,3,4] = One half cycle
[M, 1,2,3,4] = One half cycle

正如你所看到的,他们共享一些属性。它们最多有零个或一个M。这个标准足以识别它们。我们稍后再看。

"一个完整"组的列表中有两个"M"。尽管如果"M"不是最后一个,我们需要添加"和一个半周期"。

[M,1,2,3,4,5,6,M] = One full cycle
[M,1,2,3,4,M,6] = One Full and one halfcycle

两个以上的"M"以"两个满"结尾。再次,如果"M"不是最后一个,我们需要添加"半周期"。

[M,1,2,3,4,M,6,7,8,M] = Two Full Cycles
[M,1,2,3,4,M,6,7,8,M,M,9] = Two Full Cycles and a half cycle

我们如何实现这一点?我们需要计算各个例子中"M"的个数。给定列表:

a=["M",1,2,3,4,5,6]

你可以使用:

a.count("M")

在列表"a"上,它将返回1。

现在,对于所有的情况,我们都可以编写一个简单的例程。请阅读代码中的注释。

def find_cycles(alist):
# we define the events, half, one or two cycle
ares=["One half cycle", "One full cycle", "Two full cycle"]
half=" and one half cycle"
# here we count the number of "M" in the list
indices = alist.count("M")
# we define a counter "r" that will be used in "ares"
r=-1
# zero or one "M" are the "one half cycle"
if(indices==0 or indices==1):
r=0
# two "M" are the "One full cycle"
elif(indices==2):
r=1
# more than two "M" are "Two full cycle"
elif(indices>2):
r=2
### BUT we need to check if there is an "halfcycle" more
### in the case where there are more than 1 M
### to do this we need to check that the last element
### in our array is not a "M" and we r should be different than 0
if(alist[-1]!="M" and r!=0):
return(ares[r]+half)
else:
return(ares[r])

现在测试一下(注意M需要引号(:

a=["M",1,2,3,4,5,6]
b=[1,2,3,4,5,"M"]
c=[1,2,3,4]
d=["M", 1,2,3,4]
e=["M",1,2,3,4,5,6,"M"]
f=["M",1,2,3,4,"M",6]
g=["M",1,2,3,4,"M",6,7,8,"M"]
h=["M",1,2,3,4,"M",6,7,8,"M","M",9]
all_lists=[a,b,c,d,e,f,g,h]
for i in all_lists:
print(find_cycles(i))

输出:

One half cycle
One half cycle
One half cycle
One half cycle
One full cycle
One full cycle and one half cycle
Two full cycle
Two full cycle and one half cycle

请记住,这只适用于您给出的示例。更多的"M"都将以"两个完整周期"结束。从这个问题来看,不清楚你是否想推广到两个以上的完整周期。

最新更新