Wonder why you did that:
noun1 = noun
verb1 = verb
adjective1 = adjective
moan = sound_disgust
You had perfectly good variable names already.
Wonder why you did that:
noun1 = noun
verb1 = verb
adjective1 = adjective
moan = sound_disgust
You had perfectly good variable names already.
A while ago our friend "a1eio" suggested the Python tutorial at http://bembry.org/technology/python/index.php
I liked that one! Very good for Python starters!
There are modules like numpy, that do high speed array and matrix manipulations. Google for numpy, its free.
Nice little song! This is how you make things wait for a few seconds:
# by Christopher O'Leary
# The death of Charlie!
import time
def print_charlieVerse():
print "Charlie was a pidgeon, a pidgeon, a pidgeon."
print "Charlie was a pidgeon, a pidgeon that flew."
print "He flew in the morning, he flew in the night."
print "And when he came home he was covered in ..." # covered in what?
print
n = 0
while n < 10:
print_charlieVerse()
n = n + 1
time.sleep(5) # sleep/wait 5 seconds
print "This song is annoying, annoying, annoying."
time.sleep(2)
print "This song is annoying, that much is true."
time.sleep(2)
print "It pisses me off, how about you?"
time.sleep(2)
print "If one more verse happens he will not sur ..." # survive?
time.sleep(4)
print "CHARLIE WAS A PIDGEON, A PIDGEON, A PIDGEON!"
time.sleep(4)
print "CHARLIE WAS A PIDGEON, A PIDGEON I SHOT!"
Richard Gruet has very good quick-reference of Python on his home page:
http://rgruet.free.fr/
The reference can be downloaded as HTML, zipped HTML or PDF file. It is in English.
Yes, wrap your Python code into these code tags to have it show up correctly indented on DaniWeb. I started Python about one year ago, but have used C/C++ much longer.
Please bring up any of your code question here on the forum, so others can help and learn too!
Usually memory is saved by keeping data in files. In your case, you would have to keep data in memory using module StringIO. That is swimming upstream.
You could compress your datafile with methods in module zipfile or better tarfile. That will speed up loading time.
A more foolproof way would be to loop each data entry like this:
# let's say your attacking army can be from 1 tp 100
# keeps looping until entry is acceptable
aArmy = 0
while aArmy < 1 or aArmy > 100:
try:
aArmy = input("Enter the size of the attacking army (1 to 100): ")
except NameError: # a letter is entered
aArmy = 0
print aArmy
Looks like first thing you need to add is menu loop to add, edit, search data, also exit program should be in loop.
Took the liberty to put your code into code tags, added some remarks:
import shelve
import string
UNKNOWN = 0
HOME = 1
WORK = 2
FAX = 3
CELL = 4
class Phoneentry: # by convention class names start with capital letter
def __init__(self, name='Unknown', number='Unknown', type=UNKNOWN):
self.name = name
self.number = number
self.type = type
# create string representation
def __repr__(self):
return('%s:%d' % ( self.name, self.type ))
# "fuzzy" compare of two items
def __cmp__(self, that):
this = string.lower(str(self))
that = string.lower(that)
if string.find(this, that) >= 0:
return(0)
return(cmp(this, that))
def showtype(self):
if self.type == UNKNOWN: return('Unknown')
if self.type == HOME: return('Home')
if self.type == WORK: return('Work')
if self.type == FAX: return('Fax')
if self.type == CELL: return('Cellular')
class Phonedb:
def __init__(self, dbname = 'phonedata.slv'): # added ext .slv
self.dbname = dbname;
self.shelve = shelve.open(self.dbname);
def __del__(self):
self.shelve.close()
self.shelve = None
def add(self, name, number, type = HOME):
e = Phoneentry(name, number, type)
self.shelve[str(e)] = e
def lookup(self, string):
list = []
for key in self.shelve.keys():
e = self.shelve[key]
if cmp(e, string) == 0:
list.append(e)
return(list)
# if not being loaded as a module, run a small test
if __name__ == '__main__':
foo = Phonedb()
foo.add('Sean Reifschneider', '970-555-1111', HOME)
foo.add('Sean Reifschneider', '970-555-2222', CELL)
foo.add('Evelyn Mitchell', '970-555-1111', HOME)
print 'First lookup:'
for entry in foo.lookup('reifsch'):
print '%-40s %s (%s)' % ( entry.name, entry.number, entry.showtype() ) …
Which version of wxPython did you install?
Here is site that seems to have many difficult install questions/answers for wxPython:
http://lists.wxwidgets.org/cgi-bin/ezmlm-cgi/11
For image files I would stick with binary file operation, it can handle text too. Here is example:
# typical image header
str1 = \
"""BANDS = 1
BAND_STORAGE_TYPE = BAND_SEQUENTIAL
BAND_NAME = "N/A"
LINES = 2240
LINE_SAMPLES = 3840
SAMPLE_TYPE = UNSIGNED_INTEGER
SAMPLE_BITS = 8
END
~~now starts binary image data~~
"""
filename = "mc03.img"
# write test image file
fout = open(filename, "wb")
fout.write(str1)
fout.close()
# read image file line by line
for line in open(filename, "rb"):
if 'END' in line:
break
if 'LINES' in line:
# remove trailing newline
line = line.rstrip('\n')
# extract integer value
print int(line.split('=')[1]) # 2240
For learning about Python and XML see this website:
http://pyxml.sourceforge.net/topics/howto/xml-howto.html
For GUI package for Python I would use wxPython. It is much more powerful than Tkinter.
Python is useful for just about anything you are interested in. Things like scientific calculations, problem solving, working with databases, networking, WEB programming, audiovisual processing, text processing and many more.
Take short look at "Projects for Beginners"
http://www.daniweb.com/techtalkforums/thread32007.html
and Python code snippets on Daniweb.
http://www.daniweb.com/code/python.html
Is there a way to verify an exit, if you click on the exit symbol on a wxPython frame?
I left a short example in code snippet area:
http://www.daniweb.com/code/snippet526.html
"Beautiful Soup" is an HTML/XML parser for Python that can turn even poorly written markup code into a parse tree, so you can extract information.
Download the free program and documentation from:
http://www.crummy.com/software/BeautifulSoup/
If you insist writing your own destructor for class Tree, change it to this:
class Tree:
def __init__(self):
self.Root = None
def __del__(self):
if self.Root != None:
del self.Root
def LNR(self):
...
...
Note: Destructors are optional thing in Python.
This was not a dumb question! It was a question that needed to be asked! So, thanks for asking it and answering it!
Helena is lucky to have her own programmer! I too had Windows problem and solved it by putting message in label. I couldn't help myself, just had to add some colour. I hope Helena is not colorblind. I also show you how to bind the return key. Here is your program with some colour:
from Tkinter import *
import tkMessageBox
import random
#import string # not needed!
def ask():
global num1
num1 = random.randint(1, 12)
global num2
num2 = random.randint(1, 12)
global answer
answer = num1 * num2
label1.config(text='What is ' + str(num1) + 'x' + str(num2) + '?')
# put the cursor into the Enter-Box
entry1.focus_set()
def checkAnswer():
herAnswer = entry1.get()
# if empty give message
if len(herAnswer) == 0:
tkMessageBox.showwarning(message='Need to enter some number!')
return
if int(herAnswer) != answer:
tkMessageBox.showwarning(message='The answer is: ' + str(answer))
else:
tkMessageBox.showinfo(message='Correct!')
#set the window
root = Tk()
# add some color
root.tk_bisque()
root.title("Helena's Multiplication Quiz")
root.geometry('500x500')
# replaces tkMessageBox.showinfo()
label2 = Label(root, text="Hi, Helena!\n Let's do some multiplication problems!")
# add a colorful font
label2.config(font=('times', 18, 'bold'), fg='red', bg='yellow')
label2.grid(row=0, column=0)
#add label
label1 = Label(root)
label1.grid(row=2, column=0)
#add entry
entry1 = Entry(root)
entry1.grid(row=3, column=0)
# bind the return key
entry1.bind('<Return>', func=lambda e:checkAnswer())
#add button
askBtn = Button(root, text='Ask Me a Question!', bg='green', command=ask)
askBtn.grid(row=4, column=0)
okButton = Button(root, text='OK', command=checkAnswer)
okButton.grid(row=4, column=1)
# seems to create a problem with the entry1 focus in Windows, replace with label2
#tkMessageBox.showinfo(message="Hi, Helena! Let's do some multiplication problems!")
root.mainloop()
Please show your code. It makes it tough to help without it. Others too can learn from your code and the answers.
This would be one way to bind Entry box enter1 to return key:
enter1.bind('<Return>', func=my_function)
The data is then in enter1.get() as a string.
A kbyte is 1024 bytes. This would be more correct:
fsize = os.path.getsize(fname)
print "size = %0.1f kb" % float(fsize/1024.0)
I assume you want to sum numeric values. Here is slight modification, also removing return statement out of the loop:
def three2one(prot):
code = {"G" : "6", "A" : "7", "L" : "1", "I" : "4",
"R" : "2", "K" : "3", "M" : "5", "C" : "8",
"Y" : "9", "T" : "10", "P" : "11", "S" : "12",
"W" : "14", "D" : "15", "E" : "16", "N" : "17",
"Q" : "18", "F" : "19", "H" : "20", "V" : "21" , "R" : "22"}
newprot = 0
for aa in prot:
newprot += int(code.get(aa))
print newprot # just for testing
return newprot
prot ="""FGYYHFRPTKLRQWEI"""
# split this up to make testing go better
result = three2one(prot)
print "result =", result
>>> a = "string"
>>> b = "string"
>>> id(a)
11147264
>>> id(b)
11147264
"string" is really the object here, an immutable object, so both a and b reference the same object. Now, if you use "string ", then string with a space is a different and new object.
In the case with the two lists, you have a mutable object that can be changed in place, like you could reverse list1 but not list2. For that reason list1 and list2 have different references.
Hey vega, that works pretty smooth!
If you have two lists like
list1 = [1, 2, 3]
list2 = [1, 2, 3]
then
list1 == list2 is True, they have equal content
but
list1 is list2 would give False, they are not the same object.
Which Python GUI kit are you using?
What is your operating system?
Well, I can help with the startButton text:
def dieSimulator():
startButton.configure(text="Restart")
# rest of your code .......
Have you checked into function reload(my_module)?
What happened to your indentations?
Give me an example of your list.
Also, wouldn't use list as variable name since list() is built-in function, just as len().
Could you enlighten me, what is this all used for?
Actually, I like your friend's solution. You can easily expand it to bring up the widget's name:
# which widget has been clicked?
from Tkinter import *
root = Tk()
root.title('Click on ovals')
canvas1 = Canvas()
canvas1.pack()
def func1(event):
print widget_list[canvas1.find_withtag(CURRENT)[0]-1]
oval1 = canvas1.create_oval(10, 30, 40, 50, fill='red', tags='click')
oval2 = canvas1.create_oval(50, 70, 80, 90, fill='blue', tags='click')
oval3 = canvas1.create_oval(90, 110, 120, 130, fill='green', tags='click')
widget_list = ['oval1', 'oval2', 'oval3']
# left mouse click = '<1>'
canvas1.tag_bind('click', '<1>', func1)
mainloop()
What operating system do you have?
Did you install proper version of wxPython?
I have Windows XP and my wx package is in
C:\Python24\Lib\site-packages\wx-2.6-msw-unicode\wx\__init__.py
Here is a simple sample of wxPython code:
import wx
class MyFrame(wx.Frame):
def __init__(self):
# create a frame/window, no parent, default to wxID_ANY
wx.Frame.__init__(self, None, wx.ID_ANY, 'wxPython', pos=(300, 150), size=(300, 350))
self.SetBackgroundColour('green')
# show the frame
self.Show(True)
application = wx.PySimpleApp()
# call class MyFrame
window = MyFrame()
# start the event loop
application.MainLoop()
You have to set widget for name to come up. At the moment I don't quite know how, I don't have my notes along.
Given featureList = what do you expect as result?
Please give complete result.
Can you give sample of the first ten lines of each file?
If the lines match (word and number), then you can read in one line from each file at a time, process and write/append back out.
I started playing with code from you and came to this conclusion:
# want 'abc' to generate a list [['a','bc'],['bc','a'],['c','ab'],['ab','c'],['b','ac'],['ac','b']]
def gensubset(colocation):
rulesList= []
length = len(colocation)
for i in range(0,length):
rule1 = [colocation[i:i+1],colocation[i+1:length]]
rule2 = [colocation[i+1:length],colocation[i:i+1]]
rulesList.append(rule1)
rulesList.append(rule2)
return rulesList
colocation = 'abc'
sublist = gensubset(colocation)
# not quite there yet, also when i+1 exceeds index you get empty elements ''
print sublist # [['a', 'bc'], ['bc', 'a'], ['b', 'c'], ['c', 'b'], ['c', ''], ['', 'c']]
To use slicing to create for example 'ab' or 'ac' you need to add more to rules you use:
str1 = 'abc'
length = len(str1)
i = 0
print str1[i:length-1] # 'ab'
print str1[i:i+1] + str1[i+2:length] # 'ac'
I don't see these type of slices in rules you have written.
This is cool, so initially list1[0] is zero to start the count!
How can you wrap that into a normal bread and butter function?
You put program code in a loop and designate one key to break out of loop:
while True:
# this is an example of your program:
print
print "My program! Really!"
print
choice = raw_input("Enter r (repeat) or q (quit): ")
if 'q' in choice:
break # exits the while loop, any other key repeats loop
Sorry, this is little clumsy, but I am using good friend's notebook in busy coffee shop. I hope this explains what you want to do:
# list of lists
list1 = [['a', 1], ['b', 2]]
# list of numbers
list2 = [44, 77]
# convert list of lists to a tuple of tuples using list comprehension
tuple1 = tuple([tuple(sublist) for sublist in list1])
print tuple1 # (('a', 1), ('b', 2))
# create a dictionary from a tuple and a list using zip()
# the tuple forms the key and the list forms the value
dict1 = dict(zip(tuple1, list2))
print dict1 # {('a', 1): 44, ('b', 2): 77}
is an invalid construct and gives a syntax error!
Do you mean dictionary {'a': 1,'b': 2} ?
If you want the same data/info in a tuple you could use (('a', 1),('b', 2)) and later on ...
# convert tuple of tuples to dictionary
print dict((('a', 1),('b', 2))) # {'a': 1, 'b': 2}
You need to give more details of what you want to accomplish.
At first look, there are quite a few errors in your code. Your indentations are a mess (they are not cosmetic, they actually form statement blocks in Python!), if needs == as comparison operator, for needs colon at the end of line, and pruned_new has to be initiated as empty list.
Indentations are the bread and butter of Python. Yours are all messed up! Did you mix tabs and spaces in your code? Avoid the mix!
This is corrected code:
def get_colocations(filename):
sentences = open(filename).read().split("\n")
colocations = []
for sent in sentences:
colocations.append(sent)
return colocations
def main():
colocations = get_colocations("colocations.txt") # !!!!!!!!!
print "Colocations are",colocations
main()
Dictionary keys have to be immutable objects. Lists are mutable objects. Comvert all the lists to tuples.
I don't have linux OS on my machine, but fail to understand why wxPython should bring up a gtk error?
Also, is gdk and gtk a mix up?
Please use code tags around your Python code to show proper indentations, take a look here:
http://www.daniweb.com/techtalkforums/announcement114-3.html
All statement lines that belong to while loop get an indentation of 4 spaces (4 is traditional with Python code). I have removed main() as that is throwback to C. Also wrap your code in code tags,see:
http://www.daniweb.com/techtalkforums/announcement114-3.html
print "This program calculates how long it takes for an investment to double in size."
print
investment = 1000 #initial investment
rate = input("Please enter the applicable interest rate: ") #interest rate input
years = 0 #sets years to zero
value = investment
while value <= investment*2: #defines loop sentinel
value = value + value*((float(rate)/100)) #calculates investment
years = years + 1 #adds a year for every loop
print "The investment doubles in",years,"years" #prints the years it took to double the investment
raw_input("Press enter to go on ...") # optional console wait
Also, some of your statement lines are so obvious that comment is simply not needed, or is distraction at best!
OK Ene,
pretty smooth! I used
if next_day.weekday() == 4 and next_day.day == 13:
after reading through help("datetime")
How did you know my first name was Henri?
Hi Ene, looks like you are working on Friday the 13th project. It took me a while, but I solved it. I can give you a hint, replace the line
print next_day
with this expanded line
print next_day, "day of week =", next_day.weekday()
The week starts with Monday = 0 that means Friday = 4
Have fun!
...
Also, why are you using self.button1 = Button( ... ) and not just button1 = Button( ... )?
The self. prefix makes the button global within the class, so it can be used by methods of the class.
Im sort of new to python, and I have been looking at some tutorials, manuals, etc. and I saw how to find prime numbers, so I thought it would be a good place to start, so I added some stuff to hopefully allow for user input, and it doesnt work.
>>> z=input('please enter the lowest number to search for prime numbers from') if z<=1: z=2 print "low value changed to 2" >>> y=input('please enter the highest number to search for prime numbers to') >>> for n in range(z, y): for x in range(z, n): if n % x == 0: break else: # loop fell through without finding a factor print n, 'is a prime number'
What am I doing wrong?
Please use editor or IDE to write program, using the shell with the >>> prompts makes it hard to test your program for most of us. Here is my correction:
z = input('please enter the lowest number to search for prime numbers from ')
if z <= 1:
z = 3
print "low value changed to 3"
y = input('please enter the highest number to search for prime numbers to ')
for n in range(z, y+1): # range to include y
for x in range(2, n): # x starts with 2 !!!!!!!!!!
if n % x == 0:
break
else:
# else belongs to for, loop fell through without finding a factor
print n, 'is a prime number'
I am sorry I was out and so could not reply in time
what exactly i am looking for is in reverse way
is it possible to define test_path = "test1234" in testing module
and can be accessed by test1.pyso that i can provide some browsing interface for file path selection for
test_path in testing fileThank you for the reply
You could save test_path info in file that is opened by test1.py every time it is imported/ativated. Make sure there is default path, in case the file does not exist.