Starting Python

Reply

Join Date: Oct 2004
Posts: 3,947
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 914
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #31
Sep 25th, 2005
Python's lambda allows you to declare a one-line nameless minifunction on the fly. The format is:
lambda parameter(s): expression using the parameter(s)
It returns the result of the expression. The expression has to be a one-liner (no newlines)! Here is a little example ...
  1. # sort strings in a list, case insensitive
  2. import string
  3.  
  4. wordList = ['Python', 'is', 'really', 'great', 'stuff']
  5. print "Original list:"
  6. print wordList
  7.  
  8. wordList.sort()
  9. print "After standard sort (ASCII upper case is before lower case):"
  10. print wordList
  11.  
  12. wordList.sort(lambda x, y: cmp(string.lower(x), string.lower(y)))
  13. print "After case insensitve sort with lambda and lower:"
  14. print wordList
Last edited by vegaseat; May 15th, 2007 at 6:47 pm. Reason: changed php tags
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,947
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 914
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #32
Sep 25th, 2005
List comprehension is something Python borrowed from a language called Haskell. It returns a new list and is shorter and simply faster than the traditional loop/append alternative. Look at the two functions and you can get an idea how list comprehension works within the one-line [ ... ].
  1. # the module profile is used to compare the two functions
  2.  
  3. import profile
  4.  
  5. def evenList1():
  6. """returns a list of even numbers from 0 to 99998 using append in a loop
  7. the 50000 calls to append() consume a lot of CPU time
  8. """
  9. L1 = []
  10. for x in range(100000):
  11. if x % 2 == 0:
  12. L1.append(x)
  13. return L1
  14.  
  15. def evenList2():
  16. """returns a list of even numbers from 0 to 99998 using list comprehension
  17. much faster in CPU time than the standard loop with append()
  18. """
  19. L2 = [ x for x in range(100000) if x % 2 == 0 ]
  20. return L2
  21.  
  22.  
  23. # test first 30 elements
  24. print evenList1()[0:30]
  25. print evenList2()[0:30]
  26.  
  27. print
  28. print "Profile of evenList1(), check the time consumed by the many append() calls:"
  29. print "(ignore time consumed by the profiler itself)\n"
  30. profile.run('evenList1()')
  31.  
  32. print "Profile of evenList2():"
  33. print "(ignore time consumed by the profiler itself)\n"
  34. profile.run('evenList2()')
Last edited by vegaseat; Mar 1st, 2007 at 3:49 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Jul 2005
Posts: 1,222
Reputation: bumsfeld will become famous soon enough bumsfeld will become famous soon enough 
Solved Threads: 137
bumsfeld's Avatar
bumsfeld bumsfeld is offline Offline
Nearly a Posting Virtuoso

Re: Starting Python

 
0
  #33
Oct 13th, 2005
Can you figure results?
  1. a, b, c, d, e = range(100, 1000, 200)
  2.  
  3. print a, b, c, d, e
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,947
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 914
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #34
Oct 21st, 2005
If you have been thinking about some GUI programming using wxPython, one hassle is to properly position and size the widgets (components) on the coordinates of the window. I prefer to use the position (x, y) tuple for the upper left corner of the widget, and the size (width, height) tuple. For example ...
  1. # wx.Choice(parent, id, pos, size, choices, style)
  2.  
  3. import wx
  4.  
  5. class MyPanel(wx.Panel):
  6.  
  7. def __init__(self, parent, id):
  8. # initial panel fills the frame
  9. # pos defaults to (0, 0) and size to (-1, -1)
  10. wx.Panel.__init__(self, parent, id)
  11. self.SetBackgroundColour("white")
  12.  
  13. # assigning keys-words, style is not used and assumes a default style
  14. self.choice1 = wx.Choice(self, -1, pos=wx.Point(10, 10), size=wx.Size(100, 150), choices=tenList)
  15. # a little less typing ...
  16. #self.choice1 = wx.Choice(self, -1, pos=(10, 10), size=(100, 150), choices=tenList)
  17. self.Bind(wx.EVT_CHOICE, self.selChoice1, self.choice1)
  18.  
  19. # simpler, but you have to follow the exact parameter sequence
  20. # (parent, id, position_tuple, size_tuple, choices)
  21. self.choice2 = wx.Choice(self, -1, (170, 10), (100, 150), oneList)
  22. self.Bind(wx.EVT_CHOICE, self.selChoice2, self.choice2)
  23.  
  24. def selChoice1(self, event):
  25. item1 = event.GetString()
  26. print "choice1 =", item1 # test
  27.  
  28. def selChoice2(self, event):
  29. item2 = event.GetString()
  30. print "choice2 =", item2 # test
  31.  
  32.  
  33. oneList = ['one', 'two', 'three', 'four']
  34. tenList = ['ten', 'twenty', 'thirty', 'forty']
  35.  
  36.  
  37. app = wx.PySimpleApp()
  38. # create a window/frame, no parent, -1 is default ID, title, size
  39. # pos is not used and defaults to (0, 0)
  40. frame = wx.Frame(None, -1, "wx.Size", size = (400, 310))
  41. MyPanel(frame,-1)
  42. frame.Show(True)
  43. app.MainLoop()
Last edited by vegaseat; Mar 1st, 2007 at 3:49 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,947
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 914
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #35
Nov 1st, 2005
If you have a list of tuples, you can sort by the index of the tuple element, as long as the tuples have the same number of elements. In some cases the first element of each tuple can be used as a sorting key. Here is an example showing the different alternatives at your disposal.
  1. # sorting a list of tuples by tuple index
  2.  
  3. def sortTupList(myList, n):
  4. """sort a list of tuples by tuple index n, returns a new list"""
  5. nlist = [(x[n], x) for x in myList]
  6. nlist.sort()
  7. return [val for (key, val) in nlist]
  8.  
  9. def sortTupList_inplace(myList, n):
  10. """sort a list of tuples by tuple index n in-place, myList will change"""
  11. myList[:] = [(x[n], x) for x in myList]
  12. myList.sort()
  13. myList[:] = [val for (key, val) in myList]
  14.  
  15.  
  16. originalList = [(2, 'ape', 'medium'), (3, 'bull', 'large'), (1, 'cat', 'small')]
  17.  
  18. # make a copy of the original list, beginning to end
  19. newList1 = originalList[:]
  20. # basic sort in-place, only sorts by first element (index=0) in tuple, list will change
  21. # (first element may be used as a sorting key)
  22. newList1.sort()
  23.  
  24. print newList1 # [(1, 'cat', 'small'), (2, 'ape', 'medium'), (3, 'bull', 'large')]
  25.  
  26. # make a copy of the original list, beginning to end
  27. newList2 = originalList[:]
  28. # sort in-place, sorts by specified element (index=2) in tuple, list will change
  29. sortTupList_inplace(newList2, 2)
  30.  
  31. print newList2 # [(3, 'bull', 'large'), (2, 'ape', 'medium'), (1, 'cat', 'small')]
  32.  
  33. # sort by specified element (index=1) of the tuple, original list will not change
  34. newList3 = sortTupList(originalList, 1)
  35.  
  36. print newList3 # [(2, 'ape', 'medium'), (3, 'bull', 'large'), (1, 'cat', 'small')]
  37.  
  38. # similar to above, but using operator.itemgetter() and sorted() (needs Python24)
  39. import operator
  40. index1 = operator.itemgetter(1)
  41. newList4 = sorted(originalList, key=index1)
  42.  
  43. print newList4 # [(2, 'ape', 'medium'), (3, 'bull', 'large'), (1, 'cat', 'small')]
Last edited by vegaseat; Mar 1st, 2007 at 3:50 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,947
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 914
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #36
Nov 4th, 2005
I used to program in C/C++ and still scan the forums. It is amazing how many people write functions within a function either by design or mistake caused by poor identation.

In contrast to C/C++ Python does allow you to define functions within a function, but remember that they are local to that function, unless you apply special considerations. Let's take a look ...
  1. # define functions within a function
  2.  
  3. def printCircle(radius):
  4. """functions defined within this function are strictly local"""
  5. def pi():
  6. # pi is built in, but this is for the demonstration
  7. return 355/113.0
  8. def circleArea(r):
  9. return pi()*r*r
  10. def circleCircumference(r):
  11. return pi()*2*r
  12. # access the local (nested) functions
  13. print "A circle with a radius of %f ..." % radius
  14. print "... has an area of %f" % circleArea(radius)
  15. print "... has a circumference of %f" % circleCircumference(radius)
  16.  
  17. printCircle(1)
  18.  
  19. #print pi() # local, would give NameError: name 'pi' is not defined
  20.  
  21. print
  22.  
  23. def func1 () :
  24. """a function can return local functions"""
  25. def func2 () :
  26. print "this is a message from func2"
  27. def func3 () :
  28. print "this message courtesy of func3"
  29. # needed to access the local functions globally
  30. return func2, func3
  31.  
  32. #func2() # would give NameError: name 'func2' is not defined
  33.  
  34. # let Python know that func2 and func3 are in func1
  35. func2, func3 = func1()
  36. # now you can call these functions
  37. func2()
  38. func3()
Last edited by vegaseat; Mar 1st, 2007 at 3:51 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,947
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 914
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #37
Nov 26th, 2005
This is an example of a word frequency program. It combines a few lines to make it look shorter, but I hope you can still figure it out ...
  1. str1 = """Man who run in front of car, get tired.
  2. Man who run behind car, get exhausted."""
  3.  
  4. # create a list of lower case words
  5. word_list = str1.lower().split(None)
  6.  
  7. # create a word:frequency dictionary
  8. word_freq = {}
  9. for word in word_list:
  10. # strip any trailing punctuation marks
  11. if word[-1:] in ".,!?;:":
  12. word = word.rstrip(word[-1:])
  13. word_freq[word] = word_freq.get(word, 0) + 1
  14.  
  15. # create a sorted list of keys
  16. keys = sorted(word_freq.keys())
  17. for word in keys:
  18. print "%-10s %d" % (word, word_freq[word])
Last edited by vegaseat; Mar 1st, 2007 at 3:52 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,947
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 914
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #38
Dec 6th, 2005
This shows you how to start an external file from within Python code. In this case a small Windows media player to play midi or MP3 files. Sorry, the funky graphics display only gets active with .mp3 files. A zip file with the player and a few sample midi files is attached.
  1. # play a midi file with an external midiplayer like
  2. # the small (32k) BCX created WMPlay5.exe by vegaseat
  3.  
  4. import subprocess
  5. import os
  6.  
  7. midi_player = "WMPlay5.exe"
  8. # change folder and midi file to your needs
  9. midi_folder = "D:/Python24/Atest/Mplay"
  10. midi_file = "DGZ1.mid"
  11.  
  12. player = os.path.join(midi_folder, midi_player)
  13. midi = os.path.join(midi_folder, midi_file)
  14.  
  15. subprocess.call([player, midi])
Last edited by vegaseat; May 15th, 2007 at 6:48 pm. Reason: replaced php tags
Attached Files
File Type: zip Mplay.zip (52.9 KB, 19 views)
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Jul 2005
Posts: 1,222
Reputation: bumsfeld will become famous soon enough bumsfeld will become famous soon enough 
Solved Threads: 137
bumsfeld's Avatar
bumsfeld bumsfeld is offline Offline
Nearly a Posting Virtuoso

Re: Starting Python

 
0
  #39
Dec 27th, 2005
A logic shortcut:
  1. x, y, z = 1, 2, 3
  2. # test if y value is between x and z value
  3. if x < y < z:
  4. print x, y, z # 1 2 3
  5. print
  6. # same test, longer logic
  7. if x < y and y < z:
  8. print x, y, z # 1 2 3
  9. print
Notice you can even do logic tests like:
  1. if u < w < v < y < x:
  2. do some things
Reply With Quote Quick reply to this message  
Join Date: Jan 2006
Posts: 1
Reputation: floalin13 is an unknown quantity at this point 
Solved Threads: 0
floalin13 floalin13 is offline Offline
Newbie Poster

Re: Starting Python

 
0
  #40
Jan 7th, 2006
hey i am interested in programming, and i dont know where to start. i found this forum on google. can anyone please help.

Edited by vegaseat: Start right here!!!! If you have any questions, please start a thread in the regular Python forum!
Last edited by vegaseat; Jan 8th, 2006 at 12:42 pm.
Reply With Quote Quick reply to this message  
Reply

Message:



Similar Threads
Other Threads in the Python Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC