If anyone figures out a different way to sort by word length, or form a unique word list, please attach your code to this thread! Would be fun to see your ideas!!!!!
If anyone figures out a different way to sort by word length, or form a unique word list, please attach your code to this thread! Would be fun to see your ideas!!!!!
There are several ways to do this.
First use a for loop, word.lower() and list2.append(word) to create a new list2 from list1 with all lower case words.
Now you can convert list2 to a set with set1 = set(list2) which by design has only unique words. Convert this back to a list with list3 = list(set1). Use print in each case to check your interim results.
You can also construct the for loop so that you only append the lowercase word if its not already in list2. Then you don't need to do the set() stuff.
Vegaseat makes you think, doesn't he?
Oh, one of Vegaseat's brain teasers. There are several ways to solve this. If you look in the Python reference manual under sort for lists, you find that you can specify your own custom sort method. In this case it would be sorting by length of each word/string in the list. Here is an example:
list1 = ['Herring','used','to','be','abundant','in','the','Atlantic','Ocean','then','herring','got','overfished']
print "Original list1:"
print list1
print
print "Using list1.sort(), which is case sensitive sort:"
list1.sort()
print list1
print
print "using list1.sort(key=str.lower), makes a case insensitive sort:"
# actually compares everything as all lower case
list1.sort(key=str.lower)
print list1
print
print "Reverse the last list using list1.reverse()"
list1.reverse()
print list1
print
print "Sort list1 by length of word, short to long:"
def bylength(word1, word2):
"""
write your own compare function:
returns value > 0 of word1 longer then word2
returns value = 0 if the same length
returns value < 0 of word2 longer than word1
"""
return len(word1) - len(word2)
# change the compare method of sort
list1.sort(cmp=bylength)
print list1
I have added some comments, please study it carefully and experiment with it until you undertand fully.
Good! The try/except is part of error checking you will tackle next.
What it does in the above code is the following, it tries to load the data file, if there is an error like a missing data file, it does the except part. In the except part you can be more specific about the exact error. Well anyway, have fun learning Python.
Watch out when you start your program that your basic students dictionary does not override the newly loaded dictionary. Here is your code sample that works:
import pickle
max_points = [25,25,50,25,100]
assignments = ["hw ch 1","hw ch 2","quiz ","hw ch 3","test"]
try:
file = open("students.dat", "r")
students = pickle.load(file)
file.close()
except:
students = {"#Max":max_points}
print "students.dat file not found, starting with", students
def print_menu():
print "1. Add student"
print "2. Remove student"
print "3. Print grades"
print "4. Record grade"
print "5. Exit"
def print_all_grades():
print "\t",
for i in range(len(assignments)):
print assignments[i],"\t",
print
keys = students.keys()
keys.sort()
for x in keys:
print x,"\t",
grades = students[x]
print_grades(grades)
def print_grades(grades):
for i in range(len(grades)):
print grades[i],"\t\t",
print
print_menu()
menu_choice = 0
while menu_choice != 5:
print
menu_choice = input("Menu Choice (1-6): ")
if menu_choice == 1:
name = raw_input("Student to add: ")
students[name] = [0]*len(max_points)
elif menu_choice == 2:
name = raw_input("Student to remove: ")
if students.has_key(name):
del students[name]
else:
print "Student: ",name," not found"
elif menu_choice == 3:
print_all_grades()
elif menu_choice == 4:
print "Record Grade"
name = raw_input("Student: ")
if students.has_key(name):
grades = students[name]
print "Type the number of the grade to record"
print "Type a 0 (zero) to exit"
for i in range(len(assignments)):
print i+1," ",assignments[i],"\t",
print
print_grades(grades)
which = 1234
while which != -1:
which = input("Change which Grade")
which = which-1
if 0 <= which < len(grades):
grade = input("Grade: ")
grades[which] = grade
elif which != -1:
print "Invalid Grade Number"
else:
print …
Since you want to save and later load an entire container object, the module pickle is what you want to use. Hre is a simple example:
# pickle saves and loads any Python object intact
# via a byte stream, use cpickle for higher speed
import pickle
myList1 = [12, 52, 62, 02, 3.140, "Monte"]
print "Original list:"
print myList1
file = open("list1.dat", "w")
pickle.dump(myList1, file)
file.close()
file = open("list1.dat", "r")
myList2 = pickle.load(file)
file.close()
print "List after pickle.dump() and pickle.load():"
print myList2
In your case you would pickle the students dictionary!
I agree! Since you are just going down the line with the same variable, if/elif makes more sense IMHO. The if/elif ties the conditional together.
Lint Filters give warnings that are not always sensible. Using elif instead of all if is faster, since Python has to evaluate all the if, but stops at the first true elif condition.
In your case it doesn't make much difference since you have a return statement, which will stop Python from going through the rest of the if conditionals. So 'if' is less to type than 'elif'.
Write a Python program using the Tkinter GUI that shows a series of buttons with the names of your favorite programs. Click the button to launch the program. Would be great for all your games on the PC.
I think bash is a script language on Linux computers. I don't use Linux (yet), so I can't test it, but the program flow is easy to follow. The first part is a menu from which you select, and the second part is a case statement that activates a slected program on Linux.
Python does not have a case statement, but you can use a series of if/elif condionals or a dictionary made to look like a case statement. To run an external program from Python, you can use os.system("program")
Here is a simplified version in Python:
import os
while True:
print
print "PROGRAM MENU"
print "1 - open xmms"
print "2 - open emacs"
print "3 - open gparted"
print "4 - open gedit"
print "5 - open firefox"
print "6 - open gaim"
print "7 - open kopete"
print "8 - open console"
print "0 - exit program"
print
selection = input("Enter selection: ")
if selection >= 0:
break
if selection == 0:
raise SystemExit
elif selection == 1: os.system("xmms")
elif selection == 2: os.system("emacs")
elif selection == 3: os.system("sudo gparted")
elif selection == 4: os.system("gedit")
elif selection == 5: os.system("firefox")
elif selection == 6: os.system("gaim")
elif selection == 7: os.system("kopete")
elif selection == 8: os.system("konsole")
You can use function sys.exc_info() to fetch the error created by my_program.py:
# save as my_file.py
# executes a file my_program.py which has an error
from Tkinter import*
import sys
root=Tk()
text=Text()
text.pack()
try:
execfile('my_program.py')
except:
error = "%s --> %s in file my_program.py"% (sys.exc_info()[0], sys.exc_info()[1])
# put error msg raised by my_program.py into text field
text.insert(END, error)
mainloop()
I am always surprised by the things Python can do! Have fun with Python!
Write a program that maintains a list of things you have to do, want to do, should have done and have done. You ought to be able to sort this list by importance, time left, and certain keywords amongst other things. You get the drift! Could be a great time organizer.
If you get confused with the builtin functions input() and raw_input() (Who came up with raw_input anyway?), you can change the names of these functions in your program to something you understand better:
input_str = raw_input
input_int = input
# now you can use ...
name = input_str("Enter your name: ")
age = input_int("Enter your age: ")
print "Hi %s, you are %d old!" % (name, age)
# or if this is more readable use this ...
print "Hi %(name)s, you are %(age)d old!" % vars()
Just a few observations, hope you don't mind:
1) Python has True = 1 and False = 0 builtin
2) define your functions outside of the conditional if, or Python will redefine your functions whenever you take a test. This would slow down the program. The memory manager cleans up properly though.
3) use a try/except to protect against non numeric entries
Here is the code sample updated:
#true = 1 # Python has True = 1
#false = 0 # Python has False = 0
def get_questions(x = -1):
lista = [["What colour is the daytime sky on a clear day?","blue"],
["What is the answer to life, the universe and everything?","42"],
["What is a three letter word for mouse trap?","cat"],
["What noise does a truly advanced machine make?","ping"]]
if x == -1:
return lista
else: #of course, it's recommended to check if x is out of bounds
return lista[x]
def check_question(question_and_answer):
question = question_and_answer[0]
answer = question_and_answer[1]
given_answer = raw_input(question)
if answer == given_answer:
print "Correct"
return True
else:
print "Incorrect, correct was: ",answer
return False
def run_test(questions):
if len(questions) == 0:
print "No questions were given."
return
index = 0
right = 0
while index < len(questions):
if check_question(questions[index]):
right = right + 1
index = index + 1
print "You got ", right*100/len(questions),"% right out of",len(questions)
menu_item = 0
while menu_item != 9:
print "------------------------------------"
print "1. Take test"
print "2. Display all questions and answers."
print "9. quit"
try:
menu_item = …
This goes along with vegaseat's Python code riddles. Hide your email address in Python code like this clever example shows:
print "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz")
I have put together a dictionary of the Morse code:
morseDict = {
'A': '.-',
'B': '-...',
'C': '-.-.',
'D': '-..',
'E': '.',
'F': '..-.',
'G': '--.',
'H': '....',
'I': '..',
'J': '.---',
'K': '-.-',
'L': '.-..',
'M': '--',
'N': '-.',
'O': '---',
'P': '.--.',
'Q': '--.-',
'R': '.-.',
'S': '...',
'T': '-',
'U': '..-',
'V': '...-',
'W': '.--',
'X': '-..-',
'Y': '-.--',
'Z': '--..'
}
# test it
print morseDict
Write a Python program that takes a text string and converts it into a string of Morse code characters separated by a space.
If you have a PC with Windows OS, then you can sound off this string on the internal speaker:
# if you have a computer using Windows you can
# sound a morse code string off on the internal computer speaker
# using winsound.Beep(frequency-cps, duration-ms)
# you can experiment with tone frequency and duration
import winsound
import time
morseStr = "--.. ..- .-.. ..-" # ZULU
for c in morseStr:
print c
if c == '-':
winsound.Beep(800, 500)
elif c == '.':
winsound.Beep(800, 100)
else:
time.sleep(0.4) # rest between each letter
time.sleep(0.2) # rest between each dash/dot
A much more complicated project would be to catch Morse code (microphone?) and convert into an alphabetic string.
I go for a grilled panini sandwich with chicken, spinach and mushrooms.
Version 2.5 of Python final release is planned for 12sep2006. It will have a few nice improvements. On of them is class partial. Bumsfeld has talked about adding arguments to GUI callback functions earlier. This new class will help. Here is a fun example that can be used with Python 2.4:
# class partial is similar to currying to add arguments
# starting with Python 2.5 you can simply import class partial
# using: from functools import partial
from Tkinter import Tk, Canvas, Button
class partial(object):
"""partial application using both positional and keyword arguments"""
def __init__(*args, **kw):
self = args[0]
self.fn, self.args, self.kw = (args[1], args[2:], kw)
def __call__(self, *args, **kw):
if kw and self.kw:
d = self.kw.copy()
d.update(kw)
else:
d = kw or self.kw
return self.fn(*(self.args + args), **d)
root = Tk()
c = Canvas(root,width=200,height=50)
c.pack()
color_list = ['red','blue','green','yellow','black','white']
for color in color_list:
# uses class partial to construct callbacks for Tkinter widgets
# called as though it were a function
# basically passes/implements c.config(bg=color)
b = Button(root, text=color, command=partial(c.config, bg=color))
b.pack(side='left')
root.mainloop()
Edit: A correction has been made, in the final production release of Python 2.5 partial() is in module functools.
To find experiments with the Python random module see:
http://www.daniweb.com/code/snippet306.html
For loops and function range() are covered in:
http://www.daniweb.com/code/snippet386.html
You can search the Python snippets and this forum for other things like lists, strings, dictionaries, tuples, file handling and so on.
Different text types are the realm of GUI programming with Tkinter for instance.
Here is an example of a Tkinter GUI program that sets a text font and uses random:
# display random sentences from a list using colorful Tkinter
from Tkinter import *
import random
black = '#000000'
blue = '#0000FF'
red = '#FF0000'
yellow = '#FFFF00'
lime = '#00FF00'
sentenceList = [
'the dog is on skates',
'the bird is on a plane',
'the pig rides the horse',
'the snake is on rollerskates',
'the fish drives a car']
def setText():
str1 = random.choice(sentenceList)
push1.config(text=str1)
#create the form
form1 = Tk()
# set the form's title
form1.title('Random Text')
# create a button
push1 = Button(form1, text='Click to set new text .............', command=setText)
# configure the button's text font and foreground/background colors
push1.config(height=3, font=('times', 20, 'bold'), fg=black, bg=yellow)
# pack the button into the frame
push1.pack(expand=YES, fill=BOTH)
# start the event loop (run the program)
form1.mainloop()
A good tutorial for beginners is in this online book:
http://www.ibiblio.org/g2swap/byteofpython/read/
Thank you vegaseat and azimuth0. I have to play with that for a while to comprehent it. By the way, vegaseat's code is Python put into a PHP code field to give it some color highlighting (use a PHP tags instead of CODE).
The word game Scrabble has a total of 100 letter tiles. I listed a dictionary of the letters in the game showing the letter and a tuple containng the frequency of the letter and its value.
# scrabble letter (frequency, value) total 100 tiles
# from http://thepixiepit.co.uk/scrabble/rules.html
scrabbleD = {
'A': (9, 1),
'B': (2, 3),
'C': (2, 3),
'D': (4, 2),
'E': (12, 1),
'F': (2, 4),
'G': (3, 2),
'H': (2, 4),
'I': (9, 1),
'J': (1, 8),
'K': (1, 5),
'L': (4, 1),
'M': (2, 3),
'N': (6, 1),
'O': (8, 1),
'P': (2, 3),
'Q': (1, 10),
'R': (6, 1),
'S': (4, 1),
'T': (6, 1),
'U': (4, 1),
'V': (2, 4),
'W': (2, 4),
'X': (1, 8),
'Y': (2, 4),
'Z': (1, 10),
'blank': (2, 0)
}
# test it ...
print "%6s %6s %6s" % ("letter", "freq", "val")
print "-"*24
for letter, (freq, val) in scrabbleD.iteritems():
print "%6s %6s %6s" % (letter, freq, val)
You can use this information to write a Python program to play Fastscrabble, a variation of the game that can be played without a board. The rules are simple:
All 100 tiles are laid on the table face down.
Each player takes a turn to expose one tile.
If any player can make a word from any of the exposed tiles, he/she says "scrabble", sets the tiles of the word aside, and counts the values to his/her score.
Players who yell "scrabble" and …
This little code gives you the hour, minute and second of the present time:
# get just hr, min, sec of present time tuple:
import time
hr, min, sec = time.localtime()[3:6]
print hr, min, sec
Use this to create an alarm timer in Python that plays a wave sound file when the set alarm time has been reached.
If you have similar text files, write a program that shows which lines of text are different. Hint: module difflib has a few tricks up its sleeves.
Thanks for thinking out loud, I found it interesting!
Once you go to GUI programming, your approach has to change past just making labels. User actions are initiated by clicking on buttons, data is entered in an entry widget, results and messages can be displayed in labels.
Get used to callback functions. Also, you might as well start a class Risk, so variables are transferred properly via the self. prefix. Just a little extra learning curve here! GUI programming is not too hard, just a mildly different way of thinking
Thanks Vega,
works like a charm, got to keep playing with it.
What is a closure? I keep reading this word in programming, but never got a good explanation.
Wow! Your code is hard to read!
See Dani's remarks at: http://www.daniweb.com/techtalkforums/announcement114-3.html
The common way to save data each time you use a program is to save it to a data file. Then bring in the latest saved data each time the program is run. If you want to save data as an object like a complete list, use the module pickle or cpickle.
I think your trouble comes from the fact that Python itself actually has a module Queue. Rename your module MyQueue.py and it works just fine.
This small code shows you all the modules Python has installed:
help("modules")
To avoid conflicts give your own modules a prefix like "my"or "My".
Thank you Vega!
How long will you be on the road?
Hey thanks Henri! Nice code!
I am looking for a good example of the tarfile module, writing to and reading from an archive. Particularly the highly compressed filename.tar.bz2 format.
If you want to create a unique filename in a given folder use the Python module tempfile:
import tempfile
# creates a random file (text=True is textfile, text=False is binary file)
ext = '.txt'
pfx = 'tmp'
dir = 'C:\\Temp'
filename = tempfile.mkstemp(suffix=ext, prefix=pfx, dir=dir, text=True)[1]
print filename # eg. C:\Temp\tmpsnrfgk.txt
# test it ...
fout = open(filename, 'w')
fout.write("Just a text file")
fout.close()
Is there a way to verify an exit, if you click on the exit symbol on a wxPython frame?
Does anyone have a good example of a wx.FlexGridSizer() application.
This short code finds all files in a given drive or folder/directory that end with a selected file extension. It also checks all the subdirectories:
import os
# pick a folder or drive
folder = 'C:\\'
# pick a file extension
extension = ".css"
print "All files in %s ending with %s :" % (folder, extension)
file_list = []
for (paths, dirs, files) in os.walk(folder):
for file in files:
if file.endswith(extension):
# show progress
print '.',
file_list.append(os.path.join(paths, file))
print
for full_filename in file_list:
print full_filename
Write a program to show all the files in a given drive that have been modified in the last 24 hours.
You mean something like that:
# write out each text containing line
# (other than '\n') to a separate file
str1 = """sentence one
sentence two
sentence three
"""
# write str1 to the test file
fout = open("test.txt", "w")
fout.write(str1)
fout.close()
# read the test file as a list of lines
fin = open("test.txt", "r")
list1 = fin.readlines()
fin.close()
print list1 # just testing
n = 0
for line in list1:
if len(line) > 1:
n += 1
filename = "test%d.txt" % n
fout = open(filename, "w")
fout.write(line)
fout.close()
print "%s --> %s" % (line, filename) # just testing
I kind of like this little poem:
The Spell Checker Poem ...
Eye halve a spelling chequer
It came with my pea sea
It plainly marques four my revue
Miss steaks eye kin knot sea.Eye strike a key and type a word
And weight four it two say
Weather eye am wrong oar write
It shows me strait a weigh.
As soon as a mist ache is maid
It nose bee fore two long
And eye can put the error rite
Its rare lea ever wrong.Eye have run this poem threw it
I am shore your pleased two no
its letter perfect awl the weigh
My chequer tolled me sew.
What is your favorite poem?
Display the letters in a text sorted by their frequency of occurance:
import string
# create a list of lower case letters
# ['a', 'b', 'c', 'd', 'e', ... ]
alpha_list = list(string.lowercase)
text = """The Spell Checker Poem ...
Eye halve a spelling chequer
It came with my pea sea
It plainly marques four my revue
Miss steaks eye kin knot sea.
Eye strike a key and type a word
And weight four it two say
Weather eye am wrong oar write
It shows me strait a weigh.
As soon as a mist ache is maid
It nose bee fore two long
And eye can put the error rite
Its rare lea ever wrong.
Eye have run this poem threw it
I am shore your pleased two no
its letter perfect awl the weigh
My chequer tolled me sew.
"""
# convert text to all lower case letters
text = text.lower()
# create a list of (frequency, letter) tuples
tuple_list = []
for letter in alpha_list:
tuple_list.append((text.count(letter), letter))
# sort by frequency (high value first)
tuple_list.sort(reverse=True)
#print tuple_list
# show all letters with frequency above 0
for freq, letter in tuple_list:
if freq > 0:
print letter, freq
"""
result =
e 67
t 33
a 32
r 29
s 26
...
"""
Moderator's note: php tags didn't work properly, replaced them.
Does Python have a module to display when a file has been last modified?
Also, how do you get the file length?
Print a 9x9 diamond shaped pattern like this
*
***
*****
*******
*********
*******
*****
***
*
using loops.
Is there a way to do math with hexadecimal numbers in Python?
In the USA yo have the following currency options:
100 Dollars
50 Dollars
20 Dollars
10 Dollars
5 Dollars
1 Dollar ( the 2 Dollar bill is very rare, ignore it)
25 cents ( the 50 cent coin is rare, also ignore it)
10 cents
5 cents
1 cent
Let's say a customer has a charge of $161.13 and pays with two 100 Dollar bills. Write a Python program to figure out how to pay the customer his change with the least amount of currency items.
Write a program that gives a list of 100 unique random integers in the range of 0 to 999.
The advantage of BF is that it allows you to use the f-word in an academic setting.
Give the idiot an audience of fools. TV is living proof!