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

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

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

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

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

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

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

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

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.

woooee 814 Nearly a Posting Maven

tuple (4,22,51) = 1515 so this means i have 1515 lines in my file that have the above tuple init

How do you know this is accurate? Have you counted them, or tested on a smaller sample and counted those to make sure it is correct? It is impossible to test with huge amounts of data. You have to create a small sub-set and work with that. The following code stores record numbers for each key tuple using a dictionary of lists, and then prints all of the associated records. You can, of course, pick and choose which ones you want to print using random numbers, etc.

tuple_test = (("a", "b", "c"), ("d", "e", "f"), ("g", "h", "i"))

##---  create some test data
records_test = []
records_test.append(tuple_test[0])
records_test.append(tuple_test[2])
records_test.append(tuple_test[1])
records_test.append(tuple_test[0])
records_test.append(tuple_test[0])
records_test.append(tuple_test[1])

##--- a dictionary with the tuple as key, pointing to a
#     list of record numbers
record_num_dic = {}
for rec_num, tuple_rec in enumerate(records_test):
   print "processing", tuple_rec, "rec number =", rec_num
   if tuple_rec not in record_num_dic:
      ## add a new key pointing to an empty list
      record_num_dic[tuple_rec] = []
   record_num_dic[tuple_rec].append(rec_num)

for key in record_num_dic:
   print key, record_num_dic[key]
   rec_num_list = record_num_dic[key]
   for rec_num in rec_num_list:
      print "      ", rec_num, records_test[rec_num]
woooee 814 Nearly a Posting Maven

I would suggest using lsusb, but this will list all usb devices, so if you have a printer or mouse, or possibly an sda drive, you will have to weed them out.

woooee 814 Nearly a Posting Maven
woooee 814 Nearly a Posting Maven

Effbot is a good resource. You might want to bookmark it and New Mexico Tech's site http://infohost.nmt.edu/tcc/help/pubs/tkinter/ for future reference. Please mark this post "Solved" so no one wastes their time on a solved post.

woooee 814 Nearly a Posting Maven

thanks woooeee im going to try all this out thanks for the advice i'm goona try this out i want to have one key with numerous values which are my record numbers uuff im just getting myself in a muddle :( thank you i will post back soon

What are you going to try? Take Gribouillis' advice and use just a part of the file for testing. First, read the records one at a time and print each one so you know that part is correct, as you are only using 20 records or so.

Then, create the tuple and add it to a dictionary and print the dictionary after each add so you know that part is correct. Once that is done, post your code, and state what you want to do next for some more advice. You also have to define "random" in more concrete terms. What if you want the second record that contains the tuple (a, b, c) and there was only one record with that tuple? Or do you want to choose any random record? Why must it have a specific tuple and how do you decide which tuple to use?

woooee 814 Nearly a Posting Maven

According to effbot, you can use wrap=NONE http://www.google.com/search?client=opera&rls=en&q=tkinter+wrap+text&sourceid=opera&ie=utf-8&oe=utf-8 I've never used it though.

woooee 814 Nearly a Posting Maven

Please don't double post. Stick with one thread and mark the other "Closed" or "Solved". And a title like "someone please help!!!!!!!!!!" will get less responses not more. It does not state a specific problem and indicates someone who is looking for someone to write free programs for them. The few who donate some time answering questions would soon be overwhelmed if we allowed that to happen.

woooee 814 Nearly a Posting Maven

Try some print statements,

match={}

for rec_num, v in enumerate(a):
    rec_num+=1
    print "\n Next rec: rec_num is now", rec_num
    for values in a:
        print "     values =", values[0], values[2], values[3])
        triple=(values[0], values[2], values[3])
        if not match.has_key(triple):
            match[triple] =0
        print "     triple is now", values
    print "     second dictionary add", triple, rec_num
    match.setdefault(triple,[].append(rec_num))

Since the dictionary contains zero for every key, it appears that this line
match.setdefault(triple,[].append(rec_num))
is not working correctly. Are you getting error messages? Also, read up on dictionaries and decide if you are going to use "if not triple in match" (which you define as a dictionary of one integer), or "setdefault" (which you define as a dictionary of lists). When you get a clean dictionary, you can use the rec_num associated with each key to access that record, although you might want to allow for duplicate keys, i.e. use a dictionary of lists instead of a dictionary of one integer. You appear to have just copied code and do not understand what is happening. It is almost impossible to get something to work if you don't understand it, so add print statements and anything else that helps clear up the picture.

woooee 814 Nearly a Posting Maven

is there a way to make a scrollbar widget automatically scroll to the bottom?

Use scrollbar.config ()
scrollbar.config( command = listbox_widget.yview )
listbox_widget.see(listbox_widget.size())

I think it is something like this for a text widget
Text.see(Text.END)

in a Text widget, how would I be able to make everything...colored

Most all of Tkinter's widget's have a background and foreground option. See the docs.

woooee 814 Nearly a Posting Maven
myapp = MyGUI()

There is no MyGUI() class or function so who knows what myapp contains. I don't see an import Tkinter either. Also, try a myapp.mainloop() right after the myapp = MyGUI to test if the mainloop() is working properly, and then print myapp in the GUILoop class and where it is created, to see if it is being passed correctly. HTH.

woooee 814 Nearly a Posting Maven

There is no difference, as far a calling a function goes, between calling a function within or without a program. The following works for me with the calc() function contained in the same program file.

from Tkinter import *

def calc(one, two, result):

        def addition():
            add = one + 1
            print(add)

            result.insert(END, 'first='+str(one)+' second='+str(two)+' addition='
                               +str(add))

        def subtraction():
            subs = two - 1
            print(subs)

            result.insert(END, 'first='+str(one)+' second='+str(two)+' subtraction='
                               +str(subs))


        result.insert(END, 'first='+str(one))

        addition()

        result.insert(END, 'second='+str(two))

        subtraction()


class App:

    def __init__(self, parent):

        frame = Frame(parent.title("primary window"))
        frame.pack()

        self.lbfirst = Label(frame, text="First number:")
        self.lbfirst.grid(row=0,column=0)

        self.first = Entry(frame)
        self.first.grid(row=1,column=0)

        self.lbsecond = Label(frame, text="Second number:")
        self.lbsecond.grid(row=2,column=0)

        self.second = Entry(frame)
        self.second.grid(row=3,column=0)

        self.number=Button(frame, text="calc", fg="red", \
                                            command=self.call_calc)
        self.number.grid(row=4,column=0)

        self.result = Listbox(frame)
        self.result.grid(row=5,column=0, columnspan=5, sticky=N+S+E+W)

    def call_calc(self):
        calc(float(self.first.get()), float(self.second.get()), \
                 self.result)


root = Tk()

app = App(root)
woooee 814 Nearly a Posting Maven

It works fine for me.

mlist = [ "first = 3", "second =", "third = 1"]
item_list = ["third = 1", "second = 2", "junk"]
for item in item_list:
    x = -1
    print "\ntesting", item
    if item in mlist:
        x = item[-1]
        print "if: x is now", x
    else:
        x = 0
        print("else")
    print x

x is being set to one in both of your examples. The only place that can come from is the file, so you changed the wrong file or something similiar. Post the output of the print mlist statement.

woooee 814 Nearly a Posting Maven

Run this piece of code and then take a look at where you can add some print statements to your code so you will know what is actually happening.

item = "third = 1"
if item.find("third"):
    print "item found at position", item.find("third")
else:
    print "item NOT found, value returned =", item.find("third")
#
if item.find("first"):
    print "item found at position", item.find("first")
else:
    print "item NOT found, value returned =", item.find("first")

You also want to take a look at the "startswith" string method as that is more in line with what you are doing.

woooee 814 Nearly a Posting Maven

Note the quotation marks, so it is just a string so you can substitute anything you like.

SQL_str="CREATE TABLE %s (name_last VARCHAR(20), age INT)" % (name_to_use)
cur.execute(SQL_str)
woooee 814 Nearly a Posting Maven

You would use a variable like "table_name" in the first line here, and pass that to the connect function. If you are creating a new table, then you would also have to input the field names and type, or use a standard layout for all databases.

table_name = "people_db"
   con = sqlite.connect(table_name )

   # Get a Cursor object that operates in the context of Connection con
   cur = con.cursor()

   ##--- ONLY CREATE FIRST TIME
   cur.execute("CREATE TABLE people (name_last VARCHAR(20), age INT)")
woooee 814 Nearly a Posting Maven

You should state what you are trying to accomplish and perhaps someone will help with that. We are not your personal answering machine. Please don't waste everyone's time.

woooee 814 Nearly a Posting Maven

Store the record number in the dictionary, (this code was not tested)

match={}
for rec_num, values in enumerate(lines):
    truple=(values[0], values[2], values[3])
    if not match.has_key(truple):
       match[truple] =[]

    match[truple].append(rec_num)

for key in match.keys():
    if len(match[key]) > 1:
        print "more than one record found for", match[key]
        for rec_num in match[key]:
            print "     ", lines[rec_num]
        print
woooee 814 Nearly a Posting Maven

It;s just personal preference, but I prefer multiprocessing to threading (If you are using Python2.5 or lower, then you will have to download pyprocessing and substitute "processing" for "multiprocessing" in the code below). http://pyprocessing.berlios.de/ This is just something used to test a dictionary and a list as a way to pass variables to one of the two processes that are running.

import time
from multiprocessing import Process, Manager


def test_f(test_d, test_l):
   test_d['2'] = 2
   test_d["QUIT"] = False
   while test_l[0] == "False":
      print "test_f", test_d["QUIT"], test_l
      test_d["ctr"] += 1
      time.sleep(1.0)
     
def test_f2(name):
    for j in range(0, 10):
       print "   test_f2", j
       time.sleep(0.5)

if __name__ == '__main__':
   manager = Manager()

   test_d = manager.dict()
   test_list = manager.list()
   test_list.append("False")
   test_d["ctr"] = 0
   test_d["QUIT"] = False
   
   p = Process(target=test_f, args=(test_d,test_list,))
   p.start()
##   p.join()
   
   p2 = Process(target=test_f2, args=('P2',))
   p2.start()

   #--- Change the dictionary/list so the first process ends
   time.sleep(2.0)
   test_d["QUIT"] = True
   test_list[0] = "True"
   print "\ntest_d/list changed"
   time.sleep(3.0)

   print "terminate first process just to be sure"
   p.terminate()   ##  p terminated here
   print "data from first process", test_d, test_list
woooee 814 Nearly a Posting Maven

please has anyone got any suggestions im still stuck

Suggestions about what? If you want 100 random samples, then you can select the dictionary's keys randomly.

import random

##---  create dictionary with 1000 keys
test_data_d = {}
for j in range(1001, 2001):
   test_data_d[j] = "data for key %d" % (j)

##--- keys_list is in hash order (appears random) and not
##    numerical order which actually works better for randomness
keys_list = test_data_d.keys()

##---  10 random keys is enough
stop = len(keys_list) - 1
for j in range(0, 10):
   random_num = random.randint(1, stop)
   this_key = keys_list[random_num]
   print j+1, test_data_d[this_key]

Note that any random number can appear more than once, so might want to store the numbers in a list and if that random number has already been used, choose another one.

woooee 814 Nearly a Posting Maven

You can use the decimal module if you want very, very precise results http://docs.python.org/library/decimal.html#quick-start-tutorial
One of the hits from a search on this forum
http://www.daniweb.com/forums/thread95473.html

woooee 814 Nearly a Posting Maven

I tried last night (about 12 hours ago) and it was down then. It is still down this morning. It is hosted in the Netherlands, so I doubt it's connected to the Twitter/Facebook stuff. I also Googled for mirrors, but Python doesn't host mirrors anymore. Too bad.

Of course this is the weekend that I was going to install 3.X and start converting. I could use Active State's version, but I think I'll wait until python.org comes back up.

woooee 814 Nearly a Posting Maven

It's just
self.conn = sql.connect(dbname)

Here's some code (just a bunch of crap really) from when I was first testing SQLite that shows how to add, change and delete recs. Note that when you retrieve records you have to test for None, i.e. no records found in db. That threw me for a curve when first starting out.

import sqlite3 as sqlite

##----------------------------------------------------------------------
def add_rec(cur, con):
   ##cur.execute("INSERT INTO people (name_last, age) values ('Yeltsin',   72)")
   cur.execute("INSERT INTO people (name_last, age) values ('Putin',   50)")
   cur.execute("INSERT INTO people (name_last, age) values ('Putin',   50)")
   cur.execute("INSERT INTO people (name_last, age) values ('Putin',   50)")
   cur.execute("INSERT INTO people (name_last, age) values ('Yeltsin',   70)")

   ##---  add using a tuple instead
   person_tuple = ('Barisinov', '30')
   cur.execute("insert into people (name_last, age) values (?, ?)", person_tuple)
   con.commit()

##----------------------------------------------------------------------
def change_recs_test(cur, con):
   cur.execute("UPDATE people SET name_last==:who_dic WHERE age==:age_dic",
       {"who_dic": "Chg_Yeltsin", "age_dic": 70})
   con.commit()

##----------------------------------------------------------------------
def del_recs_test(cur, con):
   who = "Putin"
   age=50
   cur.execute("DELETE from people where name_last==:who_dic and age==:age_dic",
       {"who_dic": who, "age_dic": age})
   con.commit()
   print "-" * 30, "AFTER Delete"
   print_all_recs(cur)
   print
   
##----------------------------------------------------------------------
def print_all_recs(cur):
   # Execute the SELECT statement:
   print "Printing all recs"
   cur.execute("select * from people order by age")

   # Retrieve all rows as a sequence and print that sequence:
   print cur.fetchall()

#==========================================================================
if __name__ == "__main__":
   # Create a connection to the database file
   table_name = "people_db"
   con = sqlite.connect(table_name )

   # Get a Cursor object that operates in the context of Connection con
   cur = con.cursor()

   ##--- ONLY CREATE FIRST TIME
   cur.execute("CREATE TABLE people (name_last VARCHAR(20), …
woooee 814 Nearly a Posting Maven

You have to commit
self.conn.commit()
after the adds

woooee 814 Nearly a Posting Maven

The problem is in
loseLimb(choice, armRight, armLeft, legRight, legLeft, head)
You return one of the booleans but don't catch any returns at the calling statement.

loseLimb(choice, armRight, armLeft, legRight, legLeft, head)
#
def loseLimb(choice, armRight, armLeft, legRight, legLeft, head):
    if choice == 1:
        print "The BattleBot destroys Mr. Taylor\'s right arm!"
        print "Mr. Taylor screams in pain and doesn't like you anymore."
        print
        armRight = True

        ## return is here  *******************************
        return armRight
#---------------------------------------------------------------------
# The problem is that you have no idea which variable is being 
# returned.  You want to pass and return a list or a dictionary instead.
#----------------------------------------------------------------------
# with a dictionary
limbs_dic = {}
limbs_dic['armRight'] = False
limbs_dic['armLeft'] = False
limbs_dic['legRight'] = False
limbs_dic['legLeft'] = False
limbs_dic['head'] = False
#
#---  pass the dictionary and keep the returned dictionary
limbs_dic = loseLimb(choice, limbs_dic)
print "limbs_dic =", limbs_dic  ## test that the changes were made
#
def loseLimb(choice, limbs_dic):
    if choice == 1:
        print "The BattleBot destroys Mr. Taylor\'s right arm!"
        print "Mr. Taylor screams in pain and doesn't like you anymore."
        print
        limbs_dic['armRight'] = True

        return limbs_dic

You can also change chooseLimb() so that it only returns a correct answer and do away with the
while(choice != 1 and choice != 2 and choice != 3 and choice != 4 and choice != 5):
but I don't have any more time until tonight. Start with Shadwickman's suggestion and have one funtion do all the work, which will get the code …

woooee 814 Nearly a Posting Maven

You haven't recieved many answers, and probably won't because your examples are incomplete. You are obviously doing something in the code that is not posted that alters the result. Take a look at the following code that is a complete program that can be run. It shows that your contention does not hold up, at least as far as I can tell from what has been posted. You may be re-defining variables or it may be a scope problem, but there is no way to tell from the snippets that were posted. Also, this bit of code

result = checkAnswer("C", userAnswer)
    if(result):
    #if answer is incorrect, display message as such
        wrongAnswer()

will not even run because of improper indents.

def change_bool(bool_arg):
   bool_arg = not bool_arg
   print "in first function", bool_arg     ## prints 'False'

def change_2():
   test_1 = False
   print "in 2nd function", test_1     ## prints 'False'

test_1 = True
change_bool(test_1)
print "first", test_1     ##(prints 'True')
change_2()
print "second", test_1     ##(prints 'True')
woooee 814 Nearly a Posting Maven

[(a, alist.count(a)) for a in set(alist)]

A nice solution. Convert to a set to eliminate duplicates and then count each one. It still requires that the list be processed as many times as there are integers in the set, and would yield the results in hash table order, but the list of tuples could be easily sorted.

woooee 814 Nearly a Posting Maven

Not that I know of. You would have to use a dictionary with the integer as a key, with the value being a counter integer that you would increment each time. There is a count function for lists that would return the number of times something occurs in a list, but you would have to process the entire list however many times you count, instead of once, and you would have to keep track of what counts have already been done so you don't do them twice, and there are probably other problems that make count() more trouble than it is worth for this particular case. The other solution would be to sort the list and count until you find a difference, then print, rinse and repeat.

woooee 814 Nearly a Posting Maven

It appears that you are using "text" twice.

##--- here "text" is the list of records from the file
    text = file.readlines()
    file.close()

    keyword = re.compile("searchword")

##--- here you are reading from the list of records which is named "text"
    for line in text:
        result = keyword.search (line)
        if result:
##--- here you are trying to "INSERT, '\n' + line" into the
##     list named "text", which can not be done
            text.insert(INSERT, '\n' + line)
woooee 814 Nearly a Posting Maven

This should print the matches once only but it is untested.

nextrow = 0
thisrow = 0
prev_number = ""
while thisrow < listmax-1:
    nextrow = thisrow + 1
    this_record = edgelist1[thisrow]
    while (nextrow < listmax) and \
            (this_record[0]==edgelist1[nextrow][0]):

       ##  print new number
       if this_record[0] != prev_number:
           print ("\n-----", this_record[0])
           prev_number = this_record[0]

       print (thisrow, this_record[1], nextrow, edgelist1[nextrow][1])

       ##   skip over these records
       thisrow = nextrow
       nextrow=nextrow+1
    thisrow += 1
woooee 814 Nearly a Posting Maven

Your original code will give results until it finds a record that does not match, and not necessarily all of the matches. It is also redundant. You print
ANTIMICROBIAL RESISTANCE CARRIAGE
ANTIMICROBIAL RESISTANCE EXPERIENCE
because they are all equal, then you print
CARRIAGE EXPERIENCE
which is a duplication of the first printing. I don't know if this is what you want or not.

The problem with the original code is that it has to process the file many, many times. That is, each record is compared with every other record (potentially). If the program doesn't take too long to run, then this is OK. Otherwise you want to process the file in one pass. The best way to do this is probably to place the records in a dictionary of lists, where the key is the number, pointing to a list of lists, each list containing whatever you want, the description and the record number perhaps. You then extract any key that has more than one entry. Post the first 10 or so records if you want any more help, as the code snippet that I posted should work for the 3 record examples in your first post.

If you want to use the while() statement then you must test for end of file

while (nextrow < listmax) and \
      (edgelist1[i][0]==edgelist1[nextrow][0]):