Thread: Lists

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Posts
    217
    Rep Power
    0

    Lists


    Are there any lib functions that will let me find the most common number in a list, or find the middle number of a list?
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2001
    Location
    Houston, TX
    Posts
    383
    Rep Power
    14
    No, but it should be easy enough to code working versions of those:
    Code:
    def mostCommonElement(L):
        d = {}
        for item in L:
            if item in d:
                d[item] += 1
            else:
                d[item] = 1
        counts = [(k,v) for k, v in d.items()]  # This basically makes a list that looks like
                                                # [(item, numoccurrences), (item2, numoccurrences2), ...]
        counts.sort(lambda x,y: cmp(y[1], x[1]))   # This sorts that list in reverse, based on the second
                                                   # element in each little tuple/pair
        return counts[0][0]
    
    def findMedian(L):
        import copy
        listCopy = copy.copy(L)
        listCopy.sort()
        return listCopy[int(len(listCopy)/2)]  # Note that int will just floor() the result if it's
                                               # something.5, if you want this to be different change int() to ceil()
    Note, these are untested and absolutely unoptimized.

    edit: they are fixed and tested, just minor errors in each
    Last edited by Strike; January 26th, 2004 at 07:46 PM.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Posts
    217
    Rep Power
    0
    Your median version will only work with a list of an uneven amount of numbers. If you move the /2 out of len() it works fine with and even number.

    Here is my version
    Code:
    def findMedian(nums):
    
    	"""
    	Finds the median of a set of numbers (The one in the middle).
    	"""
    	
    	tmp = len(nums) / 2
    
    	if len(nums) % 2:
    		median = nums[tmp]
    	else:
    		median = (nums[tmp] + nums[tmp - 1]) / 2.0
    		
    	return median
    Thanks for your reply, it helped me out!
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Posts
    217
    Rep Power
    0
    mostCommonElement has a bug that I can't fix, partly because I don't understand it

    Code:
    Traceback (most recent call last):
      File "./bleh.py", line 39, in ?
        main()
      File "./bleh.py", line 33, in main
        common = mostCommonElement(nums)
      File "./bleh.py", line 16, in mostCommonElement
        counts = [(k,v) for k,v in d]
    TypeError: unpack non-sequence
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Posts
    217
    Rep Power
    0
    I wrote my own mostCommonElement function based off of the one I did in C. It probably does not take advantage of Python, so ANY help with it would be appreciated!

    Code:
    def mostCommonElement(nums):
    
    	"""
    	Finds the mode of a set of numbers (Most common number).	
    	"""
    	
    	modes = []
    	total = 0
    	top = 0
    	skip = 0
    	
    	for x in nums:
    		for i in nums:
    			if x == i:
    				total += 1
    	
    		if total > top:
    			top = total
    			modes = []
    			modes.append(x)
    		
    		if total == top:
    			for j in modes:
    				if x == j:
    					skip = 1
    					break
    				else:
    					skip = 0
    			
    			if not skip:
    				modes.append(x)
    	
    		total = 0
    		skip = 0
    
    	return modes
  10. #6
  11. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2001
    Location
    Houston, TX
    Posts
    383
    Rep Power
    14
    See my edited versions above
  12. #7
  13. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2001
    Location
    Houston, TX
    Posts
    383
    Rep Power
    14
    I've seen people do the whole "average the middle two elements for even-length lists" thing for median, but I prefer just to floor() it and pick the lower one. I don't think one is especially more valid than the other. Also, your findMedian assumes that the list is sorted, which is hardly a safe assumption
  14. #8
  15. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    Heres my most common element script

    Code:
    def most(sequence):
    	index = {}
    	for value in sequence:
    		index[sequence.count(value)] = value
    	items = index.items()
    	return items[-1][1]
    Mark.
    Last edited by netytan; January 26th, 2004 at 08:02 PM.
    programming language development: www.netytan.com Hula

  16. #9
  17. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2003
    Posts
    325
    Rep Power
    12
    Elegently done Mark!

    And for anyones info, this :
    Code:
            if item in d:
                d[item] += 1
            else:
                d[item] = 1
    can be shortcutted with a default.
    dun have the code with me to give an example right now tho =/

    Cheers
    Eli
  18. #10
  19. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Posts
    217
    Rep Power
    0
    lol, that's sure a change. One thing though: how would one expand it to conclude that there is no most common number if all the value totals are equal? Thanks alot, again
  20. #11
  21. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Posts
    217
    Rep Power
    0
    Originally posted by Strike
    I've seen people do the whole "average the middle two elements for even-length lists" thing for median, but I prefer just to floor() it and pick the lower one. I don't think one is especially more valid than the other. Also, your findMedian assumes that the list is sorted, which is hardly a safe assumption
    I sort it before I call the function, but I guess it can be moved into the function
    Last edited by XxChris; January 26th, 2004 at 08:35 PM.
  22. #12
  23. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Posts
    217
    Rep Power
    0
    Well, since your all in the "helping chris" mood I might as well ask if there are any equivelents to isnum() and isalpha() (from C) for Python. I'm getting a user inputted hex number and I need to know which digits are acutaly numbers. Thanks for all your help.

    EDIT: would this be a resonable solution?

    bleh = ["a", 1, "b", 2]

    try:
    num = int(bleh[0])
    #do stuff
    except:
    # do stuff
    Last edited by XxChris; January 26th, 2004 at 09:12 PM.
  24. #13
  25. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2001
    Location
    Houston, TX
    Posts
    383
    Rep Power
    14
    Yeah, in fact, you can do:
    Code:
    >>> int('a', 16)
    10
    >>>
    int() accepts a "base" argument. So, invalid letters wouldn't work, but valid ones would.
  26. #14
  27. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Posts
    217
    Rep Power
    0
    Thanks alot

IMN logo majestic logo threadwatch logo seochat tools logo