| | |
Starting Python
![]() |
One way to approach multidimensional arrays in Python is to use a dictionary container with the index tuple as a key ...
python Syntax (Toggle Plain Text)
# create a 3x4x2 3D-array using a dictionary with index tuples as keys # initialize values to zero arr3d = dict([((x,y,z), 0) for x in range(3) for y in range(4) for z in range(2)]) # Python3 has dictionary comprehension to simplify this #arr3d = {(x,y,z):0 for x in range(3) for y in range(4) for z in range(2)} # sorts the key index tuples for ix in sorted(arr3d): print( "ix=%s val=%s" % (ix, arr3d[ix]) ) print('-'*20) # change some values, basically assign to index arr3d[2, 1, 0] = 5 arr3d[1, 0, 1] = 17 # or ... ix = (0, 0, 0) arr3d[ix] = 9 # or just ... ix = 1, 1, 1 arr3d[ix] = 3 for ix in sorted(arr3d): print( "ix=%s val=%s" % (ix, arr3d[ix]) ) print('-'*20) # get a specific value from a given index print(arr3d[1, 1, 1]) # 3 # or ... ix = 0, 0, 0 print(arr3d[ix]) # 9 print('-'*20) # get the lowest and highest key low = (min(arr3d.keys())) # --> (0, 0, 0) heigh = (max(arr3d.keys())) # --> (2, 3, 1) # show values print( "ix=%s val=%s" % (low, arr3d[low]) ) print( "ix=%s val=%s" % (heigh, arr3d[heigh]) ) # get the heighest value in the array print(max(arr3d.values())) # 17 """ my result --> ix=(0, 0, 0) val=0 ix=(0, 0, 1) val=0 ix=(0, 1, 0) val=0 ix=(0, 1, 1) val=0 ix=(0, 2, 0) val=0 ix=(0, 2, 1) val=0 ix=(0, 3, 0) val=0 ix=(0, 3, 1) val=0 ix=(1, 0, 0) val=0 ix=(1, 0, 1) val=0 ix=(1, 1, 0) val=0 ix=(1, 1, 1) val=0 ix=(1, 2, 0) val=0 ix=(1, 2, 1) val=0 ix=(1, 3, 0) val=0 ix=(1, 3, 1) val=0 ix=(2, 0, 0) val=0 ix=(2, 0, 1) val=0 ix=(2, 1, 0) val=0 ix=(2, 1, 1) val=0 ix=(2, 2, 0) val=0 ix=(2, 2, 1) val=0 ix=(2, 3, 0) val=0 ix=(2, 3, 1) val=0 -------------------- ix=(0, 0, 0) val=9 ix=(0, 0, 1) val=0 ix=(0, 1, 0) val=0 ix=(0, 1, 1) val=0 ix=(0, 2, 0) val=0 ix=(0, 2, 1) val=0 ix=(0, 3, 0) val=0 ix=(0, 3, 1) val=0 ix=(1, 0, 0) val=0 ix=(1, 0, 1) val=17 ix=(1, 1, 0) val=0 ix=(1, 1, 1) val=3 ix=(1, 2, 0) val=0 ix=(1, 2, 1) val=0 ix=(1, 3, 0) val=0 ix=(1, 3, 1) val=0 ix=(2, 0, 0) val=0 ix=(2, 0, 1) val=0 ix=(2, 1, 0) val=5 ix=(2, 1, 1) val=0 ix=(2, 2, 0) val=0 ix=(2, 2, 1) val=0 ix=(2, 3, 0) val=0 ix=(2, 3, 1) val=0 -------------------- 3 9 -------------------- ix=(0, 0, 0) val=9 ix=(2, 3, 1) val=0 17 """
Last edited by vegaseat; Apr 29th, 2009 at 9:43 pm.
May 'the Google' be with you!
You can use the local dictionary vars() to introduce variables into strings ...
String templating was introduced in Python 2.4 ...
If you want to know what vars() looks like, just print it.
python Syntax (Toggle Plain Text)
# using the local dictionary vars() to put # variables into strings name = "Harry" name2 = "Verderchi" for i in range(1, 5): # %d for integers and %s for strings print( "#%(i)d: %(name)s %(name2)s" % vars() ) """ my result --> #1: Harry Verderchi #2: Harry Verderchi #3: Harry Verderchi #4: Harry Verderchi """
python Syntax (Toggle Plain Text)
# using string.Template() and the local dictionary vars() # for formatted printing import string name = "Harry" name2 = "Verderchi" # create the template (note the $ before each variable name) t = string.Template("#$i: $name $name2") for i in range(1, 5): # use safe_substitute() for potential missing variables print( t.safe_substitute(vars()) ) """ my output --> #1: Harry Verderchi #2: Harry Verderchi #3: Harry Verderchi #4: Harry Verderchi """
May 'the Google' be with you!
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:
python Syntax (Toggle Plain Text)
# extract the numeric value from a data string # snee def extract_number(data_str): """ extract the numeric value from a string the string should contain only one number return the number as int, float or None """ s = "" for c in data_str: if c in '1234567890.-': s += c if s: # convert number to int or float return eval(s) else: return None data_raw = """ header 23 bushels 43 years old 4323 Maiden Lane -$23.44/kg +$12.32 footer """ # create a list of the string data data_list = data_raw.split('\n') print(data_list) # test print('-'*60) # extract numeric values from the data in the list for data_str in data_list: print(extract_number(data_str)) """ my result --> ['', 'header', '23 bushels', ' 43 years old', '4323 Maiden Lane', '-$23.44/kg', ' +$12.32', 'footer', ''] ------------------------------------------------------------ None None 23 43 4323 -23.44 12.32 None None """
No one died when Clinton lied.
For those of you who like to calculate in fractions:
python Syntax (Toggle Plain Text)
# Python30 has a module fraction that allows you to # calculate with fractions, the result is a fraction # is more precise than using floating point numbers # ene from fractions import Fraction # Fraction(numerator, denominator) # for instance fraction 2/3 would be Fraction(2, 3) a = Fraction(2, 3) b = Fraction(2, 5) c = Fraction(3, 7) print( "%s + %s = %s" % (a, b, a + b) ) print( "%s + %s + %s = %s" % (a, b, c, a + b + c) ) print( "(%s + %s)/(%s) = %s" % (a, b, c, (a + b)/c) ) """ my display --> 2/3 + 2/5 = 16/15 2/3 + 2/5 + 3/7 = 157/105 (2/3 + 2/5)/(3/7) = 112/45 """
drink her pretty
The latest Python version has added some candy:
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.
python Syntax (Toggle Plain Text)
# Python3.1 allows formatting of thousands # and defaults format indexing in print() # ene n = 123456789 print(format(n, ',d')) """ my display --> 123,456,789 """ m = 1234567.8912 print(format(m, ',.2f')) """ my display --> 1,234,567.89 """ amount = format(1234567, ',d') price = format(1234.56, ',.2f') # note that {} defaults to the proper arg index print('{} bottles at ${} each'.format(amount, price)) """ my display --> 1,234,567 bottles at $1,234.56 each """
Last edited by Ene Uran; Jun 13th, 2009 at 8:13 pm. Reason: Launch
drink her pretty
Just a table of ASCII characters ...
python Syntax (Toggle Plain Text)
# print a 16 column table of ASCII characters from 0 to 127 # dictionary of non-printable asccii characters controls_dic = { 0: 'NUL', 1: 'SOH', 2: 'STX', 3: 'ETX', 4: 'EOT', 5: 'ENQ', 6: 'ACK', 7: 'BEL', 8: 'BS', 9: 'HT', 10: 'LF', 11: 'VT', 12: 'FF', 13: 'CR', 14: 'SO', 15: 'SI', 16: 'DLE', 17: 'DC1', 18: 'DC2', 19: 'DC3', 20: 'DC4', 21: 'NAK', 22: 'SYN', 23: 'ETB', 24: 'CAN', 25: 'EM', 26: 'SUB', 27: 'ESC', 28: 'FS', 29: 'GS', 30: 'RS', 31: 'US' } n = 1 for k in range(0, 128): if k < 32: s = controls_dic[k] else: s = chr(k) if n % 16 > 0: print "%4s" % s, else: print "%4s" % s n += 1
May 'the Google' be with you!
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:
python Syntax (Toggle Plain Text)
def fuzzyequals(a, b, delta=0.0000001): """ returns true if a is between b-delta and b+delta used for comparison of floating point numbers a and b """ return abs(a-b) < delta a = 0.61 c = 0.49 b = 1.1 - c # b should be 0.61 # fuzzy comparison if fuzzyequals(a, b): print("fuzzy_true") else: print("fuzzy_false") # direct comparison if a == b: print("direct_true") else: print("direct_false") # shows true floating point number representation print("should be [0.61, 0.61, 0.49]") print([a, b, c]) """ my output --> fuzzy_true direct_false should be [0.61, 0.61, 0.49] [0.60999999999999999, 0.6100000000000001, 0.48999999999999999] """
No one died when Clinton lied.
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:
python Syntax (Toggle Plain Text)
def frange(start=0, stop=0, step=1.0): """similar to xrange, but handles floating point numbers""" if step <= 0: while start > stop: yield start start += step else: while start < stop: yield start start += step # testing ... for x in frange(1.5, 4.7): print(x) print("-"*20) for x in frange(17, 4, -2.9): print(x) print("-"*20) for x in frange(stop=2.5, step=0.4): print(x) print("-"*20) print(list(frange(1.5, 5.2))) """ my output --> 1.5 2.5 3.5 4.5 -------------------- 17 14.1 11.2 8.3 5.4 -------------------- 0 0.4 0.8 1.2 1.6 2.0 2.4 -------------------- [1.5, 2.5, 3.5, 4.5] """
No one died when Clinton lied.
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:
python Syntax (Toggle Plain Text)
# add the proper suffix to integer numbers # the suffix list index coincides with the number # apply modulus 100 for numbers that exceed the list index # snee # list_0to9 also holds true for list_20to29 etc. list_0to9 = ['th', 'st', 'nd', 'rd'] + ['th']*6 # 11th to 13th are exceptions list_10to19 = ['th']*10 # suffix list for numbers 0 to 99 suffix_list = list_0to9 + list_10to19 + (list_0to9)*8 #print suffix_list # test it for x in range(1000): # use modulus 100 to recycle through the list # in case numbers exceed the list index print( "%d%s" % (x, suffix_list[x%100]) ) """ part of my output --> 0th 1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th 13th 14th 15th 16th 17th 18th 19th 20th 21st 22nd 23rd 24th 25th ... ... 990th 991st 992nd 993rd 994th 995th 996th 997th 998th 999th """
No one died when Clinton lied.
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:
python Syntax (Toggle Plain Text)
# test the sqlite3 module, write and read a database file # note that Python 2.5 and higher versions have sqlite3 builtin # sqlite3.connect(database, timeout=5.0, isolation_level=None, # detect_types=0, factory=100) # timeout=5.0 --> allows multiple access for 5 seconds (for servers) # isolation_level=None --> autocommit mode # detect_types=0 --> native types TEXT, INTEGER, FLOAT, BLOB and NULL # factory=100 --> statement cache to avoid SQL parsing overhead # tested with Python 2.5 and Python 3.0 # snee import sqlite3 # create/connect to a permanent file database #con = sqlite3.connect("my_db.db3") # for temporary testing you can use memory only con = sqlite3.connect(":memory:") # establish the cursor, needed to execute the connected db cur = con.cursor() # create/execute a table: cur.execute('CREATE TABLE IF NOT EXISTS clients \ (id INT PRIMARY KEY, \ firstname CHAR(60), \ lastname CHAR(60))') # insert several lines at once using a # list of (id, firstname, lastname) tuples # use try/except or the existing db will complain about # the non-unique id since it is already in the db try: clients = [ (106, "Hugo", "Winterhalter"), (107, "Ella", "Fitzgerald"), (108, "Louis", "Armstrong"), (109, "Miles", "Davis") ] cur.executemany("INSERT INTO clients (id, firstname, lastname) \ VALUES (?, ?, ?)", clients ) except: pass # add another client # again, use try/except or the existing db will complain about # the non-unique id if it is already in the db try: new_client = (110, "Benny", "Goodman") cur.execute("INSERT INTO clients (id, firstname, lastname) \ VALUES (?, ?, ?)", new_client) except: pass # important if you make changes to the database # commits current data to the db file (data is persistant now) con.commit() # now test it # get data row by row print("Show data row by row:") # also tell it to sort/order data by lastname cur.execute('SELECT id, firstname, lastname FROM clients \ ORDER BY lastname') for row in cur: print(row) print('-'*40) # select just one data item from each row ... cur.execute('SELECT firstname FROM clients') print(cur.fetchall()) print('-'*40) # or ... cur.execute('SELECT firstname FROM clients') for row in cur: print(row[0]) print('-'*40) # select a specific data row ... cur.execute('SELECT * FROM clients WHERE lastname="Davis"') print(cur.fetchall()) # finally ... con.close() """ my output --> Show data row by row: (108, u'Louis', u'Armstrong') (109, u'Miles', u'Davis') (107, u'Ella', u'Fitzgerald') (110, u'Benny', u'Goodman') (106, u'Hugo', u'Winterhalter') ---------------------------------------- [(u'Ella',), (u'Louis',), (u'Miles',), (u'Benny',), (u'Hugo',)] ---------------------------------------- Ella Louis Miles Benny Hugo ---------------------------------------- [(109, u'Miles', u'Davis')] """
No one died when Clinton lied.
![]() |
Similar Threads
- CGPA calculator (Python)
- Beginning: Starting Python (Python)
- Clear the console screen (Python)
- Re: Starting Python (Python)
Other Threads in the Python Forum
- Previous Thread: wxpython GUI issue with database
- Next Thread: error in numpy
| Thread Tools | Search this Thread |
access ada anti api arax array beginner blogger blogging bug c++ code combo convert csv cx-freeze daniweb data database development dictionary digital dropdownlist embed event exam examples excel fanniemay file format function game gdata google gui images innovation input introduction itunes java joomla keycontrol linux list lists maze method microsoft module mouse mvcmodel2 net news obexftp parameters password php post problem program programming projects py2exe pygame pyopengl python random recursive reuse reverse rss ruby script security shutdown skinning source sprite string syntax terminal text threading tutorial ubuntu url urllib urllib2 variable vb virus vista visual visualbasic6 web web-scrape wxpython xml







