Why does my code not cover all cases? - Python 3 Casino Chips challenge in Codewars

Viewed 246

I'm a beginner in programming just started learning a couple of weeks ago. When I don't have much time, I go on codewars to grab something to think about how to solve, this time it was a casino challenge. I came up with something that felt like it would cover everything, but it still fails 4 cases out of 208, and I'm stuck.

Here's the challenge:

The challenge is called Casino Chips. There's 3 stacks of chips, white, green, black chips.

Every day you take exactly 2 chips, and they can't be the same color. I have to return the maximum amount of days i can take chips on these conditions. MUST take 2 each day, and they MUST be different colors.

Example: [1,2,1] <= (1white, 2 green, 1 black) => returns: 2 days. [4,1,1] => 2, [8,1,4] => 5 etc.

No Bruteforcing.

And here's my code

def solve(arr):
    arr.sort()
    s = arr[0] + arr[1]
    if arr == [1,1,1]:
        return arr[0]
    elif arr[0] + arr[1] <= arr[2]:
        return s
    elif arr[1] == arr[2] and arr[1] != arr[0]:
        m = arr[0] - 1 + arr[1]
        return m
    elif arr[0] == arr[1] and arr[0] == arr[2]:
        d = arr[0] / 2 + arr[1]
        return int(d)
    elif arr[0] + arr[1] > arr[2]:
        e = (arr[0] + arr[1] + arr[2]) / 2
        return int(e)

I've skipped math classes when I was small, which lead to not being able to keep up so my math knowledge is 0.

Any ideas what options my code doesn't cover, or does anyone know a formula for this that gets the job done? or how would you code it personally?

3 Answers

Your third case is wrong, one counter example is arr = [3, 4, 4]

What is more interesting however is that your cases 2 and 5 together cover all possibilities and solve them correctly already:

def solve(arr):
  arr.sort()
  s = arr[0] + arr[1]
  if s <= arr[2]: #your case 2
    return s
  else: #your case 5
    e = (arr[0] + arr[1] + arr[2]) / 2
    return int(e)

Here's a very simple recursive solution, might be easier to understand:

from typing import List

def casino(chips: List[int], days: int = 0) -> int:
    chips.sort(reverse=True)
    chigh, cmed, clow = chips
    if chigh == 0 or cmed == 0:
        # can't remove any more chips
        return days
    # remove one chip from the highest stack and one from the medium stack
    # advance to next day
    return casino([chigh-1, cmed-1, clow], days+1)

Here's one way that also allows the user to visualize the options:

white = ['white']*8
green = ['green']*1
black = ['black']*4
chips = white+green+black

l = []

while not all([a==b for a in chips for b in chips]):
    m1 = max(chips,key=lambda x:chips.count(x))
    m2 = max(chips,key=lambda x:[a for a in chips if a!=m1].count(x))
    chips.remove(m1)
    chips.remove(m2)
    l.append([m1,m2])

print(l)
print(len(l))

Output:

[['white', 'black'],
 ['white', 'black'],
 ['white', 'black'],
 ['white', 'green'],
 ['white', 'black']]
5
Related