Sword finger offer: playing card shunzi (Python)

Title Description

LL is in A good mood today, because he bought A deck of playing cards and found that there are two kings and two Xiao Wang in it He randomly took out five cards from them and wanted to test his luck to see if he could get A good luck. If he did, he decided to buy sports lottery, hehe!! "Hearts A, spades 3, Wang, Wang, square 5", "Oh My God!" is not shunzi ... LL is not happy. He thinks about it. He decides that big / small Wang can be regarded as any number, and A is regarded as 1,J as 11,Q as 12, and K as 13. The five cards above can be changed into "1,2,3,4,5" (big and small kings are regarded as 2 and 4 respectively), "So Lucky!". LL decided to buy A sports lottery. Now, ask you to use this card to simulate the above process, and then tell us how lucky LL is. For the sake of convenience, you can think that the king of size is 0.

Solving problems

Train of thought 1: hard solution

def IsContinuous(self, numbers):
    if not numbers:
        return False
    numbers.sort()
    zeroNums = 0
    for i in range(len(numbers) - 1):
        if numbers[i] == 0:
            zeroNums += 1
        elif 0 < numbers[i + 1] - numbers[i] <= zeroNums + 1:
            zeroNums -= (numbers[i+1] - numbers[i] -1)
        else:
            return False
    return True

Train of thought 2:
Two conditions are satisfied.
1. Number without repetition except 0
2. max - min < 5

def IsContinuous(self, numbers):
    min, max, flag = 14, -1, 0
    if len(numbers) != 5: return False
    for num in numbers:
        if num == 0: continue
        if (flag>>num)&1 == 1: return False#Use binary bits to determine whether there is a digit repetition
        flag = flag | (1<<num)
        if num > max: max = num
        if num < min: min = num
        if max - min >= 5: return False
    return True

If you do not understand one of the above codes, compare the following codes. This code is a "code description" of the above code.

def IsContinuous(self, numbers):
    min, max, flag = 14, -1, 0
    if len(numbers) != 5: return False
    for i in range(len(numbers) - 1):
        if numbers[i] == 0:continue
        if numbers[i] in numbers[:i]+numbers[i+1:]: return False

        if numbers[i] > max: max = numbers[i]
        if numbers[i] < min: min = numbers[i]
        if max - min >= 5: return False
    return True

Posted by zachrose on Mon, 30 Mar 2020 14:17:33 -0700