- 編寫?個函數,求1+2+3+...+N
def my_sum(num:int):
sum1 = 0
for x in range(num+1):
sum1 += x
return sum1
- 編寫?個函數,求多個數中的最?值
def wjj_max(*args):
max1=args[0]
for num in args:
if num > max1:
max1=num
return max1
- 編寫?個函數,實現搖??的功能抖拴,打印n個??的點數和
import random
def my_game(The_number_of_dice:int):
input_str=input('輸入1搖色子,輸入end退出')
if input_str == '1':
sum1 = 0 #儲存色子總點數
count = 0
for _ in range(The_number_of_dice):
num1 = random.randint(1,6)
count += 1
print('第%d個色子點數為%d'%(count,num1))
sum1 += num1
return '%d個色子總點數是%d'%(The_number_of_dice,sum1)
else:
print('成功退出H馗浴城舞!')
print(my_game(6))
- 編寫?個函數,交換指定字典的key和value寞酿。
例如:{'a':1, 'b':2, 'c':3} ---> {1:'a', 2:'b', 3:'c'}
def exchange_dict(dict1:dict):
dict2={}
for key in dict1:
dict2.setdefault(dict1[key],key)
return dict2
print(exchange_dict({'a':1, 'b':2, 'c':3}))
dict1={'a':1, 'b':2, 'c':3}
gen2=dict((value,key) for key,value in dict1.items())
print(gen2)
- 編寫?個函數家夺,三個數中的最?值
def my_max(*args):
return max(*args)
print(my_max(1,2,3))
- 編寫?個函數,提取指定字符串中的所有的字?伐弹,然后拼接在?起后打例如:'12a&bc12d--' ---> 打印'abcd'
def joint_str(str1):
str2=''
for x in str1:
if 'a' <= x <= 'z' or 'A' <= x <='Z':
str2 += x
return str2
print(joint_str('12a&bc12d--'))
- 寫?個函數拉馋,求多個數的平均值
def mean(*args):
sum1 = 0
for x in args:
sum1 += x
return sum1/len(args)
print(mean(10,20,30,40,50))
- 寫?個函數,默認求10的階層惨好,也可以求其他數的階層
def factorial(num=10):
product = 1
for x in range(1,num+1):
product *= x
return product
print(factorial())
- 寫?個函數煌茴,可以對多個數進?不同的運算
例如: operation('+', 1, 2, 3) ---> 求 1+2+3的結果
operation('-', 10, 9) ---> 求 10-9的結果
operation('', 2, 4, 8, 10) ---> 求 24810的結
def operation(str1:str,*args:float):
if str1 == '+':
sum = 0
for x in args:
sum += x
return sum
elif str1 == '-':
list1=list(args)
num = list1[0]
for x in list1[1::]:
num -= x
return num
elif str1 == '*':
product = 1
for x in args:
product *= x
return product
elif str1 == '/':
list1=list(args)
num2 = list1[0]
for x in list1[1::]:
num2 /= x
return num2
else:
print('暫時不支持其他算法')
print(operation('+',24,4,6)) # 34
print(operation('-',24,4,6)) # 14
print(operation('*',24,4,6)) # 576
print(operation('/',24,4,6)) #1.0