Starting Python

Reply

Join Date: Oct 2004
Posts: 3,978
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: 921
Moderator
vegaseat's Avatar
vegaseat vegaseat is online now Online
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #171
Apr 29th, 2009
One way to approach multidimensional arrays in Python is to use a dictionary container with the index tuple as a key ...
  1. # create a 3x4x2 3D-array using a dictionary with index tuples as keys
  2. # initialize values to zero
  3. arr3d = dict([((x,y,z), 0) for x in range(3) for y in range(4)
  4. for z in range(2)])
  5.  
  6. # Python3 has dictionary comprehension to simplify this
  7. #arr3d = {(x,y,z):0 for x in range(3) for y in range(4) for z in range(2)}
  8.  
  9. # sorts the key index tuples
  10. for ix in sorted(arr3d):
  11. print( "ix=%s val=%s" % (ix, arr3d[ix]) )
  12.  
  13. print('-'*20)
  14.  
  15. # change some values, basically assign to index
  16. arr3d[2, 1, 0] = 5
  17. arr3d[1, 0, 1] = 17
  18. # or ...
  19. ix = (0, 0, 0)
  20. arr3d[ix] = 9
  21. # or just ...
  22. ix = 1, 1, 1
  23. arr3d[ix] = 3
  24.  
  25. for ix in sorted(arr3d):
  26. print( "ix=%s val=%s" % (ix, arr3d[ix]) )
  27.  
  28. print('-'*20)
  29.  
  30. # get a specific value from a given index
  31. print(arr3d[1, 1, 1]) # 3
  32. # or ...
  33. ix = 0, 0, 0
  34. print(arr3d[ix]) # 9
  35.  
  36. print('-'*20)
  37.  
  38. # get the lowest and highest key
  39. low = (min(arr3d.keys())) # --> (0, 0, 0)
  40. heigh = (max(arr3d.keys())) # --> (2, 3, 1)
  41. # show values
  42. print( "ix=%s val=%s" % (low, arr3d[low]) )
  43. print( "ix=%s val=%s" % (heigh, arr3d[heigh]) )
  44.  
  45. # get the heighest value in the array
  46. print(max(arr3d.values())) # 17
  47.  
  48. """
  49. my result -->
  50. ix=(0, 0, 0) val=0
  51. ix=(0, 0, 1) val=0
  52. ix=(0, 1, 0) val=0
  53. ix=(0, 1, 1) val=0
  54. ix=(0, 2, 0) val=0
  55. ix=(0, 2, 1) val=0
  56. ix=(0, 3, 0) val=0
  57. ix=(0, 3, 1) val=0
  58. ix=(1, 0, 0) val=0
  59. ix=(1, 0, 1) val=0
  60. ix=(1, 1, 0) val=0
  61. ix=(1, 1, 1) val=0
  62. ix=(1, 2, 0) val=0
  63. ix=(1, 2, 1) val=0
  64. ix=(1, 3, 0) val=0
  65. ix=(1, 3, 1) val=0
  66. ix=(2, 0, 0) val=0
  67. ix=(2, 0, 1) val=0
  68. ix=(2, 1, 0) val=0
  69. ix=(2, 1, 1) val=0
  70. ix=(2, 2, 0) val=0
  71. ix=(2, 2, 1) val=0
  72. ix=(2, 3, 0) val=0
  73. ix=(2, 3, 1) val=0
  74. --------------------
  75. ix=(0, 0, 0) val=9
  76. ix=(0, 0, 1) val=0
  77. ix=(0, 1, 0) val=0
  78. ix=(0, 1, 1) val=0
  79. ix=(0, 2, 0) val=0
  80. ix=(0, 2, 1) val=0
  81. ix=(0, 3, 0) val=0
  82. ix=(0, 3, 1) val=0
  83. ix=(1, 0, 0) val=0
  84. ix=(1, 0, 1) val=17
  85. ix=(1, 1, 0) val=0
  86. ix=(1, 1, 1) val=3
  87. ix=(1, 2, 0) val=0
  88. ix=(1, 2, 1) val=0
  89. ix=(1, 3, 0) val=0
  90. ix=(1, 3, 1) val=0
  91. ix=(2, 0, 0) val=0
  92. ix=(2, 0, 1) val=0
  93. ix=(2, 1, 0) val=5
  94. ix=(2, 1, 1) val=0
  95. ix=(2, 2, 0) val=0
  96. ix=(2, 2, 1) val=0
  97. ix=(2, 3, 0) val=0
  98. ix=(2, 3, 1) val=0
  99. --------------------
  100. 3
  101. 9
  102. --------------------
  103. ix=(0, 0, 0) val=9
  104. ix=(2, 3, 1) val=0
  105. 17
  106.  
  107. """
Last edited by vegaseat; Apr 29th, 2009 at 9:43 pm.
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,978
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: 921
Moderator
vegaseat's Avatar
vegaseat vegaseat is online now Online
DaniWeb's Hypocrite

Re: Starting Python

 
1
  #172
Apr 30th, 2009
You can use the local dictionary vars() to introduce variables into strings ...
  1. # using the local dictionary vars() to put
  2. # variables into strings
  3.  
  4. name = "Harry"
  5. name2 = "Verderchi"
  6.  
  7. for i in range(1, 5):
  8. # %d for integers and %s for strings
  9. print( "#%(i)d: %(name)s %(name2)s" % vars() )
  10.  
  11. """
  12. my result -->
  13. #1: Harry Verderchi
  14. #2: Harry Verderchi
  15. #3: Harry Verderchi
  16. #4: Harry Verderchi
  17. """
String templating was introduced in Python 2.4 ...
  1. # using string.Template() and the local dictionary vars()
  2. # for formatted printing
  3.  
  4. import string
  5.  
  6. name = "Harry"
  7. name2 = "Verderchi"
  8.  
  9. # create the template (note the $ before each variable name)
  10. t = string.Template("#$i: $name $name2")
  11.  
  12. for i in range(1, 5):
  13. # use safe_substitute() for potential missing variables
  14. print( t.safe_substitute(vars()) )
  15.  
  16. """
  17. my output -->
  18. #1: Harry Verderchi
  19. #2: Harry Verderchi
  20. #3: Harry Verderchi
  21. #4: Harry Verderchi
  22. """
If you want to know what vars() looks like, just print it.
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 2,273
Reputation: sneekula has a spectacular aura about sneekula has a spectacular aura about 
Solved Threads: 175
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Maven

Re: Starting Python

 
0
  #173
Jun 6th, 2009
This demonstrates a little function to extract the numeric value from a string like "$12.34/pound" where you want just 12.34 to do calculations:
  1. # extract the numeric value from a data string
  2. # snee
  3.  
  4. def extract_number(data_str):
  5. """
  6. extract the numeric value from a string
  7. the string should contain only one number
  8. return the number as int, float or None
  9. """
  10. s = ""
  11. for c in data_str:
  12. if c in '1234567890.-':
  13. s += c
  14. if s:
  15. # convert number to int or float
  16. return eval(s)
  17. else:
  18. return None
  19.  
  20.  
  21. data_raw = """
  22. header
  23. 23 bushels
  24. 43 years old
  25. 4323 Maiden Lane
  26. -$23.44/kg
  27. +$12.32
  28. footer
  29. """
  30.  
  31. # create a list of the string data
  32. data_list = data_raw.split('\n')
  33. print(data_list) # test
  34.  
  35. print('-'*60)
  36.  
  37. # extract numeric values from the data in the list
  38. for data_str in data_list:
  39. print(extract_number(data_str))
  40.  
  41. """
  42. my result -->
  43. ['', 'header', '23 bushels', ' 43 years old', '4323 Maiden Lane',
  44. '-$23.44/kg', ' +$12.32', 'footer', '']
  45. ------------------------------------------------------------
  46. None
  47. None
  48. 23
  49. 43
  50. 4323
  51. -23.44
  52. 12.32
  53. None
  54. None
  55. """
No one died when Clinton lied.
Reply With Quote Quick reply to this message  
Join Date: Aug 2005
Posts: 1,523
Reputation: Ene Uran has a spectacular aura about Ene Uran has a spectacular aura about 
Solved Threads: 169
Ene Uran's Avatar
Ene Uran Ene Uran is offline Offline
Posting Virtuoso

Re: Starting Python

 
0
  #174
Jun 13th, 2009
For those of you who like to calculate in fractions:
  1. # Python30 has a module fraction that allows you to
  2. # calculate with fractions, the result is a fraction
  3. # is more precise than using floating point numbers
  4. # ene
  5.  
  6. from fractions import Fraction
  7.  
  8. # Fraction(numerator, denominator)
  9. # for instance fraction 2/3 would be Fraction(2, 3)
  10. a = Fraction(2, 3)
  11. b = Fraction(2, 5)
  12. c = Fraction(3, 7)
  13.  
  14. print( "%s + %s = %s" % (a, b, a + b) )
  15. print( "%s + %s + %s = %s" % (a, b, c, a + b + c) )
  16. print( "(%s + %s)/(%s) = %s" % (a, b, c, (a + b)/c) )
  17.  
  18. """
  19. my display -->
  20. 2/3 + 2/5 = 16/15
  21. 2/3 + 2/5 + 3/7 = 157/105
  22. (2/3 + 2/5)/(3/7) = 112/45
  23. """
drink her pretty
Reply With Quote Quick reply to this message  
Join Date: Aug 2005
Posts: 1,523
Reputation: Ene Uran has a spectacular aura about Ene Uran has a spectacular aura about 
Solved Threads: 169
Ene Uran's Avatar
Ene Uran Ene Uran is offline Offline
Posting Virtuoso

Re: Starting Python

 
0
  #175
Jun 13th, 2009
The latest Python version has added some candy:
  1. # Python3.1 allows formatting of thousands
  2. # and defaults format indexing in print()
  3. # ene
  4.  
  5. n = 123456789
  6. print(format(n, ',d'))
  7.  
  8. """
  9. my display -->
  10. 123,456,789
  11. """
  12.  
  13. m = 1234567.8912
  14. print(format(m, ',.2f'))
  15.  
  16. """
  17. my display -->
  18. 1,234,567.89
  19. """
  20.  
  21. amount = format(1234567, ',d')
  22. price = format(1234.56, ',.2f')
  23. # note that {} defaults to the proper arg index
  24. print('{} bottles at ${} each'.format(amount, price))
  25.  
  26. """
  27. my display -->
  28. 1,234,567 bottles at $1,234.56 each
  29. """
I have Python25, Python26, Python30, and Python31 installed on my homely Vista computer. To easily select which Python version to use I like the IDE Editra (wxPython based) and its Launch plugin.
Last edited by Ene Uran; Jun 13th, 2009 at 8:13 pm. Reason: Launch
drink her pretty
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,978
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: 921
Moderator
vegaseat's Avatar
vegaseat vegaseat is online now Online
DaniWeb's Hypocrite

Re: Starting Python

 
2
  #176
Jun 16th, 2009
Just a table of ASCII characters ...
  1. # print a 16 column table of ASCII characters from 0 to 127
  2.  
  3. # dictionary of non-printable asccii characters
  4. controls_dic = {
  5. 0: 'NUL', 1: 'SOH', 2: 'STX', 3: 'ETX', 4: 'EOT', 5: 'ENQ', 6: 'ACK',
  6. 7: 'BEL', 8: 'BS', 9: 'HT', 10: 'LF', 11: 'VT', 12: 'FF', 13: 'CR',
  7. 14: 'SO', 15: 'SI', 16: 'DLE', 17: 'DC1', 18: 'DC2', 19: 'DC3',
  8. 20: 'DC4', 21: 'NAK', 22: 'SYN', 23: 'ETB', 24: 'CAN', 25: 'EM',
  9. 26: 'SUB', 27: 'ESC', 28: 'FS', 29: 'GS', 30: 'RS', 31: 'US'
  10. }
  11.  
  12. n = 1
  13. for k in range(0, 128):
  14. if k < 32:
  15. s = controls_dic[k]
  16. else:
  17. s = chr(k)
  18. if n % 16 > 0:
  19. print "%4s" % s,
  20. else:
  21. print "%4s" % s
  22. n += 1
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 2,273
Reputation: sneekula has a spectacular aura about sneekula has a spectacular aura about 
Solved Threads: 175
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Maven

Re: Starting Python

 
0
  #177
Jun 21st, 2009
Floating point numbers are often close approximations of a value, very close, but approximations never the less. So if you directly compare floating point number results you can get surprises as shown here:
  1. def fuzzyequals(a, b, delta=0.0000001):
  2. """
  3. returns true if a is between b-delta and b+delta
  4. used for comparison of floating point numbers a and b
  5. """
  6. return abs(a-b) < delta
  7.  
  8. a = 0.61
  9. c = 0.49
  10. b = 1.1 - c # b should be 0.61
  11.  
  12. # fuzzy comparison
  13. if fuzzyequals(a, b):
  14. print("fuzzy_true")
  15. else:
  16. print("fuzzy_false")
  17.  
  18. # direct comparison
  19. if a == b:
  20. print("direct_true")
  21. else:
  22. print("direct_false")
  23.  
  24. # shows true floating point number representation
  25. print("should be [0.61, 0.61, 0.49]")
  26. print([a, b, c])
  27.  
  28. """
  29. my output -->
  30. fuzzy_true
  31. direct_false
  32. should be [0.61, 0.61, 0.49]
  33. [0.60999999999999999, 0.6100000000000001, 0.48999999999999999]
  34. """
No one died when Clinton lied.
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 2,273
Reputation: sneekula has a spectacular aura about sneekula has a spectacular aura about 
Solved Threads: 175
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Maven

Re: Starting Python

 
0
  #178
Jun 21st, 2009
In Python2.5 the range() function returns a list and the xrange() function an iterator (generator). Python 3.0 replaces range() with xrange() and now calls it range(). Anyway, range(start, stop, step) handles only integer values, and if you want to use floats, you have to role your own, as show in this example:
  1. def frange(start=0, stop=0, step=1.0):
  2. """similar to xrange, but handles floating point numbers"""
  3. if step <= 0:
  4. while start > stop:
  5. yield start
  6. start += step
  7. else:
  8. while start < stop:
  9. yield start
  10. start += step
  11.  
  12. # testing ...
  13. for x in frange(1.5, 4.7):
  14. print(x)
  15.  
  16. print("-"*20)
  17.  
  18. for x in frange(17, 4, -2.9):
  19. print(x)
  20.  
  21. print("-"*20)
  22.  
  23. for x in frange(stop=2.5, step=0.4):
  24. print(x)
  25.  
  26. print("-"*20)
  27.  
  28. print(list(frange(1.5, 5.2)))
  29.  
  30.  
  31. """
  32. my output -->
  33. 1.5
  34. 2.5
  35. 3.5
  36. 4.5
  37. --------------------
  38. 17
  39. 14.1
  40. 11.2
  41. 8.3
  42. 5.4
  43. --------------------
  44. 0
  45. 0.4
  46. 0.8
  47. 1.2
  48. 1.6
  49. 2.0
  50. 2.4
  51. --------------------
  52. [1.5, 2.5, 3.5, 4.5]
  53. """
No one died when Clinton lied.
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 2,273
Reputation: sneekula has a spectacular aura about sneekula has a spectacular aura about 
Solved Threads: 175
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Maven

Re: Starting Python

 
1
  #179
Jun 22nd, 2009
In the English language you can add a suffix to a number, so for instance first becomes 1st, second 2nd, third 3rd, fourth 4th and so on. Here is a little Python program that does it for you, and teaches a few list tricks too:
  1. # add the proper suffix to integer numbers
  2. # the suffix list index coincides with the number
  3. # apply modulus 100 for numbers that exceed the list index
  4. # snee
  5.  
  6. # list_0to9 also holds true for list_20to29 etc.
  7. list_0to9 = ['th', 'st', 'nd', 'rd'] + ['th']*6
  8. # 11th to 13th are exceptions
  9. list_10to19 = ['th']*10
  10.  
  11. # suffix list for numbers 0 to 99
  12. suffix_list = list_0to9 + list_10to19 + (list_0to9)*8
  13.  
  14. #print suffix_list
  15.  
  16. # test it
  17. for x in range(1000):
  18. # use modulus 100 to recycle through the list
  19. # in case numbers exceed the list index
  20. print( "%d%s" % (x, suffix_list[x%100]) )
  21.  
  22. """
  23. part of my output -->
  24. 0th
  25. 1st
  26. 2nd
  27. 3rd
  28. 4th
  29. 5th
  30. 6th
  31. 7th
  32. 8th
  33. 9th
  34. 10th
  35. 11th
  36. 12th
  37. 13th
  38. 14th
  39. 15th
  40. 16th
  41. 17th
  42. 18th
  43. 19th
  44. 20th
  45. 21st
  46. 22nd
  47. 23rd
  48. 24th
  49. 25th
  50. ...
  51. ...
  52. 990th
  53. 991st
  54. 992nd
  55. 993rd
  56. 994th
  57. 995th
  58. 996th
  59. 997th
  60. 998th
  61. 999th
  62. """
No one died when Clinton lied.
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 2,273
Reputation: sneekula has a spectacular aura about sneekula has a spectacular aura about 
Solved Threads: 175
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Maven

Re: Starting Python

 
0
  #180
Jun 26th, 2009
Starting with Python 2.5 the database module sqlite3 is part of the distribution. Once you start using sqlite3, you discover the world of database programs with their powerful query language. I have used capital letters for the query language part to make it stand out. Here is a simple example of sqlite3:
  1. # test the sqlite3 module, write and read a database file
  2. # note that Python 2.5 and higher versions have sqlite3 builtin
  3. # sqlite3.connect(database, timeout=5.0, isolation_level=None,
  4. # detect_types=0, factory=100)
  5. # timeout=5.0 --> allows multiple access for 5 seconds (for servers)
  6. # isolation_level=None --> autocommit mode
  7. # detect_types=0 --> native types TEXT, INTEGER, FLOAT, BLOB and NULL
  8. # factory=100 --> statement cache to avoid SQL parsing overhead
  9. # tested with Python 2.5 and Python 3.0
  10. # snee
  11.  
  12. import sqlite3
  13.  
  14. # create/connect to a permanent file database
  15. #con = sqlite3.connect("my_db.db3")
  16. # for temporary testing you can use memory only
  17. con = sqlite3.connect(":memory:")
  18.  
  19. # establish the cursor, needed to execute the connected db
  20. cur = con.cursor()
  21.  
  22. # create/execute a table:
  23. cur.execute('CREATE TABLE IF NOT EXISTS clients \
  24. (id INT PRIMARY KEY, \
  25. firstname CHAR(60), \
  26. lastname CHAR(60))')
  27.  
  28. # insert several lines at once using a
  29. # list of (id, firstname, lastname) tuples
  30. # use try/except or the existing db will complain about
  31. # the non-unique id since it is already in the db
  32. try:
  33. clients = [
  34. (106, "Hugo", "Winterhalter"),
  35. (107, "Ella", "Fitzgerald"),
  36. (108, "Louis", "Armstrong"),
  37. (109, "Miles", "Davis")
  38. ]
  39. cur.executemany("INSERT INTO clients (id, firstname, lastname) \
  40. VALUES (?, ?, ?)", clients )
  41. except:
  42. pass
  43.  
  44. # add another client
  45. # again, use try/except or the existing db will complain about
  46. # the non-unique id if it is already in the db
  47. try:
  48. new_client = (110, "Benny", "Goodman")
  49. cur.execute("INSERT INTO clients (id, firstname, lastname) \
  50. VALUES (?, ?, ?)", new_client)
  51. except:
  52. pass
  53.  
  54. # important if you make changes to the database
  55. # commits current data to the db file (data is persistant now)
  56. con.commit()
  57.  
  58. # now test it
  59. # get data row by row
  60. print("Show data row by row:")
  61. # also tell it to sort/order data by lastname
  62. cur.execute('SELECT id, firstname, lastname FROM clients \
  63. ORDER BY lastname')
  64. for row in cur:
  65. print(row)
  66.  
  67. print('-'*40)
  68.  
  69. # select just one data item from each row ...
  70. cur.execute('SELECT firstname FROM clients')
  71. print(cur.fetchall())
  72.  
  73. print('-'*40)
  74.  
  75. # or ...
  76. cur.execute('SELECT firstname FROM clients')
  77. for row in cur:
  78. print(row[0])
  79.  
  80. print('-'*40)
  81.  
  82. # select a specific data row ...
  83. cur.execute('SELECT * FROM clients WHERE lastname="Davis"')
  84. print(cur.fetchall())
  85.  
  86. # finally ...
  87. con.close()
  88.  
  89. """
  90. my output -->
  91. Show data row by row:
  92. (108, u'Louis', u'Armstrong')
  93. (109, u'Miles', u'Davis')
  94. (107, u'Ella', u'Fitzgerald')
  95. (110, u'Benny', u'Goodman')
  96. (106, u'Hugo', u'Winterhalter')
  97. ----------------------------------------
  98. [(u'Ella',), (u'Louis',), (u'Miles',), (u'Benny',), (u'Hugo',)]
  99. ----------------------------------------
  100. Ella
  101. Louis
  102. Miles
  103. Benny
  104. Hugo
  105. ----------------------------------------
  106. [(109, u'Miles', u'Davis')]
  107. """
No one died when Clinton lied.
Reply With Quote Quick reply to this message  
Reply

Tags
code, hints, python, tricks, tutorial

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