软件测试—Python笔试题2

文章目录

    • 06-交换
    • 07-水仙花数
    • 08-完全数
    • 09-冒泡排序
    • 10-sort排序

06-交换

# 已知a=9,b=8,如何交换a和b的值,得到a的值为8,b的值为9

# 方法1
a = 9
b = 8
a,b = b,a
print("a=%d" % a)
print("b=%d" % b)

# 方法2
a = 9
b = 8
# 用中间变量c
c = a
a = b
b = c
print("a=%d" % a)
print("b=%d" % b)

07-水仙花数

# 判断是否是水仙花数
while True:
    # 输入一个3位数的数值:
    num = input("请输入一个数值:")
    m = len(num)
    # print(m)
    num = int(num)
    # 判断是否是数值,是否是三位
    if 100 <= num <= 999:
        a = num // 100
        b = num % 100 // 10
        c = num % 10
        result = a ** m + b ** m + c ** m == num
        if result:
            print("%d是水仙花数" % num)
        else:
            print("%d不是水仙花数" % num)

# 打印出100-999所有的“水仙花数”
# 1.for 循环
for num in range(100,1000):
    # 百位
    a = num // 100
    # 十位
    b = num % 100 //10
    # 个位
    c = num % 10
    if a ** 3 + b ** 3 + c ** 3 == num:
        print(num)
# 2.while 循环
num = 100
while num < 1000:
    # 百位
    a = num // 100
    # 十位
    b = num % 100 //10
    # 个位
    c = num % 10
    if a ** 3 + b ** 3 + c ** 3 == num:
        print(num)
    num += 1

#3.利用字符串
for num in range (100,1000):
    s = str(num)
    a =int(s[0])
    b = int(s[1])
    c = int(s[2])
    if a ** 3 + b ** 3 + c ** 3 == num:
        print(num)

08-完全数

# 求出1000以内的完全数
a = []
for i in range(1,1000):
    sum = 0
    for j in range  (1,i):
        if i % j == 0 and j < i:
            sum += j
    if sum == i:
        a.append(i)
print("1000以内完全数:%s" % a )

09-冒泡排序

# 用python写个冒泡排序
def bubble_sort (alist):
    n = len(alist)
    for j in range(n-1):
        # 判断走几次
        count = 0
        # 交换次数
        for i in range (0,n-1-j):
            # 从头走到尾
            if alist[i] > alist[i+1]:
                alist[i],alist[i+1] =  alist[i+1],alist[i]
                count +=1
        if count == 0:
            return
if __name__== "__main__":
    alist = [1, 3, 10, 9, 21, 35, 4, 6]
    print(alist)
    bubble_sort(alist)
    print(alist)
    
    
# alist[0]~alist[n-1]
# j=0 0~n-2 range(0,n-1)
# j=1 0~n-3 range(0,n-1-1)
# j=2 0~n-4 range(0,n-1-2)

# for j in range(len(alist)-1,0,-1)
# [n-1,n-2,n-3,...1]
# for i in range (j):

10-sort排序

# 已知一个队列[1,3,6,9,7,3,4,6]
a = [1,3,6,9,7,3,4,6]

# 1.sort排序,正序
a.sort()
print(a)

# 2.sort排序,倒序
a.sort(reverse=True)
print(a)

#3.去重
b = list(set(a))
b.sort(key=a.index)
# 保持原来列表顺序输出
print(b)
# set本质是无序,不重复的集合

你可能感兴趣的:(软件测试)