0209leetcode brushes 5 python questions

Sword refers to offer60

Title description:
Throw n dice on the ground, and the sum of the points on the upward side of all dice is s. Enter n to print out the probabilities of all possible values ​​of s.
You need to use an array of floating-point numbers to return the answer, where the i-th element represents the probability of the i-th smallest in the set of points that can be thrown by the n dice.

Example:
Insert picture description here
Answer:

class Solution:
    def dicesProbability(self, n: int) -> List[float]:
        dp = [ [0 for _ in range(6*n+1)] for _ in range(n+1)]
        for i in range(1,7):
            dp[1][i] = 1

        for i in range(2,n+1):
            for j in range(i,i*6+1):
                for k in range(1,7):
                    if j >= k+1:
                        dp[i][j] +=dp[i-1][j-k]
        res = []
        for i in range(n,n*6+1):
            res.append(dp[n][i]*1.0/6**n)
        return res

Sword refers to offer61

Topic description:
Randomly draw 5 cards from the playing cards to determine if it is a straight, that is, if the 5 cards are consecutive. 2~10 are the numbers themselves, A is 1, J is 11, Q is 12, K is 13, and the big and small kings are 0, which can be regarded as any number. A cannot be regarded as 14.

Example:
Insert picture description here
Answer:

class Solution:
    def isStraight(self, nums: List[int]) -> bool:
        nums.sort()
        numZeros=nums.count(0)
        if len(set(nums[numZeros:]))<len(nums[numZeros:]):
            return False
        return nums[-1]-nums[numZeros]<=4

Sword refers to offer62

Title description:
0,1,···,n-1 These n numbers are arranged in a circle, starting from the number 0, and each time the mth number is deleted from the circle (after deletion, the counting starts from the next number). Find the last number remaining in the circle.
For example, the 5 numbers 0, 1, 2, 3, and 4 form a circle. Each time the third number is deleted from the number 0, the first 4 numbers to be deleted are 2, 0, 4, and 1, so at the end The remaining number is 3.

Example:
Insert picture description here
Answer:

class Solution:
    def lastRemaining(self, n: int, m: int) -> int:
        if n<1 or m<0:
            return -1
        last=0
        for i in range(2,n+1):
            last=(last+m)%i
        return last

Sword refers to offer65

Topic description:
Write a function to find the sum of two integers. The four arithmetic symbols "+", "-", "*", and "/" must not be used in the function body.

Example:
Insert picture description here
Answer:

class Solution:
    def add(self, a: int, b: int) -> int:
        while b:
            result = (a ^ b) & 0xffffffff
            carry = ((a & b) << 1) & 0xffffffff
            a = result
            b = carry
        if a <= 0x7fffffff:
            result = a
        else:
            result = -((a - 1) ^ 0xffffffff)
        return result  

Sword refers to offer67

Title description:
Write a function StrToInt to convert a string into an integer. You cannot use atoi or other similar library functions.
First, the function discards useless beginning space characters as needed, until it finds the first non-space character.
When the first non-empty character we find is a positive or negative sign, combine this symbol with as many consecutive digits as possible behind it as the sign of the integer; if the first non-empty character is Number, it is directly combined with the following consecutive number characters to form an integer.
In addition to the valid integer part of the string, there may also be extra characters, these characters can be ignored, they should not affect the function.
Note: If the first non-space character in the string is not a valid integer character, the string is empty, or the string contains only blank characters, your function does not need to be converted.
In any case, if the function cannot perform a valid conversion, please return 0.

Example:
Insert picture description here
Answer:

class Solution:
    def strToInt(self, str: str) -> int:
        str = str.strip()                      # 删除首尾空格
        if not str: 
            return 0                   # 字符串为空则直接返回
        res, i, sign = 0, 1, 1
        int_max, int_min, bndry = 2 ** 31 - 1, -2 ** 31, 2 ** 31 // 10
        if str[0] == '-': 
            sign = -1            # 保存负号
        elif str[0] != '+': 
            i = 0              # 若无符号位,则需从 i = 0 开始数字拼接
        for c in str[i:]:
            if not '0' <= c <= '9' : 
                break     # 遇到非数字的字符则跳出
            if res > bndry or res == bndry and c > '7': 
                return int_max if sign == 1 else int_min # 数字越界处理
            res = 10 * res + ord(c) - ord('0') # 数字拼接
        return sign * res


Guess you like

Origin blog.csdn.net/yeqing1997/article/details/113675705