Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

A detailed explanation of the Python problem

2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains the "detailed explanation of Python issues". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "detailed explanation of Python issues".

Question1: who wins first? Microsoft

Amy and Brad take turns rolling a beautiful hexagonal mold. Who throws "6" first to win the game? Amy scrolls first. What are Amy's chances of winning?

(1) thinking

This is a core simulation problem, and there is no better way than to simulate a large number of processes and check the possibility of Amy winning.

Amy, go first. If the result is 6, the game is over and Amy wins. Otherwise, Brad will flip the card, if it is 6, he will win the game. If not, go back to Amy. Repeat the process until someone ends the game with 6.

Here, the key is to understand the logical process: who wins and under what circumstances. If Amy gets six points, does Brad have to throw? No.

(2) solving problems

Import numpy as np def who_won (die, size): A_count = 0 # initialize A_count B_count = 0 # initialize B_count for i in range (size): # create an iteration Aids 6 = np.random.choice (die) # roll the fair dice and choose a random value from 0 to 6 if Aids 6 = = 6: # if A rolls a 6 Then A_count adds 1. A_count+=1 # a side-note for Python beginners: the full expression is "A_countA_count = A_count+1." Else: # if the above if condition does not fullfill bond 6 = np.random.choice (die) # then, it's B's turn to roll the dice, which is a random choice from 0 to 6. If bond 6 = = 6: # if B rolls a B B_count adds 1. B_count+=1 return A_count/ (A_count+B_count) # return the total number of cases that A won divided by the combined number of An and B wonaka. The result is the probability that Amy wins.

Check line 11: Agg6 is the data distribution of Amy, and if her data is 6, the count is + 1. Otherwise, Brad can roll the dice.

In the end (line 25), the final result should be the number of wins by Amy divided by the total number of wins by Amy and Brad. A common mistake is to divide A_count by the total number of simulations. This is incorrect because there will be iterations when both Amy and Brad fail to throw 6.

Let's test the above algorithm.

Np.random.seed (123) die = [1 who_won 2 die,size 3 4 5 5] size = 10000 who_won (die,size) view raw

0.531271015467384

It turns out that Amy started rolling to win the game before Brad. Amy has a 53% chance of winning in 10000 simulations.

> Photo by john vicente on Unsplash

Question 2: the maximum number of each major company is 69

-given a positive integer num consisting only of the numbers 6 and 9. -returns the maximum number that can be changed by up to one number (6 becomes 9 and 9 becomes 6). Https://leetcode.com/problems/maximum-69-number/

(1) thinking

Given a positive integer, there is only one way to increase the value, that is, "6" to "9", not the other way around. In addition, we must change the leftmost 6; otherwise, it is not the maximum quantity. For example, we must change "6996" to "9996" instead of "6999".

I came up with several variants of this problem: you can change it once, or you can change it all to 6.

(2) solution 1: replace once

# replace once def max_69_once (num): return int (str (num). Replace

996666669

In line 3, we convert the integer to a string, then replace the first "6" with "9"; use int () to return it as an integer.

(3) solution 2: replace all

Def max_69_all (num): K = len (str (num)) return int (str (num). Replace ('6 records, 9 girls, 10)) # test case num = 966666669 max_69_all (num)

999999999

In the second case, we don't have to specify k, because the replace () method changes all appropriate values by default. I specified a k value for teaching purposes. Another variant of this problem is to replace the first two or three "6s" to maximize the number.

> Photo by Alessandro Capuzzi on Unsplash

Question 3: an effective perfect square. Facebook

Given a positive integer num, write a function that returns True; if num is a perfect square, otherwise False. -follow-up operations: do not use any built-in library functions (such as sqrt).

Https://leetcode.com/problems/valid-perfect-square/

(1) thinking

This is very simple: check whether a positive integer has an ideal square root, and if so, return True, which can be done in two steps.

Find the square root.

Check whether it is the perfect square root.

The tricky part is that we have to use built-in libraries (for example, math, Numpy) to calculate square roots, which is a simple problem on LeetCode. If we can't use these libraries, it will become a more challenging and repetitive problem, which is a medium-level problem for LeetCode.

(2) solution 1: built-in library

Import math def valid_perfect_square (num): return int (math.sqrt (num)) * * 2==num # the int () method only returns the integer part and leaves out the decimal part. # For perfect squares, there should be no decimal part. The equation should thus hold. # test case valid_perfect_square (16)

The algorithm passed the test case easily. It should be noted that we need to use the int () method to get only the integer portion of the square root and ignore any decimal parts. For a perfect square, it doesn't make any difference, so the equation holds. For imperfect squares, the equation will not hold and return False.

Special thanks to Han Qi for finding the mistake!

Solution 2: no built-in libraries and binary search

# 1 find the squre root of num # 2 check if it is a perfect square number # solution: no built-in library & binary search def valid_perfect_square (num): if num

< 2: return True left, right = 2, num//2 # create two pointers: left and right while left 1 : # step 1: iteratively calculate the product product *= (n-1) n-=1 count = 0 while product == 0: # step 2: calculate the number of trailing zeros productproduct = product/10 count+=1 return count 第一部分与解决方案1相同,唯一的区别是我们使用while循环来计算尾随数字:对于乘积除以10的乘积,最后一位必须为0。因此,我们使用while循环不断更新while循环,直到条件不成立为止。 顺便说一句,解决方案2是我最喜欢的计算零的方法。 >

Photo by Jamie Fenn on Unsplash

Question 5: perfect number, Amazon

An ideal number is a positive integer that is equal to the sum of its positive factors, but does not include the number itself.

The divisor of the integer x is an integer that can be evenly divided by x.

Given the integer n, returns true if n is a perfect number, false otherwise.

Https://leetcode.com/problems/perfect-number/

(1) thinking

This problem can be divided into three steps:

Find out the positive factor

Calculate the sum

Decision: perfect or not

Steps 2 and 3 are self-evident, with no more than one layer at most. But the tricky part is finding a positive divisor. To do this, we can use the brute force method and iterate through the entire sequence from 1 to an integer.

In theory, it should apply to a small integer, but if we run a large number, it will exceed the time limit. Time efficiency is not high.

(2) solution 1: violence

# 1. Find the positive divisors # 2. Calculate the sum # 3. Perfect or not def perfect_number (num): divisors = [] for i in range (1Zhennum): if num%i==0: divisors.append (I) if sum (divisors) = = num: return True else: return False # test case 1 perfect_number (2)

This method does not apply to larger values. Your interviewer may ask for a more effective solution.

(3) solution 2:sqrt (n)

# solution 2: sqrt (n) def perfect_number (num): if num

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report