In <364bcdb3-fdd5-4774-b7d2-040e2ccb4...@googlegroups.com> William Bryant 
<gogobe...@gmail.com> writes:

> Hello, I've done this so far but why doesn't the mode function work?

> def mode():
>     global NumberOfXItems, Themode
>     for i in List:
>         NumberOfXItems.append(i)
>         NumberOfXItems.append(List.count(i))
>     Themode = max(NumberOfXItems)
>     print(Themode)

As far as I can see, you're appending each of the user's numbers onto
NumberOfXItems, and you're also appending the number of times each number
occurs.

So, if the user had entered these numbers:

    5 9 9 9 15 100 100

NumberOfXItems would end up looking like this:

    5 1 9 3 9 3 9 3 15 1 100 2 100 2

The max is 100, but 9 is the most often-occuring number.

Also, since NumberOfXItems mixes user input and the counts of that input,
you risk getting a max that the user didn't even enter.  For example if the
user entered these numbers:

    1 1 1 1 1 1 2 3

NumberOfXItems would end up looking like this:

    1 6 1 6 1 6 1 6 1 6 1 6 2 1 3 1

The max is 6, which is a count, not user input.

mode would be much better written like this:

  def mode(mylist):

      max_occurrences = 0
      themode = None

      for i in mylist:
          thecount = mylist.count(i)
          if thecount > max_occurrences:
              max_occurrences = thecount
              themode = i

      print(themode)

-- 
John Gordon                   A is for Amy, who fell down the stairs
gor...@panix.com              B is for Basil, assaulted by bears
                                -- Edward Gorey, "The Gashlycrumb Tinies"

-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to