我试着做这两个功能:
# majority(x)
# pre-condition: x is a list of booleans (True or False values)
# post-condition: returns True if there are strictly more Trues than False in x; otherwise returns False.
def majority(x):
numTrue = 0
numFalse = 0
for i in x:
if (i==True):#check to see how many Trues there are
(numTrue) += 1
else:# check to see how many Falses there are
(numFalse) += 1
if ((numTrue) > (numFlase)):# check to see what is the majority of the list(trues or falses)
return True
else:
return False
在这一部分中,它向我显示numFalse
未定义,我不知道原因:
# expletive_deleted(x)
# pre-condition: x is a list of strings
# post-condition: replace each string of length 4 in x with the string ****.
#return nothing.
def expletive_deleted(x):
for n,i in enumerate(x):#enumerate works like 2 for loops together
if (len(x[n])==4):
x[n] = '****'
并且每当我尝试测试该功能时,它都没有显示任何内容。
答案 0 :(得分:1)
您在第一个numFalse
区块numFlase
中拼错了if
。
至于第二个,你实际上并没有打印/做任何事情。假设您从其他地方调用该函数,则需要根据您的要求打印或返回该值。另外,在您的情况下,您可以说if len(i) == 4
,因为x[n]
等同于i
(n
是索引,i
是值)。
答案 1 :(得分:1)
def majority(lst):
return sum(1 for b in lst if b) > (len(lst) // 2)
def expletive_deleted(lst): #note: not inplace as required
return [s if len(s) != 4 else "****" for s in lst]
就地:
def expletive_deleted(lst):
for i, s in enumerate(lst):
if len(s) == 4:
lst[i] = "****"
答案 2 :(得分:0)
试试这个:
def majority(x):
return len([y for y in x if y]) > len(x) / 2
和
def expletive_deleted(x):
replacer = lambda s: len(s) == 4 and "****" or s
return map(replacer, x)