Re: [閒聊] python小白問個問題

作者: erimow (Erimo)   2024-08-01 11:57:22
今天寫四題,新手上路
Write a function called "findSmallCount" that takes one list of integers and
one integer as input, and returns an integer indicating how many elements in
the list is smaller than the input integer.
findSmallCount([1, 2, 3], 2); # returns 1
findSmallCount([1, 2, 3, 4, 5], 0); # returns 0
答案
def findSmallCount(list, y):
counter = 0
for i in list:
if i < y:
counter += 1
return counter
第二題卡了
Write a function called "findSmallerTotal" that takes one list of integers and
one integer as input, and returns the sum of all elements in the list that
are smaller than the input integer.
findSmallerTotal([1, 2, 3], 3) # returns 3
findSmallerTotal([1, 2, 3], 1) # returns 0
findSmallerTotal([3, 2, 5, 8, 7], 999) # returns 25
findSmallerTotal([3, 2, 5, 8, 7], 0) # returns 0
def findSmallerTotal(list, y):
for i in list
if i < y:
total = i + ?
print(total)
return total
本來第四行那邊想用sum,可是sum不能用在不是int的上面
所以我得想出一行來表達 total= 所有i<y的相加
def findSmallerTotal(list, y):
total = 0
for i in list:
if i < y:
total = total + i
print(total)
return total
想很久便這樣,我好像一直在考慮我要定義出每個數字在list裡面的位置
沒想到直接把i相加就好了
第三題也卡了
Write a function called "findAllSmall" that takes one list of integers and
another integer as input, and returns an list of integers that contains all
elements that are smaller than the input integer.
findAllSmall([1, 2, 3], 10); # returns [1, 2, 3]
findAllSmall([1, 2, 3], 2); # returns [1]
findAllSmall([1, 3, 5, 4, 2], 4); # returns [1, 3, 2]
我第一時間想用.remove()來做
寫這樣
def findAllSmall(list, y):
for i in list:
if i >= y:
list.remove(i)
print(list)
return list
可是return的結果
[1, 2, 3]
[1, 3]
[1, 3, 4, 2]
有問題沒料,換一個
def findAllSmall(list, y):
newlist = []
for i in list:
if i < y:
newlist.append(i)
print(newlist)
return newlist
append就行了
Write a function called "summ" that takes one list of numbers, and return the
sum of all elements in the input list.
最後一題最簡單
summ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); # returns 55
summ([]); # return 0
summ([-10, -20, -30]); # return -60
def summ(list):
total = 0
for i in list:
total += i
print(total)
return total
就第一題的變種
這樣下來大概花了90分鐘==
我覺得最難的部分就是要馬上想到有那些function可以被用
然後還要清楚for迴圈怎麼去定義,只能多練
作者: Smallsh (Smallsh)   2024-08-01 11:58:00
大師
作者: orangeNoob (橘子色的肥肥)   2024-08-01 12:02:00
別捲了
作者: MurasakiSion (紫咲シオン)   2024-08-01 12:14:00
第三題用remove會不行是因為後面元素往前補==
作者: erimow (Erimo)   2024-08-01 12:24:00
對啊 只remove掉一個 不知道怎麼讓他重複做

Links booklink

Contact Us: admin [ a t ] ucptt.com