Find the winner of a game where scores are given as a binary string in Python


Suppose we have one binary string representing the scores of a volleyball match, we have to find the winner of the match based on following conditions −

  • There are two teams play with each other and the team which scores 15 points first will be the winner except when both teams have reached to 14 points.

  • When both teams have reached 14 points at that time the team maintaining a lead of two points will be the winner.

From the given binary string, the 0 is representing team lose a point and 1 indicates team win a point. We have to check whether the team had won or lost the match.

So, if the input is like score = "1001100110111001110011011", then the output will be Team won

To solve this, we will follow these steps −

  • score_cnt := [0,0]

  • for i in range 0 to size of score, do

    • pos := ASCII of(score[i]) - ASCII of('0')

    • score_cnt[pos] := score_cnt[pos] + 1

    • if score_cnt[0] is same as n and score_cnt[1] − n - 1, then

      • return "Team lost"

    • if score_cnt[1] is same as n and score_cnt[0] < n - 1, then

      • return "Team won"

    • if score_cnt[0] is same as n - 1 and score_cnt[1] is same as n - 1, then

      • score_cnt[0] := 0

      • score_cnt[1] := 0

      • come out from the loop

  • i := i + 1

  • for i in range i to size of score, do

    • pos := ASCII of(score[i]) - ASCII of('0')

    • score_cnt[pos] := score_cnt[pos] + 1

    • if |score_cnt[0] - score_cnt[1]| is same as 2, then

      • if score_cnt[0] > score_cnt[1], then

        • return "Team lost"

      • otherwise,

        • return "Team won"

Example

Let us see the following implementation to get better understanding −

 Live Demo

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 "Team lost"
      if (score_cnt[1] == n and score_cnt[0] < n - 1):
         return "Team won"
      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 "Team lost"
         else:
            return "Team won"
score = "1001010101111011101111"
n = 15
print(predictWinner(score, n))

Input

"1001010101111011101111"

Output

Team won

Updated on: 27-Aug-2020

148 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements