Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |
 User Name: Password: Remember me

The Shed is going Social! Join us on FaceBook and Twitter and chime in on the conversation.

 Dev Shed Forums Sponsor:
#1
January 26th, 2004, 10:32 AM
 XxChris
Registered User

Join Date: Aug 2003
Posts: 217
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?

#2
January 26th, 2004, 02:46 PM
 Strike
Contributing User

Join Date: Dec 2001
Location: Houston, TX
Posts: 383
Time spent in forums: 1 h 41 m 27 sec
Reputation Power: 12
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.

#3
January 26th, 2004, 06:16 PM
 XxChris
Registered User

Join Date: Aug 2003
Posts: 217
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!

#4
January 26th, 2004, 06:24 PM
 XxChris
Registered User

Join Date: Aug 2003
Posts: 217
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```

#5
January 26th, 2004, 06:25 PM
 XxChris
Registered User

Join Date: Aug 2003
Posts: 217
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```

#6
January 26th, 2004, 06:36 PM
 Strike
Contributing User

Join Date: Dec 2001
Location: Houston, TX
Posts: 383
Time spent in forums: 1 h 41 m 27 sec
Reputation Power: 12
See my edited versions above

#7
January 26th, 2004, 06:48 PM
 Strike
Contributing User

Join Date: Dec 2001
Location: Houston, TX
Posts: 383
Time spent in forums: 1 h 41 m 27 sec
Reputation Power: 12
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

#8
January 26th, 2004, 06:59 PM
 netytan
Hello World :)

Join Date: Mar 2003
Location: Hull, UK
Posts: 2,537
Time spent in forums: 1 Week 2 Days 18 h 17 m 47 sec
Reputation Power: 68
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.

#9
January 26th, 2004, 07:28 PM
 lazy_yogi
Contributing User

Join Date: Mar 2003
Posts: 325
Time spent in forums: 7 h 58 m 36 sec
Reputation Power: 11
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

#10
January 26th, 2004, 07:30 PM
 XxChris
Registered User

Join Date: Aug 2003
Posts: 217
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

#11
January 26th, 2004, 07:32 PM
 XxChris
Registered User

Join Date: Aug 2003
Posts: 217
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.

#12
January 26th, 2004, 07:46 PM
 XxChris
Registered User

Join Date: Aug 2003
Posts: 217
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.

#13
January 26th, 2004, 08:16 PM
 Strike
Contributing User

Join Date: Dec 2001
Location: Houston, TX
Posts: 383
Time spent in forums: 1 h 41 m 27 sec
Reputation Power: 12
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.

#14
January 26th, 2004, 08:28 PM
 XxChris
Registered User

Join Date: Aug 2003
Posts: 217
Time spent in forums: < 1 sec
Reputation Power: 0
Thanks alot

 Viewing: Dev Shed Forums > Programming Languages > Python Programming > Lists

## Developer Shed Advertisers and Affiliates

 Thread Tools Search this Thread Search this Thread: Advanced Search Display Modes Rate This Thread Linear Mode Rate This Thread: 5 : Excellent 4 : Good 3 : Average 2 : Bad 1 : Terrible

 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 Please select one User Control Panel Private Messages Subscriptions Who's Online Search Forums Forums Home -------------------- Programming Languages    PHP Development        PHP FAQs and Stickies    Perl Programming        Perl FAQs and Stickies    C Programming        C Programming FAQs and Stickies    Java Help        Java FAQs    Python Programming        Python Programming FAQs    Ruby Programming        Ruby Programming FAQs    Game Development        Game Development FAQs Programming Languages - More    ASP Programming        ASP Programming FAQs    .Net Development        .Net Development FAQs    Visual Basic Programming        Visual Basic Programming FAQs    Software Design        Software Design FAQs    ColdFusion Development        ColdFusion Development FAQs    Delphi Programming        Delphi Programming FAQs    Regex Programming        Regex Programming FAQs    XML Programming        XML Programming FAQs    Other Programming Languages        Other Programming Languages FAQs Web Design    HTML Programming        HTML Programming FAQs    JavaScript Development        JavaScript Development FAQs    CSS Help        CSS Help FAQs    Flash Help        Flash Help FAQs    Photoshop Help        Photoshop Help FAQs    Web Design Help        Web Design Help FAQs    Website Critiques        Website Critiques FAQs    Search Engine Optimization        Search Engine Optimization FAQs Mobile Programming    Mobile Programming        Mobile Programming FAQs    iPhone SDK Development        iPhone SDK Development FAQs    Android Development        Android Development FAQs    BlackBerry Development        BlackBerry Development FAQs Web Site Management    Business Help        Business Help FAQs    Development Software        Development Software FAQs    Scripts        Scripts FAQs Databases    Database Management        Database Management FAQs    DB2 Development        DB2 Development FAQs    MySQL Help        MySQL Help FAQs    PostgreSQL Help        PostgreSQL Help FAQs    Firebird SQL Development        Firebird SQL Development FAQs    MS SQL Development        MS SQL Development FAQs    Oracle Development        Oracle Development FAQs    LDAP Programming        LDAP Programming FAQs System Administration    Mail Server Help        Mail Server Help FAQs    Apache Development        Apache Development FAQs    Security and Cryptography        Security and Cryptography FAQs    Antivirus Protection        Antivirus Protection FAQs    DNS        DNS FAQs    IIS        IIS FAQs    Networking Help        Networking Help FAQs    FTP Help        FTP Help FAQs Operating Systems    BSD Help        BSD Help FAQs    Linux Help        Linux Help FAQs    UNIX Help        UNIX Help FAQs    Windows Help        Windows Help FAQs    Mac Help        Mac Help FAQs Web Hosting    Web Hosting        Web Hosting FAQs    Free Web Hosting        Free Web Hosting FAQs    Web Hosting Requests        Web Hosting Requests FAQs    Web Hosting Offers        Web Hosting Offers FAQs Computer Hardware    Computer Hardware    CPUs        CPUs FAQs    Cooling        Cooling FAQs    Embedded Programming        Embedded Programming FAQs    Motherboards        Motherboards FAQs    Multimedia Hardware        Multimedia Hardware FAQs Other    Dev Shed Lounge        Dev Shed Lounge FAQs    Development Articles        Development Articles FAQs    Beginner Programming        Beginner Programming FAQs    Hire A Programmer        Hire A Programmer FAQs    Project Help Wanted        Project Help Wanted FAQs Latest News Updated Hourly    Technology News    Business News    Science News Forum Information    Forum Rules/Guidelines        Forum Rules/Guidelines FAQs    Forum Announcements        Forum Announcements FAQs    Dev Shed Gaming Center        Go to the Dev Shed Battle Arena        Go to the Dev Shed Arcade Games        Go to the Legend of the Green Dragon    Suggestions & Feedback        Suggestions & Feedback FAQs

 Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |