woooee 814 Nearly a Posting Maven

This should be textfile, not textfile.name (a simple "print line" will show that nothing was read). Also, look at the indents. I am assuming that this was a cut and paste error as the interpreter should give an error for the code you posted. Also, textfile.close() doesn't do anything. It is not the file name that you close but the pointer, which in the case is done by Python's garbage collector.

def readComments (textfile):         ## <-- textfile
    comments = []
    inComment = False
    for i, line in enumerate(open(textfile.name)): # <-- textfile.name
woooee 814 Nearly a Posting Maven

Run this code with some added print statements and see if it helps.

for i in range(n):
        y = input("Enter number: ")
        print "after input y =", y
        y = y + y
        print "after adding y =", y, "\n"
woooee 814 Nearly a Posting Maven

Note that you have a similar problem with the arithmetic. In the first function you subtract 32 from t and multiply by 5/9. In c2f you multiply t by 9/5 and then add 32. Perhaps this is the correct way to do it and I'm wrong, in which case appologies to the OP. I just use 9C + 160 = 5F for both conversions and solve for the unknown variable.

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
woooee 814 Nearly a Posting Maven

Defining and then calling the functions under the if() statements serves no purpose. Stripped to the minimum, it would be:

#Convert C to F
if x == 1:
    Tc = input ("What is the Celsius Temperature ?   " )
    print 'The temperature is %.2f Degrees Fahrenheit' % \
             (9.0/5.0 * Tc + 32 )

And generally, it would be more along the lines of this to avoid a double compare on "x", although there is nothing wrong with the way you did it.

def Tc_to_Tf ():        
    Tc = input ("What is the Celsius Temperature ?   " )
    print 'The temperature is %.2f Degrees Fahrenheit' %(9.0/5.0 * Tc + 32 )

def Tf_to_Tc ():
    Tf = input ("What is the Fahrenheit Temperature ?   " )
    print 'The temperature is %.2f Degrees Celsius' %((5.0/9.0)*(Tf - 32) )

##--------------------------------------------------------------------------------------------------
## "select" is a python function and should not be used as a variable
selection = True
while selection:
    x = int(raw_input ('To convert Celsius to Farenheit, enter 1\nTo convert Farenheit to Celsius, enter 2\n'))   
    if x == 1:
        Tc_to_Tf ()
        selection = False
    elif x == 2:
        Tf_to_Tc ()
        selection = False
    else:
        print 'Only options are 1 or 2'

Finally, check your arithmetic.
This subtracts 32 from Tf and then multiplies
(5.0/9.0)*(Tf - 32)

This multiplies Tc by 9/5 and then adds 32
9.0/5.0 * Tc + 32

When in doubt, use parens.

woooee 814 Nearly a Posting Maven

Note that you add 2 to numbertotest before you break, so the prime would have been 3001 (don't know if that really is a prime).

## assume numberofprimesfound = 999
while numberofprimesfound < 1000:
   .
   .
   .
   elif numbertotest%divisor <> 0:
           numbertotest = numbertotest +2
           numberofprimesfound = numberofprimesfound +1
           divisor = 2
           break
woooee 814 Nearly a Posting Maven

Indeed it should, but test for "key in x" as well, or use a try/except, as you can never tell. Please mark this "solved" so no wastes their time on a solved thread.

Edit: I just did the following and it worked fine so you don't have to test for "key in x" as update takes care of that for you.

x = {}
x[1] = {}
x[1][1]=1
x[1][2]=2

y = {}
y[2] = {}
y[2][3]=3
x.update(y)
print x
#
# prints
{1: {1: 1, 2: 2}, 2: {3: 3}}
woooee 814 Nearly a Posting Maven

Apparently the question is not specific enough. Do you want a numpy array or a multi-dimension list? If you want a multi-dimension list, that can be done with for loops. You can also use a dictionary of lists, using the row number as the key, if that is easier to use. A simple example:

master_list = []
row_list = []
row_list.append("a")
row_list.append("b")
master_list.append(row_list)

## declare row_list in a new block of memory
## if you just delete the contents you will be
## using the same object so any changes to 
## one will change the other as they both point
## to the same block of memory
row_list = []
for j in range(0, 3):
    row_list.append(j)
master_list.append(row_list)

print master_list
print
for child_list in master_list:
   print child_list
print
print master_list[1]
print master_list[1][2]
woooee 814 Nearly a Posting Maven

Apparently the question is not specific enough. Do you want a numpy array or a multi-dimension list? If you want a multi-dimension list, that can be done with for loops. You can also use a dictionary of lists, using the row number as the key, if that is easier to use. A simple example:

master_list = []
row_list = []
row_list.append("a")
row_list.append("b")
master_list.append(row_list)
row_list = []
row_list.append("c")
row_list.append("d")
row_list.append("e")
master_list.append(row_list)

print master_list
print
for child_list in master_list:
   print child_list
print
print master_list[1]
print master_list[1][2]
woooee 814 Nearly a Posting Maven

This is correct, as you are updating x[1], that is y's key is also 1 and so overwrite's whatever is in x for that key. Change to
y[2][3]=3
or use
x[1].update(y[1])
and you should get what you expect.. If that's not satisfactory then you will have to write your own routine to update however you want.

woooee 814 Nearly a Posting Maven

Making counts on a months data

You should be able to process the data file(s) once, i.e. one 5 hour period, and store the counts for all of the customers in a dictionary or SQL file in one pass. Worst case is that you process the data once and output a separate, smaller file for each customer which is then processed in much less time. If you give us some sample input data and explain what you are trying to do, we can probably help with this.

woooee 814 Nearly a Posting Maven

For exactness, use the decimal class. My take on the program using decimal. Note that decimal.Decimal is imported as "dec" to avoid confusion with the variable names. Also, I am not a decimal class expert and so use divmod to get the integer and remainder/decimal portions of a number. There are probably other ways, some of which may be better. Finally, using the decimal class is much slower than floats but is not noticeable for the normal type operations.

from decimal import Decimal as dec

def extractDecimals(num):
   """ the variable 'num' is expected to be a decimal.Decimal
   """
   try:
      whole, remainder = divmod(num, 1)
      print "whole =", whole, "  remainder =", remainder
      if remainder > 0:
         decimals = num - whole
         ctr = 0
         while (decimals > whole) and (ctr < 100):
            ctr += 1
            decimals *= 10
            whole, remainder = divmod(decimals, 1)
            print 'decimal: ' + str(decimals),
            print '     int: ' + str(whole)
         return int(decimals)
      else:
         raise DecimalError(num)
   except DecimalError, e:
      e.printErrorMessage()

extractDecimals(dec("0.988"))
sneekula commented: good point +8
woooee 814 Nearly a Posting Maven
for file in open(a):
    for line in file:
        if b in line:

One problem is here. First, do not use "file" as it is a reserved word. Second, it should be

for file_name in a:
    for rec in open(file_name):
        if b in rec:

Third, you could have directories in "a" as well as files, so you want to test with
if os.path.isfile(a): so try this

print a
for fname in a:
    full_name = os.path.join("C:", "Python26",  fname)
    if os.path.isfile(full_name):
        print "checking", full_name
        for rec in open(full_name):
            if b in rec:
woooee 814 Nearly a Posting Maven

There is an error on this line, no colon
for line in objconfigfile.readlines()

I would suggest that you print every line because
if line == None:
will probably never be true, but you will have to print it and see. Also, exec(line) expects "line" to be a valid python statement.

sneekula commented: good comment +8
woooee 814 Nearly a Posting Maven

Generally, this is called a callback. You have to connect the widget to a slot (function) when a signal happens. See the second example here http://www.commandprompt.com/community/pyqt/x1408

woooee 814 Nearly a Posting Maven

unable to execute gcc: no such file or directory

You also have to have libcurl installed. PyCurl is just the Python bindings for libcurl. Apparently, you are installing from source and so have to compile with the C/C++ compiler installed (gcc). Try to find a compiled binary for libcurl and pyCurl for OSX instead. Failing that. you have to install gcc which I think is in the xcode package on OSX.

woooee 814 Nearly a Posting Maven

Te following works fine for me. What version of Python are you using?

def sum_average(*args):
    size = len(args)
    sum1 = sum(args)
    average = sum1/float(size)
    # return a tuple of three arguments
    # args is the tuple we passed to the function
    return args, sum1, average

print sum_average(1, 2, 3, 4, 5)

## prints ((1, 2, 3, 4, 5), 15, 3.0)
woooee 814 Nearly a Posting Maven

For future coding conundrums, an "or" can be viewed as an if / elif, and "and" can be viewed as two nested if statements, which you would adapt to while() statements.

while overwrite != 'Y'.lower() or overwrite != 'N'.lower():  becomes
if overwrite != 'Y'.lower():
    do something
elif overwrite != 'N'.lower():
    do the same thing

For completeness, the 'and' would be
if overwrite != 'Y'.lower() and overwrite != 'N'.lower():  becomes
if overwrite != 'Y'.lower():
    if overwrite != 'N'.lower():
       do something

Hopefully this will help sort out the and/or's in the future.

nunos commented: very good post. explained in great detail. +1
woooee 814 Nearly a Posting Maven

Yes, "for line in f:" is buffered, meaning it reads more than one record at a time into a buffer. Use readline instead

fp=open(fname, 'r')
data_in = fp.readline()
while data_in: 
   print data_in,     ## assumes "\n" in record
   data_in=fp.readline()
woooee 814 Nearly a Posting Maven

Less exotic

import random

def random_tri():
    return int(random.triangular(1,100))

a=random_tri()
c=0
while random_tri() != a:
      c+=1
print(c)
woooee 814 Nearly a Posting Maven

I started doing a script that would search for the column headers (ie."datas") and get the next lines (and maybe store these in a dictionary datas {} ... ? but, I'm getting stuck on this

This is a fairly common use for computers and a fairly common question.

def process_data(list_in):
    """ 
    this function will process one group of data because 
    'list_in' starts with the record containing 'datas' plus all 
    records up to, but not including, the next 'datas' record.
    """
    if len(list_in):     ## the first list will be empty
        ##  just print to show what is being processed
        for rec in list_in:
            print rec
    print "-" * 50

data=open("file000").readlines()
ratios = ()
recs_list = []
for line in data:
    if "datas" in line:
        ## process the list before adding this record
        process_data(recs_list)

        ## re_define as an empty list
        recs_list = []

    recs_list.append(line)

##  process the final list since there won't be any
##  "datas" rec at the end
process_data(recs_list)
woooee 814 Nearly a Posting Maven

The standard anagram solver solution is to sort all of the letters in the words and place them in a dictionary, so to find the anagrams for "dog", you look up "dgo" in the dictionary and, it will give you 'dog' and 'god'. You don't have to mess with all possible combinations of the letters.

woooee 814 Nearly a Posting Maven

Doesn't that make the Person object an attribute of the clubmember class

I thought that was what you wanted. You can define the Person prototype and use it in several ClubMember class instances for several different people. You could also use a text file or an SQL file to store the data and access it from the file. A comma delimited text file would just be
Name=Harry, Score=12
Name=Joe, Score=1
which you would parse to find the name, etc. Otherwise, use a class and pickle to save the results.

I'd have to access it by saying
CM.new_clubmember.name

Yes. You can also use inheritance so the Person class becomes a child of the ClubMember class, and ClubMember would have access to all of its variables and methods.

woooee 814 Nearly a Posting Maven

The Person object has to be accessible to the whole program

It's the same, use "self". You are perhaps trying to make this harder than it is.

class Person:
    def __init__(self,name):
         self.name = name

class ClubMember:
     def __init__(self,name):
         self. new_clubmember = Person(name)

         print "testing print_name in class =",
         self.print_name()

         self.change_name("no longer " + self.new_clubmember.name)
         self.print_name()

     def change_name(self, next_name):
         self.new_clubmember.name = next_name

     def print_name(self):
         print self.new_clubmember.name

CM = ClubMember("Harry")
print
CM = ClubMember("Hands")
woooee 814 Nearly a Posting Maven

Now why does calling the new_member instance raise an error?

Look at the indentations. Generally, that kind of thing happens when you use tabs instead of spaces, which is why spaces is the preferred way to go.

woooee 814 Nearly a Posting Maven

Just to make it interesting, this is the same code, but it stops after 5 tries or one minute. It uses multiprocessing (pyprocessing for Python 2.5), instead of threading which is easier and better IMHO. You have to pass an object to the process, in this case a dictionary with the keyword 'QUIT', which can be accessed both inside and outside of the process if you want to limit the number of quesses and have a time limitation. The commented code under "__main__" can be used if you just want a time limitation. Note that you would also have to remove the 'test_d' dictionary from the class' code as well.

from multiprocessing import Process, Manager

import os
from Tkinter import *
import datetime
import time

class LoginScreen:
    def __init__(self):

        self.root = Tk(screenName=None, baseName=None, className='start screen', useTk=1)
        self.str_1 = StringVar()

        self.root.title('Login')
        self.root.geometry('300x200+270+50')
        self.userlabel = Label(self.root,text='Anvandarnamn')
        self.user = Entry(self.root)
        self.passwordlab = Label(self.root,text='losenord')
        self.password = Entry(self.root, show="*")
        self.Time = Label(self.root,textvariable = self.str_1,fg='green',bg='black')
        self.Time.pack()
        self.userlabel.pack()
        self.user.pack()
        self.passwordlab.pack()
        self.password.pack()
        self.logon = Button(self.root,text = 'Login',command = self.log)
        self.logon.pack()

        ##--- start the process with a manager dictionary
        tries = 5
        manager = Manager()
        test_d = manager.dict()
        test_d["QUIT"] = False
        p = Process(target=self.get_password, args=(test_d, tries,))
        p.start()

        start_time = datetime.datetime.now()
        stop_time = start_time + datetime.timedelta(minutes = 1)
        print start_time, stop_time
        time_to_stop = False
        while (not test_d['QUIT']) and (not time_to_stop):
           now = datetime.datetime.now()
           if stop_time < now:
              time_to_stop = True
              print "time to stop"
           time.sleep(0.1) ## eliminate some unnecessary processor cycles
        p.terminate()


    def get_password(self, test_d, tries):
        self.test_d = test_d …
woooee 814 Nearly a Posting Maven

Threading is not necessary. You can just use a while loop and exit after a certain amount of time or number of guesses.

class LoginScreen:
    def __init__(self):

        self.root = Tk(screenName=None, baseName=None, className='start screen', useTk=1)
        self.str_1 = StringVar()

        self.root.title('Login')
        self.root.geometry('300x200+270+50')
        self.userlabel = Label(self.root,text='Anvandarnamn')
        self.user = Entry(self.root)
        self.passwordlab = Label(self.root,text='losenord')
        self.password = Entry(self.root, show="*")
        self.Time = Label(self.root,textvariable = self.str_1,fg='green',bg='black')
        self.Time.pack()
        self.userlabel.pack()
        self.user.pack()
        self.passwordlab.pack()
        self.password.pack()
        self.logon = Button(self.root,text = 'Login',command = self.log)
        self.logon.pack()

        ## commented because this has nothing to do
        ##  with time, but subtracts one for every guess
        ##Time = 59
        self.guesses_left = 5
        self.str_1.set(str(self.guesses_left))
        self.root.mainloop()
        while self.guesses_left > 0:
            print self.guesses_left

        print 'bye bye :)'

##        self.t = threading.Thread(target=count, args=(self.root,))
##        self.t.setDaemon(True)
##        self.t.start()


    def log(self):
            if self.user.get() == 'XXXX' and self.password.get()== 'XXXXX':
                self.root.destroy()
                print 'welcome'
                self.guesses_left = 0
            else:
                print 'wrong password'
                self.guesses_left -= 1
                self.str_1.set(str(self.guesses_left))

##===============================================================
if "__main__" == __name__  :
   LS=LoginScreen()

See here for entry widget options
http://effbot.org/tkinterbook/entry.htm

woooee 814 Nearly a Posting Maven

You have to install both libxml2 and the python binding for libxml2. You can find download links for both libraries here http://xmlsoft.org/ What distro are you using. Most disto's package managers can install these.

ImportError: /usr/local/lib/python2.5/site-packages/libxml2mod.so: undefined symbol:

See if the python bindings for libxml2 are in /usr/local/lib/python2.5/site-packages/. They could very well be installed in /usr/lib/python2.5/site-packages/ (no /local). If so, just symlink to /usr/local/lib...etc.

woooee 814 Nearly a Posting Maven

It appears that you are trying to code one ot the two following examples. Do you want one name, time, etc., or to print all combinations of them?

##---  print one name, time, and thing ----------------------
def find_text(text_to_find, list_in):
   if text_to_find in list_in:
       ##  will return only the first item found
       return word
   return ""   ## nothing found

text = ['Mary', 'went', 'out', 'at', '7pm', 'to','buy','some','candy']
key_person = ['Mary', 'Clark', 'Steven']
key_time = ['7pm', '6am', '2pm']
key_thing =['candy','eggs','fruit']

final_list = []
append_this = [" went out at ", " to buy some "]

word_found = find_text("Mary", key_person)
final_list.append(word_found + append_this[0])

word_found = find_text("7pm", key_time)
final_list.append(word_found + append_this[1])

word_found = find_text("candy", key_thing)
final_list.append(word_found)

print "".join(final_list)
print "\n"

##-----  print all combos for one person  --------------------------
for person in key_person:
   print "%s went out at 7pm to buy candy" % (person)
woooee 814 Nearly a Posting Maven

Add a print statement to see what is going on

from progress import PB
from time import sleep
 
def main():
    bar = PB(300, 50)
    bar.open()
    for i in range(10):
        print "updating bar by",  (10.0 * i) / 100
        bar.update((10.0 * i) / 100)
        sleep(1)
    bar.close()
 
main()
woooee 814 Nearly a Posting Maven

I think you are talking about something like this, although it seems a round-about way of doing it.

class Person:
    def __init__(self,name):
         self.name = name
 
class ClubMember:
     def __init__(self,name):
         self. new_clubmember = Person(name) 

CM = ClubMember("Harry")
print CM.new_clubmember.name
woooee 814 Nearly a Posting Maven

I'm very new to python,

Depends entirely on your level of knowledge. If you understand dictionaries, then that would be the easiest to understand. The dictionary key would be the letter, pointing to a list of values. For any letter, list_value[0] would be the first line, list_value[1] the second, etc. So if you want to print "HELLO", you would use

string_to_print = "HELLO"
for row in range(0, num_rows_for_any_letter):
   row_to_print = ""
   ##---  print next row for each letter
   for letter in string_to_print:
      row_to_print +=  letter_dict[letter][row] + " "
   print row_to_print

You would of course have to check each letter to make sure it is in the dictionary, as well as for less than the maximum letters that will fit on one page.

As far as your text file goes, you would have to cut and paste that into the dictionary, or read it and test for an empty line, which would indicate the next letter. Each record in the file would become a separate row in the dictionary's value list.

woooee 814 Nearly a Posting Maven

I really don't find any reason to "dumb it down" for the general population.

Agreed, although compared to 15 years ago when I first started, Linux has a much, much wider acceptance and is growing at the expense of other OS's.

woooee 814 Nearly a Posting Maven

Don't forget that the NSA maintains SELinux (maybe someone should tell the British Navy). I would guess that a study is the first step in the process towards moving away from expensive, proprietary software. A member of Congress would not really stand up and say "I think we might save a few bucks if..", but would say "This official study by an officially recognized studier says...".

woooee 814 Nearly a Posting Maven

Add some print statements to see what is going on

def load_products(filename):
    filename = 'C:\Users\User\Desktop\cssetute\products.txt'
    f = open(filename, 'U')
    dictionary={}
    for line in f:
        line = line.rstrip()
        list1 = line.strip().split(',')
        print "list1 created =", list1

    tuple_list=[]

    print "searching list1", list1
    for item in list1:
 
       print "     item =", item
        if ':' in item:
            text, num = item.split(":")
            tuple_list.append((text, int(num)))
            print "     tuple_list =", tuple_list, "\n"

    dictionary[list1[0]] = tuple_list
    print "\ndictionary is now", dictionary, "\n"

    f.close()

    return dictionary

And if it easier to understand, use an additional function.

def add_to_dictionary(list_in, dictionary):
    tuple_list=[]

    for item in list_in:
        if ':' in item:
            text, num = item.split(":")
            tuple_list.append((text, int(num)))

    dictionary[list_in[0]] = tuple_list
    return dictionary

def load_products(filename):
    filename = 'C:\Users\User\Desktop\cssetute\products.txt'
    f = open(filename, 'U')
    dictionary={}
    for line in f:
        line = line.rstrip()
        list1 = line.strip().split(',')
     
        dictionary = add_to_dictionary(list1, dictionary)

    f.close()
woooee 814 Nearly a Posting Maven

if ID in product_dict:
for starters.

values_list = product_dict.values()
will give a list of all the values. This http://www.daniweb.com/code/snippet806.html is an example, but the easiest way is to reverse the original dictionary, unless it is huge. That is, have one dictionary that is key-->value to look up the key, and a second dictionary that is name-->key to look up the value (unless this is homework and you have to do it a certain way). If you have a lot of records, consider using SQL, as it easily does a lookup by field. Also, instead of the globals, consider using a dictionary with "ID", "name", and "parts" as the keys to store the info, and pass the dictionary to the function. Speaking of passing variables, you pass a filename to the function but don't use it.

woooee 814 Nearly a Posting Maven

The only way that I know is to use a container. The list would only contain a reference to the container and so print the current value.

print "\n", "list test", "-"*50
t_list = [3]
omega_list = [0]
write_loop = [t_list, omega_list]
for j in range(0, len(write_loop)):
   print write_loop[j][0]
print "  After"
t_list[0] = 2
for j in range(0, len(write_loop)):
   print write_loop[j][0]


##=========================================================
print "\n", "dictionary test", "-"*45
write_loop = {}
write_loop[0] = 0
write_loop[1] = 1
for j in range(0, len(write_loop)):
   print write_loop[j]

print "  After"
write_loop[0] = 2
for j in range(0, len(write_loop)):
   print write_loop[j]


##=========================================================
class Test:
   def __init__(self):
      self.t = 0

print "\n", "class test", "-"*50
write_loop = [Test(), Test()]
for j in range(0, len(write_loop)):
   print write_loop[j].t

print "  After"
write_loop[1].t = 2
for j in range(0, len(write_loop)):
   print write_loop[j].t
woooee 814 Nearly a Posting Maven

My attempt. Once again, if not correct, post back with more info. The trick (I think) is to split each string on the "\n" to create individual rows, and is similiar to Gribouillis' solution but doesn't use list comprehension (which is an amazing tool). It instead uses a dictionary with row number as the key, in this case 0 through 4, and appends each row to the corresponding key. Finally, the joined rows are spaced and printed. Hopefully, using a dictionary with the row number is easy to understand.

def join_letters( letter_list, base_dict ):
   combined_rows_dict = {}

   ##---  base length to test for equality
   len_letter = len(base_dict[letter_list[0]])

   for j in range(0, len(letter_list)):
      this_letter = letter_list[j]

      ##--- all letters must be in the dictionary
      if this_letter not in base_dict:
         print "letter %s not in base_dict" % (this_letter)
         return "***"

      ##--- test for all translations are equal in length
      if len(base_dict[this_letter]) != len_letter:
         print "unequal letter lengths", len_letter, len(base_dict[this_letter])
         return "***"

      ##--- convert triple quote string into rows in a list
      string_list = base_dict[this_letter].split("\n")
      print "string_list", string_list

      ##---  append each row to the corresponding dictionary key
      for row in range(0, len(string_list)):
         if row not in combined_rows_dict:
            combined_rows_dict[row] = []
         combined_rows_dict[row].append(string_list[row])

   print
   for row in range(0, len(combined_rows_dict)):
      this_row = combined_rows_dict[row]
      print " ".join(this_row)
   return "Success"

base_dict = {}
base_dict["A"] = """X 0 X X
0 X 0 X
0 0 0 X
0 X 0 X
0 X 0 X"""

base_dict["B"] = """0 0 X X
0 X 0 X
0 0 …
Gribouillis commented: You're the best teacher in forum 114 ! +4
woooee 814 Nearly a Posting Maven

I for one am not sure what you are trying to do. It is something like this? If not, please post some input and desired output examples. Also, if joining, remember that each triple quoted string is one string and not a list.

base_dict = {}
base_dict["A"] = """X 0 X X
0 X 0 X
0 0 0 X
0 X 0 X
0 X 0 X"""

base_dict["B"] = """0 0 X X
0 X 0 X
0 0 X X
0 X 0 X
0 0 X X"""

base_dict["C"] = """X 0 X X
0 X 0 X
0 X X X
0 X 0 X
X 0 X X
"""

for key in ("A", "B", "C"):
   print key, "-" *60
   print base_dict[key]
woooee 814 Nearly a Posting Maven

You can also use callbacks, which are pretty handy. This is an example. The "buttons" function is the significant part of the code for callbacks. You define a function that is attached to each button, so when that button is pressed you can perform some action based upon which button is checked. This example code just prints something and keeps track of which buttons are on and which are off. It does require the Pmw extension to Tkinter. If you do not have it installed you may want to as it has additional widgets.

from Tkinter import *
import Pmw

class CB:
   def __init__(self, master):
      master.geometry("290x200+5+10" )
      self.master = master
      self.button_num = 0
      self.button_dic = {}
      self.maps_list = self.retrieve_maps()
      self.var_list = []
      self.cb_list = []
      self.choice_list = []

      ##   frame to contain the list boxes
      self.frame = self.scrolled_frame('Available', 150)

      self.exit_button()
      self.label_box()
      self.buttons()


   ##-------------------------------------------------------------------
   def buttons(self):
      """ one checkbutton for each item in the list
      """
      for map_c in self.maps_list:
         self.button_dic[self.button_num] = map_c
         var = IntVar()
         var.set(0)          ## off=default
         self.var_list.append(var)

         b = Checkbutton(self.frame, text = map_c, variable=var)
         b.pack()
         self.cb_list.append ( b )
         def handler ( event, self=self, button_num=self.button_num ):
                return self.cb_handler( event, button_num )
         b.bind ( "<Button-1>", handler )

         self.button_num += 1


   ##-------------------------------------------------------------------
   def cb_handler( self, event, cb_number ):
      store_name = self.button_dic[cb_number]
      if store_name not in self.choice_list :
         self.choice_list.append(store_name)   ## add to selected
      else:
         self.choice_list.remove(store_name)   ## remove from selected
      self.choice_list.sort()

      text_label = "\n".join(self.choice_list)
      self.label_box.configure(text="---Print These---\n" + text_label)

   ##-------------------------------------------------------------------
   def exit_button(self):
      """  Print and Exit buttons
      """
      but_frame=Frame(self.master)
      prt =  Button(but_frame, …
woooee 814 Nearly a Posting Maven

word = raw_input("What word should we convert? ").upper()
word.translate(cypher)

If the first statement, you define 'word' as a string. In the second statement, it appears to be a class with the method "translate". You can not use the same variable name for two different types of memory.

woooee 814 Nearly a Posting Maven
woooee 814 Nearly a Posting Maven
def extract(list_in):
    if len(list_in):
        print "New Group", "-" *60
        for rec in list_in:
            print rec

##f = open("a.txt", "rb")   ## why are you reading this as binary
f = open("a.txt", "r")
temp = []
##r = f.readline()   ## this skips the first rec
for r in f:
    if "Computer name:" in r:
        extract(temp):
        temp = []
    temp.append(r)
extract(temp)  ## the final group 

Use "(CODE)" instead of "(QUOTE)" for code samples.

woooee 814 Nearly a Posting Maven

You can use "lsof" (list open files) but that gives a huge amount of data since it will list any and all system files, etc. as well.

The application cannot generate any indication of completion of the process.

Why not? That is the standard way of doing things. Processes are meant to be independent and were designed with that in mind. If you want inter-process communication you will have to design it in.

woooee 814 Nearly a Posting Maven

Break the file up into groups by reading the file one line at a time and append to a list. When you hit a "Computer name" record, send the list to a function and process that group of records however you want. Then re-define the list as empty and rinse and repeat. You will have to have an additional statement to send the last group of records to the function, since there will be no "Computer name" record found to do that. If you run into problems, post the code that you have and ask for help.

woooee 814 Nearly a Posting Maven

TkSnack is one of the simpliest http://www.daniweb.com/code/snippet414.html
Also, try the Python Music wiki http://wiki.python.org/moin/PythonInMusic

woooee 814 Nearly a Posting Maven

Doing this in memory is definitely the way to go. It could be 1000 times faster. Putting 17,000 records into memory is not a big deal in today's world. If each of the records is 100 bytes long, then you have 1,700,000 bytes. If your computer has 2 gig of memory (to make the calcs easy) then you are using 1/10 of one percent.

Some ideas:
1. Set a minimum distance that is an automatic for going to that school. If a child lives a block away then they will obviously go to that school and you don't have to test the rest of the schools.

2. Assign a small, simple grid system. If a child lives north of Main St. and west of First Ave. then you can eliminate half of the schools as being too far away, and half of the processing time. As long as the number of schools eliminated is greater than the number of distances calculated to get the right grid, you come out ahead. If you can eliminate one school per child, you have eliminated 17,000 calculations, or 2% of 50 schools, whichever way you want to look at it.

woooee 814 Nearly a Posting Maven

This easiest to understand, IMHO, is to create a dictionary with the row & col values as a tuple, for the key pointing to a list of the element number(s). Then, if the list has a length greater than one you have duplicates and can add the corresponding Var1, or Var2 elements, or whatever. For the example given, the dictionary would look like
{ (52, 513) : [0, 3],
(34, 22) : [1],
(423, 421) : [2],
etc.
So a test for length would say that the (52, 513) pair has more than one value and you would add Var1[0] + Var1[3]. Then, it is safest to create a new list with the new, combined values or whatever you would like the output to be. And if I understand this correctly, if the dictionary had an entry like
(52, 513) : [0, 3, 6]
and you wanted to add [0]+[3], and then [3]+[6], you would have to keep track of pairs using two for() loops or some other method.

woooee 814 Nearly a Posting Maven
def word(word):
     print("do you wanna save" + word)
     print("y=yes n=not this time nn=never")
     define = input("Enter choice: ")

## if define.lower() not in never and define.lower() == "nn":
##     never.append(word)
     if word.lower() not in never and define.lower() == "nn":
         never.append( word.lower() )

     elif define.lower() == "y":
	word = word + " "
	words.append(word)

     elif define.lower() == "n":
	pass
     else:
	print("invalid choice")
woooee 814 Nearly a Posting Maven

I thought old_leader was assigned in the constructor?

Look again. You declared self.old_leader, so what is the difference in a class structure between self.old_leader and just old_leader.

woooee 814 Nearly a Posting Maven

"=" means they are equal, i.e. the same memory address, so when you change one, you change the memory that they both point to. You can instead use:
a = [1,2,3]
b = a[:] ## copy all of the elements in "a" to a new block of memory
Also, there is copy and deepcopy depending on whether or not the list is nested. See here http://docs.python.org/library/copy.html Google will of course yield more copy and deepcopy examples if you decide to go that way.