在 Python 中,以二进制字符串的形式给出比分,找出比赛的获胜者
假设我们有一个二进制字符串表示一场排球比赛的比分,我们必须根据以下条件找出比赛的获胜者 −
有两支球队相互比赛,先得 15 分的球队获胜,除非两支球队的得分都达到 14 分。
当两支球队都达到 14 分时,领先两分的球队获胜。
从给定的二进制字符串中,0 表示球队失一分,1 表示球队赢一分。我们必须检查球队是赢了还是输了比赛。
因此,如果输入为 score = "1001100110111001110011011",则输出将是 Team won
要解决这个问题,我们将遵循以下步骤 −
score_cnt := [0,0]
对于范围从 0 到分数大小的 i,执行
pos := ASCII of(score[i]) - ASCII of('0')
score_cnt[pos] := score_cnt[pos] + 1
如果 score_cnt[0] 与 n 相同,则score_cnt[1] − n - 1,则
返回 "球队输了"
如果 score_cnt[1] 与 n 相同且 score_cnt[0] < n - 1,则
返回"球队赢了"
如果 score_cnt[0] 与 n - 1 相同,且 score_cnt[1] 与 n - 1 相同,则
score_cnt[0] := 0
score_cnt[1] := 0
退出循环
i := i + 1
对于 i 在 i 到分数大小的范围内,执行
pos := ASCII of(score[i]) - ASCII of('0')
score_cnt[pos] := score_cnt[pos] + 1
如果 |score_cnt[0] - score_cnt[1]| 与 2 相同,则
如果 score_cnt[0] > score_cnt[1],则
返回 "球队输了"
否则,
返回 "球队赢了"
示例
让我们看看下面的实现以便更好地理解 −
def predictWinner(score, n):
score_cnt = [0,0]
for i in range(len(score)):
pos = ord(score[i]) - ord('0')
score_cnt[pos] += 1
if (score_cnt[0] == n and score_cnt[1] < n - 1):
return "球队输了"
if (score_cnt[1] == n and score_cnt[0] < n - 1):
return "球队赢了"
if (score_cnt[0] == n - 1 and
score_cnt[1] == n - 1):
score_cnt[0] = 0
score_cnt[1] = 0
break
i += 1
for i in range(i, len(score)):
pos = ord(score[i]) - ord('0')
score_cnt[pos] += 1
if (abs(score_cnt[0] - score_cnt[1]) == 2):
if (score_cnt[0] > score_cnt[1]):
return "球队输了"
else:
return "球队赢了"
score = "1001010101111011101111"
n = 15
print(predictWinner(score, n))
输入
"1001010101111011101111"
输出
Team won
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

