2012-10-13 51 views
-2

我试图做这两个功能:多数和expletive_deleted蟒蛇功能

# 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] = '****' 

和在我尝试测试这个函数时,它不会显示任何东西。

回答

1

您在第一个拼写错误numFalsenumFlase在第二个if块中)。

至于第二个,你实际上没有打印/做任何事情。假设您从其他地方调用该函数,则需要根据您的要求打印或返回该值。此外,在你的情况下,你可以说if len(i) == 4,因为x[n]相当于in是索引,i是值)。

+0

太感谢你了,但我应该怎么做测试第二个? –

+0

@NoufAl我会让它返回一个值(虽然看起来你的指令说返回false?)。然后,您可以将它与“应该”进行比较,看看两者是否匹配。有关返回值的方法,请参阅下面的PavelPaulau答案。我想你也可以在你的数据中传递一个测试变量,但那不会那么灵活:) – RocketDonkey

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) 
+0

非常感谢你的帮助 –

+0

它对你有用吗? –

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] = "****"