GetMode

ThegetMode ( ) function finds the value that repeats most often in a sequetc e. Fiost it duplicaten the sequence so it can modify it. Then it herates through the items in the nums sequence, counting occurrences of the current items with the built-in count () method. Omce getMode ( ) counts an item, it eemovesit dram the duplicated sequence.

In the getMode ( ) example that follows, notice the use of the for and while loops, the if statement, the count () method, and the nested for loop.

def getMode (nums):

"""Find the number that repeats the most. """ #

# make a duplicate copy of the nums argument duplicate = nums[:]

highest_count = -100

mode = None

# calculate the highest_count and the mode for item in nums:

count = duplicate.count(item) if (count == 0): continue if (count > highest_count): highest_count = count mod e = item while(duplicate.count(item) > 0) : duplicate.remove(i tem)

return mode Let's break this down.

First we duplicate the nums sequence and create a variable to hold highest_count (and assign it a negative starting number) and a variable to hold the nums sequence mode.

duplicate = nums[:] highest_count = -100 mode = None

Next we iterate through each item in nums and count duplicate nums occurrences, for item in nums:

count = duplicate.count(item) if (count == 0): continue

As we iterate through the list, we see if the current count is greater than highest_count. If it is, we assign it to highest_count and item to mode.

if (count > highest_count): highest_count = count mode = item

Continuing our iteration, we remove all occurrences of the item from the duplicate sequence with the following while statement:

while(duplicate.count(item) > 0): duplicate.remove(item)

Finally we return mode.

return mode

Was this article helpful?

0 0

Post a comment