學習python,每日練習0601

最大數字第一個元素交換,最小數字和最後一個元素交換

#定義一個數組:
list = [int(i) for i in input('請輸入一組數字,用空格隔開: ').split(' ')]
print("未交換前的list:",list)
#數組排序,這樣賦值,兩個list不會互相影響
newlist = list.copy()
#對newlist進行排序,得到最小和最大值
newlist.sort()
mini = newlist[0]
maxi = newlist[len(newlist)-1]
#得到最小最大值在list中的索引
indexMin = list.index(mini)
indexMax = list.index(maxi)
#最大的元素與第一個交換,最小的元素與最後一個元素交換
list[0],list[indexMax] = list[indexMax],list[0]
list[len(list)-1],list[indexMin] = list[indexMin],list[len(list)-1]
print("交換後的list:",list)

結果:
請輸入一組數字,用空格隔開: 12 4 2 67 90 45 5 123 45
未交換前的list: [12, 4, 2, 67, 90, 45, 5, 123, 45]
交換後的list: [123, 4, 45, 67, 90, 45, 5, 12, 2]

編寫一個函數,輸入n爲偶數時,調用函數求1/2+1/4+…+1/n,當輸入n爲奇數時,調用函數1/1+1/3+…+1/n

知識點

整數變爲字符串:str();字符串拼接;去掉最後一個字符str[:-1]

result = ""
def isEven(n):
    global result
    if(n % 2 == 0):
        for i in range(2,n+1):
            if i % 2 == 0:
                result += "1"+"/"+str(i)+"+"
    else:
        for i in range(1,n+1):
            if i %2 !=0:
                result += "1"+"/"+str(i)+"+"
    return result
    
n = int(input("請輸入一個數字:"))
s = isEven(n)
s = str(n)+"="+s
print(s[:-1])
結果:
請輸入一個數字:9
9=1/1+1/3+1/5+1/7+1/9

題目來源:
https://fishc.com.cn/forum.php?mod=viewthread&tid=84968&ctid=588
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章