woooee 814 Nearly a Posting Maven

Try adding print statements to both functions. "None" means that no pattern match was found.

def find_name():
    folder = "C:/Users/Sam/Desktop"
    for filename in os.walk(folder).next()[2]:
        print "testing filename", filename
        if pattern.match(filename):
            print "find_name returning", filename
            return filename
 
def main():
    newname = str(duration) + ".txt"
    filename = find_name()
    print "filename returned is", filename
    ## comment the next line for now, until you get
    ## the program fixed
##    os.rename(filename, newname)

Then see the article here, especially the os.path.normpath() http://pythonconquerstheuniverse.blogspot.com/2008/06/python-gotcha-raw-strings-and.html (This question has been asked so many times that it seems no one will answer it anymore.)

woooee 814 Nearly a Posting Maven

Another idea. You can also split on the "AND" and then split on "|" removing the [-1] element.

test_input = "AND Category 07|Spec 01|ABC 01 AND Category 07|Spec 02|XYZ 02 AND Category 07|Spec 03|PQR 03 "
after_and_split = test_input.split("AND")
print after_and_split

new_str = ""
for str in after_and_split:
   after_line_split = str.split("|")
   ## length has to be > 1, otherwise nothing is left after removing -1
   if len(after_line_split) > 1:
      print "     after_line_split", after_line_split
      del after_line_split[-1]
      new_str += "AND" 
      new_str += "|".join(after_line_split) + " "
print new_str 

AND Category 07|Spec 01 AND Category 07|Spec 02 AND Category 07|Spec 03

Edit: I hope this isn't homework since it's too late now.

woooee 814 Nearly a Posting Maven

Please don't spam this site or someone will report you and you will be banned. Since the OP didn't say which toolkit or OS was involved, it is obvious that there is no way to recommend anything, hence MESHIKUMAR and mohankumar554 are the same and are spamming.

vegaseat commented: thnaks for the spam fight +12
woooee 814 Nearly a Posting Maven

This was the second entry from a Google for "python list write"
http://www.daniweb.com/forums/thread173615.html

and effbot is usually in search results. This explains writelines(), but writelines() does not insert a newline but is useful for transferring lists to a file.
http://effbot.org/zone/python-list.htm

slate commented: Straihgt to the point. +1
woooee 814 Nearly a Posting Maven

Double post deleted.

woooee 814 Nearly a Posting Maven

We posted at the same time. Here is http://packages.ubuntu.com/dapper/python2.4-imaging-tk You wil probably have to click the download link on the far right and install using dpkg. And then you can use "search" at the top of the page for the rest. Try to get the package for the specific disto you are using or as close as possible. I use Slackware so am not sure, but it's something like "dpkg -i package-name" installs. Check man dpkg for details. Again, if it does not install into /usr/lib/python2.4/site-packages then simlink it Also, asking here is a good idea, but the Ubuntu forums are usually very good also for something Ubuntu specific.

Just wanted to see if they were available,
Tkinter should already be in /usr/lib/python2.4/lib and readline is not python specific
http://packages.ubuntu.com/search?searchon=names&keywords=numeric+2.4
http://packages.ubuntu.com/search?suite=default&section=all&arch=any&searchon=names&keywords=python+imaging+2.4
http://packages.ubuntu.com/search?suite=default&section=all&arch=any&searchon=names&keywords=pmw
http://packages.ubuntu.com/search?suite=default&section=all&arch=any&searchon=names&keywords=python+opengl
So clicking on dapper for Pmw says that it requires python 2.4, so you probably want packages built for that distro http://packages.ubuntu.com/dapper/python-pmw

woooee 814 Nearly a Posting Maven

I'm doing a project doing atomic models and am using a toolkit that was developed for Python 2.4 on Ubuntu

That toolkit should run under 2.6 even though it was developed using 2.4, so your first option is to try running it using 2.6. /usr/bin/python should point to python2.6 somewhere on the system (where depends on how it was configured).

If that doesn't work then you want to symlink the necessary libraries from/usr/lib/python(2.6)/site-packages to /usr/lib/python2.4/site-packages since they were obviously installed into the 2.6 libraries. They should work even though they were compiled against 2.6. The shebang in the toolkit would then be "#!/usr/bin/python2.4" or whatever. Alternatively you can run it with "/usr/bin/python2.4 toolkit.py".

If that doesn't work, then you will have to install each of these packages and make sure they are in, or symlinked to /usr/lib/python2.4/site-packages. Installing should be simple since they are mostly python scripts, but I'm not sure about all of them

woooee 814 Nearly a Posting Maven

You read it one line at a time, but write only if the counter is between the numbers. And don't use "i", "l", or "o" as single variables because they look too much like numbers.

f = open(infile,'r')
o = open(outfile,'w')
ctr = 1

for line in f:
   if first <= ctr <= last:
      o.write(str(ctr)+'\t'+line)
   ctr += 1

f.close()
o.close()
woooee 814 Nearly a Posting Maven

These are the rpms for 2.3 on the Python web site. I would install all 5 of them just to be safe. http://www.python.org/ftp/python/2.3/rpms/redhat-9/ If you can step up to 2.5, then try Active State's version, as they have everything bundled with it.

woooee 814 Nearly a Posting Maven

This thread is almost 2 years old.

woooee 814 Nearly a Posting Maven

This is the Python forum. Try the MySQL forums.
http://www.daniweb.com/forums/forum126.html
http://forums.mysql.com/

woooee 814 Nearly a Posting Maven

Thanks for the replies but I get forbidden page everytime when i try to go to my address with additional variables in slashes. I assume there should be some .htaccess setting for the server to be able to divide the url into the "actual url" and the variables.
More of a server issue i suppose, any1 had experience with this? :)

Post the relevant code and print, then post also, the URL you are trying to use. You can insert the slash, if that is what you are trying to do, the same way you insert any other character or string.

slash = "/"
mm = 5
dd = 17
ccyy = 2009
URL = "http:%s%swww.google.com%s%02d%s%02d%s%d%s" % \
       (slash, slash, slash, mm, slash, dd, slash, ccyy, slash)
print URL
woooee 814 Nearly a Posting Maven

Ugh I hate these elif errors!

Then don't use it. Some examples that also simplify the code.

## instead of if line == 0 ,1 2, etc.
for line in f:
   if (line > -1) and (line < 10):
      row0.extend([line[x] for x in range (0, 10)])
##
##------------------------------------------------------------------
"""
#the initial state of the board is all blank
#im storing each row of the board as a list
#this is pretty much only for displaying the board
 
row0 = []
row1 = []
row2 = []
row3 = []
row4 = []
row5 = []
row6 = []
row7 = []
row8 = []
row9 = []
"""
## use a list of lists or a dictionary instead
## this is a dictionary with the key = 0 --> 9 instead
## of row0 --> row9
row_dic = {}
for j in range(0, 10):
  row_dic[j] = []
##
##------------------------------------------------------------------
""" instead of
elif (player == "p2"):, etc.
"""
player_dic = {}
player_dic["p1"] = player1
player_dic["p2"] = player2
player_dic["pc1"] = comp1
player_dic["pc2"] = comp2
for p in range(0,numPlayers):
 
   print "Would you like to be Player 1, Player 2, PC 1, or PC 2?\n"
   player = raw_input("p1, p2, pc1, or pc2:")
   player = player.lower()
   if (player in player_dic):
      currentPlayers.append( player_dic[player] ) 
   else:
      print "That is not a valid player"

Hopefully you get the idea.

woooee 814 Nearly a Posting Maven

It's just personal preference, but I would use sets for the partial match, and compare two sorted lists for the exact match. Using existing methods that are tested is always a better option. If I understand what you are doing, the following code should illustrate.

def exact_match(guess, secretCode):
   guess_list = [x for x in guess.lower()]
   secret_list = list( secretCode.lower() )
   guess_list.sort()
   secret_list.sort()
   if guess_list == secret_list:
      return True
   return False

def partial_match(guess, secretCode):
   guess_set = set(guess.lower())
   secret_set = set(secretCode.lower())
   intersection_set = guess_set.intersection(secret_set)
   return len(intersection_set)



   
test_list = [ ("ABCDE", "de"),
              ("ABCDE", "ecbad"),
              ("ABCDE", "FGH") ]
for each_test in test_list:
   found = partial_match(each_test[0], each_test[1])
   if found:
      print "partial match for", found, "letters",
   else:
      print "no partial match for", 
   print each_test[0], each_test[1]

   found = exact_match(each_test[0], each_test[1])
   if found:
      print "exact match for", 
   else:
      print "no exact match for", 
   print each_test[0], each_test[1]
   print "---------------------------------------------------"
woooee 814 Nearly a Posting Maven

You want to add a print statement to see what is going on

exact = 0
            while (exact != 4):
               userGuess = guess.askForGuess()

               exact = exactMatchCount.exactMatch(userGuess,secretCode)
               print "exact =", exact
               if exact != 4:
                  print "Another while loop is necessary\n"

               partial = partialMatchCount.partialMatch(userGuess,secretCode)
               print "Black pegs: " + str(exact)
               print "White pegs: " + str(partial)

Also, this code should produce an error since there is no partialMatchCount class declared or imported.

woooee 814 Nearly a Posting Maven

I want it to sort both the map name and the map index though should I use a dictionary instead?

If you want to look up the name or index then use one dictionary for each, unless there is a very large data set. If you want to sort and print, then sort using a normal items.sort() or
items.sort(key=operator.itemgetter(-1)) for the last element

woooee 814 Nearly a Posting Maven

Running the following code yields the result posted. id is one of the first things you want to know when two objects appear to be the same.

f = FD_field(4, 4, 4)
f.At(1, 1, 1)
print ("f #1 id = %d" % id(f.data))

f.Set(1, 1, 1, 5)
f.At(1, 1, 1)
print ("f #2 id = %d" % id(f.data))

g = FD_field(4, 4, 4)
g.At(1, 1, 1)
print ("g #1 id = %d" % id(g.data))

This prints
f #1 id = 3083171468
f #2 id = 3083171468
g #1 id = 3083171468
Note they all have the same id, and so are the same object. First avoid globals, such as the ones at the beginning of your class. Second, add a unique self.data for each instance. Running the code below should result in what you want.

class FD_field:
    """Finite-difference Maxwell Solver Field Data-type"""
    # Data declarations and initialization
    lenx = 0
    leny = 0
    lenz = 0
    data = []
    #
    # --- Class __init__ declarations ---
    #
    def __init__(self, jj, ll, nn):
        self.lenx = jj
        self.leny = ll
        self.lenz = nn

        ##---  added a unique self.data field for each instance
        self.data = []

        l = []
        for i in range(self.lenx):
            dl = []
            for j in range(self.leny):
                dm = []
                for k in range(self.lenz):
                    dm.append(0)
                dl.append(dm)
            self.data.append(dl)
        del dl, dm, l, jj, ll, nn, i, j, k
    #
## The rest of the code remains the same

The id's print
f #1 id = 3083034188
f #2 id = 3083034188
g #1 id = 3082646892 <----- different

woooee 814 Nearly a Posting Maven

One of you should have just written the entire program in the beginning, since the OP didn't have to produce even one line of original code, and saved everyone the trouble of having to read through all of the posts.

woooee 814 Nearly a Posting Maven

I keep getting an error that says Im giving it more arguments than it can take.

You are sending player1 and player2 to the class, but don't have arguments for them. If that doesn't answer your question, then post back.

class Application(Frame):

    def __init__(self, master, player1, player2):
        Frame.__init__(self, master)
        self.pack(expand = 1, fill = BOTH)
        print "this Frame is for", player1, player2
        ##
        ##   And generally you want to use this instance of Frame
        ##   outside of this class
        self.this_frame = Frame( master)
        ##   you can then pass app.this_frame to another function
        ##   from the __dtaw_window function

def __draw_window(player1, player2):
    root = Tk()
    root.title("WAR")
    dimensions = str(root.winfo_screenwidth()-100) + "x" + str(root.winfo_screenheight()-300)
    root.geometry(dimensions)
    root.resizable(0,0)
    app = Application(root, player1, player2)
    app.mainloop()
woooee 814 Nearly a Posting Maven

First, usrlist is not a list but a dictionary and you should get a syntax error (a list uses brackets usrlist = [] not {} ). Anyway, note the use of a dictionary of dictionaries to do this at the bottom for 'bob'. A dictionary hashes it's keys, meaning that it won't print in the order it was entered, so the first print is in a different order, but you want to look something up in a dictionary, not print in some order.

"""   This code is commented because it will yield a syntax error
usrlist = {
      'bob',
      'harvy',
      'oscar'
      }
       
oscar = {
      'name':'Oscar T. Grouch',
      'password':'ilovetrash',
      'info':'This is info specific to Oscar.',
      'value':18
      }
print type(usrlist), usrlist
print "\n", type(oscar), oscar
"""
#
# Use a dictionary of dictionaries
usr_dic = {}       ## main dictionary 

usr_dic['bob'] = {}   ## a sub dictionary for 'bob's info
usr_dic['bob']['name'] = 'Bob Bobsworth'
usr_dic['bob']['password'] = 'fishinglure'
usr_dic['bob']['info'] = 'This is info specific to Bob.'
usr_dic['bob']['value'] = 10

# another way to add data using 'oscar'
usr_dic['oscar'] = {}   ## a sub dictionary for 'oscar's info
this_user = usr_dic['oscar']
this_user['name'] = 'Oscar T. Grouch'
this_user['password'] = 'ilovetrash'
this_user['info'] = 'This is info specific to Oscar.'
this_user['value'] = 18

print usr_dic   ## entire dictionary
print

## example of lookup (of course there are only two keys)
if 'bob' in usr_dic:
   print usr_dic['bob']
   print "name for bob ==>", usr_dic['bob']['name']
   print "info for bob ==>", usr_dic['bob']['info']

##   a simple simulate input test
print "\nSimulating …
woooee 814 Nearly a Posting Maven

What positive integer is equal to its own Scrabble score when spelled out?

12: T,E, & L = one point
W & V = four points

Compliments of "Professor Stewart's Cabinet of Mathematical Curiosities"

woooee 814 Nearly a Posting Maven

You should be able to call it with
subprocess.call("./program < " + input_string, shell=True)
Using subprocess to send the input; since you also have a printf, you might have to include an output pipe as well, and you might as well use a stderr pipe which may be more specific about errors. I don't know if c/scanf empties or otherwise modifies the input stream on startup, so you may also have to wait for the first printf output before sending input to the scanf to avoid any program startup mangling.

woooee 814 Nearly a Posting Maven

Also, you should not be using input , you should be using raw_input

Note the print() statement. The OP is maybe using 3.0, especially if a string is returned for the input name statement.

woooee 814 Nearly a Posting Maven

There should be a comma after PIPE (I'm guessing that this is a tuple), and then a communicate statement

proc2 = subprocess.Popen("/home/samush/Documents/kandidat_arbete/python/cr_to_fr/fortreaderc",
          shell=True,
          stdin = subprocess.PIPE,)
proc2.communicate('\tstdin: to stdin\n')

http://blog.doughellmann.com/2007/07/pymotw-subprocess.html

woooee 814 Nearly a Posting Maven

This part is a little screwy. You have username entered from the console so there is no need to use users.username instead, so a modified version of your code would be

if username not in users.usrlist:
	print()
	print('User does not exist.')
	sys.exit()
else:
	## user = users.username   Not necessary
	print( "\nHello" + username)
	print('Please enter your password. Note that for security reasons, nothing will appear as you type.')
	print()
	pw = getpass.getpass(">")
                ##   this line changed to username
	if pw == user.username['password']:
		print()
		print('Welcome, ' + username + '.')
		print()
	else:
		print()
		print('Incorrect password.')
		sys.exit()

Also note that in the above post the user name was changed to lower case to make it case insensitive which will find "Bob", "bob", "BOB" etc. Generally, a password program uses a dictionary with the user name as the key, pointing to the password as in Jim699's example. Since we don't have the code for users.py it's difficult to tell what the data structure is, but it appears to be a class, which is overkill for this. For future posts, please include the relevant parts of users.py. Then you can get more specific help.

woooee 814 Nearly a Posting Maven

Try the pygame forum. Most of us are not game programmers http://z7.invisionfree.com/pygame/

woooee 814 Nearly a Posting Maven

This link is to the while() loop page in one of the many tutorials http://en.wikibooks.org/wiki/Python_Programming/Loops You have no while loop in your program, so I think you want to start by inserting a loop and experimenting with it.

woooee 814 Nearly a Posting Maven

if username not in users.usrlist:

It appears that usrlist contains the user names, so you would want to append any new names to that list.

woooee 814 Nearly a Posting Maven

def __init__(self, name):
self.__monName = name

monFile.write(self.__monName)

Somehow you are passing a tuple to the class. How do you call the class and what name are you entering? Also, add a print statement before the write
print type(self__monName), self.__monName
monFile.write(self.__monName)

woooee 814 Nearly a Posting Maven

You can save the state to a dictionary as the process is running, and use the dictionary in whatever way after that pid is terminated. I can't take much time now, so ask if there are other questions (docs are here http://pyprocessing.berlios.de/ ). A simple example of dictionary use.

import time
from processing import Process, Manager

def test_f(test_d):
   test_d['Name'] = "test_f process"
   test_d['Number'] = 1
   for j in range(0, 5):
     print "test_f", j
     test_d["ctr"] = j   ## update the dictionary
     time.sleep(1.0)
     
def test_f2(name):
    for j in range(0, 15):
       print "   test_f2", j
       time.sleep(0.5)

if __name__ == '__main__':
   manager = Manager()
   test_d = manager.dict()

   p = Process(target=test_f, args=(test_d,))
   p.start()
   p_pid = p.getPid()
   print "getpid", p_pid
   
   ##---  associate the pid and the process
   pid_dic = {}
   pid_dic[p_pid] = p

   p2 = Process(target=test_f2, args=('P2',))
   p2.start()
   p2_pid = p2.getPid()

   ##---  add the second process to the dictionary  
   pid_dic[p2_pid] = p2

   ##---  sleep and terminate the first process
   time.sleep(3.0)
   print "\nterminate", p_pid
   pid_dic[p_pid].terminate()
   print "data from first process", test_d
   print "\nThe second process continues to run to conclusion"
woooee 814 Nearly a Posting Maven

exc is just a module within sqlalchemy that I'd wanna import along with everything else.

Then I think you want
from sqlalchemy import exc
but I don't use sqlalchemy. In any case,
from lib.sqlalchemy import * is different from
from sqlalchemy import * so I would suggest trying the latter first, and if that works then there is something wrong with the "exc" wording.

woooee 814 Nearly a Posting Maven

If you are using a normal flat file instead of pickling, you can only store strings. While you can use writelines for writing a list, I would suggest that you write to the file in a format that you understand, so you can read it back into a program as well. If you present some code for what you are trying to do, then perhaps we can be more specific.

woooee 814 Nearly a Posting Maven

which prodcues

*element,type=s4r,elset=WSLAB
100001,6,4719,6308
,12
*element,type=s4r,elset=WSLAB
100002,4719,2328,2327
,6308

It appears that you have a newline in with the final element of the list, so after the exchange, the next to the last element prints the newline which puts the last element on the next line. You should .strip() before appending to the list which will get rid of the newline.

woooee 814 Nearly a Posting Maven

ImportError: No module named sqlalchemy.exc

Is the program/file actually named "sqlalchemy.exc". Looks like it's maybe a typo. Also, import usually assumes a ".py" ending.

woooee 814 Nearly a Posting Maven

I use multiprocessing / pyprocessing as follows. Also subprocess has replaced the os.popenX functions http://blog.doughellmann.com/2007/07/pymotw-subprocess.html

import subprocess
import time
from processing import Process

class TestClass():

   def test_f(self, name):
      subprocess.call("ping www.google.com", shell=True)
         
if __name__ == '__main__':
   CT=TestClass()
   p = Process(target=CT.test_f, args=('P',))
   p.start()

   ## sleep for 5 seconds and terminate
   time.sleep(5.0)
   p.terminate()
woooee 814 Nearly a Posting Maven

You can download an Ubuntu live CD from here (are there are a lot of tutorials on how to put it on a USB drive), but Knoppix is better IMHO because they have tools like GParted for repairing the system. https://help.ubuntu.com/community/LiveCD Also, there is a netbook version if you don't already know https://wiki.ubuntu.com/UNR

woooee 814 Nearly a Posting Maven
i_getdata_test = [ \
(30, 0, 0), \
(29, 0, 0), \
(28, 0, 0), \
(27, 0, 0), \
(26, 0, 0), \
(25, 0, 0), \
(24, 0, 6), \
(23, 0, 0), \
(22, 0, 0), \
(21, 0, 0) ]

for pixel in i_getdata_test:
   print pixel
   ##  0, 1, and 2 are the memory offsets for
   ##  the three integers in the tuple
   if pixel[2] > 0:
      print "          we want this one"
    
## if you want to explore what the "2" means,
## then uncomment the lines below
##print "\n"
##for pixel in i_getdata_test:
##   print pixel[0], "-->", pixel[1], "-->", pixel[2]
woooee 814 Nearly a Posting Maven

os.system("cd \..\Program Files\Mozilla Firefox\ Start firefox.exe")

"cd" = change directiory. You want to execute the program which you should be able to do by calling it from os.system()
os.system("\..\Program Files\Mozilla Firefox\ Start firefox.exe")
Check this directory to make sure you want to call "Start firefox.exe" instead of "firefox.exe" or "/Start/firefox.exe". I'm not familiar with MS windows but the file has to exist in order to call it. os.system is the same as clicking on the file, so you want whatever name you would click on.

But you should get used to using subprocess instead of os.system as it is the preferred way.
subprocess.call(["\..\Program Files\Mozilla Firefox\ Start firefox.exe"], shell=True)
You can find info about os.system and subprocess here http://www.doughellmann.com/PyMOTW/modindex.html

woooee 814 Nearly a Posting Maven

Print dirList1 and dirList2 at the beginning of the function, or at least the length of each. The first step is to make sure that both contain what you think they contain.

woooee 814 Nearly a Posting Maven

Assuming that sum_results is a dictionary that contains numbers of decimal class, you can use

total_cost = float(sum_results['list_price']) + salestax + shipping_cost + rush_cost

If this doesn't work, then print the type for each variable
print type(sum_results) etc.
You can check the docs for the decimal class at python.org if you want to know more about it.

woooee 814 Nearly a Posting Maven

As of today Daniweb has 522,642 members, and I have 663 posts. Who is evil enough to be #666?

woooee 814 Nearly a Posting Maven

Your existing code looks like it wants to find records where the field "month" equals myprice. The field "sql" is just a string so you format it like any other string. Post back if this isn't enough to get it to work.

##   assuming month, myprice and mytel are integers
    sql = 'UPDATE mydatabase SET %d = %d WHERE number = %d' % \
                                  (month, myprice, mytel)
    print sql
    cursor.execute( sql )
    connection.commit()
woooee 814 Nearly a Posting Maven

1. Sort the list and test for this_number == next_number and add one to a counter if a duplicate.
2. Use a dictionary (if you are familiar with dictionaries) with the number as key pointing to a counter. Increment the counter every time that number is found.

woooee 814 Nearly a Posting Maven

Add some print statements to see what is going on. I have added two in the following code.

from random import choice as rc
def total(hand):
 aces = hand.count(11)
 t = sum(hand)
 if t > 21 and aces > 0:
     while aces > 0 and t > 21:
         t -= 10
         aces -= 1
         return t
cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]
 
cwin = 0 # computer win counter
pwin = 0 # player win counter  
while True:
     player = []
     player.append(rc(cards))
     player.append(rc(cards))
     print "player list now =", player
    
pbust = False # player busted flag
cbust = False # computer busted flag
while True:    
      # loop for the player
      tp = total(player)
      print "total", tp, player
    
      if tp > 21:
          
          pbust = True
          break
      elif tp < 16:
             player.append(rc(cards))    
      else:
          break
while True:
    comp = []
    comp.append(rc(cards))
    comp.append(rc(cards))
while True:
      tc = total(comp)
      if tc < 17:
          comp.append(rc(cards))    
      else:
          break
        
      if tc > 21:
    
        cbust = True
      if pbust == False:
        pwin += 1
      elif tc > tp:
        cwin += 1
      elif tc == tp:
         pwin += 0       
      elif tp > tc:
         if pbust == False:
            
           pwin += 1
                    
      elif cbust == False:
                 
          cwin += 1
          break
       
print pwin
woooee 814 Nearly a Posting Maven

I like using sets because they have a difference function.

alphabet = set("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
keyword = raw_input("Enter word ").upper()
difference = alphabet.difference(keyword)

## sets are in hash order not in alphabetical order
print "Hash sequence", difference, "\n"

## convert to a list so it can be sorted
difference = list(difference)    
difference.sort()

## now it is in alphabetical order
print "Alpha order", difference, "\n"

## create a new list with the keyword first
final_list = list(keyword) + difference
print "Final_list", final_list
woooee 814 Nearly a Posting Maven

First, make sure that all repositories are enabled, and that you update after that. If you have Gnome Ubuntu and you want to install a KDE package for example, the default repos will not find KDE apps because those repos are not enabled.

woooee 814 Nearly a Posting Maven

the error is coming up at r squared minus y squared

That would be two calculations, not one, so you have to break that down and see which one is causing the error message. If this doesn't give an error message
r_squared = r*r
y_squared = y*y
sqrt_2 = math.sqrt(2)
sub_total = r_squared - y_squared
etc. (insert the rest of the equation on the lines that follow)
Then why would the one-liner show an error, and why that particular message and what does the error message mean?
l = abs(math.sqrt(2)(r*r)-(y*y))

woooee 814 Nearly a Posting Maven

Hopefully your teacher did not give a passing one.

That was a joke BTW. It's an easy mistake to make.

woooee 814 Nearly a Posting Maven

l = abs(math.sqrt(2)(r*r)-(y*y))
Break this formula down into one calc per line and see where the error occurs, then print the variable and it's type(variable_name), and that should tell you where you went wrong. Also, it is not polite to use "i", "l",. or "o" as single letter variable names. They look like numbers and can be confusing to someone trying to decipher someone else's code.

woooee 814 Nearly a Posting Maven

I've modified you code by adding a function to do the "HTH" and "HTT" search. Since it is basically the same for 'H' and "T', one function can do it instead of two blocks of the same code . Note that the if heads/tails > 0 appears to be worthless, since you add one to the variable on the previous line. There is one "thought group" per function. One function to flip the coin, etc., and one function to test for the string to end it.

import random
import time

def find_it(text):
   htt = "HTT"
   hth = "HTH"
   time.sleep(.1)
   if hth in text:
      print "found HTH first", text
      return True
   elif htt in text:
      print "found HTT first", text
      return True

   ##  neither found
   return False
 
def htthth(N):
    
    heads = 0
    tails = 0
    flips = 0
    text = ""
    hthCount = 0
    httCount = 0
    found = 0

    while (flips < N):
        print flips
        flips += 1
        flip = random.randint(1,2)
        if flip == 1:
            heads += 1
##            heads will always be > 0 since you 
##            just added one to it
##            if heads > 0:
            
            text += 'H'
            found = find_it(text)
            if found:
               hthCount = 1
               flips = N
        else:
            tails += 1
            text += 'T'
            found = find_it(text)
            if found:
               httCount = 1
               flips = N
            
htthth(10)