Test interview python questions

1. Bubble algorithm

method one:

num = [1, 5, 10, 58, 12, 2]
for i in range(len(num)-1):# 比较n-1轮,n为元素个数
    for j in range(len(num)-1-i):# 剩余两两进行比较的次数
        if num[j] < num[j + 1]:
            num[j + 1], num[j] = num[j], num[j + 1]

print(num)  #打印结果为:[58, 12, 10, 5, 2, 1]

Method Two:

list1 = [2, 6, 9, 10, 18, 15, 1]
a =len(list1) # 统计列表元素的长度:len()函数(统计)
print(a) # 列表的长度为7
for i in range(a): # 那么a的取值为:0123456 #控制循环的次数
    for j in range(i+1,a): # 当i=0时 j=1.2.3.4.5.6
        if list1[i]>list1[j]: # 如从大到小只需要将大于号改为小于号
            #list1[]=list1[j] 调试,满足条件就替换
            list1[i],list1[j]=list1[j],list1[i]
        # 双向赋值语法,两者替换,无先后循序同时取值,把i的值赋值给j,
        print(list1)#调试解释用的
print(list1) # 运行结果:[1, 2, 6, 9, 10, 15,18]


2. Print the 99 multiplication table

method one:

for i in range(1,10):  
    for j in range(1,i+1):
        print("{}*{}={}".format(i,j,i*j),end=' ')  #使用format格式化输出
    print()

Method Two:

for i in range(1,10): # 用来控制循环次数,外循环 i的结果循环次数为:1-9
    for j in range(1,i+1): # 内循环 j=1 内循环循环完毕后才会回到外
循环
        print(j,'*',i,'=',j*i,'\t',end='') # \t 转义字符:表示空格 \n :表示换行
    print('\n')
# 解析
当i = 1 j = 1 1 * 1 = 1
当1 = 2 j = 1,2 1x2=2 2x2=4


3. Yang Hui Triangle**

massage = '''
Yang Hui's triangle is essentially a triangle formed by the coefficients of each item after the nth power expansion of the binomial (a+b). Its properties include: the number of endpoints of each row is 1, and a number is also 1; each number is equal to the sum of the two numbers on its upper left and upper sides.
'''

n = eval(input("输入要打印的行数:"))
triangle = [[1], [1, 1]]
for i in range(2, n):  # 已经给出前两行,求剩余行
    pre = triangle[i-1]  # 上一行
    cul = [1]  # 定义每行第一个元素
    for j in range(i-1):  # 算几次
        cul.append(pre[j]+pre[j+1])  # 每个数字等于上一行的左右两个数字之和。
    cul.append(1)  # 添加每行最后一个元素
    triangle.append(cul)
print("普通输出:{}".format(triangle))
for i in range(n):  # 按等边三角形格式输出
    s = " "*(n-i-1)
    for j in triangle[i]:
        s = s + str(j)+" "
    print(s)

4. Daffodils

massage = """
Find all the "Narcissus numbers" from 100-999. The so-called "Daffodils number" refers to a three-digit number, and the sum of the cubes of each digit is equal to the number itself. For example: 
153 is a "Daffodils number" , 153 = 1^3 + 5^3 + 3^3, so 153 is a daffodil number
"""

l = []
for i in range(100,1000):
    a = i // 100
    b = (i%100) // 10
    c = i % 10
    if a**3 + b**3 + c**3 == i:
        l.append(i)
for i in range(len(l)):
    print(l[i],end = " ")
 # 输出结果 153 370 371 407 



5. Pyramid Pattern
Prints a pyramid pattern composed of "*".
Input description:
multiple sets of input, an integer (2~20), indicating the length of the pyramid side, that is, the number of "*", and also indicating the number of output lines.

Output description:
For each line of input, output a pyramid composed of "*", each "*" is followed by a space.

def pypart(n):
    myList = []
    for i in range(1, n + 1):
        myList.append("*" * i)
    print("\n".join(myList))


# 驱动程序代码
n = 5
pypart(n)


6. Bofinacci sequence

method one:

def fib(lenght):
    a, b = 0, 1
    n = 0
    while n < lenght:
        yield b
        a,b = b,a+b
        n += 1
gen = fib(9)
for i in gen:
    print(i,end=' ')

Method Two:

def fun(n): # n = 9
    list1 = []
    for i in range(n): # i = 0-8
        if i == 0 or i == 1:
            list1.append(1) #当i=0或者1的时候往列表添加1,先确定前面的两个数位1
        else:
            list1.append(list1[i-2] + list1[i-1]) #[i-2]索引位是减两位的和减一位的相加得到的结果
    print(list1)
fun(9)


7. Deduplication of Integers in Sequence
Title Description
Given an integer sequence, remove the repeated integers, and sort and output the deduplicated sequence from small to small.
Input description:
In the first line, enter an integer n, indicating that the sequence has n integers.
In the second line, input n integers (each integer is greater than or equal to 1 and less than or equal to 1000), and the integers are separated by spaces.
Output description:
A sequence of integers that are deduplicated and arranged in ascending order, and the integers are separated by spaces.
'''

n = int(input('请输入:'))
l = list(map(int,input('请输入一段整数:').split(' ')))
new_l = []
for i in range(len(l)):
    if l[i] not in  new_l:
        new_l.append(l[i])
print(new_l)


8. Digital Right Triangle Pattern

massage = '''
Print a number triangle pattern with numbers.
Input description:
multiple sets of input, an integer (3~20), indicating the length of the side of the digital triangle, that is, the number of numbers, and also indicating the number of output lines.
Output description:
For each line of input, output a digital triangle of the corresponding length composed of numbers, with a space after each number.
'''

while True:
    try:
        n = int(input("请输入3-20的数字:"))
        for i in range(n):
            for j in range(1,i+1):
                print(j,end=' ')
            print()
    except:
        break


       
 """


9. One line of code realizes the sum of 1~100

print(sum([i for i in range(1,101)]))


10. Output a string in reverse

method one:
 

s = str(input("请输入一个需要排序字符串:"))
# new_s = s[-1::-1]
new_s = s[::-1]
print(new_s)

Method Two:

str = list(input('input a string:'))
str.reverse()#该方法没有返回值,若打印则出现None,但会对列表元素进行反向排序
print(''.join(str))

11. Find the sum of 1/1 + 1/3 + 1/5...+1/99 (1 /1 + 1 /3+5 branch 1....)

i=1.0 # 定义变量i 赋予浮点值(用作控制循环的次数)
sum=0 # 定义一个求和的变量
while i <= 99: # while循环
    sum = sum + 1/i # i为可变分子和分母必须要有一个为浮点数
    i+=2
print(sum) # 结果为:2.93777484847

12. Use the loop statement to calculate the value of the loop multiplication of integers between 2 - 10 ( 2X3X4X5....10)

sum = 1 # 定义一个求和的变量
for i in range(2,11): # i变量值是用遍历range函数内的值来循环
    sum = sum * i #这个地方不需要i=i+1,一般是结合while使用
print(sum) # 运行结果:3628800

Guess you like

Origin blog.csdn.net/m0_57028677/article/details/128872855