python小题

交换两个变量值

def ex_1(a,b):
    a,b = b,a
    return a,b
def ex_2(a,b):
    c = b
    b = a
    a = c
    return a,b
if __name__ == ‘__main__‘:
    print(ex_1(1,2))
    print(ex_2(1,2))

删除列表重复元素

def del_repeat_1(a):
    #创建一个空列表用来存放不重复元素
    list1 = []
    #遍历需要删除重复元素的列表
    for i in a:
        #如果list1中不存在的列表才添加
        if i not in list1:
            list1.append(i)
    return list1
def del_repeat_2(a):
    # 我们知道set是不重复的数据容器
    return list(set(a))
if __name__ == ‘__main__‘:
    a = list(input())
    print(del_repeat_1(a))
    print(del_repeat_2(a))

判断是否为素数

def prime(number):
    if 0 not in [number / i for i in range(2,number)]:
        return f‘{number} is prime‘
    else:
        return ‘%d is not prime‘%(number)
if __name__ == "__main__":
    print(prime(int(input())))

求数字各位数之和

def sum(a):
    result = 0
    for i in a:
        result += int(i)
    return result

if __name__ == ‘__main__‘:
    print(sum(input(‘请输入一个整数:‘)))

求最大公约数

def cc(a,b):

    return max([i for i in range(1,min(a,b) + 1) if a % i == 0 and b % i == 0])
if __name__ == ‘__main__‘:
    print(cc(8,10))

温度转换

def transform(a):
    result = (a - 32) / 1.8
    return str(round(result,2)) + ‘度‘
if __name__ == "__main__":
    print(transform(float(input())))

生成随机数

import random
def arange(a):
    return random.randint(0,a)
if __name__ == ‘__main__‘:
    print(arange(100))

翻转字符串

def reverse_1(a):
    return a[::-1]
if __name__ == ‘__main__‘:
    print(reverse_1(input()))