woooee 814 Nearly a Posting Maven

You either use the grid manager or a separate Frame for each set of 3 buttons.

from Tkinter import *
 
class GUI():
    def __init__(self, r):
        self.r = r
 
        self.i = StringVar()
 
        self.f = Frame(self.r)
        self.f.pack(fill = BOTH)
 
        self.g = LabelFrame(self.f, text = 'Groupbox 1', height = 90, width = 150, font = 'Lucida 8')
        self.g.pack_propagate(0)
        self.g.pack(side = LEFT, pady = 10, padx = 10)
 
        self.id = Entry(self.g, justify = CENTER, textvariable = self.i, font = 'Lucida 8')
        self.id.pack(pady = 22)
 
        self.opt = LabelFrame(self.f, text = 'Groupbox 2', height = 90, width = 200, font = 'Lucida 8')
        self.opt.pack_propagate(0)
        self.opt.pack(side = TOP)
 
        f1 = Frame(self.opt)
        for ctr in range(3):
            but = Button(f1, text = 'Button '+str(ctr+1), height=1, width=5, font='Lucida 8')
            but.pack(side = LEFT, anchor = N, pady = 5, padx = 4)
        f1.pack(side=TOP) 
 
 
        f2 = Frame(self.opt, height = 50, width = 200)
        for ctr in range(3):
            but = Button(f2, text = 'Button '+str(ctr+4), height=1, width=5, font='Lucida 8')
            but.pack(side = LEFT, anchor = N, pady = 5, padx = 4)
        f2.pack(side=BOTTOM)

t = Tk()
t.title('test')
#t.configure(bg = 'white')
t.geometry('400x120')
t.pack_propagate(0)
 
GUI(t)
t.mainloop()
woooee 814 Nearly a Posting Maven

Dupe post...Doh.

woooee 814 Nearly a Posting Maven

File "par.py", line 6
line = line.replace("
^

Note the mark at the beginning of the line, which usually means the problem is the previous line.

## test with this first
for line in fileinput.FileInput(files="./test.txt"):
    print line
#
## iterates over the lines of all files listed in sys.argv[1:]
for line in fileinput.input():
##
## otherwise use
for line in open("./test.txt", "r"):

print line

woooee 814 Nearly a Posting Maven

The main problem is that you don't pass board to the function, update it, and then return the new board. Consider using a list instead of a string as it makes things much easier. Also use a loop to get the input instead of 5 separate sets of statements.

import random
 
def compturn(board):
    print 'Computer turn:'
    comp = str(random.randint(1, 9))
    while comp not in board:     ## occupied
        comp = str(random.randint(1, 9))
    """
	if comp == a:
		compturn()
	elif comp == b:
		compturn()
	elif comp == c:
		compturn()
	elif comp == d:
		compturn()
	elif comp == e:
		compturn()
	elif comp == f:
		compturn()
	elif comp == g:
		compturn()
	elif comp == h:
		compturn()
	elif comp == i:
		compturn()
	else:
    """
    board=board.replace(comp, "O")
    print "computer moves to square", comp
    print board
    return board
 
print """ I have yet to make a device that tells you if you win but enjoy!"""
 
board = """ 1 | 2 | 3
---+---+---
 4 | 5 | 6
---+---+---
 7 | 8 | 9 """
print board
 
move1 = raw_input('Where do you want to place your X? ')
#a = b = c = d = e = f = g = h = i = move1
board = board.replace(move1, "X")
print board
 
board=compturn(board)
 
#b = comp
 
move2 = raw_input('Where do you want to place your X? ')
#c = d = e = f = g = h = i = move1
board = board.replace(move2, "X")
print board
 
board=compturn(board)
 
#d = comp
 
move3 = …
woooee 814 Nearly a Posting Maven

So adding the 8 wild cards, which it appears is what the code is trying to do, makes 84, so the problem is in the wild cards which should be 32 to make 108 cards, but so far we only have info on 14 more cards, 6 action cards + 8 black action cards. Are there 2 sets of 9 more cards or 6 sets of 3 more cards? In any case, the OP is not finished with the code if a complete deck is the desired result. But the deck may also be simplified for this exercise. We won't know unless the OP posts back.

woooee 814 Nearly a Posting Maven
def create_deck():
    deck = []
    for i in range(10):
        for color in ['blue','green','red','yellow']:
            if i == 0:
                card = StandardCards(color,i)
                deck.append(card)
 
            else:
                card = StandardCards(color,i)
                deck.append(card)
                card = StandardCards(color,i)
                deck.append(card)

You create 1 + 2*9 cards for each of the colors=76 cards, plus the wild cards.

woooee 814 Nearly a Posting Maven

Use a function to draw the rectangles. Within a loop, send the function the parameters for the smaller rectangle, then send the parameters for the 4 larger rectangles, and finally a smaller rectangle. It will draw a row for every iteration in the loop.

woooee 814 Nearly a Posting Maven

For starters, this does not make sense

if line.count('<') == 0:
            line

Here, you are splitting a list which should yield an error message that says you can only split strings, not lists.

else:
            frag1 = line.split('<')[1]
            try:
                frag2= frag1.split('>')

And why are you implementing all of the stack stuff? Do you want to implement your own stack code, or analyze an html file? It is not obvious which of the two you are trying to do. Something like this will work even though it is clumsy, and you will have to work out the counting-the-same-tag-multiple-times problem yourself.

test_file = """<html>
 <head>
 <title>
 </title>
 </head>
 <body>
 <center>
 <h1>
 </h1>
 </center>
 <b>
 </b>
 <P>
 </P>
 <P>
 <br />
 <br />
 <br />
 </P>
 <hr />
 <P>
 <foo>
 </foo>
 </P>
 <P>
 <br />
 <tag1>
 <br />
 <tag2>
 <br />
 <tag3>
 <br />
 </tag3>
 <br />
 </tag2>
 <br />
 </tag1>
 <br />
 </P>
 <P>
 </P>
 </body>
 </html> """

## convert the test data into a file read type object
tags = ["<"+t.strip() for t in test_file.split("<") if len(t)]
print tags

for tag in tags:
    ## eliminate closing and self-closing tags
    if (not tag.startswith("</")) and (not tag.endswith("/>")):
        tag_count = tags.count(tag)
        end = "</"+tag[1:]
        end_count = tags.count(end)
        print tag, tag_count, end, end_count
woooee 814 Nearly a Posting Maven

The computer should make the user always select from a pile where the number of matchsticks has a remainder of 1 when divided by 4.

import random

# choose some random numbers and the appropriate number to pick up
# so that the number of sticks = num*4+1
# no clue given for when the user chooses so the number of sticks = num*4+1
for ctr in range(5):
    num_of_sticks = random.randint(5, 50)
    print "%d sticks in the pile" % (num_of_sticks)
    whole, remain = divmod(num_of_sticks, 4)
    if remain == 0:
        remain=4
    print "     The computer will pick up %d sticks" % (remain-1)

You can also use a function that contains an infinite loop to get the input.

def get_choice(sticks):
    while True:
        choice=int(input("How many sticks would you like to pick up (1, 2, or 3)? "))
#    if choice<=sticks:    ## doesn;t choice have to be 1,2 or 3?
        if 0 < choice < 4 and choice <= sticks:
            return choice

        else:
            print("Invalid choice. Please try again.")
woooee 814 Nearly a Posting Maven

lpr is the print spooler on Linux so you should be able to do something similar to

import subprocess
subprocess.call("lpr "+filename.txt, shell=True)

"man lpr" will give you all of the print options that lpr supports.

woooee 814 Nearly a Posting Maven

All he needed was $1,500.00 USD for the plain ticket.

It was smart to ask her for the money for a plain ticket instead of the more expensive elaborate ticket.

woooee 814 Nearly a Posting Maven

My main problem is that you are appending a class instance to the list and not using the class as a class, but just as a way to insert "X", which would work just as well with a variable. Also, this code creates a class instance and you pass a variable to the class that is already part of the class, and the class does nothing useful with it.
aPiece = Piece(Piece.EMPTY_MARK)
You do use the "displayConsole()" function but all it does is print the character that was passed to the class (that is already a class variable). So, instead of

aPiece = Piece(Piece.EMPTY_MARK)
            self.grid[rowIndex].append(aPiece)
## and then later
            self.grid[rowIndex][columnIndex].displayConsole()
##
# you can use
            self.grid[rowIndex].append(Piece.EMPTY_MARK)   ## append 3 times for 3x3 grid
# and
            print self.grid[rowIndex][columnIndex]

I hope this helps your understanding of classes and instance variables vs. class variables. Classes are used in most non-trivial programs and understanding how they work is something that is worth the time and effort spent IMHO.

woooee 814 Nearly a Posting Maven

Note how the variables increase by one in this code (but in your example output they decrease??)

for a in range(n, 0, -1):
        print(a, end="\n")
    for i in range(n+1, 0+1, -1):
        print(i, end="\n")
    for j in range(n+2, 0+2, -1):
        print(j, end="\n")
    for f in range(n+3, 0+3, -1):
        print(f, end="\n")

You can use a for loop and increase the variable's value by the value of the for loop's variable.

woooee 814 Nearly a Posting Maven

"grid is not an instance variable, but a class variable. That means that it is common to all class instances. See the example below. I think you want to use an instance variable.

class Board:
   SIZE = 3
   grid = []
 
   def __init__(self, var):
      self.grid.append([var])
      print self.grid

b = Board("b")     ## first class instance
c = Board("c")     ## another class instance

Updating done with a list of lists.

class Board:
    def __init__(self):
        self.grid = []          ## instance variable
        for ctr in range(3):
            self.grid.append(['-', '-', '-'])

    def print_grid(self):
        for gr in self.grid:
            print "%s|%s|%s" % (gr[0], gr[1], gr[2])

    def get_row_col(self):
        ## note that this check is not complete----->test for 1 <= entry <= 3
        row=raw_input("Enter row # (1, 2, 3) ")
        if row in ["1", "2", "3"]:
            col=raw_input("Enter column # (1, 2, 3) ")
            if col in ["1", "2", "3"]:
                ## convert to a list offset by subtracting one
                list_index_row = int(row)-1
                list_index_col = int(col)-1
                if self.grid[list_index_row][list_index_col] == "-": # not occupied
                    self.grid[list_index_row][list_index_col] = "X"
        self.print_grid()


b=Board()

## a simple test
b.get_row_col()

c=Board()     # a different board
## will not print entries from the first class instance
c.get_row_col()

There are multiple problems with your code so you might want to read this tutorial for classes http://hetland.org/writing/instant-python.html

woooee 814 Nearly a Posting Maven

If you want to save more than one grade per student, use a dictionary of lists.

marks = {"alice" : ["A+", "B-"], "smith" : ["A", "A"], "daemon" : ["B+", "B"], "lily" : ["B", "C"] }
woooee 814 Nearly a Posting Maven

Assuming self.cards is a list:

cards = range(1, 53)
print cards

cards_shuffled = cards[26:] + cards[:26]
print cards_shuffled
#
# or to modify your code  (this assumes cards are numbered 1-52, not 0-51)
        cut_deck = []
        for loop in range(26, 53):   ## 53, __not__ 52 = 1-52
            cut_deck.append(self.__cards[loop])
        for loop in range(1, 27): 
            cut_deck.append(self.__cards[loop])
woooee 814 Nearly a Posting Maven

A hint regarding accessing the dictionary.

class Polynomial:
    def __init__(self, *termpairs):
        self.termdict = dict(termpairs)
        print (self.termdict)
 
    def print_result(self, key):
        print "%dx^%d" % (key, self.termdict[key])

if __name__ == '__main__':
    d1 = Polynomial((2,3), (4,5), (8,9))
    ## extract and sort keys to process in numerical order
    keys=d1.termdict.keys()
    keys.sort()
    for key in keys:
        d1.print_result(key)
woooee 814 Nearly a Posting Maven

There are examples on Daniweb that you can use as well as on the web. This is a very simple and common question.

I am not using 'textctrl' as i will have to create a seperate frame , add buttons and add functionality to that again which is again tedious.

Laziness is not a good quality. Everything, including programming, has a tedious part. In programming you do have to do it yourself, that is why it is called "programming", and not "already programmed". So if you don't enjoy it, find something that you do enjoy.

woooee 814 Nearly a Posting Maven

It's not obvious what you want to do. If you want to capitalize the first word of the sentence:

test_recs = "The quick brown fox jumped over the lazy dog.  test sentence number two."
new_rec_list=[]
for sentence in test_recs.split(". "):
    if len(sentence):
        new_sentence = sentence.strip().capitalize()
        new_rec_list.append(new_sentence)
print ". ".join(new_rec_list)
woooee 814 Nearly a Posting Maven

still having problems with the program...
Won't go past question three and checking answers section wrong

Dont' know what "Won't go past guestion three" means. On input, on writing, on checking answers? And have you already created the file "few_questions.txt" with the questions in it (that could be the cause of the "won't go past three" problem). You did not say. If not, that is the first thing your program must do. If you know functions, use one function to output the file the first time, a second function to read the file, ask for an answer, and write to the new file, etc. As stated before, use a loop:

print "Please answer these questions."
print

few_Questions = open("few_questions.txt","r")
few_responses = open("few_responses.txt","w")

## Your program does not store the question in the variable to use to write to new file
for rec in few_Questions:
    rec = rec.strip()     
    print rec
    response = raw_input ("Enter an answer: ")
    response = response.strip()
    few_responses.write("%s: %s\n" % (rec, response))    ## delimiter = colon
few_Questions.close()
few_responses.close()
woooee 814 Nearly a Posting Maven

The easiest to understand is to store the previous record, and find the number for the record previous to the ">" record.

seq=""">s1\n
 MPPRRSIVEVKVLDVQKRRVPNKHYVYIIRVTWSSGATEAIYRRYSKFFDLQMQMLDKFP MEGGQKDPKQRIIPFLPGKILFRRSHIRDVAVKRLIPIDEYCKALIQLPPYISQCDEVLQ FFETRPEDLNPPKEEHIGKKKSGNDPTSVDPMVLEQYVVVADYQKQESSEISLSVGQVVD\n

 >s2\n
 MAEVRKFTKRLSKPGTAAELRQSVSEAVRGSVVLEKAKLVEPLDYENVITQRKTQIYSDP LRDLLMFPMEDISISVIGRQRRTVQSTVPEDAEKRAQSLFVKECIKTYSTDWHVVNYKYE DFSGDFRMLPCKSLRPEKIPNHVFEIDEDCEKDEDSSSLCSQKGGV\n"""

split_seq = seq.split("\n")
name = ""
pattern = 0
previous_rec = ""
for line in split_seq:
    line = line.strip()
    if line.startswith('>'):     ## print previous name and use previous record
        if len(name):            ## first ">" won't have a previous
            pattern = previous_rec.count('P') 
            print '%s:%s' %(name,pattern)
        name=line
    else:
        if len(line):            ## skip any empty lines
            previous_rec = line

if len(name):
    pattern = previous_rec.count('P') 
    print '%s:%s' %(name,pattern)
woooee 814 Nearly a Posting Maven

You can do it this way, but it would be better to use a for() loop:

ctr = 0
line1 = myFile.readline()
while line1:
    myOut.write(line1.strip("\n"))     ## 4 records without end-of-line
    ctr += 1
    if ctr > 3:                    ## 4 records written
        myOut.write("\n")
        ctr = 0

    line1 = myFile.readline()
woooee 814 Nearly a Posting Maven

One way is to use a StringVar. When you change it's contents, the change shows up on the GUI. And you should read up on buttons as yours don't do anything when clicked.

from Tkinter import *
from tkFileDialog import *

class Game():
    def __init__(self,root):
        self.root = root
        self.var1 = StringVar()
        self.var1.set("D")
        btn = Button (self.root, textvariable=self.var1, width=5, command=self.change_var)
        btn.grid(row=1,column=1)	

    def change_var(self):
        var=self.var1.get()
        if "A"==var:
            self.var1.set("D")
        else:
            self.var1.set("A")

root = Tk()
root.title("Sample Application")
root.geometry("100x50")
Game(root)
root.mainloop()
woooee 814 Nearly a Posting Maven

See this link on functions http://www.tutorialspoint.com/python/python_functions.htm You should also have a function_1 that will input the name and grade until told to stop. It would also receive the "data" list and append to it. If the length of "data" is zero, then option 2 has not been selected. You can either print an error message or call function_2 from function_1 to read the data. It is a good habit to include some useful info about what the function does with every function call for future reference.

def function_2():
    """ get the file name, open and read the file, and return the data
    """
    fname = input("What is the file name?")
 
    file1 = open(fname, "r")
    data = file1.readlines()
    file1.close()
    return data

def function_3(data):
    """ process the data by calculating the mean
    """
    for rec in data:
        print rec
 

def main():
    data=""
    choice = input("Please enter the number for your choice or press <enter> to quit\n\n1.) Add a student to File\n2.) Display course info\n3.) Display course stats.")
    if choice == '1':
        function_1(data)
    elif choice == '2':
     data=function_2() #should open file to read file
     print data
    elif choice == '3':
     function_3(data) #display results from arithmetic mean and range for the course
 
    else:
        print "Enter 1, 2, or 3 only"

    file1 = open(filename1,"a")
    file1.write(myInfo + ","   ",\n" )
    file1.close()
 
 
 
 
 
if __name__ == '__main__':
    main()
woooee 814 Nearly a Posting Maven

I like this explanation of the parts of a function http://www.tutorialspoint.com/python/python_functions.htm. Tutorials are there for a reason, i.e they can be written once and read many times by many people. Start a list of good tutorials so you don't have to post to a forum with questions about very basic concepts that are covered in virtually every tutorial.

woooee 814 Nearly a Posting Maven

I would suggest that you print word_freq. You possibly want to use setdefault instead of .get although there is no description of what you want this part of the code to do so there is no way to tell for sure.

for word in word_list:
        word_freq.setdefault(word.lower(),0)
        word_freq[word.lower()] += 1

2.Analyze file and graph (with bar plot)the 25 most frequent words with length greater than 4

I would test for word length > 4 and place in a list of lists = [frequency, word], sort in reverse order, and print/plot the first 25.

woooee 814 Nearly a Posting Maven

Then you just want to use
while True:
instead of messing with a counter since it has no meaning, or
for cards in range(52):
assuming there are no jokers (in the deck not in this forum). Also, you will have to post the code for "cards" if you have questions in the future and want us to be able to test the code.

woooee 814 Nearly a Posting Maven

Use a list of lists

card_list = [ [], [], [], [], [], [], [] ]
x = 0
while x < 7:     ## number of cards to be dealt to each hand
    ## each for() loop deals one card to each of the hands in card_list
    for ctr in range(len(card_list)):     ## = 7 (# hands in card_list)
        card = mydeck.deal()
        if card != None:
            card_list[ctr].append(card)
    x += 1  
for hand in card_list:
    print hand

or a dictionary which is similiar

card_dict = [1:[], 2:[], 3:[], 4:[], 5:[], 6:[], 7:[] ]
x = 0
while x < 7:
    for ctr in range(1, 8):
        card = mydeck.deal()
        if card != None:
            card_dict[ctr].append(card)
    x += 1
for ctr in range(1, 8):
    print card_dict[ctr]

Also note that you have an infinite loop as you reset "x" so it will never be greater than 7.

Gribouillis commented: very clear explanation +13
woooee 814 Nearly a Posting Maven

I would go with something like this, and why is there a main() function for no reason? Note that only the powers of 2 can be divided down to 1.

## Assumes Python 3.X
#
def get_input():
    while True:
        n = input("Enter a number: ")
        try:
            return int(n)
        except:
            print("Enter a number only")

orig_number = get_input()
count = 0
number = orig_number
next = True
while next:
    number, remain = divmod(number, 2)
    if remain != 0:
        print("You can divide %d by two %d times" % (orig_number, count))
        next = False    
    count = count + 1
woooee 814 Nearly a Posting Maven

Open and read the file once into a list at the start of the program. If there are adds, simply add them to the list. Write the file once at the end of the program. I am guessing that each record in the file will contain the student's name and the grade so you can satisfy the requirements for #3. Start by getting the name and grade many times and appending each to a list, until the user enters "quit" for the student name, then write the file to disk and verify it's contents. The other parts have to wait until this is finished.

woooee 814 Nearly a Posting Maven

Put the objects in a list or dictionary and draw the appropriate object each time there is a miss.

win = GraphWin("Test", 500, 650)
start_x = 200

object_dict  = {}

obj = Circle(Point(start_x,200),50)
object_dict[0] = obj
 
ctr = 1
for ln in ((0, 150,    0, 100),
           (0, 100,    -100, 100),
           (-100, 100, -100, 500),
           (0, 250,    0, 380),
           (0, 380,    -50, 450),
           (0, 380,    50, 450),
           (0, 300,    -50, 380),
           (0, 300,    50, 380)):
    obj = Line(Point(start_x+ln[0], ln[1]), Point(start_x+ln[2], ln[3]))
    object_dict[ctr] = obj
    ctr += 1

rect = Rectangle(Point(start_x-100,350),Point(start_x+170,400))
rect.setWidth(3)
object_dict[ctr] = rect
ctr += 1
 
rect2 = Rectangle(Point(start_x-100,400),Point(start_x+100,600))
rect2.setWidth(3)
object_dict[ctr] = rect2

win.getMouse()     ## start game

## simulate wrong guesses
ctr = 0
while ctr < len(object_dict):
    object_dict[ctr].draw(win)
    ctr += 1
    print "wrong guess #", ctr
    time.sleep(1.0)
win.getMouse()
win.close()
woooee 814 Nearly a Posting Maven

What would the syntax be to do that?

This has just become a "keep-asking-questions-until-someone-codes-it-for-you" thread.

woooee 814 Nearly a Posting Maven

I mean how could I do this?

Pass a parameter to the function, and return the desired result as many times as you want. You can start at "A first program" here and also here and here. No on wants to do this for you as it is simple and is something you can do for yourself, and should understand if you are going to write programs.

woooee 814 Nearly a Posting Maven
content = row[0] + row[4] +  row[5] +  row[11] +  row[12] + row[13] +  row[16] + row[17] + row[22]
	csv_out.writerow( content )

The above uses 9 fields.

# I want it to save the file in csv format as: 1,2,yhnujmik,2121212121

This has 4 fields.

however the code is generating this: 1,2,y,h,n,u,j,m,i,k,2,1,2,1,2,1,2,1,2,1

This has 20 fields. 9 != 4 != 20. There is no way to answer a question that does not make sense. Post some sample input and desired output and perhaps we can then offer some help.

woooee 814 Nearly a Posting Maven

That's because there is an infinite loop in the program. Because "n" does not change, the while loop never exits. We have no way of knowing how you want to change the number if it is divisible by 2, or how you want to change it if it is not. When testing a while loop it is a good idea to limit the number of iterations. This is an illustration of how to limit the loop, not how to change it to exit properly.

limit = 0
    while (n > 0) and (limit < 1000):
        limit += 1
woooee 814 Nearly a Posting Maven

Start with organizing the questions. I'm not real familiar with the game, but I think a cube and ladder are the first two objects.

print "Describe a cube"
features=(("Size", "large", "medium", "small"),
          ("Made Of", "steel", "iron", "wood", "styrofoam", "cloth"))
cube_response = []
for feature in features:
    print "\npick one of the following"
    print feature[0]
    for ctr in range(1, len(feature)):
        print "     %d %s" % (ctr, feature[ctr])
    choice = raw_input("What is your choice? ")
    cube_response.append(choice)

You can define the parameters for each object and send them to a common function to process.

woooee 814 Nearly a Posting Maven

Instead of all the individual calls to wait_for_guess you can use a loop and counter like this pseudo-code example.

# all of the code like the following is redundant
            for s in word1:
                wait_for_guess(win, WINSIZE)
                guess = entrybox.getText()
                guessed += guess
                messagebox.setText(guessed)
                draw_head(win, headpoint)
                print('guess: ', guess)
#
# instead use
def check_letter(ltr, word1, blank_word):
    print("testing", ltr)
    found = False
    for ctr in range(len(word1)):
        if guess == word1[ctr]:
            blank_word[ctr]=guess
            found = True
    guesses_so_far = "".join(blank_word)
    print guesses_so_far
    if guesses_so_far == word1:
        print "You guessed it"

    return found, blank_word


blank_word = ["_" for x in range(len(word1))]
total = 6
print "You get %d incorrect guesses" % (total)
ctr = 0
while ctr < total:
    wait_for_guess(win, WINSIZE)
    guess = entrybox.getText()
    result, blank_word = check_letter(guess, word1, blank_word)
    guessed += guess
    messagebox.setText(guessed)
    if not result:  ## incorrect guess
        ctr += 1
        if 1==ctr:
            draw_head(win, headpoint)
        elif 2==ctr:
            draw_body(win, headpoint)
        ## etc

You will now have to test for the word being found before all attempts are exhausted and if so, exit.

woooee 814 Nearly a Posting Maven

Post the code you have so far along with any problems.

woooee 814 Nearly a Posting Maven

Post the formula that you would like to use for solving the problem. The most common method is layer by layer. Also, post the code here if you want people who don't have, or want to deal with MS Windows archiver to respond.

woooee 814 Nearly a Posting Maven

I prefer using a list.

word1 = "hangman"
blank_word = []
for c in word1:
    blank_word.append('_')
print blank_word

for guess in ["a", "b", "n"]:
    print("testing", guess)
    for ctr in range(len(word1)):
        if guess == word1[ctr]:
            blank_word[ctr]=guess
    print(" ".join(blank_word))
woooee 814 Nearly a Posting Maven

Print event_dict to see if it contains anything. Also, output_file should be file_out, and the close() statement is indented incorrectly.

woooee 814 Nearly a Posting Maven

I think you want something like this, but post back if I do not understand

## store the recs in a set to make look up fast
## this assumes no two records are the same
recs_list = open('event_from_picks', 'r').readlines()
event_set = set(recs_list)

for key, list_of_numbers in event_dict.items():
    if key in event_set:
        ## event_set.remove(key)   ??? only use first rec found
        for item in list_of_numbers:
            output_file.write("%s " % (item))
        output_file.write("\n")
output_file.close()
woooee 814 Nearly a Posting Maven

ouyay areyay elcomeway

woooee 814 Nearly a Posting Maven

Is there a reason you are not storing the data in an in-memory SQLite database where you can easily select ("main component"=x and "main component number"=y and "timestamp"=z) or ("monitored component name"=a and "monitored variables"=b) etc.? An example usage from somewhere on the internet:

import sqlite3 as sqlite

##----------------------------------------------------------------------
def add_rec(cur, con, add_tuple):
   cur.execute("insert into test_it values (?, ?, ?, ?, ?, ?, ?, ?, ?)", add_tuple)
   con.commit()

##----------------------------------------------------------------------
def print_all_recs(cur):
   # Execute the SELECT statement:
   print "Printing all recs"
   cur.execute("select * from test_it")

   # Retrieve all rows as a sequence and print that sequence:
   recs_list = cur.fetchall()
   for rec in recs_list:
      print rec
      print "     stage=%s, REAC_W=%s" % (rec[1], rec[5])

##----------------------------------------------------------------------
def add_test_data(cur, con):
   #                   Stage     REAC_PS  WR(T)/P    TTO       REAC_W    W0       0wR(THCR)E/D  PTO
   data_list=[ ('2.0', 'Stage1', '0.509',  '4.3010', '1602.30', '0.515', '3.191',   '2.8191',   '29.7010'), \
               ('2.0', 'Stage2', '0.488',  '6.0074', '1470.43', '0.500', '3.200',   '3.9309',   '20.4275'), \
               ('2.0', 'Stage1', '0.524',  '4.4623', '1602.30', '0.560', '3.311',   '2.9243',   '29.7010'), \
               ('2.0', 'Stage2', '0.579',  '6.6682', '1444.78', '0.700', '3.320',   '4.3593',   '18.9262'), \
               ('3.0', 'Stage1', '0.524',  '4.4623', '1602.30', '0.560', '3.311',   '2.9243',   '29.7010'), \
               ('3.0', 'Stage2', '0.579',  '6.6682', '1444.78', '0.700', '3.320',   '4.3593',   '18.9262'), \
               ('3.5', 'Stage1', '0.525',  '4.4695', '1602.30', '0.563', '3.316',   '2.9290',   '29.7010') ]

   for data_tuple in data_list :
      add_rec(cur, con, data_tuple)

##----------------------------------------------------------------------
def del_recs_test(cur, con):
   num = "2.0"
   st = "Stage1"
   cur.execute("DELETE from test_it where number==:dic_num \
                          and stage==:dic_st", \
                         {"dic_num": num, "dic_st": st})
   con.commit()

   print "-" * 30, "AFTER Delete --- Should not find any recs"
   lookup_dic={"dic_num":"2.0", "dic_st":"Stage1"}
   recs_list=cur.execute('SELECT * FROM test_it where number=:dic_num \
                          and …
woooee 814 Nearly a Posting Maven

First have you tried difflib or something like it, as this has to have already been done by someone? If you are using readlines to read the files or reading the recs into a list, we don't know, then these conditions will never be true, because letter or letters does not equal one complete line, which is what "in" is looking for in a list. You can break this down

## what does this mean?  Is it found at all? is it found on the same line? 
# is it found at the same postion on the same line??
print "looking for", letter, lines
x = letter in lines
y = letters in data
if x == y:
woooee 814 Nearly a Posting Maven

Since words are not very long, it is not a problem to iterate through the entire word and keep track of the position of the first vowel, and if there is a consonant.

first_vowel = -1         ## location of first vowel
    consonant_found = False  ## assume no consonants
    t = 0
    for x in word:
        ## use lower() or upper() and one list of vowels
        if x.lower() in ["a", "e", "i", "o", "u", "y"]:
            if first_vowel == -1:     ## -1 == not found yet
                first_vowel = t
        else:
            consonant_found = True
        t += 1

    prefix = word[:first_vowel]
    stem = word[first_vowel:]
    if not consonant_found:
        print "Translated word:",
        print word + "yay"
    # etc.

"Yay" translates to "Yayyay"

woooee 814 Nearly a Posting Maven

The popular Christmas song "Jingle Bells" was actually written for Thanksgiving. The song was composed in 1857 by James Pierpont, and was originally called "One Horse Open Sleigh".

In 1941, Thanksgiving was declared by Congress to be a legal holiday, held on the fourth Thursday in November.

Come on, everyone thought it had been a holiday for hundreds of years.

woooee 814 Nearly a Posting Maven

There are not any answers presumably because no one uses 5 nested dictionaries. State what you are trying to do and why a 5-deep dictionary is necessary, along with a simple example, 184 lines of code is more than someone wants to wade through for a question like this, so something like

#10 or so dictionary entries is enough
sample_dictionary={"a":{"b":{"c":{"d":{"e":}}}}}
#
# create one panel and menu
class NestedPanelOne(wx.Panel):
    #----------------------------------------------------------------------
    # First notebook that creates the tab to select the component number
    #----------------------------------------------------------------------
    def __init__(self, parent, label, data):
        wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY)
#
# and then the function called when the menu is clicked
woooee 814 Nearly a Posting Maven

My mistake, that should be
for ctr, rec in enumerate(all_movies):

And this line
print "%5d %-20, %-20s %-s" % (name, genre, desc)
should be
print "%5d %-20, %-20s %-s" % (ctr, name, genre, desc)

woooee 814 Nearly a Posting Maven

You open movies.txt twice and don't close either one. Delete line #5, the first open is not used. It would work better if you open the file in a function.

def view_existing():
    all_movies = open("movies.txt", "r").readlines()
    ## print the all_movies list and allow the user to select one
    ## something like this, although this is simplified
    for ctr, rec in all_movies:
        name, genre, desc = rec.strip().split("**")
        print "%5d  %-20, %-20s %-s" % (name, genre, desc)


def add_new_movie():
    fp_out = open("movies.txt", "a")

    enter_another = True
    while enter_another:
        msg='Please enter the name of the movie'
        # etc.
        myString = "**".join(fieldValues)  ## the fields require a delimiter for reading
        fp_out.write("%s\n" % (myString))

        msg="Enter another movie?"
        # etc.

    fp_out.close()
huntaz556 commented: this helped alot ! thanks +1