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