Starting Python

Reply

Join Date: Jul 2007
Posts: 489
Reputation: shadwickman will become famous soon enough shadwickman will become famous soon enough 
Solved Threads: 76
shadwickman's Avatar
shadwickman shadwickman is offline Offline
Posting Pro in Training

Re: Starting Python

 
1
  #181
Jul 2nd, 2009
For Python 2.x:
People seem to overlook the usefulness of built-in functions for handling common issues with lists. A lot of times, filter , map , and reduce can easily and efficiently serve typical purposes that most people attempt without these. Here's an example of their usage (I use lambda expressions in them - you can read up on lambda expressions here):
  1. # filter
  2. # in the interactive shell, use help(filter) for more info.
  3. # filter takes a function and a list, and returns a list of
  4. # the items that returned True for the given function.
  5. # This example takes a list and returns one with the
  6. # unallowed words removed.
  7.  
  8. words = ['This', 'sentence', 'has', 'unallowed', 'words']
  9. unallowed = ['has', 'words']
  10. remainder = filter(lambda x: x not in unallowed, words)
  11.  
  12. """result ->
  13. ['This', 'sentence', 'unallowed']
  14. """
  1. # map
  2. # in the interactive shell, use help(map) for more info.
  3. # map takes a function and a list, and returns a list of
  4. # the items after applying the specified function to them.
  5. # This example takes a list and returns one in which
  6. # every index was squared.
  7.  
  8. data = [2, 5, 9, 16, 31, 35]
  9. squared = map(lambda x: x*x, data)
  10. """result ->
  11. [4, 25, 81, 256, 961, 1225]
  12. """
  1. # reduce
  2. # in the interactive shell, use help(reduce) for more info.
  3. # reduce takes a function and a list, and returns a single
  4. # value formed by taking the result of the function on the
  5. # first two indices, then applying the function on that result
  6. # and the third index, and so forth.
  7. # This example takes a list and returns an integer calculated
  8. # by multiplying all the indices together.
  9. data = [1, 3, 4, 7, 8, 9]
  10. reduce(lambda x, y: x * y, data)
  11. """result ->
  12. 6048
  13. """
With reduce, note that it is redundant to use this to sum all the indices in a list, as there is a built-in function for that, sum . (This is because getting the sum of a list is such a common need.)

Python docs' examples of these three functions.
Last edited by shadwickman; Jul 2nd, 2009 at 12:58 am.
"Two good old boys in a fire-apple red convertible. Stoned. Ripped. Twisted. Good people."
- Hunter S. Thompson

my photography
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 2,275
Reputation: sneekula has a spectacular aura about sneekula has a spectacular aura about 
Solved Threads: 174
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Maven

Re: Starting Python

 
0
  #182
Aug 1st, 2009
This code shows you how to get file information of a given folder into a table. It also is modified to work with Linux or Windows, as these Operating Systems have differences in some of the file functions and folder syntax:
  1. # File_Info2.py
  2. # show some file details in a table
  3. # note that Linux file names are case sensitive
  4. # Linux uses different folder syntax and getctime() for last changes
  5. # Windows uses getmtime() for last changes/modifications
  6. # this program has been written to accept Windows or Linux
  7. # tested with Python 2.5.4
  8.  
  9. import os
  10. import time
  11. import sys
  12.  
  13. # check if your OS is linux or windows
  14. # pick an appropriate folder/directory you have
  15. if sys.platform[:5] == "linux":
  16. folder = "/home/dell/Atest25/Chemistry"
  17. win_flag = False
  18. else:
  19. folder = 'C:/Python25/Atest25/Chemistry'
  20. win_flag = True
  21.  
  22. #print(win_flag) # test
  23.  
  24. # create list of (fname, size, date_time) tuples
  25. file_info = []
  26. for item in os.listdir(folder):
  27. # get full path for isdir() to work
  28. path = os.path.join(folder, item)
  29. # make sure item is a filename
  30. if os.path.isdir(path):
  31. continue # skip any folder names
  32. if win_flag:
  33. change = os.path.getmtime(path) # Windows
  34. else:
  35. change = os.path.getctime(path) # Linux
  36. # (year,month,day,hour,min,sec,weekday(Monday=0),yearday,dlsflag)
  37. # eg. (2009, 7, 31, 21, 37, 6, 4, 212, 1)
  38. change_tuple = time.localtime(change)
  39. date_time24 = time.strftime("%m/%d/%Y %H:%M:%S", change_tuple)
  40. size = os.path.getsize(path)
  41. # convert to kb
  42. if size > 999:
  43. size = round(size/1024.0, 1)
  44. else:
  45. size = round(size/1024.0, 3)
  46. file_info.append((os.path.basename(path), size, date_time24))
  47.  
  48. # show result as formatted table ...
  49. # for longer file names use eg. "%-36s %8s %s"
  50. fs = "%-25s %8s %s"
  51. print(fs % (' Name', 'Size (kb)', ' Date&Time (24hr)'))
  52. for line in file_info:
  53. print(fs % line)
  54.  
  55. """my output example -->
  56. Name Size (kb) Date&Time (24hr)
  57. MWcalc2a.py 3.2 05/10/2009 10:21:51
  58. PeriodicTable1.py 5.6 06/04/2009 17:12:15
  59. CONST.TXT 1.0 05/10/2009 10:21:51
  60. ELEMORDR.TXT 0.417 05/10/2009 10:21:51
  61. AirEarth.txt 1.5 05/10/2009 10:21:51
  62. ELEMENT9.TXT 11.2 05/10/2009 10:21:51
  63. ChemHelp.exe 237.0 05/10/2009 10:21:51
  64. wxgridGrid3_solvents.pyw 4.7 06/04/2009 17:12:15
  65. MWcalc1.py 3.2 05/10/2009 10:21:51
  66. CHEMICAL.BMP 43.2 05/10/2009 10:21:51
  67. MWtable1.py 2.4 05/10/2009 10:21:51
  68. """
No one died when Clinton lied.
Reply With Quote Quick reply to this message  
Join Date: Jul 2005
Posts: 1,205
Reputation: bumsfeld will become famous soon enough bumsfeld will become famous soon enough 
Solved Threads: 130
bumsfeld's Avatar
bumsfeld bumsfeld is offline Offline
Nearly a Posting Virtuoso

Re: Starting Python

 
0
  #183
Aug 2nd, 2009
Python31 is joy, here I am exploring named tuples and ordered dictionaries and their interconnection:
  1. # some play with named tuples and ordered dictionaries
  2. # needs Python3
  3.  
  4. import collections as co
  5.  
  6. # set up named tuple where staff is the identifier
  7. # and the field names are fname, sname, age
  8. ntup = co.namedtuple('staff', 'fname, sname, age')
  9.  
  10. # load the tuple
  11. nt1 = ntup('Hank', 'Zoller', 27)
  12. nt2 = ntup('Bjorn', 'Bartok', 34)
  13. # this would give an error, not enough args
  14. #nt3 = ntup('Jack', 'Schiett')
  15.  
  16. # show the named tuple
  17. print(nt1) # staff(fname='Hank', sname='Zoller', age=27)
  18. print(nt2) # staff(fname='Bjorn', sname='Bartok', age=34)
  19.  
  20. print(nt2.fname) # Bjorn
  21. print(nt2.age) # 34
  22.  
  23. # show the field names
  24. print(nt1._fields) # ('fname', 'sname', 'age')
  25.  
  26. # replace/update items by field name
  27. nt4 = nt1._replace(sname='Zeller', age=28)
  28. print(nt1) # staff(fname='Hank', sname='Zoller', age=27)
  29. print(nt4) # staff(fname='Hank', sname='Zeller', age=28)
  30.  
  31. # convert to ordered dictionary
  32. odict = nt2._asdict()
  33. print(odict)
  34. # convert ordered dictionary to regular dictionary
  35. print(dict(odict))
  36. # pop the last item
  37. odict.popitem()
  38. print(odict)
  39. print(odict['sname'])
  40.  
  41. """my output -->
  42. OrderedDict([('fname', 'Bjorn'), ('sname', 'Bartok'), ('age', 34)])
  43. {'age': 34, 'sname': 'Bartok', 'fname': 'Bjorn'}
  44. OrderedDict([('fname', 'Bjorn'), ('sname', 'Bartok')])
  45. Bartok
  46. """
  47.  
  48. # convert dictionary to named tuple
  49. d = {'age': 34, 'sname': 'Bartok', 'fname': 'Bjorn'}
  50. nt5 = ntup(**d)
  51. print(nt5) # staff(fname='Bjorn', sname='Bartok', age=34)
Last edited by bumsfeld; Aug 2nd, 2009 at 5:49 pm.
Should you find Irony, you can keep her!
Reply With Quote Quick reply to this message  
Join Date: Jun 2007
Posts: 3
Reputation: castegna is an unknown quantity at this point 
Solved Threads: 0
castegna castegna is offline Offline
Newbie Poster

Re: Starting Python

 
0
  #184
Aug 4th, 2009
My favorite part of python is regular expressios: Here is a nice example you could use:

Like creating a program that searches a database:

import re

a = re.compile("(^(?:0?[1-9]:[0-5]|1"
r"(?=[012])\d:[0-5])\d"
r"(\s)(AM|PM))$")

b = re.compile(r"(-?[1-9]\d?[\w])$|^\d$")

c = re.compile(r"^(\[('([A-Z]|[a-z])'"
r"(,\s'([A-Z]|[a-z])')*"
r")*\])$")

print "----Part a tests that match:"
print a.search("1:45 PM")
print a.search("10:36 AM")
print a.search("12:00 PM")
print a.search("11:59 AM")
print a.search("8:27 AM")

print "----Part a tests that do not match:"
print a.search("21:45 PM")
print a.search("13:36 AM")
print a.search("12:00 XM")
print a.search("11:59 AP")
print a.search("8:3 AM")
print a.search("1:23PM")
print a.search("3:62 PM")

print "----Part b tests that match:"
print b.search("0")
print b.search("5")
print b.search("-16")
print b.search("1873")
print b.search("-89345")

print "----Part b tests that do not match:"
print b.search("X")
print b.search("-0")
print b.search("00")
print b.search("007")
print b.search("-000")
print b.search("-3453!")

print "----Part c tests that match:"
print c.search("['H', 'e', 'l', 'l', 'o']")
print c.search("['H']")
print c.search("['H', 'e']")
print c.search("[]")
print c.search("['C', 'S', 'S', 'E']")

print "----Part c tests that do not match:"
print c.search("['H', 'e', 'l', '7', 'o']")
print c.search("['H', 'e', 'l', 'l', 'o'")
print c.search("['H', 'e', 'l', 'l', 'o',]")
print c.search("['H', 'e', 'l', 'l', 'o' ]")
print c.search("[ 'H', 'e', 'l', 'l', 'o']")
print c.search("['H', 'e', 'lf', 'l', 'o']")
print c.search("[ ]")
print c.search("['H', ]")
print c.search("['5']")

print "----Part d tests that do not match:"
print d.search("901 12th Ave.\nSeattle, WA 98122")
print d.search("901 12th Ave.\nSeattle, WA 98122-1090")
print d.search("1 12th Ave.\nMy City, WA 98122")
print d.search("12 12th Ave.\nSeattle, WA 98122")
print d.search("9 E B&O St.\nB R F, CO 12345")
print d.search("123345 12th Ave.\nSeattle, WA 98122")

print "----Part d tests that do not match:"
print d.search("901 12th Ave.\nSeattle, WA 9812")
print d.search("901 12th Ave.\nSeattle, WA 98122-100")
print d.search("901A 12th Ave.\nSeattle, WA 98122-1090")
print d.search("901 12th Ave.\nSeattle, WAX 98122")
print d.search("901 12th Ave.\nSeattle WA 98122")
print d.search("901 12th Ave.\nSeattle,WA 98122")
print d.search("901 12th Ave.\n\nSeattle, WA 98122")
print d.search("901 12th Ave.\nSeattle, WA 981221090")
print d.search("0 12th Ave.\nSeattle, WA 98122")
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,858
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: 867
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #185
Aug 9th, 2009
Let's assume you want to sort a list of dictionaries by the value of a given key. The module operator will be of great help ...
  1. # sorting a list of dictionaries by the value of a specific key
  2.  
  3. import operator as op
  4.  
  5. # list of {function, priority} dictionaries
  6. staff = [
  7. {'function' : 'waiter', 'priority' : 3},
  8. {'function' : 'cook', 'priority' : 1},
  9. {'function' : 'janitor', 'priority' : 4},
  10. {'function' : 'cashier', 'priority' : 2}
  11. ]
  12.  
  13. # sort list by the values of key 'priority'
  14. staff2 = []
  15. for dic in sorted(staff, key=op.itemgetter('priority')):
  16. staff2.append(dic)
  17.  
  18. print(staff2)
  19.  
  20. """my prettied result -->
  21. [
  22. {'function': 'cook', 'priority': 1},
  23. {'function': 'cashier', 'priority': 2},
  24. {'function': 'waiter', 'priority': 3},
  25. {'function': 'janitor', 'priority': 4}
  26. ]
  27. """
Last edited by vegaseat; Aug 9th, 2009 at 2:56 pm.
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Jun 2008
Posts: 106
Reputation: zachabesh is an unknown quantity at this point 
Solved Threads: 16
zachabesh's Avatar
zachabesh zachabesh is offline Offline
Junior Poster

Re: Starting Python

 
0
  #186
Aug 14th, 2009
Or, sort a list of class objects by an attribute (similar idea as above):

  1. import operator
  2. import string
  3.  
  4. def normcaps(strg):
  5. s = string.upper(strg[0]) + strg[1:]
  6. return s
  7.  
  8.  
  9. class Man:
  10. def __init__(self,name,pos,age):
  11. self.name = name.lower()
  12. self.pos = pos.lower()
  13. self.age = age
  14. def __getitem__(self,key):
  15. return self.__dict__[key]
  16. def __repr__(self):
  17. return self.__str__()
  18. def __str__(self):
  19. print_name = normcaps(self.name)
  20. print_pos = normcaps(self.pos)
  21. s = "%s - %s - %s" %(print_name,print_pos,self.age)
  22. return s
  23.  
  24. bill = Man('bill','CEO',65)
  25. zach = Man('zach','intern',19)
  26. jerry = Man('jerry','alpha',52)
  27.  
  28. man_list = [jerry,bill,zach]
  29.  
  30.  
  31. get_age = operator.itemgetter('age')
  32. get_pos = operator.itemgetter('pos')
  33. get_name = operator.itemgetter('name')
  34.  
  35. by_age = sorted(man_list,key = get_age)
  36.  
  37. by_name = sorted(man_list,key = get_name)
  38.  
  39. by_pos = sorted(man_list,key = get_pos)
  40.  
  41. print man_list
  42.  
  43. print by_age
  44.  
  45. print by_name
  46.  
  47. print by_pos
Last edited by zachabesh; Aug 14th, 2009 at 8:36 pm.
-Zac
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,858
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: 867
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #187
Aug 15th, 2009
With the introduction of Python version 3 a number of builtins (functions, methods, classes, ...) have been removed and others added. Here is a way to look at the differences.

First create a file of 'builtins' in Python25 ...
  1. # write a sorted 'list' of all Python builtins
  2. # (does not include statements) to a file (run with Python 2.5.4)
  3. fout = open("Builtins25.txt", "w")
  4. print >> fout, '\n'.join(sorted(dir(__builtins__), key=str.lower))
... now the 'builtins' in Python31 ...
  1. # write a sorted 'list' of all Python builtins
  2. # (does not include statements) to a file (run with Python 3.1)
  3. fout = open('Builtins31.txt', 'w')
  4. print('\n'.join(sorted(dir(__builtins__), key=str.lower)), file=fout)
After we have written the two files we want Python to look at them and show us which 'builtins' are unique for each version ...
  1. # use Python module difflib to find the line by
  2. # line differences between two text files
  3. # modified to work with Python25 and Python31
  4. """
  5. technical details ...
  6. the difflib result will be a list of all lines with a marker
  7. prefix followed by a space for each original line
  8. - line unique to text list 1
  9. + line unique to text list 2
  10. space marks a line common to both text lists
  11. ? extra line used to point out character differences in lines
  12. + pointer --> word has extra char,
  13. ^ pointer --> spelling,
  14. - pointer --> word has missing char
  15. """
  16.  
  17. import difflib
  18.  
  19. lines25 = open("Builtins25.txt").readlines()
  20. lines31 = open("Builtins31.txt").readlines()
  21.  
  22. # set up module difflib
  23. diff_instance = difflib.Differ()
  24. diff_list = list(diff_instance.compare(lines25, lines31))
  25.  
  26. # testing ...
  27. #for line in diff_list: print(line.rstrip())
  28.  
  29. # lines unique to lines25
  30. unique25 = ""
  31. for line in diff_list:
  32. if line[0] == '-':
  33. unique25 += line[2:]
  34.  
  35. # lines unique to lines31
  36. unique31 = ""
  37. for line in diff_list:
  38. if line[0] == '+':
  39. unique31 += line[2:]
  40.  
  41. print('-'*48)
  42. print("Builtins unique to Python25 and not in Python31:")
  43. print(unique25)
  44.  
  45. print('-'*48)
  46. print("Builtins unique to Python31 and not in Python25:")
  47. print(unique31)
  48.  
  49. """my result -->
  50. ------------------------------------------------
  51. Builtins unique to Python25 and not in Python31:
  52. apply
  53. basestring
  54. buffer
  55. callable
  56. cmp
  57. coerce
  58. execfile
  59. file
  60. intern
  61. long
  62. raw_input
  63. reduce
  64. reload
  65. StandardError
  66. unichr
  67. unicode
  68. xrange
  69.  
  70. ------------------------------------------------
  71. Builtins unique to Python31 and not in Python25:
  72. __build_class__
  73. __package__
  74. ascii
  75. bin
  76. BufferError
  77. bytearray
  78. bytes
  79. BytesWarning
  80. exec
  81. format
  82. memoryview
  83. next
  84. print
  85.  
  86. Note that exec, next and print are considered statements in Python25
  87. """
Last edited by vegaseat; Aug 15th, 2009 at 7:32 pm.
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Aug 2005
Posts: 1,514
Reputation: Ene Uran has a spectacular aura about Ene Uran has a spectacular aura about 
Solved Threads: 168
Ene Uran's Avatar
Ene Uran Ene Uran is offline Offline
Posting Virtuoso

Re: Starting Python

 
0
  #188
Sep 5th, 2009
Have you ever wondered what 'self' is doing when you use Python classes? Here is the short and sweet of it:
  1. # role of self in Python classes
  2. # self can be named different, but 'self' is convention
  3.  
  4. class Snake(object):
  5. def __init__(self, name):
  6. # self keeps track of each instance
  7. # and also makes self.name global to class methods
  8. self.name = name
  9. # for test only
  10. print(self)
  11.  
  12. def isnice(self):
  13. # a class method has self as the first argument
  14. return self.name + " is very nice"
  15.  
  16. # create 2 instances of class Snake
  17. bob = Snake('Bob Python')
  18. mary = Snake('Mary Rattle')
  19.  
  20. print('-'*40)
  21.  
  22. # now you can get the name that has been assigned to self.name
  23. print(bob.name)
  24. print(mary.name)
  25.  
  26. # access the class method
  27. print(mary.isnice())
  28.  
  29. """my result (Python 3.1.1) -->
  30. # self for each instance has a different location in memory
  31. <__main__.Snake object at 0x01E0B2B0>
  32. <__main__.Snake object at 0x01E0B090>
  33. ----------------------------------------
  34. Bob Python
  35. Mary Rattle
  36. Mary Rattle is very nice
  37. """
drink her pretty
Reply With Quote Quick reply to this message  
Join Date: Aug 2005
Posts: 1,514
Reputation: Ene Uran has a spectacular aura about Ene Uran has a spectacular aura about 
Solved Threads: 168
Ene Uran's Avatar
Ene Uran Ene Uran is offline Offline
Posting Virtuoso

Re: Starting Python

 
0
  #189
Sep 5th, 2009
Sometimes it's nice to have static variable in a function. A static variable remembers its last value. Here is one way to do it with Python:
  1. # a class can give all global variables a save namespace
  2. # also behaves like a static variable in a function
  3.  
  4. class Global(object):
  5. """
  6. declare all global variables here
  7. """
  8. x = 0
  9. z = False
  10.  
  11.  
  12. # now all global variables can have the class instance
  13. # as a namespace, use something simple like ww
  14. ww = Global()
  15.  
  16. # testing ...
  17. print( ww.x ) # 0
  18. print( ww.z ) # False
  19.  
  20. def incr_wwx() :
  21. """
  22. ww.x does not need to be declared global
  23. and functions as a static variable here
  24. """
  25. ww.x += 1
  26. return ww.x
  27.  
  28. print( incr_wwx() ) # 1
  29. print( incr_wwx() ) # 2
  30. print( incr_wwx() ) # 3
  31. print( ww.x ) # 3
  32.  
  33. print( '-'*10)
  34.  
  35. def toggle():
  36. """
  37. toggle between True and False on each call
  38. """
  39. ww.z = not ww.z
  40. return ww.z
  41.  
  42. print( toggle() ) # True
  43. print( toggle() ) # False
  44. print( toggle() ) # True
  45. print( ww.z ) # True
For instance, if you put
ww.x += 1
into a function, ww.x keeps track of how many times the functions has been called.
Last edited by Ene Uran; Sep 5th, 2009 at 12:12 pm.
drink her pretty
Reply With Quote Quick reply to this message  
Join Date: Jul 2008
Posts: 841
Reputation: Gribouillis has a spectacular aura about Gribouillis has a spectacular aura about Gribouillis has a spectacular aura about 
Solved Threads: 192
Gribouillis's Avatar
Gribouillis Gribouillis is offline Offline
Practically a Posting Shark

Re: Starting Python

 
0
  #190
Sep 6th, 2009
Another classical way to have a static variable in a function in python is to add this variable as an attribute of the function:
  1. def countcalls():
  2. countcalls.counter += 1
  3. print("countcalls was called %d time(s)" % countcalls.counter)
  4. countcalls.counter = 0
  5.  
  6. for i in range(5):
  7. countcalls()
  8.  
  9. """ my output -->
  10. countcalls was called 1 time(s)
  11. countcalls was called 2 time(s)
  12. countcalls was called 3 time(s)
  13. countcalls was called 4 time(s)
  14. countcalls was called 5 time(s)
  15. """
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