woooee 814 Nearly a Posting Maven

You can push each letter onto the stack and then pop each letter off into a new string. Since stacks are last-in-first-out, the new string will be a reverse of the original string. The two strings can then be compared http://greenteapress.com/thinkpython/thinkCSpy/html/chap18.html

woooee 814 Nearly a Posting Maven

I don't know about anyone else, but I'm getting a little tired of the "I goggled for this" lie http://tinyurl.com/3ldotwl Perhaps we should boycott the too obvious fibs and point them out as above.

Edit: But then I guess that's the same thing, as that's doing the search effort which provides the lazy with the code from the search. Back to pointing out the "we only help those who show effort" links. They are http://www.daniweb.com/software-development/computer-science/threads/573
http://www.daniweb.com/software-development/computer-science/threads/573/3625#post3625
http://www.daniweb.com/software-development/cpp/threads/78223

woooee 814 Nearly a Posting Maven

You can slice off the first two records.

f = open('data.txt', 'r') # Open file
 
data = f.readlines()
data = data[2:]
f.close()

print max(data), min(data)

but this may or may not give you what you want depending on the values and type of values in data.

woooee 814 Nearly a Posting Maven

You can iterate through the list, taking each sub-list and printing the individual items within that sub-list.

test_list=[['123', 19, '13', 'Fa0/19', '100000000'],
           ['13', 22, '13', 'Fa0/22', '100000000'],
           ['123', 19, '123', 'Fa0/19', '100000000']]

for sub_list in test_list:
    print sub_list
    for ctr in range(len(sub_list)):
        print "     ", ctr, "-->", sub_list[ctr]
    print
woooee 814 Nearly a Posting Maven

There is no way to tell without a complete error message which the contains the errant line. Also, do you instantiate the class and then call the setupUI function with a parameter? As the code stands now, nothing will happen even if the code does not contain errors.

woooee 814 Nearly a Posting Maven

You don't save the original file name so there is no "copy from" name. Be sure to back up the directory before testing any rename code.

import os
 
#read in file from the directory
for filename in os.listdir("."):
 
#    f = open(filename, "w")
 
#    i = True
 
#    while i:  doesn't do anything
	#if filename starts with a digit, lose first index by renaming and 
        #try again
     new_filename = filename
     while new_filename[0].isdigit():
 
	    new_filename = new_filename[1:]
 
     if new_filename != filename:
         print "renaming %s to %s" % (filename, new_filename)
         os.rename(filename, new_filename)

 
print 'Any filename starting with a digit has been renamed.'
woooee 814 Nearly a Posting Maven

Everyone pays 10%. If income is greater than $8500, add 5%. If income is greater than $34,500 then add 10% more, etc. Deductions are a separate process and would be calculated before the tax is calculated as it reduces income. For more assistance, post your code so far.

woooee 814 Nearly a Posting Maven

Use a return from the function (untested code).

def callcard ():
    IOU="0"
    while IOU not in ["1", "2", "3", "4"]:
        print
        print "1. For $5 or $10."
        print "2. For a $25 charge, you get $3 of extra phone time."
        print "3. For a $50 charge, you get $8 of extra phone time."
        print "4. For a $100 charge, you get $20 extra phone time."
        print " "
        print " "
        IOU = raw_input ("Please enter the number for the amount you wish to charge: ")
    print " "
 
    loop=True
    while (loop):    ## not necessary as the above guarantees correct input
        if (IOU == '1'):
            amount = "0"
            while amount not in ["5", "10"]:
                print "You have chosen to charge $5 or $10."
                amount = raw_input ("Please enter '5' for $5 or '10' for $10: ")
            if (amount == '5'):
                print "You have charged $5, thank you for your purchase."
            elif (amount == '10'):
                print "You have charged $10, thank you for your purchase."
#            else:
#                print "Incorrect value"
            return  ## exit function 
#
# etc for the other options

again="Y"
while again == "Y":
    callcard()
    print  
    again = raw_input("Enter 'Y' for a transaction;  any other key to exit ")
    again = again.upper()

Since options 2, 3, & 4 are all the same except for the amount, you can pass the necessary parameters to a function, and use it for any of those three options.

PlUmPaSsChIcKeN commented: Awesome +0
woooee 814 Nearly a Posting Maven

Post your code. In the code you posted earlier, you redefine newlines. It's too late here for me to test this, so you'll have to fix typos yourself.

for line in newarray:  # defined here
            newarray = line.strip().split()  # redefined here
            if len(line) > 2:
                break
            newarray = line.split()  # and a third time
#
#
       grouped = []
       this_group=[]
       for line in newarray:
            split_line = line.strip().split()
            if len(split_line) > 2:
                if len(this_group):
                    grouped.append(this_group)
                    print "appended", this_group
                this_group=[]
            else:
                this_group.append(line.strip())

        print grouped
woooee 814 Nearly a Posting Maven

You can also use the return from a function.

def compare_columns(a, b):
    # sort on descending index 0, ascending index 1
    return cmp(b[0], a[0]) or cmp(a[1], b[1])

repeat = {"c":1, "b":2, "a":1, "d":1, "e":2}

repeat_list=[(repeat[key], key) for key in repeat]
print repeat_list
out = sorted(repeat_list, compare_columns)
print out

Creating "repeat_list" is not necessary as you can pass the result of the list comprehension to the sorted function, but it is perhaps easier to understand this way.

woooee 814 Nearly a Posting Maven

reverse=True means that it is sorted in reverse order, (largest to smallest), and [:3] only prints the first 3 items. To print them all in ascending order, use:

repeat = {"c":1, "b":2, "a":1}
print sorted([ (freq,elem) for elem, freq in repeat.items()])

You can not sort by descending order for frequency and ascending order for the key using sorted. You have to write your own sort. We would be happy to help if you post some code to start with.

Also, you should only set the default once, not every pass through the for loop.

A bad hack is to add -1 for each one found instead of +1, and sort in ascending order, as -5 is smaller than -1.

repeat = {"c":-1, "b":-2, "a":-1}
print sorted([ (freq,elem) for elem, freq in repeat.items()])
woooee 814 Nearly a Posting Maven

strip() the line and then split() it and test the length. The ones you want should have a length of 2 if I understand correctly.

woooee 814 Nearly a Posting Maven

Pmw has a nice set of extensions to Tkinter. I would take a look at ScrolledText for starters, as it has a get method, as do TextDialog and other similar widgets (I think). Pmw also has curselection and getcurselection methods, in the combobox and notebook, but I have not used them and am not sure if they exist in other widgets.

woooee 814 Nearly a Posting Maven

PARIS (Reuters) - Boeuf bourgignon, veal blanquette, duck a l'orange and gratin dauphinois -- all mainstays of French cuisine, and a familiar sight on the menus of bistros and brasseries across the country.

Except these dishes aren't on offer in a quaint eatery with flavours that vary according to the chef's mood -- rather they've been mass produced, vacuum-sealed in congealed 2-kg packs and sold wholesale to restaurants from an icy warehouse, with microwave re-heating instructions stuck on the side.

But insiders in the catering industry say the phenomenon is more prevalent than customers would like to think.

Roland Heguy, chairman of the French syndicate for the hotel and restaurant industry (UMIH), estimates only 20,000 of France's 120,000 food establishments could actually claim to make all their produce from fresh ingredients.

woooee 814 Nearly a Posting Maven

See the comments.

def text():
	sentence = 0
	while sentence !="EOF":
		sentence = raw_input()
		line1 =[]
		processed_line = ""
		for char in sentence:  ## use the input string
                        ## isalnum() includes isalpha()
			#if char.isalpha() or char.isalnum():
			if char.isalnum():
				processed_line = processed_line+char

			else:
                                if len(processed_line): ## test for empty string
        				line1.append(processed_line)
				processed_line = ""  ## empty, not a space
                if len(processed_line):  ## append the final word
                    line1.append(processed_line)
		print processed_line
                print sentence.split()  ## second way to do it
		print line1
	
text()
woooee 814 Nearly a Posting Maven

Usually the GUI or text processor that you are using to view the data has a word wrap limit. You can set that to 20 characters or what ever you want.

woooee 814 Nearly a Posting Maven

You can just use "command=search" for the next button, and add a get-a-file-name routine to the top of the function.

woooee 814 Nearly a Posting Maven

it will only list and skip work because there is no non alpha character after work

Correct, so you have to test after the loop, for "processed_line" has length (something in it since the input could end with a period), and if so, append it to the list. Post your new code.

woooee 814 Nearly a Posting Maven

Your indentation is funky, probably using tabs instead of spaces. First, "print processed_line.split()" at the end of your code. Lists do not have a split() method.

You can use split() on the original string, but then you still have to iterate letter by letter and test for alpha as you do in your code. To get your code to run correctly, you should append "processed_line" when a non-alpha character is found (under the else) and then set "processed_line" to an empty string, ready to accept the next new word. Note that if you have some input like "I am a dog, I am not a cat.", you will get a break on the comma and on the space, leading to an empty "processed_line" being appended to the list. So, check processed_line for a positive length before appending. It would also be a good idea to print both "processed_line" and "line1" both before and after the append, while testing this code, so you know what is going on.

Also, the while() loop will never exit since "line" is never defined and therefore will never equal "EOF".
while line !="EOF":

woooee 814 Nearly a Posting Maven

You have to define w1...wn, and g. They should be in the list "words". You can see what is in "words" with this code. Note that arithmetic only works with numbers, not strings. See this page for starters.

#FileName = input("Enter the name of the file")     ## not used by the program
 
infile = open("grades.txt","r")
 
 
sum = 0
for line in infile:
    words = line.split(" ")
    for ctr in range(len(words)):
        print ctr, words[ctr], type(words[ctr])
woooee 814 Nearly a Posting Maven

If you want to return the original list, then modify it's contents. If not, return a new list (you only return one number, not the entire list).

def square_each(nums):
    for ctr in range(len(nums)):
        nums[ctr] **= 2
    return nums        
 
def square_new_list(nums):
    return_list = []
    for num in nums:
        return_list.append(num**2)
    return return_list

#def main():

nums = [3,4]
print(square_each(nums))

nums = [3,4]
print(square_new_list(nums))
woooee 814 Nearly a Posting Maven

You can pack them all into a Frame and destroy the Frame.

try:
    import Tkinter as tk     ## Python 2.x
except ImportError:
    import tkinter as tk     ## Python 3.x

class DestroyTest():
    def __init__(self, top):
        self.top=top
        self.top.geometry("+10+10")

        self.frame=tk.Frame(self.top)
        self.frame.grid()

        test_label=tk.Label(self.frame, text="Label")
        test_label.grid(row=1, column=0)

        destroy_button=tk.Button(self.frame, text="Destroy Frame", \
                                 command=self.destroy)
        destroy_button.grid(row=10, column=0)

        exit_button=tk.Button(self.top, text="Exit", command=top.quit)
        exit_button.grid(row=10, column=0)

    def destroy(self):
        self.frame.destroy()
        self.new_toplevel=tk.Toplevel(self.top, takefocus=True)
        self.new_toplevel.geometry("+50+50")
        self.new_toplevel.grid()

        lbl=tk.Label(self.new_toplevel, text="New Toplevel")
        lbl.grid()


root=tk.Tk()
DT=DestroyTest(root)
root.mainloop()
JoshuaBurleson commented: PERFECT! +4
woooee 814 Nearly a Posting Maven

Use itertools.

import itertools
x = [['foo'], ['bar', 'baz'], ['quux'], ("tup_1", "tup_2"), {1:"one", 2:"two"}]
print list(itertools.chain(*x))
woooee 814 Nearly a Posting Maven

Damn pyguy62, that's quite a bit of effort. Hopefully it will be appreciated. Look at the indentation after line 55. I hope you read this before the 30 minute limit is up.

To sort by value can also be done with

from operator import itemgetter
print sorted(word_count.items(), key=itemgetter(1))

but homework probably means the OP is supposed to write a sort method.

The comments looked much nicer in IDLE

IDLE probably uses a fixed width font, i.e. all letter have the same width. A browser generally used a proportional font, i.e. "i" takes up less space than "w", so I just post what I have and ignore the misaligned comments.

JoshuaBurleson commented: good eye. and thanks for the itemgetter reference! +4
woooee 814 Nearly a Posting Maven

Need urgent help on python coding!

It is not our fault that you waited until the last minute.

I do not know where to go from here

Neither do I as I do not know what your assignment says you should code.

pleaseeeeeeeeeeeee HELP ME

And most especially, no one wants to see the site turn into a place where children beg for someone to do it for them.

woooee 814 Nearly a Posting Maven

Google is your friend. There are several tools depending on what you want to do.

woooee 814 Nearly a Posting Maven

There should be a "Mark as Solved" link below the last post.

woooee 814 Nearly a Posting Maven

The "standard" way is to use a while() loop.

question=0
while question not in ['1'. '2']:
    question = input("Press 1 or 2")

print("1 or 2 entered", question)
woooee 814 Nearly a Posting Maven

Please make the post "Solved" so you aren't rude to those who would otherwise read this unnecessarily.

woooee 814 Nearly a Posting Maven

Print the value for "i" each time through the while() loop. And you should not use "i", "l", or "O" as single digit variable names as they can look like numbers.

for x in text:

Also the logic is bass-ackwards so print the value for "x" each time through the for() loop

for ctr in range(32, 126):
    for ltr in text:
woooee 814 Nearly a Posting Maven

Print the contents so you aren't flying blind.

def customer_dictionary():
    balfilename= open('balance.dat', 'r')
    customer_dict={}
     
    for line in balfilename:
        print "line =", line
        print "split =", line.split()
        value, name = line.split()
        if name[3] == ' ':
            customer_dict[name[1:]] = value
        else:
            print "name[3] =", name[3]
    balfilename.close()
     
    return customer_dict
woooee 814 Nearly a Posting Maven

Everyone should also print what was entered.

conbi = ['a1','b1','c3','c4','f7']
left_unmatched = 5
wrongtimes = 0
right = 0
guess = input('Shoot: ').split(' ')  ## guess is already a list because of the split()
print "guess entered =", guess

guess = list (guess)
for ctr in range(len(guess)):
    print "     checking for", guess[ctr]
    if guess[ctr] in conbi:
            left_unmatched -=1
            right +=1
            print ('Hit:',right,'Missed: ',left_unmatched)
print ('Hit:',right,'Missed: ',left_unmatched)
woooee 814 Nearly a Posting Maven

File "<pyshell#20>", line 1, in <module>

Don't use a shell as you can only key in one line at a time. Use IDLE which comes with Python, or a text editor to key in the program, and then save as a file that you can run and/or modify. And once again, print so you know what you are adding, in this case it is "fname".

print fname
    balfilename.append(fname)
woooee 814 Nearly a Posting Maven

You would run an existing python program file from DOS. The file would be created using a text editor, just like any other text file. You can not use IDLE, which comes with Python, since is requires a GUI. Some useful info.

if somebody have some simple example

See this page on the python.org website.

woooee 814 Nearly a Posting Maven

Since you did not include the entire error message we have to guess as to which line it is referring to (and that is quite possibly an information message, not an error message), so adding a print statement after the for() loop is the obvious place to start. A tutorial for opening files.

for line in ('balance.txt'):
    ## print for testing
    print "line =", line
    acct, SSN, balance = line.split()
    balfilename[acct] = int(SSN, balance)

Note: an error message looks like this

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'balance.txt'

woooee 814 Nearly a Posting Maven

Nothing will happen until the for() loop exits
for i in range(10000000000):

Tkinter (graphics.py is a subset of Tkinter) has the after keyword, so it would create a new snowflake after x amount of time, while the rest of the program continues to run normally. I don't know if graphics.py implements that or not.

Otherwise, use a while() loop that exits when the mouse is clicked. Some pseudo-code:

snowing = True
while snowing:
    p = Point(random.randint(0,755),random.randint(0,755))
    p.draw(win)
    p.setFill('white')
    if mouse_clicked:
        snowing=False
woooee 814 Nearly a Posting Maven

The simple method is to split on the space and then on the colon. I will leave it up to you to organize the output.

test_list=["name:bob grade:a dob:1980","dob:1976 name:kate grade:c"]
for substr_1 in test_list:
    print "-"*30
    first_split =substr_1.split()
    for substr_2 in first_split:
        print substr_2.split(":")
woooee 814 Nearly a Posting Maven

A hint:

ctr=0

while ctr < len(s):
    print ctr, s[ctr]
    ctr += 1
woooee 814 Nearly a Posting Maven

Print "word" within the bottom for loop, and print "s" within IsPalindrome. It is considered poor style to have one isolated call to main() at the end of the program, which is just a function that calls statements that are better left outside, because in large programs you look to the end for anything that gets executed, and then have to search through many, many lines of code to try and find "main()".

woooee 814 Nearly a Posting Maven

From a thread on another forum, I wondered how difficult it would be to create a Tic-Tac-Toe game that could not be beaten. Since it is easiest if the computer goes first and chooses the center square, this code implements that portion. The logic is fairly simple; occupy the center square as that removes both diagonals and both middle options for the opponent. Then choose a corner square since it removes two of the remaining options, leaving two only. Before every move, check for two in a row that can lead to a win or a block of the opponent. I suppose it could be improved a little and pick a square where there are 3 that are not occupied, and so a possible win, but this is all the time I have for now.

TrustyTony commented: Thanks for demonstration of tkinter wait_variable +13
woooee 814 Nearly a Posting Maven

Pass the dictionary to all of the functions, as that is what you are operating on. Something like

def add_student(student_dict):

    ## the while() loop is only necessary for the Yes/No input
    add_student="x"
    while add_student not in ["Y", "N"]:
        add_student = input('Add Student[s]? Y/N: ')
        add_student = add_student.upper()

    if add_student == 'Y':
        a = input('Student ID: ')
        b = input('Name: ')
        c = input('Age: ')
        d = input('Course: ')
        e = input('Year: ')
        if a not in student_dict:
            student_dict[a]={'Name':b, 'Age':c, 'Course':d, 'Year':e}
        else:
            print "student", a, "is already on file"

    return student_dict

##---------- test the add
student_dict = {}
for ctr in range(3):                          ## add 3 students
    student_dict = add_student(student_dict)
print student_dict

## etc for all functions.  For example
student_dict = Del(student_dict)
woooee 814 Nearly a Posting Maven

This guy has too much time on his hands, but what else are you going to do with a floppy drive these days. Two floppy drives play Star Wars' Imperial March www.youtube.com/watch?v=X4SCSGRVAQE

From http://news.yahoo.com/watch-two-floppy-drives-play-star-wars-imperial-154305699.html
"Silent has managed to program two floppy drives to clatter away at the exact pitches necessary to send fear into the hearts of a Jedi"

"The sound comes from a magnetic head moved by stepper motor. To make a specific sound, head must be moved with appropriate frequency…"

woooee 814 Nearly a Posting Maven

A toplevel does not automatically take focus. You have to set takefocus=True.

new_gui=Toplevel(root, takefocus=True)

There is nothing about SMTP or webbrowser in the last piece of code you posted, unless you are still trying to get the icon to load, in which case you store the id for the image in what appears to be a dictionary, then apply the entire dictionary to the grid (not the image entry).

self.new_image=ImageTk.PhotoImage(file=self.file1)
self.picture['image']=self.new_image
self.picture.grid(row=1,column=2)     ## self.picture['image'].grid, etc.
woooee 814 Nearly a Posting Maven

If you are too lazy to read the rules of the forum and have waited until the very last minute, then there is little chance of a reply.

woooee 814 Nearly a Posting Maven

Dictionary keys have to be unique, so if you try to add a key that is already in the dictionary, it will not add a new key but write over the existing key, so add some code to test if the key already exists in the dictionary and print a message if it does. Finally, this code does not add to the dictionary on each pass through the loop but only adds the final pass, and I can't tell from the code if that is what you want to do or not so can't give any more help.

for b in miau2:
    print (b + '\n\n')
    l2.write(b + '\n\n')
    g +=1
 
dic[b]=i
woooee 814 Nearly a Posting Maven

but I want to try dev-ing a GUI w/o using even Tkinter

A book that is quite dated, but on the other hand probably inexpensive as a result, that describes how to access video memory and put pixels on the screen one at a time as any of the GUI tool kits like Tkinter do, is Herbert Schildt's "The Craft of C". Note that none of this is possible using Python, and even with C you have to drop down into assembly for the actual access to the video memory AFAIK, for security reasons among others. I have not had a desire to do any more of this since the age of GUI tool kits though.

woooee 814 Nearly a Posting Maven

See "List operations" here.

woooee 814 Nearly a Posting Maven

because the window doesn't go to the front

You possibly want to provide a takefocus=True parameter, but I have no idea what widget you mean by "window". Without code your questions make no sense. Both SMTP and webbrowser work on my Slackware box.

woooee 814 Nearly a Posting Maven

The thing does not work at all from IDLE

You can not run Tkinter apps in IDLE as IDLE is written in Tkinter and it falls and can't get up.

woooee 814 Nearly a Posting Maven

The functions have to receive a reference to "self" to be part of the class. Also, the indentation is not correct, and the indentation starting with spin.terminate() is screwy as well. Something along these lines is closer but I can not test it right now.

class MyProg() :
 
    def __init__(self) :
            builder = gtk.Builder()
            builder.add_from_file("blahblah.glade")
 
            self.mainWindow = builder.get_object("mainwindow")
            self.doneWindow = builder.get_object("donewindow")
            builder.connect_signals(self)
 
            spin = Process(target=self.startSpinner(), args=())
            spin.start()
 
            cop = Process(target=self.do_something(), args=(x, y))
            cop.start()
 
    def on_button_clicked(self, widget, data=None) :
                spin.terminate()
                cop.terminate()
                self.doneWindow.show()

    def startSpinner(self) :
        # Code to start the spinner and show a "Please wait" message.
        while self.running:     ## conditioned by the variable set in do_something()
            #update spinner 

    def do_something(self, x, y) :
        # How can I know when the do_something function is finished?
        self.running=True

        # Code (Copy files)
         
        self.running=False 
        # shut down GUI = call self.on_button_clicked() ??

if __name__ == '__main__' :
    myprog = MyProg()
    myprog.mainWindow.show()
    gtk.main()