Python Programming
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
User Name:
Password:
Remember me
Go Back   Dev Shed ForumsProgramming LanguagesPython Programming

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Rate Thread Display Modes
 
Unread Dev Shed Forums Sponsor:
Get inside! Sample the range of functionality easily built with JMSL Library for Time Series Data Analysis, Heat Maps, Portfolio Optimization, Monte Carlo Simulation, Stock Price Charting and more. Download Now!
  #1  
Old January 26th, 2004, 10:32 AM
XxChris XxChris is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Aug 2003
Posts: 217 XxChris User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation 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?

Reply With Quote
  #2  
Old January 26th, 2004, 02:46 PM
Strike Strike is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Dec 2001
Location: Houston, TX
Posts: 383 Strike User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 h 41 m 27 sec
Reputation Power: 7
Send a message via ICQ to Strike Send a message via AIM to Strike Send a message via Yahoo to Strike
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 06:46 PM.

Reply With Quote
  #3  
Old January 26th, 2004, 06:16 PM
XxChris XxChris is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Aug 2003
Posts: 217 XxChris User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation 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!

Reply With Quote
  #4  
Old January 26th, 2004, 06:24 PM
XxChris XxChris is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Aug 2003
Posts: 217 XxChris User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation 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

Reply With Quote
  #5  
Old January 26th, 2004, 06:25 PM
XxChris XxChris is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Aug 2003
Posts: 217 XxChris User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation 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

Reply With Quote
  #6  
Old January 26th, 2004, 06:36 PM
Strike Strike is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Dec 2001
Location: Houston, TX
Posts: 383 Strike User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 h 41 m 27 sec
Reputation Power: 7
Send a message via ICQ to Strike Send a message via AIM to Strike Send a message via Yahoo to Strike
See my edited versions above

Reply With Quote
  #7  
Old January 26th, 2004, 06:48 PM
Strike Strike is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Dec 2001
Location: Houston, TX
Posts: 383 Strike User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 h 41 m 27 sec
Reputation Power: 7
Send a message via ICQ to Strike Send a message via AIM to Strike Send a message via Yahoo to 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

Reply With Quote
  #8  
Old January 26th, 2004, 06:59 PM
netytan's Avatar
netytan netytan is offline
Hello World :)
Dev Shed Frequenter (2500 - 2999 posts)
 
Join Date: Mar 2003
Location: Hull, UK
Posts: 2,529 netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level) 
Time spent in forums: 1 Week 2 Days 17 h 19 m 5 sec
Reputation Power: 63
Send a message via ICQ to netytan Send a message via AIM to netytan Send a message via MSN to netytan Send a message via Yahoo to netytan
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.
__________________
programming language development: www.netytan.com Hula


Last edited by netytan : January 26th, 2004 at 07:02 PM.

Reply With Quote
  #9  
Old January 26th, 2004, 07:28 PM
lazy_yogi lazy_yogi is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Mar 2003
Posts: 325 lazy_yogi User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 7 h 58 m 36 sec
Reputation Power: 6
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

Reply With Quote
  #10  
Old January 26th, 2004, 07:30 PM
XxChris XxChris is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Aug 2003
Posts: 217 XxChris User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation 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

Reply With Quote
  #11  
Old January 26th, 2004, 07:32 PM
XxChris XxChris is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Aug 2003
Posts: 217 XxChris User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 0
Quote:
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 07:35 PM.

Reply With Quote
  #12  
Old January 26th, 2004, 07:46 PM
XxChris XxChris is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Aug 2003
Posts: 217 XxChris User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation 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 08:12 PM.

Reply With Quote
  #13  
Old January 26th, 2004, 08:16 PM
Strike Strike is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Dec 2001
Location: Houston, TX
Posts: 383 Strike User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 h 41 m 27 sec
Reputation Power: 7
Send a message via ICQ to Strike Send a message via AIM to Strike Send a message via Yahoo to Strike
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.

Reply With Quote
  #14  
Old January 26th, 2004, 08:28 PM
XxChris XxChris is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Aug 2003
Posts: 217 XxChris User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 0
Thanks alot

Reply With Quote
Reply

Viewing: Dev Shed ForumsProgramming LanguagesPython Programming > Lists


Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump