1

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):

# filter
# in the interactive shell, use help(filter) for more info.
# filter takes a function and a list, and returns a list of
# the items that returned True for the given function.
# This example takes a list and returns one with the
# unallowed words removed.

words = ['This', 'sentence', 'has', 'unallowed', 'words']
unallowed = ['has', 'words']
remainder = filter(lambda x: x not in unallowed, words)

"""result ->
['This', 'sentence', 'unallowed']
"""
# map
# in the interactive shell, use help(map) for more info.
# map takes a function and a list, and returns a list of
# the items after applying the specified function to them.
# This example takes a list and returns one in which
# every index was squared.

data = [2, 5, 9, 16, 31, 35]
squared = map(lambda x: x*x, data)
"""result ->
[4, 25, 81, 256, 961, 1225]
"""
# reduce
# in the interactive shell, use help(reduce) for more info.
# reduce takes a function and a list, and returns a single
# value formed by taking the result of the function on the
# first two indices, then applying the function on that result
# and the third index, and so forth.
# This example takes a list and returns an integer calculated
# by multiplying all the indices together.
data = [1, 3, 4, 7, 8, 9]
reduce(lambda x, y: x * y, data)
"""result ->
6048
"""

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.

Votes + Comments
nice code examples
0

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:

# File_Info2.py
# show some file details in a table
# note that Linux file names are case sensitive
# Linux uses different folder syntax and getctime() for last changes
# Windows uses getmtime() for last changes/modifications
# this program has been written to accept Windows or Linux
# tested with Python 2.5.4

import os
import time
import sys

# check if your OS is linux or windows
# pick an appropriate folder/directory you have
if sys.platform[:5] == "linux":
    folder = "/home/dell/Atest25/Chemistry"
    win_flag = False
else:
    folder = 'C:/Python25/Atest25/Chemistry'
    win_flag = True

#print(win_flag)  # test

# create list of (fname, size, date_time) tuples
file_info = []
for item in os.listdir(folder):
    # get full path for isdir() to work
    path = os.path.join(folder, item)
    # make sure item is a filename
    if os.path.isdir(path):
        continue  # skip any folder names
    if win_flag:
        change = os.path.getmtime(path)  # Windows
    else:
        change = os.path.getctime(path)  # Linux
    # (year,month,day,hour,min,sec,weekday(Monday=0),yearday,dlsflag)
    # eg. (2009, 7, 31, 21, 37, 6, 4, 212, 1)
    change_tuple = time.localtime(change)
    date_time24 = time.strftime("%m/%d/%Y %H:%M:%S", change_tuple)
    size = os.path.getsize(path)
    # convert to kb
    if size > 999:
        size = round(size/1024.0, 1)
    else:
        size = round(size/1024.0, 3)
    file_info.append((os.path.basename(path), size, date_time24))
    
# show result as formatted table ...
# for longer file names use eg. "%-36s %8s  %s"
fs = "%-25s %8s  %s"
print(fs % ('  Name', 'Size (kb)', ' Date&Time (24hr)'))
for line in file_info:
    print(fs % line)

"""my output example -->
  Name                    Size (kb)   Date&Time (24hr)
MWcalc2a.py                    3.2  05/10/2009 10:21:51
PeriodicTable1.py              5.6  06/04/2009 17:12:15
CONST.TXT                      1.0  05/10/2009 10:21:51
ELEMORDR.TXT                 0.417  05/10/2009 10:21:51
AirEarth.txt                   1.5  05/10/2009 10:21:51
ELEMENT9.TXT                  11.2  05/10/2009 10:21:51
ChemHelp.exe                 237.0  05/10/2009 10:21:51
wxgridGrid3_solvents.pyw       4.7  06/04/2009 17:12:15
MWcalc1.py                     3.2  05/10/2009 10:21:51
CHEMICAL.BMP                  43.2  05/10/2009 10:21:51
MWtable1.py                    2.4  05/10/2009 10:21:51
"""
0

Python31 is joy, here I am exploring named tuples and ordered dictionaries and their interconnection:

# some play with named tuples and ordered dictionaries
# needs Python3

import collections as co

# set up named tuple where staff is the identifier
# and the field names are fname, sname, age
ntup = co.namedtuple('staff', 'fname, sname, age')

# load the tuple
nt1 = ntup('Hank', 'Zoller', 27)
nt2 = ntup('Bjorn', 'Bartok', 34)
# this would give an error, not enough args
#nt3 = ntup('Jack', 'Schiett')

# show the named tuple
print(nt1)  # staff(fname='Hank', sname='Zoller', age=27)
print(nt2)  # staff(fname='Bjorn', sname='Bartok', age=34)

print(nt2.fname)  # Bjorn
print(nt2.age)    # 34

# show the field names
print(nt1._fields)  # ('fname', 'sname', 'age')

# replace/update items by field name
nt4 = nt1._replace(sname='Zeller', age=28)
print(nt1)  # staff(fname='Hank', sname='Zoller', age=27)
print(nt4)  # staff(fname='Hank', sname='Zeller', age=28)

# convert to ordered dictionary
odict = nt2._asdict()
print(odict)
# convert ordered dictionary to regular dictionary
print(dict(odict))
# pop the last item
odict.popitem()
print(odict)
print(odict['sname'])

"""my output -->
OrderedDict([('fname', 'Bjorn'), ('sname', 'Bartok'), ('age', 34)])
{'age': 34, 'sname': 'Bartok', 'fname': 'Bjorn'}
OrderedDict([('fname', 'Bjorn'), ('sname', 'Bartok')])
Bartok
"""

# convert dictionary to named tuple
d = {'age': 34, 'sname': 'Bartok', 'fname': 'Bjorn'}
nt5 = ntup(**d)
print(nt5)  # staff(fname='Bjorn', sname='Bartok', age=34)
0

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("")
print c.search("")
print c.search("")
print c.search("[]")
print c.search("")

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

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")

0

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 ...

# sorting a list of dictionaries by the value of a specific key

import operator as op

# list of {function, priority} dictionaries
staff = [
{'function' : 'waiter', 'priority' : 3},
{'function' : 'cook', 'priority' : 1},
{'function' : 'janitor', 'priority' : 4},
{'function' : 'cashier', 'priority' : 2}
]

# sort list by the values of key 'priority'
staff2 = []
for dic in sorted(staff, key=op.itemgetter('priority')):
    staff2.append(dic)

print(staff2)

"""my prettied result -->
[
{'function': 'cook', 'priority': 1}, 
{'function': 'cashier', 'priority': 2}, 
{'function': 'waiter', 'priority': 3}, 
{'function': 'janitor', 'priority': 4}
]
"""
0

Or, sort a list of class objects by an attribute (similar idea as above):

import operator
import string

def normcaps(strg):
    s = string.upper(strg[0]) + strg[1:]
    return s
    

class Man:
    def __init__(self,name,pos,age):
        self.name = name.lower()
        self.pos = pos.lower()
        self.age = age
    def __getitem__(self,key):
        return self.__dict__[key]
    def __repr__(self):
        return self.__str__()
    def __str__(self):
        print_name = normcaps(self.name)
        print_pos = normcaps(self.pos)
        s = "%s - %s - %s" %(print_name,print_pos,self.age)
        return s

bill = Man('bill','CEO',65)
zach = Man('zach','intern',19)
jerry = Man('jerry','alpha',52)

man_list = [jerry,bill,zach]


get_age = operator.itemgetter('age')
get_pos = operator.itemgetter('pos')
get_name = operator.itemgetter('name')

by_age = sorted(man_list,key = get_age)

by_name = sorted(man_list,key = get_name)

by_pos = sorted(man_list,key = get_pos)

print man_list

print by_age

print by_name

print by_pos
0

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 ...

# write a sorted 'list' of all Python builtins 
# (does not include statements) to a file (run with Python 2.5.4)
fout = open("Builtins25.txt", "w")
print >> fout, '\n'.join(sorted(dir(__builtins__), key=str.lower))

... now the 'builtins' in Python31 ...

# write a sorted 'list' of all Python builtins 
# (does not include statements) to a file (run with Python 3.1)
fout = open('Builtins31.txt', 'w')
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 ...

# use Python module difflib to find the line by
# line differences between two text files
# modified to work with Python25 and Python31
"""
technical details ...
the difflib result will be a list of all lines with a marker 
prefix followed by a space for each original line
-  line unique to text list 1 
+  line unique to text list 2 
space  marks a line common to both text lists 
?  extra line used to point out character differences in lines
    + pointer --> word has extra char,  
    ^ pointer --> spelling, 
    - pointer --> word has missing char 
"""

import difflib

lines25 = open("Builtins25.txt").readlines()
lines31 = open("Builtins31.txt").readlines()

# set up module difflib
diff_instance = difflib.Differ()
diff_list = list(diff_instance.compare(lines25, lines31))

# testing ...
#for line in diff_list: print(line.rstrip())

# lines unique to lines25
unique25 = ""
for line in diff_list:
  if line[0] == '-':
    unique25 += line[2:]

# lines unique to lines31
unique31 = ""
for line in diff_list:
  if line[0] == '+':
    unique31 += line[2:]

print('-'*48)
print("Builtins unique to Python25 and not in Python31:")
print(unique25)

print('-'*48)
print("Builtins unique to Python31 and not in Python25:")
print(unique31)

"""my result -->
------------------------------------------------
Builtins unique to Python25 and not in Python31:
apply
basestring
buffer
callable
cmp
coerce
execfile
file
intern
long
raw_input
reduce
reload
StandardError
unichr
unicode
xrange

------------------------------------------------
Builtins unique to Python31 and not in Python25:
__build_class__
__package__
ascii
bin
BufferError
bytearray
bytes
BytesWarning
exec
format
memoryview
next
print

Note that exec, next and print are considered statements in Python25
"""
0

Have you ever wondered what 'self' is doing when you use Python classes? Here is the short and sweet of it:

# role of self in Python classes
# self can be named different, but 'self' is convention

class Snake(object):
    def __init__(self, name):
        # self keeps track of each instance
        # and also makes self.name global to class methods
        self.name = name
        # for test only
        print(self)

    def isnice(self):
        # a class method has self as the first argument
        return self.name + " is very nice"

# create 2 instances of class Snake
bob = Snake('Bob Python')
mary = Snake('Mary Rattle')

print('-'*40)

# now you can get the name that has been assigned to self.name
print(bob.name)
print(mary.name)

# access the class method
print(mary.isnice())

"""my result (Python 3.1.1) -->
# self for each instance has a different location in memory
<__main__.Snake object at 0x01E0B2B0>
<__main__.Snake object at 0x01E0B090>
----------------------------------------
Bob Python
Mary Rattle
Mary Rattle is very nice
"""
0

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:

# a class can give all global variables a save namespace
# also behaves like a static variable in a function

class Global(object):
    """
    declare all global variables here
    """
    x = 0
    z = False


# now all global variables can have the class instance
# as a namespace, use something simple like ww
ww = Global()

# testing ...
print( ww.x )  # 0
print( ww.z )  # False

def incr_wwx() :
    """
    ww.x does not need to be declared global
    and functions as a static variable here
    """
    ww.x += 1
    return ww.x

print( incr_wwx() )  # 1
print( incr_wwx() )  # 2
print( incr_wwx() )  # 3
print( ww.x )  # 3

print( '-'*10)

def toggle():
    """
    toggle between True and False on each call
    """
    ww.z = not ww.z
    return ww.z

print( toggle() )  # True
print( toggle() )  # False
print( toggle() )  # True
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.

Edited by Ene Uran: n/a

0

Another classical way to have a static variable in a function in python is to add this variable as an attribute of the function:

def countcalls():
    countcalls.counter += 1
    print("countcalls was called %d time(s)" % countcalls.counter)
countcalls.counter = 0

for i in range(5):
  countcalls()

""" my output -->
countcalls was called 1 time(s)
countcalls was called 2 time(s)
countcalls was called 3 time(s)
countcalls was called 4 time(s)
countcalls was called 5 time(s)
"""
0

This class can be used to toggle between True and False, but can easily be changed to count calls ...

# a class to allow you to toggle between True and False

class Static:
    """toggle between True and False"""
    flag = False
    # decorator allows you to simply call Static.toggle()
    @classmethod
    def toggle(self):
        self.flag = not self.flag
        return self.flag

for k in range(6):
    print( '%d) flag = %s' % (k+1, Static.toggle()) )

"""my output -->
1) flag = True
2) flag = False
3) flag = True
4) flag = False
5) flag = True
6) flag = False
"""

Edited by vegaseat: n/a

3

Still another way

class Static(object):
    def __init__(self, **kwd):
        self.__dict__.update(kwd)

def toggle(static=Static(flag=True)):
    static.flag = not static.flag
    return static.flag

for i in range(5):
     print(toggle())

""" my output --->
False
True
False
True
False
"""
Votes + Comments
great
nice code
0

Just a little cosmetic code:

# a simple way to display plural strings

def visits(n):
    # adds an s to 'time' if n > 1
    return "I visited you %d time%s" % (n, ['','s'][n>1])

for n in range(1, 4):
    print( visits(n) )

"""my result -->
I visited you 1 time
I visited you 2 times
I visited you 3 times
"""
2

The ultimate user friendly Temperature Converter program. If you put an 'F' or 'f' on the end of the temperature you enter it will give you Celsius. Otherwise it simply assumes you entered a Celsius value and want Fahrenheit:

# a Fahrenheit/Celsius program easy on the user
# tested with Python25
# snee

def f2c(t):
    """given t Fahrenheit return Celsius"""
    return 5/9.0 * (t - 32)

def c2f(t):
    """given t Celsius return Fahrenheit"""
    return 9/5.0 * t + 32

def extract_number(s):
    """
    extract the numeric value from string s
    (the string can contain only one numeric value)
    return the number or None
    """
    ts = ""
    for c in s:
        if c in '1234567890.-':
            ts += c
    if ts:
        # convert number to int or float
        return eval(ts)
    else:
        return None

def pick_cf(s):
    """given a numeric string s select f or c calculation"""
    t = extract_number(s)
    print('')
    if not t:
        print("***need a number***")
        return False
    if 'f' in s.lower():
        print( "%0.2f Fahrenheit is %0.2f Celsius" % (t, f2c(t)) )
    else:
        print( "%0.2f Celsius is %0.2f Fahrenheit" % (t, c2f(t)) )
    return True
    
prompt = """
Enter a temperature ending with an F to calculate Celsius
otherwise the temperature is assumed to be Celsius and will
give the result in Fahrenheit (press just enter to quit): """

while True:
    s = raw_input(prompt)
    if not s:
        break
    s = pick_cf(s)

Yes Gloria, if you entered $12.99 it will give you the Fahrenheit temperature of 12.99 Celsius.

Edited by sneekula: n/a

Votes + Comments
good thinking
nicely done bud
2

Here is an example how to present the elements of a list or tuple in a nice tabular format ...

# create a table string from a list

def create_table(mylist, itemsperline=5):
    """
    given a list mylist return a string containing
    itemsperline of the list items in each line
    """
    table = ""
    for ix, element in enumerate(mylist):
        # add new line character after every itemsperline elements
        if ix % itemsperline == 0 and ix != 0:
            table += '\n'
        # use string formatting (adjust to your needs)
        # if length of element varies from 1 to 10 use for instance
        # table += "%-12s" % element 
        table += "%-4s" % element
    return table


# create the test list
mylist = [x+y for x in 'abcdef' for y in '1234']

#print mylist  # test ['a1', 'a2', 'a3', 'a4', 'b1', 'b2', ... ]

itemsperline = 4
table = create_table(mylist, itemsperline)
    
print(table)

"""my result -->
a1  a2  a3  a4  
b1  b2  b3  b4  
c1  c2  c3  c4  
d1  d2  d3  d4  
e1  e2  e3  e4  
f1  f2  f3  f4  
"""
Votes + Comments
works well
0

Here is an example of how you can create a C type switch/case construct using a Python dictionary ...

# a simple reverse polish notation calculator

def do_operation(a, b, op):
    """
    here a dictionary combined with the
    lambda inline function acts like C switch/case
    a and b are numbers and op is a string
    """
    return {'+': lambda: a + b,
            '-': lambda: a - b,
            '*': lambda: a * b,
            '/': lambda: a / b
           }[op]()

# evaluate a reverse Polish notation string
rev_pol = "12 3 *"

a, b , op = rev_pol.split()
result = do_operation(float(a), float(b) , op)

print( "%s --> %s" % (rev_pol, result) )  # 12 3 * --> 36.0
1

Combinations and Permutations are closely linked. The function shown here is a recursive generator function that returns permutations with selectable sample size ...

# a permutation or combination does not repeat sample items
# Python3 has a non-recursive combination function
# via itertools.combinations(iterable, sample_size)
# and a non-recursive permutation function
# via itertools.permutations(iterable, sample_size=None)
# vegaseat

def permutations(seq, n):
    """
    permutations(seq, n) is a recursive generator function where
    seq is an iterable object like a list or string
    n is the sample size
    returns a list of nonrepeating sample size items
    n = len(seq) is the max sample size
    """
    if n == 0:
        yield []
    else:
        for k in range(len(seq)):
            # a recursive function
            for p in permutations(seq[:k] + seq[k+1:], n - 1):
                yield [seq[k]] + p

def unique_combinations(seq, n):
    """
    unique_combinations(seq, n) is a recursive generator function 
    where
    seq is an iterable object like a list or string
    n is the sample size
    returns a list of nonrepeating sample size items
    n = len(seq) is the max sample size
    """
    if n == 0:
        yield []
    else:
        for i in range(len(seq) - n + 1):
            # recursion
            for uc in unique_combinations(seq[i+1:], n - 1):
                yield [seq[i]] + uc


iterable = 'abc'
sample_size = 2
perm_list = list(permutations(iterable, sample_size))

# show as a list of lists
print( perm_list )

print( '-'*40 )

# show as a list of strings
print( ["".join(item) for item in perm_list] )

print( '-'*40 )

comb_list = list(unique_combinations(iterable, sample_size))

# show as a list of lists
print( comb_list )

print( '-'*40 )

# show as a list of strings
print( ["".join(item) for item in comb_list] )

""" my result (sample size max - 1) -->
[['a', 'b'], ['a', 'c'], ['b', 'a'], 
['b', 'c'], ['c', 'a'], ['c', 'b']]
----------------------------------------
['ab', 'ac', 'ba', 'bc', 'ca', 'cb']
----------------------------------------
[['a', 'b'], ['a', 'c'], ['b', 'c']]
----------------------------------------
['ab', 'ac', 'bc']
"""

Note: corrected post, see sneekula's post at ...
http://www.daniweb.com/forums/post1086335.html#post1086335

Edited by vegaseat: snee post

1

The Python module time has many interesting functions to process date and time related problems. Here is an example that shows how you can switch one date format to another format ...

# convert one time format to another

import time

date_old = "08-Jan-2009"

# use strptime(string, format_str) to form a time tuple
# (year,month,day,hour,min,sec,weekday(Monday=0),yearday,dls-flag)
time_tuple = time.strptime(date_old, "%d-%b-%Y")

# use time.strftime(format_str, time_tuple) to create new format
date_new = time.strftime("%m/%d/%y", time_tuple)

print( "New format = %s" % date_new )
print( "Old format = %s" % date_old )
print( "Time_tuple = %s" % time_tuple )

"""my output -->
New format = 01/08/09
Old format = 08-Jan-2009
Time tuple = (2009, 1, 8, 0, 0, 0, 3, 8, -1)
"""

Edited by vegaseat: Python3 modify

1

One thing that I'm very glad I learned to do as a beginner and still use today - even though I'm probably still a beginner - is to have a basic file with code that is used more often than not in the script. I can copy this file each time I want to create a script and have several things I'd normally want to do in a polished script all ready done.

I call my file "base.py".

#!/usr/bin/env python

version = '3.1.1'

def main():
    pass

if __name__ is "__main__":
    main()

The first line is called a "shebang" I think. I'm a Windows user, but as I understand it having this line in a script allows Linux users to execute the script more easily than if it wasn't included. Having the line doesn't alter program execution so it isn't necessary, but I do it out of consideration for Linux users when I publish code.

The variable "version" does not represent the script's version, but it is the version of Python I wrote the script in. I do this out of consideration for users who might be using different versions of Python.

The 'if __name__ is "__main__":' idiom allows a script to function as an executable script or a module. If the program is executed as a script, the __name__ attribute is "__main__" and the "main" function is called. However, if the script is imported then this code is not executed. The pass statement in the "main" function is necessary for it to be a valid function, and when I add code I usually leave it at the beginning so if I need to erase code it will still function without having to remove the "main" function.

Do you have any ideas or contributions?

2

To create a simple spell checker you can search a given word list. Here is a simple example ...

# find a search word in a list of words using a linear search
# 
# DictionaryE.txt has about 110,000 lower case English words
# one word per line
# download DictionaryE.zip from ...
# http://www.daniweb.com/forums/post160495.html#post160495

# load the dictionary file
fname = "DictionaryE.txt"
word_list = []
for line in open(fname):
    # strip trailing whitespace like newline char
    word_list.append(line.rstrip())

# test
#print(word_list[:10])

# pick a search word
search = "spinach"

try:
    # do a standard linear search
    index1 = word_list.index(search)
    print( "Found word %s at index %d" % (search, index1) )
except ValueError:
    print( "Did not find word %s in the word list!" % search )

If you had to search for a larger number of words, then this code will be much faster ...

# find a search word in a list of words using a binary search
# for long lists a binary search is faster than a linear search 
#
# DictionaryE.txt has about 110,000 lower case English words
# one word per line
# download DictionaryE.zip from ...
# http://www.daniweb.com/forums/post160495.html#post160495

import bisect

# load the dictionary file
fname = "DictionaryE.txt"
word_list = []
for line in open(fname):
    # strip trailing whitespace like newline char
    word_list.append(line.rstrip())

# test
#print(word_list[:10])

# binary searches require a sorted list
word_list.sort()

# pick a search word
search = "spinach"

# note bisect.bisect() is the same as bisect.bisect_right()
# no-match gives closest index (no index error possible)
index3 = bisect.bisect(word_list, search) - 1
if word_list[index3] == search:
    print( "Found %s at index %d (sorted list)" % (search, index3) )
else:
    print( "Did not find word %s in the word list!" % search )

Of course, if you want to search for each of the words in a text, you will have to clean the words up. Make all the words lower case and remove punctuation marks after splitting the text.

1

Just a short explanation on how to create and access a Python package:

"""
assumes that you are using Python31 installed on the c drive
1) create a directory c:/Python31/MyModules
2) write an empty file __init__.py to that directory
   ( this makes MyModules a package)
3) write a test module module1.py to that directory
   ( has one code line --> text = "text from module1" )
4) test module module1.py in c:/Python31/MyModules
   with the code below, this file can be saved anywhere

since package directory MyModules is in the Python path
it will be found, remember package names are case sensitive
as are module names
"""

import MyModules.module1 as mm_module1

print(mm_module1.text)

Just change your drive and Python version as needed. On Linux you may need root permission.

1

@Ene Uran

While anyone is free to use any directory they wish, I think the common directory to store third party modules and packages in is the "site-packages" directory in the "lib" directory.

Even better, you don't have to append the "site-packages" directory to the search path which means that any import statement should be able to find your modules and packages.

0

You want to create a series of x, y data points where y is a function of x. You also want to increment x in small steps. That means x is a floating point value. Alas, you find out the Python function range() is only for integers. No problem, simply use a while loop as shown in this example ...

# find the min and max values of
# f(x) = x**3 - x**2 - 8*x
# over a x range of -1 to 3 where x is a float

# create a list of (y, x) tuples
# over a x range of floating point numbers
start = -1
# stop at 3 (add a delta value to make this float inclusive)
stop = 3 + 0.0000001
step = 0.01
q = []
x = start
while True:
    # this is f(x), the function of x
    y = x**3 - x**2 - 8*x
    # put y first in the tuple since we want the min and max of y
    q.append((y, x))
    x += step
    if x >= stop:
        break

# use min(q) and max(q) to find the minimum and 
# maximum (y, x) tuple in the list q
print( min(q) )
print( max(q) )
print( '-'*40 )
print( "Minimum y = %f at x = %f" % min(q) )
print( "Maximum y = %f at x = %f" % max(q) )

"""my result -->
(-12.0, 2.0000000000000022)
(6, -1)
----------------------------------------
Minimum y = -12.000000 at x = 2.000000
Maximum y = 6.000000 at x = -1.000000
"""

Edited by vegaseat: n/a

0

Here's a really evil Hello World program.

You see, in Python, type(type)==type,
so with that in mind, Classes are a type of type,
which means that they inherit from type.
So really, you can actually define a class by initiating a type of it,
and then defining a classDict for it, like this:

def __init__(self, msg):
    self.msg = msg

def printMsg(self):
    print(self.msg)

aNewClass = type('aNewClass', (object,), {'__init__': __init__, 'printMsg': printMsg})

hwld = aNewClass("Hello World")
hwld.printMsg()
0

If you ever wanted to split a text into a list of sentences, here is one way to accomplish this task ...

# split a text into a list of sentences

def sentence_split(text, seps=".?!"):
    """
    split a text string into a list of sentences
    assumes sentences end with characters given in seps
    """
    mylist = []
    sentence = ""
    for c in text:
        if c in seps:
            sentence += c
            # remove leading and trailing whitespaces
            sentence = sentence.strip()
            mylist.append(sentence)
            sentence = ""
            c = ""
        else:
            sentence += c
    return mylist

text = """\
Hello there! 
I am Joe's answering machine. What are you?
"""

sentence_list = sentence_split(text)
print(sentence_list)

"""my result -->
['Hello there!', "I am Joe's answering machine.", 'What are you?']
"""

Edited by vegaseat: more readable

0

Shows how to encode binary file, like sound file, to base64 encoded printable string, save the string to text file. Read the text file back in, decode to binary and optionally test play the sound (needs Windows).

# read Windows wave sound file
# save it as base64 encoded string
# to test it, read the string back, decode it and play it
# modified to work with Python 2.5.4 and Python 3.1.1

import base64
import winsound as ws
import time

# pick wave sound file you have in working directory
# or give full path, like this typical Windows XP soundfile
sound_file = "C:/Windows/Media/ding.wav"

# use mode = "rb" to read the binary file
fin = open(sound_file, "rb")
binary_data = fin.read()
fin.close()

# encode binary to base64 string (printable)
b64_data = base64.b64encode(binary_data)

b64_fname = "b64_testwave.txt"
# save base64 string to given text file
fout = open(b64_fname, "w")
try:
    # Python2
    fout.write(b64_data)
except TypeError:
    # Python3
    # convert byte string to string first
    b64_data = b64_data.decode("utf8")
    fout.write(b64_data)

fout.close

# read base64 string back in
fin = open(b64_fname, "r")
b64_str = fin.read()
fin.close()

# decode base64 string to original binary sound object
try:
    # Python2
    wave_data = base64.b64decode(b64_str)
except TypeError:
    # Python3
    # convert string to byte string first
    b64_str = b64_str.encode("utf8")
    wave_data = base64.b64decode(b64_str)

# on Windows machine you can test play
flag = ws.SND_MEMORY
ws.PlaySound(wave_data, flag)

# wait 2 seconds for sound to finish
time.sleep(2)
1

Many folks have stumbled over the behavior of floating point number representations common in most computer languages. On the surface two floating point numbers look alike or should look alike, however in the inner workings of a binary beast like the digital computer there appear tiny differences. Here is Python code showing you what I mean ...

# let's say we have a = 6.4 and b = 6.3 + 0.1
# for all practical purposes a and b should be the same
# however, there is a tiny discrepancy in the way the
# binary computer represents floating point numbers

def fuzzy_compare(a, b, delta=0.000000001):
    """
    used for == comparison of floating point numbers a and b
    returns True if the difference between a and b does not
    exceed delta otherwise returns False
    """
    return abs(a-b) < delta

# testing ...
a = 6.4
b = 6.3 + 0.1
# a list truly shows the reality
# the difference is a very tiny 0.0000000000000009
print( [a, b] )  # [6.4000000000000004, 6.3999999999999995]

print( a == b )  # False

print( fuzzy_compare(a, b) )  # True
0

Another way.

float1 = 6.4
float2 = 6.3 + 0.1

print([float1, float2]) # [6.4, 6.3999999999999995]

print(float1 == float2) # False

#print(help(round)) # Uncomment to learn about the round function.
print([round(float1, 1), round(float2, 1)]) # [6.4, 6.4]

print(round(float1, 1) == round(float2, 1)) # True

Edited by lrh9: n/a

0

Check if an input is numeric then do a calculation (Python2 syntax):

def is_numeric(s):
    """
    check if a string s is numeric
    contains only character like '-+1234567890.'
    (the period maybe a comma in some countries)
    """
    for c in s:
        if c not in '-+1234567890.':
            return False
    return True


def calc_cube(n):
    """
    calculate cube of n (for testing purposes)
    """
    return n*n*n

while True:
    mystr = raw_input("Enter a number (q to quit): ")
    if mystr.startswith(('q', 'Q')):
        break
    if is_numeric(mystr):
        number = float(mystr)
        cube = calc_cube(number)
        print "cube(%f) = %f" % (number, cube)
    else:
        print "please enter a numeric value"

Edited by vegaseat: OP request to remove coding error

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.