计数增加然后减少回零。想累积计数

时间:2014-10-26 02:31:41

标签: python

def balloonBubbleCollide(balloon,bubble):
    point1 = balloon.getCenter() #get center of user controlled balloon
    point2= bubble.getCenter() #get center of select bubble
    distance= getDistance(point1, point2) #run distance foruma
    if distance <= 30: #if distance <= to 30, given my parameters, they are colliding
        return True

def checkForBubblesAbsorbed(balloon, bubbles, window):
    count = 0 #initial number of balloons absorbed
    for bubble in bubbles: #check each bubble
       collide = balloonBubbleCollide(balloon, bubble) #True or False, if colliding
       if collide == True:
           count = count + 1 #increase the number of absorbed by 1 upon collision
       print(count)
    return count

我猜这些是感兴趣的功能。我明白为什么它不起作用。当距离&lt; = 30时,计数等于计数+ 1 。但是,如何使它成为累积计数?

2 个答案:

答案 0 :(得分:0)

您在每个return count循环中都有for,只有在return循环累积for后才count {/}}

def checkForBubblesAbsorbed(balloon, bubbles, window):
    count = 0
    for bubble in bubbles:
       collide = balloonBubbleCollide(balloon, bubble)
       if collide == True:
           count = count + 1
       print(count)
    # This return should be outside the for loop (you have an extra indent) 
    return count

注意:您可以使用if collide,尤其是因为您的函数返回True或None

积累

你可以在计数函数之外创建一个变量cumulative_count = 0(例如在.py模块的全局范围内),然后是cumulative_count += checkForBubblesAbsorbed(...),这样每次累积计数都不会重置为0函数被称为

cumulative_count = 0

def balloonBubbleCollide(...)
def checkForBubblesAbsorbed(...)

def somewhere(...)
    cumulative_count += checkForBubblesAbsorbed(...)

答案 1 :(得分:0)

你可以使用sum,因为balloonBubbleCollide返回一个布尔值,你需要在第一次迭代后没有返回的整个循环的总和,这是你自己的代码中发生的事情。 for循环中的return

def balloonBubbleCollide(balloon,bubble):
    point1 = balloon.getCenter()
    point2= bubble.getCenter()
    distance= getDistance(point1, point2)
    return distance <= 30 # will be True or False


def checkForBubblesAbsorbed(balloon, bubbles):
    return sum(balloonBubbleCollide(balloon, bubble) for bubble in bubbles)

我删除了window,因为它未在您的函数中使用