woooee 814 Nearly a Posting Maven

You possibly want to use a Frame widget. One of the online references is here.

woooee 814 Nearly a Posting Maven

move() should probably receive a distance parameter. You might use something like this, although it is not obvious from the question what the fuel and distance moved relationship is.

def move(self, distance):
        ## do you want to use floats or integers here?
        fuel_used = distance / miles_per_gallon   
        if self.fuel-fuel_used < 1:
            print "there is not enough fuel for that distance"
        else:
            self.fuel -= fuel_used
            print "You have traveled %d miles and have %d gallons of fuel" % \
                  (distance, self.fuel)
woooee 814 Nearly a Posting Maven

What exactly are you looking for and what exactly to do want to replace it with? You can also use string.find which will return the starting position or -1. If you want to remove "The POST" and "is vulnerable" then replace() is the simplest way to go.

woooee 814 Nearly a Posting Maven

I don't understand your point, unless it is to shorten the number of keystrokes for some reason.

condition = 'False'
if condition == 'True':
    print 'Condition True'
else:
    print 'Condition False'
woooee 814 Nearly a Posting Maven

Post deleted

woooee 814 Nearly a Posting Maven

There is no real difference:

if condition == True:
if condition == "True":
woooee 814 Nearly a Posting Maven

Since it is only 3 degrees of separation and a small data set, you could also do this with dictionaries, which is not as efficient, unless of course you are required to code it a certain way.

from collections import defaultdict
test_entries = ["Apollo13, Kevin Bacon, Tom Hanks, Gary Sinise",
                "HollowMan, Elisabeth Shue, Kevin Bacon, Josh Brolin",
                "AFewGoodMen, Tom Cruise, Demi Moore, Jack Nicholson, Kevin Bacon",
                "OneCrazySummer, John Cusack, Demi Moore",
                "DaVinciCode, Tom Hanks, Ian McKellen, Audrey Tautou"]

# a dictionary of titles --> actors
movie_dict = defaultdict(list)
# a dictionary of actors --> movie titles
actor_dict = defaultdict(list)
for movie_actor in test_entries:
   substrs = movie_actor.split(",")
   movie_name = substrs[0].strip()
   for actor in substrs[1:]:            ## all actors in the movie
       actor = actor.strip()
       movie_dict[movie_name].append(actor)
       actor_dict[actor].append(movie_name)
   
##   all other actors that were in John Cusack films
for title in actor_dict["John Cusack"]:  ## all John Cusack movie titles
    for actor in movie_dict[title]:   ## actors in this John Cusack film
        for actor_title in actor_dict[actor]:  ## all movies actor was in
            if actor_title in actor_dict["Kevin Bacon"]:  ## also was in
                print "Found", actor, actor_title
woooee 814 Nearly a Posting Maven

"findNode" still returns "None" in all cases.

woooee 814 Nearly a Posting Maven

I get a result of an integer 1 - 5, say 3 - I would then like the script to tell me what string is assigned to it, in this case 'a'...

Except that no one realized that the dictionary is bass-ackwards.

ltr_dic = {1: 'a',
           2:'a', 
           3:'a', 
           4:'b', 
           5:'c'}
# ~ insert process here ~
# number 3 returned
x = ltr_dic[3]
print x
for x in range[1, 6]:
    print x, ltr_dic[x]
woooee 814 Nearly a Posting Maven

How to start programming is not within the scope of most forums. Start with a tutorial
http://www.pasteur.fr/formation/infobio/python/ch11s02.html
http://www.freenetpages.co.uk/hp/alan.gauld/tutloops.htm
http://wiki.python.org/moin/BeginnersGuide/NonProgrammers
We can and will help with code that is formated properly but does not function as expected.

woooee 814 Nearly a Posting Maven

To emphasize what Tony said:

actorNode = findNode(graph,actorName)
        if actorNode == None:
            actorNode = mkNode(actorName)
            print "created", actorNode
            graph.append(actorNode)
            print "graph", graph

You want to test each function individually before going on to the next function, or you have 56 lines of code to debug and no idea what the problem is.

woooee 814 Nearly a Posting Maven

what happens if someone enters an "X" or any letter other than "N".
yet,
because my current code is not working.

You don't want all of the code under the
if (d == 'N'):
loop. Instead try something like this:

# player=1 --> computer
# player=2 --> human
player = 2
if (d == 'N'):
    player=1

winner = False
while not winner:
    print "Getting choice for player", player
etc.
woooee 814 Nearly a Posting Maven

Post some trial code for as much of
"A. put all words in lower case and omit all punctuation"
as you can so we have something to comment on.

"put all words in lower case" = use the lower() function
"omit all punctuation" = loop through the text and omit anything that is not, since it now all lower case, between "a" and "z".

woooee 814 Nearly a Posting Maven

This is a tic-tac-toe program that I coded some time ago. I doubt you will be able to use much of it, but it illustrates how much simpler it is when you break everything up into small pieces.

import random

class TicTacToe:
   def __init__(self):
      ## 0=No winner,      1=Player #1 wins,
      ## 2=Player #2 wins, 3=Tie
      self.winner = 0

      self.board = [0, 0, 0, 0, 0, 0, 0, 0, 0,]
      self.num_moves = [0, 0, 0]
      self.player = 1
      self.win_combos = (set([0, 1, 2]),
                         set([3, 4, 5]),
                         set([6, 7, 8]),
                         set([0, 3, 6]),
                         set([1, 4, 7]),
                         set([2, 5, 8]),
                         set([0, 4, 8]),
                         set([2, 4, 6]) )
      self.play_a_game()

   ##-----------------------------------------------------------------
   def play_a_game(self):
      while not self.winner:
         self.num_moves[self.player] += 1
         ##  a list of all squares not occupied
         squares_to_choose = [ctr for ctr, square in enumerate(self.board) \
                              if square==0]
         print "Choose from", squares_to_choose
         ##  choose a random available square
         square = random.choice(squares_to_choose)
         print("---> player %d occupies %d" % (self.player, square))
         self.board[square] = self.player
         self.print_squares()

         winner = self.we_have_winner()
         if not winner:
             self.tie()
 
         self.player = [0, 2, 1][self.player]

   ##-----------------------------------------------------------------
   def print_squares(self):
      for row in range(0, len(self.board), 3):
         for col in range(3):
            print self.board[row+col],
         print

   ##-----------------------------------------------------------------
   def tie(self):
     if 0 not in self.board:
         self.winner = 3
         print("Tie, you kissed your sister")

   ##-----------------------------------------------------------------
   def we_have_winner(self):
       """ extract all of the squares occupied for this player into 
           a set and check if it has a winning combo as a subset
       """
       moves = set([ctr for ctr, person in enumerate(self.board) \
                    if person==self.player])
       for win_combo in self.win_combos:
          if win_combo.issubset(moves):
               self.winner = …
woooee 814 Nearly a Posting Maven

I think the problem may be that you are not entering "N" for the "do you want to go first" question as you have an infinite while loop, and not one the doesn't repeat. The main problem with this code is that you have 54 lines of code that have not been tested. Take Tony's style, and some of his code, and start with a function to get the input. Check for a valid entry = an unoccupied row or column, and test it before going further (right now, you can enter 10 for the row and it will not catch it but will instead error out at "while (m[a]!='__'): )". Keep your functions short and sweet and you won't be confused. A maximum of 10 to 20 lines makes them easy to test and debug. Next on the coding list is a function to generate the computer's choice. After that is one function to fill the space chosen. You can pass "X" or "O", and the coordinates to the same function and use the same code for either, and test that function. Hopefully you get the idea.

woooee 814 Nearly a Posting Maven

Take a look at this previous post

woooee 814 Nearly a Posting Maven

See geometry strings here. "Geometry" sets the size and location of a widget.

woooee 814 Nearly a Posting Maven

In addition to the iterating through lists link above, there is also list comprehension which is the simplest way to do this.

testing = ['This', 'is', 'a', 'string'
print [x for x in testing if "t" in x.lower()]
woooee 814 Nearly a Posting Maven

Do I have to make the columns go from int to str?

No, use a tuple, as in my previous post, which can contain a mix of strings and integers. And comparing integers is usually superior to comparing strings, so if record[1] is an integer for example, the tuple would be built with
key1_tuple = (record[0], int(record[1]), record[2])

it takes the program forever to run. Any ideas on how can I make it more efficient?

Comparing tuples should be faster, but disk I/O is usually the time waster. Take a look at Parallel Python if you are on a multi-core machine. It seems pretty straight-forward.

woooee 814 Nearly a Posting Maven

i dont know how to make it produce 2d movements

If you have an graph with an x and y axis, you can advance in a postive or negative direction for either axis. To keep it simple, point 1=(3,1) for x and y, point 2=(-3, 2) for x and y, etc., so you have to change both x and y for 2D movements. You appear to be changing x only.

y
            2  |
               |  1
x -------------+-------------------
               |
woooee 814 Nearly a Posting Maven

Code this one step at a time. So first, get the input and check that it is indeed 'r', 'p', or 's'. Then generate a random choice for the computer, etc. BTW you have a lot of redundant code in this function.

def play_RPS(x, num_games):
    print 'Press q at any time to quit'
    text=''
    while text!='q':
        text=raw_input("Please choose rock(r), paper(p), or scissors(s):")
        if text=='q':
            print "Thanks for playing!"
            break 

        if text not in ['r', 'p', 's']:
            print "incorrect letter entered"
        else:
            random_throw=random.choice(x)
            num_games += 1
            return random_throw, num_games

    return "*", num_games


##----- the rest of the code repeats the same thing
        elif text== 'r':
            random_throw=random.choice(x)
            print random_throw 
        elif text=='s':
            random_throw=random.choice(x)
            print random_throw
        elif text=='p':
            random_throw=random.choice(x)
            print random_throw
        else:
            print "Invalid input!"]
woooee 814 Nearly a Posting Maven

Add some printing to figure out what you are testing. Link to iterating through lists.

def e_words(m):
      forbid = 'e'
      word = m.split()
      print "testing", forbid, "in", word
      if forbid in word:
          return forbidword
woooee 814 Nearly a Posting Maven

"i" and "j" (terrible names for variables, "i" can look like a one, and neither is descriptive) still have the newline character from the file, so you want to strip them.

print i.strip(), j.strip()
##
##   also, eliminate the multiple splits
for i in f1line:
    split_i = i.split()
    for j in f2line:
        split_j = j.split()
        if (split_i[0] == split_j[0]) and (split_i[1] == split_j[1] and \
           (split_i[2]==split_j[2]):
            print i.strip(), j.strip()
#
#     or you can use a loop, which may be easier to read
#
for i in f1line:
    split_i = i.split()
    for j in f2line:
        split_j = j.split()
        match = True
        for k in range(0, 3):
            if split_i[k] != split_j[k]:
                match = False
        if match:
            print i.strip(), j.strip()
woooee 814 Nearly a Posting Maven

You have to iterate through the entire array, whether you write you own or use a built in method. Since you also want the max also, go through the array once, storing any number that is larger than the current maximum, along with it's position.

woooee 814 Nearly a Posting Maven

I works fine on my Slackware system. Try it with just "gnome-terminal". You may have to pass "shell=True" depending. Also, are there any error messages as it should kill the subprocess or report some kind of error. Finally, try it split into two lines, although that shouldn't matter

proc1 = subprocess.Popen(args=["gnome-terminal"], shell=True)
os.kill(proc1.pid, signal.SIGTERM)
woooee 814 Nearly a Posting Maven

You can use a tuple of the first 3 columns as a dictionary index.

f_list=open(sys.argv[1]).readlines()

## you can use a set or dictionary
unique_dic = {}
for rec in f_list:
    sub_str = rec.split()
    key = (sub_str[0], sub_str[1], sub_str[2])
    if key not in unique_dic:
        unique_dic[key] = 1

for rec in open(sys.argv[2]):
    sub_str = rec.split()
    key = (sub_str[0], sub_str[1], sub_str[2])
    if key in unique_dic:
        print rec
woooee 814 Nearly a Posting Maven

Recursion is when a function calls itself. It is easy to illustrate by adding a counter that increases by one each time the function is called

import time
from Tkinter import *
 
def change_color(canvas, ov, color, ctr):
    color = 'yellow' if  (color != 'yellow') else 'blue'
    print "color =", color, ctr
    canvas.itemconfig(ov, fill=color)
    canvas.update_idletasks()
 
    ctr += 1
    canvas.after(1500, change_color, canvas, ov, color, ctr)
 
root = Tk()
root.title('Canvas')
canvas = Canvas(root, width=200, height=200)
 
color = 'yellow'
ov=canvas.create_oval(10,10,50,50, fill=color)
canvas.pack()
 
change_color(canvas, ov, color, 0)
 
root.mainloop()
woooee 814 Nearly a Posting Maven

That method still has a possible recursion limit problem.

Woooee, your handle looks like a bad Scrabble rack of letters

Good one. Do you know about these Tkinter links (and the Padres folded this year)
http://effbot.org/tkinterbook/
http://www.ferg.org/thinking_in_tkinter/index.html
http://pmw.sourceforge.net/doc/index.html

woooee 814 Nearly a Posting Maven

I use os.kill(), but some of these are OS dependent and Python version dependent. Take a look at Doug Hellmann's examples for starters.

woooee 814 Nearly a Posting Maven

You are continually drawing one oval on top of another, so Tkinter has to keep track of more and more widgets, not to mention that you could reach the recursion limit. Change the color instead. This code is a little crude, but I don't have any time right now.

import time
from Tkinter import *

def change_color(canvas, ov, color):
    print "color =", color
    if color == 'blue':
        color = 'yellow'
    else:
        color = 'blue'
    canvas.itemconfig(ov, fill=color)

    return color

root = Tk()
root.title('Canvas')
canvas = Canvas(root, width=200, height=200)

color = 'black'
ov=canvas.create_oval(10,10,50,50, fill=color)
canvas.pack()

root.update_idletasks()
for x in range(5):
    time.sleep(1.5)
    color = change_color(canvas, ov, color)
    root.update_idletasks()

root.mainloop()
woooee 814 Nearly a Posting Maven

Not recursion, but proof of concept only (and done quickly). Returns zero if it is a palindrome.

def ispalindrome(pal): return sum([0 if x == pal[(ctr+1)*-1] else 1 for ctr, x in enumerate(pal) if ctr < len(pal)/2])

sentence = "Red Roses run no risk, sir, on nurses order."
sentence_clean = ''.join(c.lower() for c in sentence if c.isalpha())
print ispalindrome(sentence_clean)
print ispalindrome("abcdef")
woooee 814 Nearly a Posting Maven

Find where the error is. Print
line2[j], j, len(line2)
and with a separate print statement
a[j], j, len(a).
You can then fix the specific problem. Also, include some comments in the code explaining what is happening, so we know what it is supposed to be doing. No one can be expected to write all of the code for you.

woooee 814 Nearly a Posting Maven
for lines in textf:
    if ask in textf:

Print "textf" before the "if" statement so you know what you are testing. Using logic like this, entering a word like "the" will find "the", "then, "either", etc. You might want to split the file input into words and check for equal condition with "ask".

woooee 814 Nearly a Posting Maven

but it is obvious I'm too dum to learn

or to use a spell-checker. Converting from one data type to another is called "type casting", so to an integer would use int().

str_list = ["1", "3", "5"]
for x in str_list:
   print x, type(x)
print
int_list = [int(x) for x in str_list]
for x in int_list:
   print x, type(x)
woooee 814 Nearly a Posting Maven

Did that solve the problem?

woooee 814 Nearly a Posting Maven

Indentation is covered in the style guide. Most IDEs will also auto-indent according to python standards when editing a ".py" file.

woooee 814 Nearly a Posting Maven

Yes, both can be done. You would use a for() loop to traverse the strings, or convert to a list, in both cases.

woooee 814 Nearly a Posting Maven

Generally, an IDE has a "convert tabs to spaces" option which takes care of this, and I show tabs in lines 11 and 12.

woooee 814 Nearly a Posting Maven

This is left bit shift

while Step << 32:
#
while Step < 32:     ## instead?

If you want to increase the speed of a motor, at higher motor speeds the same increase will yield a greater increase in the speed of the motor because of the initial friction which may be part of the reason that there isn't a smooth increase.

Also, depending on the version of Python you are using, you may be getting an integer instead of a floating point.

MovementStepPercentage = EffectPercentage/nSteps*Step  ## an integer
MovementStepPercentage = float(EffectPercentage)/nSteps*Step  ## convert the result to float 
#
#  which affects this 
Interpolation = (1-math.sin(MovementStepPercentage*180+90))/2*EffectPercentage+MovementStepPercentage*(1-EffectPercentage)
#
# note that the above line is the same as
# (and not sure if you want it this way or not)
(1-math.sin( (MovementStepPercentage*180) +90))
woooee 814 Nearly a Posting Maven

Generally you pass as arguments like this simplified code:

## program run.py
def print_args(name, passwd):
   print name
   print passwd

## calling program
import run
input_name = raw_input("Enter name ")
input_passwd = raw_input("Enter password ")
run.print_args(input_name, input_passwd)
woooee 814 Nearly a Posting Maven

Read about conditional statements here.

woooee 814 Nearly a Posting Maven

whenever i add in line "n = fin.readline()", i get an Mixed Iteration variable error:

for line in fin:
and
n = fin.readline()
do the same thing. Choose one or the other. You can also do a
for line in open("constitu.txt"):
(is the same thing) as well. Also, a hint below. And note that punctuation will be included in the word length if you don't remove it.

def main():
    splash()
    wordTotal = 0
    longestWord = 0
 
    fin = open("constitu.txt")
 
    for line in fin:
         #n = fin.readline()
        wordLine = line.split()
        ##------------------------------------
        for word in wordLine:
            print len(word), word, len(word) > longestWord
        ##------------------------------------
        #word = wordLine.split()
        wordTotal += len(wordLine)
         #if len(word) >= 15:
             #longestWord += 1
             #print word
woooee 814 Nearly a Posting Maven

The problem here is not getting records from the file. The problem is that you have large blocks of untested code. I am adding one print statement and a list declaration as a hint:

def read_from_file(self,room_table):
        if room_table is not None:
            fp = open(room_table, 'r')
            file_list = fp.readlines()
            fp.close()
            self.room_table = []         ## <----- start with an empty list each time
            self.class_name = file_list[0].rstrip('\n')
 
            for rec in range(1, len(file_list)):
                line = rec.split()
                self.room_table.append(line)
        print self.room_table
woooee 814 Nearly a Posting Maven

Excuse me for butting in, but this is poor style. Try instead:

for word in words:
        if word not in d:
            d[word] = word
woooee 814 Nearly a Posting Maven

_tkinter.TclError: couldn't open "horse.gif": no such file or directory

It could not open the file. Try it with the complete path.

woooee 814 Nearly a Posting Maven

Try this first:

def main():
    fileInput = 'PlayerNames.txt'
    wordList=[]
    print exportTextList(fileInput, wordList)   ## <-----

and then see the "gc_counter" function here.

woooee 814 Nearly a Posting Maven

See this link. The same question (summing items) was asked 2 days ago.

woooee 814 Nearly a Posting Maven

Or use something like easyGUI or Tkinter.

import easygui

""" test of multi-enter box
"""

def multeasygui_date() :
   title = "Date"
   msg = "Enter Date"
   fieldNames = ["mm","dd","ccyy"]
   fieldValues = []  # we start with blanks for the values
   fieldValues = easygui.multenterbox(msg,title, fieldNames, fieldValues )

   #----------------------------------------------------------------
   # from here down is basically the same for all easyGUI programs
   #----------------------------------------------------------------
   # data has been entered and button clicked
   # make sure that none of the fields was left blank
   while 1:
         if type(fieldValues) == None:
            fieldValues = [ -1, -1, -1 ]
	    break
         errmsg = ""
         for x in range(len(fieldNames)):
            if fieldValues[x].strip() == "":
               errmsg = errmsg + ('"%s" is a required field.\n\n' % fieldNames[x])
         if errmsg == "": 
            break # no problems found
         fieldValues = easygui.multenterbox(errmsg, title, fieldNames, fieldValues)
   return fieldValues[0], fieldValues[1], fieldValues[2]

##===================================================================
if "__main__" == __name__ :
   mm, dd, ccyy = multeasygui_date()
   print mm, dd, ccyy
woooee 814 Nearly a Posting Maven

File "<stdin>", line 11
t1.append(list[temp])

"list" is a function so it should be
t1.append(list(temp))
In the future, if there is an error for a compound statement, break the statement into it's individual parts to see which part is causing the error.

woooee 814 Nearly a Posting Maven

There is an error here (from the original code) so use add.lower() instead:

elif add == 'y' or 'Y':
#     This breaks down into
    elif add == 'y'
# or
    elif 'Y'     #which is always true