woooee 814 Nearly a Posting Maven

See one of the Tkinter docs on the web and take a look at forget.

woooee 814 Nearly a Posting Maven

To be complete, a solution that iterates over the tuple instead of using if statements, and can accomodate any length of numbers input.

def biggest(*nums_in):
    ret_num = nums_in[0]
    for num in nums_in:
        if num > ret_num:
            ret_num = num
    return ret_num

print biggest(3, 6, 7)
print biggest(6, 5, 3, 8, 2)
print biggest(9, 3, 6)
print biggest(3, 3, 10)
print biggest(11, 3, 11)
woooee 814 Nearly a Posting Maven

The Germans made the first artificial Christmas trees out of dyed goose feathers

Christmas trees usually grow for about 15 years before they are sold.

Contrary to popular belief, suicide rates during the Christmas holiday are low. The highest rates are during the spring

woooee 814 Nearly a Posting Maven

Typically that means that a return statement is indented incorrectly. Check all of your return statements.

woooee 814 Nearly a Posting Maven

Instead of calling the same class instance every time, you are creating a new class instance

 self.canvas.bind("<Button1>", win2(self.canvas))

As stated above, you should create one instance of each class in init() and use those.

woooee 814 Nearly a Posting Maven

Set third to 0 (False) and see how that affects things. An "and" is 2 nested if statements:

if first > second:
    if third:

See 5.1. Truth Value Testing

woooee 814 Nearly a Posting Maven

Try this for a hint

alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
key = "XPMGTDHLYONZBWEARKJUFSCIQV"
for ctr in range(len(alpha)):
    print alpha[ctr], key[ctr]

print
print alpha.find("F")
woooee 814 Nearly a Posting Maven

Since this is obvioulsy homework, I doubt they can use min, but will have to iterate over the list.

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

Add a print statement after this line to see what you are doing

for item in enumerate(a):
    for item1 in enumerate(b)
        print "checking" item, item1

You want to subtract 2 items in the list, convert the difference to a positive number, and store the smallest number found, and if you want, store the two numbers as well. See Looping Over Lists here and re-read the answers to your post on StackOverflow.com which say you are not using enumerate properly.

woooee 814 Nearly a Posting Maven

Check the line indentations up to and including that point. Also, you only want one input function instead of one in each function. You then test for the input and call the appropriate function. You can write one function to convert anything to one common measure, say millimeters for example since it is the smallest unit. You then convert the millimeters to whatever the end measure is, so convert_to_miles() for example will know that it is receiving millimeters and would only have one calculation to convert millimeters to miles.

## an example of one input function
measure=['', 'inches', 'feet', 'miles', 'millimeters', 'centimeters', 'meters', \
                 'kilometers', "yards"]
start = -1
while start > 8 or start < 1:
    for ctr in range(1, 9):
        print ctr, measure[ctr]

    start = raw_input ("Enter a number for conversion from ")
    start = int(start)

end = -1
while end > 8 or end < 1 or end == start:
    print
    for ctr in range(1, 9):
        if ctr != start:  ## eliminate start choice
            print ctr, measure[ctr]

    end = raw_input ("Enter a number to convert to ")
    end = int(end)

print "You chose %s to %s" % (measure[start], measure[end])

## assume miles to feet
if start == 3:
    ## convert everything to millimeters
    ret_mil = convert_to_millimeters(start, 'miles')
if end == 2:
    ret_value = convert_to_miles(ret_mil)
woooee 814 Nearly a Posting Maven

Note that you will replace tmp with cell no matter when it is found, i.e the for loop will always replace tmp with cell 1 on the first pass if it is found, no matter where in the line it occurs. Without more info about what input and output should be, and what row contains, there is nothing more that can be said.

woooee 814 Nearly a Posting Maven

You bind the button press to the return from the function=inn(), not the function=inn. The button call later on to "funct" is coded correctly so note the difference. Also, you still mix grid and pack which can cause problems.

woooee 814 Nearly a Posting Maven

Also, you read the file twice. If you want to use your existing code, use a set or dictionary for remove_index instead of a list, as the time is taken up by sequential lookups in "if count in remove_index:". Or use instead

recs_to_write=0

with open('input.txt') as infile:
    for line in infile:
        if line.startswith('BEUSLO') and target in line:
            recs_to_write=3
        if recs_to_write:
            output_file.write(line)
            recs_to_write -= 1
Gribouillis commented: nice +13
woooee 814 Nearly a Posting Maven

Instead of

self.firstClass = firstClass
self.economy = economy
self.business = business

which is redundant, i.e. you always have all 3, use a "class" variable that you set to "first", "economy", or "business". Also you don't have number of people or name.

woooee 814 Nearly a Posting Maven

You could also have a list of win squares instead of checking for rows, diagonals, and columns separately. The following is pseudo-code:

def check_row(self, row):
    control=this_column[0]
    for column in row
        ## not occupied or not all the same
        if column == 0 or column != control:
            return False
    return True

def checkWin(self):
    ## check rows
    for j in range(self.rows)
        result = self.check_row(self.rows[j])  ## or just use for row in self.rows
        if result:
            print "Winner is player", self.player
            return result, self.player

    ## check_column would be the same as check_row, i.e. you could use
    ## the same function if you sent it a list of all rows[0] instead
    ## for example, and the same for diagonals
    result = check_column()   
    result = check_diagonal()
woooee 814 Nearly a Posting Maven

We are here to help. Post your code and any errors, and you probably have not read this thread

woooee 814 Nearly a Posting Maven

Any ideas why using the input file is causing problems?

No, because we have no idea what the problem is or what the output to the file actually is compared to what it should be. Add some print statements in "correct()" to see what it is doing differently. Also, note that files opened with

infile = open('C:\\Python26\\text.txt','r')

do not contain lists but a string or strings.

woooee 814 Nearly a Posting Maven

You should first test that what you want is there.

for cell in row:
    tmp = ('%VAR_' + headerRow[i] + '%')
    if tmp in line:
        line = line.replace(tmp, cell) # string.replace(old, new)
        print "replaced line =", line
    else:
        print tmp, "not found"
woooee 814 Nearly a Posting Maven

In addition to lambda, you can also use partial to pass a variable indicator to a function. Also, using pack() and grid() in the same program leads to unpredictable results.

from Tkinter import*
from functools import partial

root=Tk()
root.title("Replicate DNA yourself!")

def inn(variable_passed):
    positions = ((10, 10), (60, 50), (110, 110))
    xx, yy = positions[variable_passed]
    print "variable passed =", variable_passed, "----->", xx, yy

tophelicase=Toplevel(bg="green",bd=10)
Label(tophelicase,text="Where should helicase be placed?",bg="green").pack()
Radiobutton(tophelicase,text='1',bg="green",command=partial(inn, 0)).pack()
Radiobutton(tophelicase,text='2',bg="green",command=partial(inn, 1)).pack()
Radiobutton(tophelicase,text='3',bg="green",command=partial(inn, 2)).pack()

root.mainloop()
woooee 814 Nearly a Posting Maven

I don't know how to answer your question without knowing what you have tried so far.

woooee 814 Nearly a Posting Maven

bh1=Radiobutton(tophelicase,text='1',variable=position,value=1,bg="green",command=tophelicase.destroy).pack()

Print bh1 to see what it contains and you should see that there is no reason to store the return from pack(), i.e. just use

   Radiobutton(tophelicase,text='1',variable=position,value=1,bg="green",
               command=fhelicase).pack()
woooee 814 Nearly a Posting Maven

I'm guessing the problem is the redundant calls to getX() and getY(). You do the exact same things 10 times for each boat drawn. That means 120 calls for the 12 boats. Move the call outside the for loops and store the values in variables. Also, the relationship between the "b" variables is constant so you only need one, i.e. instead of b2 you can use b1-12. And similar for the "s" variables. I originally though that perhaps you were supposed to use clone and move, but that wouldn't save anything and may even consume more computer resources.

woooee 814 Nearly a Posting Maven

Start with the deck class by itself. A hand would be a list of cards dealt from the deck, so you can have as many lists/hands as you want. Something to get you started

class Deck(object):
    def __init__(self):
        suits = ('C', 'S', 'H', 'D')
        ranks = ('A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K')
        self.deck = [rank+suit for rank in ranks for suit in suits]
        print self.deck

        self.shuffle_deck()
        self.next_card = 0
        for ctr in range(5):
            self.deal_a_card()

    def deal_a_card(self):
        print "\n  deal a card", self.deck[self.next_card]
        self.next_card += 1

    def shuffle_deck(self):
        random.shuffle(self.deck)
        print "\nshuffled deck", self.deck

DK=Deck()
woooee 814 Nearly a Posting Maven

First, use a dictionary or list of lists to hold the question and answers instead of 100 if statements. I assume you don't know about dictionaries yet so this uses a list of lists.

words = [['ano', 'um'], ['ima', 'now'], ['eego', 'english']]
random.shuffle(words)
for this_question, this_answer in words:
    print (this_question)
    translation = input('Enter the translation: ')
    if translation == this_answer:
        print('Correct!')
    else:
        print('Incorrect.')
        print('The correct answer is: '+this_answer)

    print("-"*30)

To answer your original question, learn to use print statements for simple debugging

print("comparing", words, "with ano =", translation)
if words == 'ano' and translation == 'um':
woooee 814 Nearly a Posting Maven

What does "won't work" mean? Also, use a list that you pass to the functions instead of the global variables, a1, a2, etc.

You are comparing a 3 item sub-list in done to a list that is 4 items which will never be equal.

done = [['a1','a2','a3']]
for testing in [['a1', 'a2'], ['a1', 'a2', 'a3'], ['a1', 'a2', 'a3', 'b1']]:
    print "testing", testing,
    if testing in done:
        print "True"
    else:
        print "False"  

Compare them individually instead, and you'll have to apply this yourself, so you want square numbers 0-8 for example and a list containing who occupies the square, so if list[0], 1, & 2 are all "X" or all "O" you have a winner.

def winner(control_list, player_list):
    for element in control_list:
        if element not in player_list:
            return "False " + element
    return "True"

done = [['a1','a2','a3'], ['b1', 'b2', 'b3']]
for player_list in [['a1', 'a2'], ['a1', 'a2', 'a3'], ['a1', 'a2', 'a3', 'b1']]:
    print "\n---------- player list =", player_list, "-"*20
    for sub_list in done:
        print "testing", sub_list,
        print winner(sub_list, player_list)
woooee 814 Nearly a Posting Maven

As Tony said, use a list. This can be run as is as a test.

def selection(number, list_colours, choices):
    while True:
        print("\nValid choices are %s" % (", ".join(list_colours)))
        colour = input("Please enter your %s valid colour: " % (number))

        if (colour in list_colours) and (colour not in choices):
            list_colours.remove(colour)
            return colour, list_colours

        else:
            if colour not in list_colours:
                print("That is not a valid colour")
            if colour in choices:
                print("You have already chosen that colour")
            ## always prints
            print("Please make your selection again")

list_colours = ["red", "blue", "green", "yellow", "magenta", "orange", "cyan"]
choices = []
for number in ["first", "second", "third", "fourth"]:
    choice, list_colours = selection(number, list_colours, choices)
    choices.append(choice)

print ("Choices made list =", choices)
woooee 814 Nearly a Posting Maven

You don't have an input box, you are using the command line so you would just print the error message. You should be able to modify the code you posted on the other forum

while True:
    first_colour = input("Please enter your first valid colour: ")
    if first_colour in list_colours:
        break

    print("Some error message")        ##  added

although I would use a function and a loop to get the colors instead of the 4 separate input statements.

or already existed in you(r) selections

You do not test for this in the code you posted.

woooee 814 Nearly a Posting Maven

In Tkinter is would just be
top.title("New Title")

Or use a Label and Entry box if you have several entries and want a separate title/label for each one.

Ah, you are using input, i.e. the console

x= input("blah blah blah")

then you would just print a line to get something more than "blah blah blah" to print

print("Python Input")
x= input("blah blah blah")
woooee 814 Nearly a Posting Maven

A more compact version of the snow program. I'm not obsessive really.

# drawing canvas/window with title and size
win = GraphWin("Snowman",400,500)

parts_is_parts = []
fill="white"
ctr = 0
for x, y, z in ((200, 115, 45), (200, 210, 65), (200, 345, 85), (180, 100, 3.5),
                (220, 100, 3.5), (170, 125, 3.5), (185, 132, 3.5), (200, 135, 3.5),
                (215, 132, 3.5), (230, 125, 3.5), (200, 175, 3.5), (200, 205, 3.5),
                (200, 235, 3.5)):
    cir = Circle(Point(x, y), z)
    cir.setFill(fill)
    cir.setOutline("black")
    cir.draw(win)
    parts_is_parts.append(cir)

    if 2 == ctr:
        fill="black"
    ctr += 1

hat = Rectangle(Point(290,150),Point(200,160))
hat.setFill("black")
hat.move(-43,-86)
hat.draw(win)
parts_is_parts.append(hat)
tophat = Rectangle(Point(30,30),Point(70,70))
tophat.setFill("black")
tophat.move(150,-7)
tophat.draw(win)
parts_is_parts.append(tophat)

nose = Polygon(Point(180,90),Point(130,100),Point(180,100))
nose.setFill("orange")
nose.move(20,18)
nose.draw(win)
parts_is_parts.append(nose)

incr = -40
for x, y in ((142, 185), (336, 145)):
    arm = Line(Point(x, y),Point(x-75, y+incr))
    arm.setFill("brown")
    arm.setWidth(3)
    arm.draw(win)
    parts_is_parts.append(arm)
    incr *= -1

snow = Circle(Point(100,100), 2)
snow.setFill("white")
snow.setOutline("blue")
snow.draw(win)
for x, y in ((-70, 150), (-60, 20), (-40, -70), (-40, 250), (-15, 50), (25, 100), 
             (50, -70), (150, 50), (190, -50), (200, 100), (200, 200), (230, -5), 
             (250, 150), (275, 30)):
    snow2 = snow.clone()
    snow2.move(x, y)
    snow2.draw(win)

for i in range(6):
    p = win.getMouse()
    c = parts_is_parts[0].getCenter()
    dx = p.getX() - c.getX()
    dy = p.getY() - c.getY()
    for part in parts_is_parts:
        part.move(dx,dy)

win.getMouse()
win.close()
woooee 814 Nearly a Posting Maven

You want to use numberAsked in the while loop instead of
while len(Questions) > 0 :

Also, you can use random.shuffle on the Questions list and then take them in order instead of deleting and checking for length.

woooee 814 Nearly a Posting Maven

This will give you a general idea of how to start if I understand what you want.

def drawRectanglePatch(x, y):
    win = GraphWin("Test", 300, 300)
    for i in range(10):
        for j in range(10):
               topLeftX = x + i * 10
##               topLeftY = y + j * 10
               incr = 0
               if j-i > 0:
                   incr = j-i
               topLeftY = y + incr * 10
               rectangle = Rectangle(Point(topLeftX, topLeftY),
                                              Point(topLeftX + 10 , topLeftY + 10 ))
               rectangle.setFill("red")
               rectangle.setOutline("white")
               rectangle.draw(win)
    win.getMouse()
drawRectanglePatch(10, 10)
woooee 814 Nearly a Posting Maven

It is not obvious what you are trying to do. Nor is it obvious what GUI toolkit you are using, although it is not Tkinter or Wx which is all that I use, so we can not run your code (no imports posted). If you are trying to draw the grid, you would draw 5 vertical lines and then 5 horizontal lines.

## draw 5 vertical lines
increment=20
for ctr in range(5):
    start_x = x + increment*ctr
    create_line(start_x, start_y, start_x, start_y+length)
woooee 814 Nearly a Posting Maven

You should be using "x" and "y" passed to the function for your start position instead of the hard coded one. You can then pass a different x, y (start) to the function, assuming you are always drawing the same size triangle. In Tkinter (which doesn't look what you are using) you can also move an object to the postion you want so perhaps your GUI has a similar function.

## the preferred way if your GUI has a similar method
goto(x ,y)

## offset the postion otherwise
triangle = Polygon((Point(x+100,y+20), Point(x+80,y+60), Point(x+120,y+20)))    
woooee 814 Nearly a Posting Maven

See the definition for append mode = "a" Click Here which explains why checking is not necessary.

woooee 814 Nearly a Posting Maven

You have to add the last group, and note that the counter is initialized to one since we are comparing this pixel to the next pixel, so this pixel is the first in a series.

You should also test your program with the first 2 pixels different and with the last 2 pixels different

test_list = [1,1,1,1,0,0,0,0,0,1,1,1,1,1,1,1,0,0,1,0,0,0,0]
list_out = []
num_found = 1
for ctr in range(0, len(test_list)-1):
    print "comparing", test_list[ctr], test_list[ctr+1], num_found
    if test_list[ctr] == test_list[ctr+1]:
        num_found += 1
    else:
        if num_found > 3:
            str_out='*%d%d' % (num_found, test_list[ctr])
        else:
            str_out = str(test_list[ctr])*num_found
        list_out.append(str_out)
        print "     adding", str_out
        num_found = 1

## add the last group ***** note the last pixel was not added *****
if num_found > 3:
    str_out='*%d%d' % (num_found, test_list[ctr-1])
else:
    str_out = str(test_list[ctr-1])*num_found
list_out.append(str_out)
print "     adding", str_out

print "".join(list_out)

If that is too much code to swallow at one time, then split the original list into a list of lists which breaks on each difference. You can then go through and send to a find_run function to count the number in each sub-list.

list_out = []
this_group = []
previous = ""
for pixel in test_list:
    if pixel != previous:
        if len(this_group):  ## don't append empty list on first break
            list_out.append(this_group) ## or send to find_run function
        this_group = []

    this_group.append(pixel)
    previous = pixel
## add the last group
list_out.append(this_group)

print list_out
woooee 814 Nearly a Posting Maven

Ask the user to enter a number to be guessed say between 1 and 100. The computer selects a random number in that range. If the computer guesses too low, then that number+1 becomes the lower number in the range for the next random number to choose from and so on for too high. On the first program that you posted here, what happens if the person guesses the number on the 6th and final try? A related question/answer, why is "isCorrect" declared but never used? The Python Style Guide says that variables names should be all lower case --> so "is_correct", BTW.

## only a partial solution
##
is_corect = False
while not is_correct and count < maximum:
    guess = int(input("Take a guess: "))

    if guess < secret_number:
        print("Higher...")  ## does "Higher" mean number is higher or guess is higher
    elif guess > secret_number:
        print("Lower...")
    else :   ## 2 numbers are equal
        is_correct = True
woooee 814 Nearly a Posting Maven

You are still using a dictionary instead of keywords. I would try passing the dictionary's "browsername" and "platform" separately instead of a dictionary as it appears that it doesn't know where "chrome" belongs.

woooee 814 Nearly a Posting Maven

You have to test functions instead of guessing where an error might be. To test the read function print the results, or the first 10 or so records if the file is big.

import csv

def get_csv_data(csvfile):
    """ A simpler way
    """
    with open(csvfile) as fp:
        reader = csv.reader(fp)
        reader_as_list=list(reader)
    return reader_as_list

def get_csv_data_2(csvfile):
    # Read CSV file and return  2-dimensional list containing the data
    reader = csv.reader(file(csvfile))
    result = []
    for row in reader:
        rowlist = []
        for col in row:
            rowlist.append(col)
        result.append(rowlist)
    return result

##===================================================================
test_data = """test,pricea,qtya,priceb,qtyb,pricec,qtyc
perrytest,11,22,5,9,55,10,8,88,50
testrow2,12,5,10,10,9,50
testrow3,10,5,9,10,8,75,50"""

## write a test csv file
fname = './test_it.csv'
with open(fname, 'w') as csvfile:
    for rec in test_data.split("\n"):
        csvfile.write("%s\n" % (rec))

return_list=get_csv_data(fname)
print "return list", return_list
print "\ncsv_2 data---------------------------------------"
return_list=get_csv_data_2(fname)
print return_list

To test the replace variables function (we don't know what "row" is or what the replace is supposed to do, so it's up to you), print the length of the list passed to the function and see if it is reasonable, and then print the first 10 records before and after the replace statement.

woooee 814 Nearly a Posting Maven

A complete error is required as it contains the offending line. I would guess that you would be passing a dictionary to Remote instead of browsername and platform, if you were using an data/instance attribute (self), but "capabilities" is a class attribute.

class VerifyAboutPage(unittest.TestCase):
    capabilities = None
    def setUp(self):
       driver = webdriver.Remote(desired_capabilities=self.capabilities)
woooee 814 Nearly a Posting Maven

the problem is that the program creates an empty file

Not sure what to do next

Test your program (note that the file is not technically "empty")

def main():
    inpath = input("Enter an input file: ")
    line = input("Enter what you want to remove: ")
    outpath = input("Enter an output file: ")
    with open(inpath, "r") as infile, open(outpath, "w") as outfile:
        for line in infile:
            print("replacing", line, "with", line.replace(line, ""))
            outfile.write(line.replace(line, "") + "\n")
    print("Done.")

main()
woooee 814 Nearly a Posting Maven

I don't think there are many people here who use Pyglet. Many use Tkinter or Wx with a few Pyside/QT people thrown in. The Pyglet main page says that pyglet-users is the main forum, and should know more about it than we do.

woooee 814 Nearly a Posting Maven

def replaceVariablesWithCsvData(self, headerRow, row, lines): # lines as list of strings

This function does not create a list. It creates one long string. For more precise help come up with a simple example and some test data so we can see what happens compared to what should happen.

woooee 814 Nearly a Posting Maven

This doesn't have anything to do with Python. See if the task manager gives a create time or does something simple, like number the processes sequentially so you can tell which is which. Perhaps someone else will know something more about Visual Basic and the Task Manager.

woooee 814 Nearly a Posting Maven

You should first test the calc_average function.
print calc_average(75, 75, 75, 60, 90)
Also you might want to convert to a float which depends on the version of Python you are using.

woooee 814 Nearly a Posting Maven

This is not a complete solution but should give you an idea of the program flow

minimum = None
maximum = None
while True:     ## infinite loop so use "break" to exit
        number = input('Please enter a number, or "stop" to stop: ' )
        if number in ["STOP", "stop"]:
            print "breaking while loop"
            break

        """ another way
        if number.isalpha() and number.upper() == "STOP":
            print "isalpha"
            break
        """

        try:
            num = float(number)
            if (minimum) is None or (num < minimum):
                minimum = num
            if (maximum) is None or (num > maximum):
                maximum = num
            print ("Maximum: ", maximum)
            print ("Minimum: ", minimum)

        except ValueError:
            print("Non numeric data was entered.")
        except:
            print("Error with input...")

print ("Final Maximum: ", maximum)
print ("Final Minimum: ", minimum)
woooee 814 Nearly a Posting Maven
woooee 814 Nearly a Posting Maven

Print sys.maxint to see what it says. You are probably going beyond the computer's limit. It depends on your OS: 32 bit or 64 bit. For more precision take a look at the decimal module. If you want to actually do anything with a number than contains 180,000 digits, decimal is the only way to go.

woooee 814 Nearly a Posting Maven

ls -l or use one of the GUIs like midnight commmander (google "linux file permissions" for more info). Note that you will have to be root or sudo to change them.

woooee 814 Nearly a Posting Maven

The epoch is OS dependent and has nothing to do with Python. Since we don't know what OS you are using the question can not be answered except to say print gmtime(0) and see what it tells you. 28800 seconds is something like 8 hours so it may be the difference between Greenwich time and local time.