# FAANG面试在2021年问这5个Python问题

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

A_6 = np.random.choice(die) # roll the fair dice and choose a random value from 0 to 6

if A_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_count = A_count+1.”

else: # if the above if condition does not fullfill

B_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 B_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 A and B wonaka. the result is the probability that Amy wins.

np.random.seed(123)

die = [1,2,3,4,5,6]

size = 10000

who_won(die,size)

view raw

0.531271015467384

> Photo by john vicente on Unsplash

-给定一个仅由数字6和9组成的正整数num。-返回最多可更改一个数字可得到的最大数字(6变为9，而9变为6)。https://leetcode.com/problems/maximum-69-number/

# replace once

def max_69_once(num):

return int(str(num).replace(‘6′,’9’,1))

# test case

num = 966666669

max_69_once(num)

996666669

def max_69_all(num):

k = len(str(num))

return int(str(num).replace(‘6′,’9’,k))

# test case

num = 966666669

max_69_all(num)

999999999

> Photo by Alessandro Capuzzi on Unsplash

-给定正整数num，编写一个函数，如果num是一个完美的平方则返回True;否则返回False。-后续操作：请勿使用任何内置库函数(例如sqrt)。-https://leetcode.com/problems/valid-perfect-square/

· 找到平方根。

· 检查它是否是完美的平方根。

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)

(特别感谢韩琦发现错误!)

# 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<=right: # while loop to constantly update left and right

x = left + (right-left)//2# take a wild guess and treat x as the starting point

x_squared = x*x # calculate the squared value of x

if x_squared == num: # use the following ‘if-else’ statement to constantly update x_squared.

return True # if there are the same, return True

if x_squared

left= x+1

else: # if x_squared is bigger, right decreases by 1

right= x-1

return False # the while loop should continue looping until left and right converge and no common value obtained

# test case

valid_perfect_square(16)

#问题4：阶乘尾随零。彭博社

-给定整数n，返回n中的尾随零!

-后续行动：您能否编写一种适用于对数时间复杂度的解决方案?

-https://leetcode.com/problems/factorial-trailing-zeroes/

· 计算n阶乘n!

· 计算尾随零的数量

# 1 calculate n!

# 2 calculate the number of trailing zeros

def factorial_zeros(n):

product = n

while n > 1 : # iteratively calculate the product

product *= (n-1)

n-=1

count = 0

for i in str(product)[::-1]: # calculate the number of trailing zeros

if i == ‘0’:

count+=1

else:

break

return count

factorial_zeros(20)

break命令在这里至关重要。如前所述，上述函数无需中断命令即可计算零的总数。

def factorial_zeros(n):

product = n

while n > 1 : # step 1: iteratively calculate the product

product *= (n-1)

n-=1

count = 0

while product%10 == 0: # step 2: calculate the number of trailing zeros

product = product/10

count+=1

return count

> Photo by Jamie Fenn on Unsplash

-理想数字是一个正整数，它等于其正因数之和，但不包括数字本身。-整数x的除数是可以将x均匀除的整数。-给定整数n，如果n是完美数则返回true，否则返回false。-https://leetcode.com/problems/perfect-number/

· 找出正因数

· 计算总和

· 决定：完美与否

#1. find the positive divisors

#2. calculate the sum

#3. perfect or not

def perfect_number(num):

divisors = []

for i in range(1,num):

if num%i==0:

divisors.append(i)

if sum(divisors)==num:

return True

else:

return False

# test case 1

perfect_number(2)

# solution 2: sqrt(n)

def perfect_number(num):

if num<=1:

return False

divisors = set([1])

for i in range(2,int(num**0.5)+1): # from 2 to num**0.5

if num%i==0:

return sum(divisors)==num

· 在进行了数十次”实践”编码之后，最大的收获就是理解问题并将问题分为多个可操作的组件。

· 在这些可行的部分中，总会有一个步骤使求职者绊倒。诸如”不能使用内置函数/库”之类的限制。

· 关键是逐步编写自定义函数，并尝试避免在练习例程中尽可能多地使用内置函数。

【责任编辑：赵宁宁 TEL：（010）68476606】