First of all, welcome to the forum!
To preserve the code's indentations, please use the [code=python] and [/code] tag pair to enclose your python code.
First of all, welcome to the forum!
To preserve the code's indentations, please use the [code=python] and [/code] tag pair to enclose your python code.
Illustrates the close relationship of the hard-software industry to April first:
#include <nonsense.h>
#include <lies.h>
#include <spyware.h> /* Microsoft Network Connectivity library */
#include <process.h> /* For the court of law */
#define say(x) lie(x)
#define computeruser ALL_WANT_TO_BUY_OUR_BUGWARE
#define soon next_year
#define the_product_is_ready_to_ship another_beta_version
void main()
{
if (latest_window_version>one_month_old)
{
if (there_are_still_bugs)
market(bugfix);
if (sales_drop_below_certain_point)
raise(RUMOURS_ABOUT_A_NEW_BUGLESS_VERSION);
}
while(everyone_chats_about_new_version)
{
make_false_promise(it_will_be_multitasking); /* Standard Call, in
lie.h */
if (rumours_grow_wilder)
make_false_promise(it_will_be_plug_n_play);
if (rumours_grow_even_wilder)
{
market_time=ripe;
say("It will be ready in one month);
order(programmers, stop_fixing_bugs_in_old_version);
order(programmers, start_brainstorm_about_new_version);
order(marketingstaff, permission_to_spread_nonsense);
vapourware=TRUE;
break;
}
}
switch (nasty_questions_of_the_worldpress)
{
case WHEN_WILL_IT_BE_READY:
say("It will be ready in", today+30_days," we're just testing");
break;
case WILL_THIS_PLUG_AND_PLAY_THING_WORK:
say("Yes it will work");
ask(programmers, why_does_it_not_work);
pretend(there_is_no_problem);
break;
case WHAT_ARE_MINIMAL_HARDWARE_REQUIREMENTS:
say("It will run on a 8086 with lightning speed due to"
" the 32 bits architecture");
inform(INTEL, "Pentium sales will rise skyhigh");
inform(SAMSUNG, "Start a new memorychip plant"
"'cos all those customers will need at least 32 megs");
inform(QUANTUM, "Thanks to our fatware your sales will triple");
get_big_bonus(INTEL, SAMSUNG, QUANTUM);
break;
case DOES_MICROSOFT_GET_TOO_MUCH_INFLUENCE:
say("Oh no, we are just here to make a better world for
everyone");
register(journalist, Big_Bill_Book);
when(time_is_ripe)
{
arrest(journalist);
brainwash(journalist);
when(journalist_says_windows95_is_bugfree)
{
order(journalist, "write a nice objective article");
release (journalist);
}
}
break;
}
while (vapourware)
{
introduction_date++; /* Delay */
if (no_one_believes_anymore_there_will_be_a_release)
break;
say("It will be ready in",today+ONE_MONTH);
}
release(beta_version)
while (everyone_is_dumb_enough_to_buy_our_bugware)
{
bills_bank_account += 150*megabucks;
release(new_and_even_better_beta_version);
introduce(more_memory_requirements);
if (customers_report_installation_problems)
{
say("that is a hardware problem, not a software problem");
if (smart_customer_says_but_you_promised_plug_and_play)
{
ignore(customer);
order(microsoft_intelligence_agency, "Keep an eye on this …
You have to let us know a little more, like what operating system are we talking about?
If you just want to remove the first 'n' use:
old = "open sesame nnnn"
# replace first occurance of 'n'
new = old.replace('n', '', 1)
print new # 'ope sesame nnnn'
With a console program that is tough, now you have to invent a gotoxy(x,y) equivalent to put the cursor on the spot and overwrite from there. Maybe module curses has something like that?
The old Turbo C used to have a gotoxy(x,y) function.
I modified mawe's code so you don't have to worry about the date of the day:
# using just time and not date ...
import datetime
lunch_start = datetime.time(11, 30)
lunch_end = datetime.time(12, 45)
now = datetime.datetime.now().time()
# testing
print lunch_start # 11:30:00
print lunch_end # 12:45:00
print now # eg. 09:05:59.750000
# you can compare type 'datetime.time' directly
if lunch_start < now < lunch_end:
print "Hey, it's lunch time! Mahlzeit!!"
elif now < lunch_start:
print "Lunch is pretty soon!"
else:
print "Darn, missed lunch time!!"
No need to blush, we all have made that mistake. Python allows functions to be passed to and from other functions, so all you have to remember is to use the function object and not the function call for the argument. Makes more sense once you look at it that way!
Several things:
Try to give Tkinter and Calendar a namespace, so you know where the functions come from.
Give variables names that don't confuse, like 'l1' looks a lot like '11' in many editors, switching to 'lb1' helps readability.
Please use the [code=python] and [/code] tag pair to enclose your python code.
Here is my suggestion:
# display a monthly calendar in Tkinter
import Tkinter as tk
import calendar as cd
class MyApp(object):
def __init__(self, root, m, y):
self.m = m
self.y = y
self.frame1 = tk.Frame(root)
self.frame1.pack()
str1 = cd.month(self.y, self.m)
font1 = ('courier',14,'bold')
self.lb2 = tk.Label(self.frame1, text=str1, font=font1, bg='yellow')
self.lb2.pack()
self.b1 = tk.Button(self.frame1,text=' - ', bg="green")
self.b1.pack(side=tk.LEFT, padx=3, pady=3)
self.b2 = tk.Button(self.frame1,text=' + ',bg="red")
self.b2.pack(side=tk.RIGHT, padx=3, pady=3)
self.b1.bind("<Button-1>", self.decrease)
self.b2.bind("<Button-1>", self.increase)
root.mainloop()
def increase(self, e):
if self.m == 12:
self.m = 1
self.y = self.y + 1
else:
self.m = self.m + 1
self.lb2['text'] = cd.month(self.y, self.m)
def decrease(self, e):
if self.m == 1:
self.m = 12
self.y = self.y - 1
else:
self.m = self.m - 1
self.lb2['text'] = cd.month(self.y, self.m)
if __name__ == '__main__':
y = 2007
m = 1
root = tk.Tk()
root.title("monthly calendar")
myapp = MyApp(root, m, y)
Yes, the new class style would be
class Book(object):
where object is a place holder for possible inheritance from other class objects.
You define method __str__() within the class:
class Book:
def __init__(self, author, title, price):
self.author = author
self.title = title
self.price = price
def __str__(self):
# overrides print for the instance
text = "%s by %s" % (self.title, self.author)
return text
abook = Book(author = "Amy Doe", title = "Sun rise", price = 13.50)
print abook
Yes, there is a backspace character '\b', but not all IDEs will have the right output window for it:
# backspace twice and overwrite with space
print '1234567\b\b '
raw_input('press enter') # wait
The standard DOS command window will work.
You have the following data statements:
data = """
Jim likes Larry and Jean, but hates Kim.
Bob loves Jean, and likes Larry and Kim.
Jean loves Bob, likes Jim, but hates Kim.
Kim hates Jim, likes Larry and Bob.
Larry loves Martin, and hates Karl and Jean.
"""
Write a program that lists each person and whom they love, like and hate.
Spreadsheets are really not that difficult to make with Python. Here is the beginning of a simple Tkinter based spreadsheet program:
# the beginning of a simple Tkinter spreadsheet program
import Tkinter as tk
root = tk.Tk()
root.title('Tkinter spreadsheet phase 1')
def click(event, cell):
# can do different things with right (3) and left (1) mouse button clicks
root.title("you clicked mouse button %d in cell %s" % (event.num, cell))
# test right mouse button for equation solving
# eg. data = '=9-3' would give 6
if event.num == 3:
# entry object in use
obj = dict[cell]
# get data in obj
data = obj.get()
# if it starts with '=' it's an equation
if data.startswith('='):
eq = data.lstrip('=')
print data, eq
try:
# solve the equation
result = eval(eq)
#print result, type(result) # test
# remove equation data
obj.delete(0, 'end')
# update cell with equation result
obj.insert(0, str(result))
except:
pass
def key_r(event, cell):
# return/enter has been pressed
data = dict[cell].get() # get text/data in given cell
#print cell, dict[cell], data # test
root.title("cell %s contains %s" % (cell, data))
# create a dictionary of key:value pairs
dict = {}
w = 20
h = 1
alpha = ["", 'A', 'B', 'C', 'D', 'E', 'F']
for row in range(5):
for col in range(5):
if col == 0:
# create row labels
label1 = tk.Label(root, width=3, text=str(row))
label1.grid(row=row, column=col, padx = 2, pady=2)
elif row == 0:
# create column labels
label1 = tk.Label(root, width=w, text=alpha[col])
label1.grid(row=row, column=col, padx …
Spreadsheets are really not that difficult to make with Python. Here is the beginning of a simple Tkinter based spreadsheet program:
# the beginning of a simple Tkinter spreadsheet
import Tkinter as tk
root = tk.Tk()
root.title('Tkinter spreadsheet phase 1')
def click(event, cell):
# can do different things with right (3) and left (1) mouse button clicks
root.title("you clicked mouse button %d in cell %s" % (event.num, cell))
# test right mouse button for equation solving
# eg. data = '=9-3' would give 6
if event.num == 3:
# entry object in use
obj = dict[cell]
# get data in obj
data = obj.get()
# if it starts with '=' it's an equation
if data.startswith('='):
eq = data.lstrip('=')
print data, eq
try:
# solve the equation
result = eval(eq)
#print result, type(result) # test
# remove equation data
obj.delete(0, 'end')
# update cell with equation result
obj.insert(0, str(result))
except:
pass
def key_r(event, cell):
# return/enter has been pressed
data = dict[cell].get() # get text/data in given cell
#print cell, dict[cell], data # test
root.title("cell %s contains %s" % (cell, data))
# create a dictionary of key:value pairs
dict = {}
w = 20
h = 1
alpha = ["", 'A', 'B', 'C', 'D', 'E', 'F']
for row in range(5):
for col in range(5):
if col == 0:
# create row labels
label1 = tk.Label(root, width=3, text=str(row))
label1.grid(row=row, column=col, padx = 2, pady=2)
elif row == 0:
# create column labels
label1 = tk.Label(root, width=w, text=alpha[col])
label1.grid(row=row, column=col, padx = …
Okay, this should work for the 'space in chemical name' problem:
# analyze a chemical recipe to create a chemical data list
rcp = """23 g powdered chemicalA is dissolved in 250 ml methanol. The
solution is cooled to 0 - 5 degC and 18 ml compoundB is added dropwise
over 60 minutes. The mixture is heated to reflux overnight, then cooled
to 0 - 5 degC for 3 hours. The precipated product is collected, washed
with 50 ml ice cold methanol. Yield: 28 g compoundC as a light yellow
solid after drying in vacuum at 70 degC for 6 - 12 hours.
For 'space in chemical' testing:
10 g sodium chloride
50 g potassium carbonate
"""
chem_list = [
'chemicalA',
'compoundB',
'compoundC',
'methanol',
'sodium chloride',
'potassium carbonate']
unit_list = ['g', 'ml', 'kg', 'l']
# replace space in chemical name with a special filler
# for split() and change back after split
space = ' '
# pick a filler hat is not usually in a chemical name
filler = '_'
for chem in chem_list:
if chem in rcp:
if space in chem:
chem1 = chem.replace(space, filler)
#print chem, chem1 # test
rcp = rcp.replace(chem, chem1)
#print rcp # test
print '-'*60
# break recipe text down to list and remove punctuation marks
rcp_list = [ w.rstrip(' .,?') for w in rcp.split(None)]
print rcp_list # test
print '-'*60
# split() is done, now replace the special filler back to a space
for word in rcp_list:
if filler in word: …
One potential fly in the ointment! If there is a space in the chermical name, you might have to use a dash like sodium-chloride. You could let Python analyze the text for you and do that ahead of splitting it.
Tkinter does not have a fancy spreadsheet like widget like wxPython. However, you could create a matrix of Entry widgets and go from there.
I took mawe's code and Jeff's ideas and came up with this:
# analyze a chemical recipe to create a chemical data list
rcp = """23 g chemicalA is dissolved in 250 ml methanol. The solution is cooled
to 0 - 5 degC and 18 ml compoundB is added dropwise over 60 minutes.
The mixture is heated to reflux overnight, then cooled to 0 - 5 degC
for 3 hours. The precipated product is collected, washed with 50 ml
cold methanol. Yield: 28 g compoundC as a light yellow solid after
drying in vacuum at 70 degC for 6 hours.
"""
chem_list = ['chemicalA', 'compoundB', 'compoundC', 'methanol']
unit_list = ['g', 'ml', 'kg', 'l']
# break recipe text down to list and remove punctuation marks
rcp_list = [ w.strip(' .,?') for w in rcp.split(None)]
print rcp_list
print '-'*60
recipe1 = []
for ix, item in enumerate(rcp_list):
try:
# check for number
if item.isdigit():
# check for unit
if rcp_list[ix+1].lower() in unit_list:
# check for chemical name
if rcp_list[ix+2] in chem_list:
recipe1.append([item, rcp_list[ix+1], rcp_list[ix+2]])
# case of modifier (can add more)
elif rcp_list[ix+3] in chem_list:
recipe1.append([item, rcp_list[ix+1], rcp_list[ix+3]])
except:
pass
for data in recipe1:
print data
"""
my output -->
['23', 'g', 'chemicalA']
['250', 'ml', 'methanol']
['18', 'ml', 'compoundB']
['50', 'ml', 'methanol']
['28', 'g', 'compoundC']
"""
Actually an interesting project. Tell the TA to stay close to the 'amount unit [modifier] chemical' structure and to keep the modifiers down to something manageable.
VB.NET followed by VC.NET and possibly VD.NET? My soothing condolence!
Frigg, I posted it and it got swallowed up.
An array of unions might do.
Take you pick:
Unix OS is '\n'
Windows is '\r\n'
Mac OS is '\r'
Well, this one is tough because the code is frankly a nightmare!
Here are some hints (look at !!!!!!! comments):
#Role Playing Form.py
from Tkinter import *
#Create the Start window
class character(object):
def __init__(self, master):
# \Images is a subfolder of current folder
torch=PhotoImage(file=r".\Images\Title Screen Flames.gif") #!!!!!
grave=PhotoImage(file=r".\Images\TitleScreenGraves.gif") #!!!!!
ankh=PhotoImage(file=r".\Images\TitleScreenAnkh.gif") #!!!!!
self.master = master
self.master.title('Role Playing Form V1.0')
self.master.geometry('250x250+350+450')
self.torchLabelL=Label(self.master, image=torch)
self.torchLabelL.grid(row=0, column=0)
self.cmdCreate = Button(self.master, text='Create Character', command=self.nameCreate)
self.cmdCreate.grid(row=0, column=1)
self.torchLabelR=Label(self.master, image=torch)
self.torchLabelR.grid(row=0, column=2)
self.graveLabelL=Label(self.master, image=grave)
self.graveLabelL.grid(row=1, column=0)
self.cmdDelete = Button(self.master, text='Delete Character', command=self.delete)
self.cmdDelete.grid(row=1, column=1)
self.graveLabelR=Label(self.master, image=grave)
self.graveLabelR.grid(row=1, column=2)
self.ankhLabelL=Label(self.master, image=ankh)
self.ankhLabelL.grid(row=2, column=0)
self.cmdLoad = Button(self.master, text='Load Character', command=self.load)
self.cmdLoad.grid(row=2, column=1)
self.ankhLabelR=Label(self.master, image=ankh)
self.ankhLabelR.grid(row=2, column=2)
self.master.mainloop()
def nameCreate(self):
self.nameInput = Toplevel(root)
self.nameInput.title('Name of Character?')
self.nameInput.geometry('300x100+350+450')
self.lblName = Label(self.nameInput, text='Enter Name Here')
self.lblName.grid(row=0)
self.entName = Entry(self.nameInput)
self.entName.grid(row=0, column=1)
self.cmdName = Button(self.nameInput, text='Enter', command=self.enter)
self.cmdName.grid(row=1)
self.entName.focus() #cursor helper!!!!!
def enter(self):
self.Name = self.entName.get()
print "Character Name:",self.Name
fileChar = open('Character Data\ '+self.Name+'.txt',"w")
self.classCreate()
self.nameInput.destroy()
def classCreate(self):
self.classChoose = Toplevel(root)
self.classChoose.title('Choose your Class')
self.classChoose.geometry('300x200+300+400')
self.labelChoose = Label(self.classChoose, text="Select the class you wish to be")
self.labelChoose.grid(row=0)
self.listClass = Listbox(self.classChoose, height=4)
self.listClass.grid(row=1)
self.listClass.insert(END,"Warrior")
self.confirm = Button(self.classChoose, text="Confirm", command=self.confirm)
self.confirm.grid(row=2)
def confirm(self):
fileClass = open('ClassData.txt','r')
for line in fileClass:
classInfo=line.split(',')
print "Name is:", self.Name
print "This class's stats are:",classInfo
className = classInfo[0]
self.CharHpMax = classInfo[1]
self.CharHpCurrent = classInfo[2]
self.CharMpMax = classInfo[3]
self.CharMpCurrent = classInfo[4]
self.CharStr = classInfo[5]
self.CharDef = classInfo[6]
self.CharMAtt = classInfo[7]
self.CharMDef = classInfo[8]
self.Currentexp=0
self.Requiredexp=10
print "The name of the class is: ",className
print "The Character's max HP is: …
cant you just use windows.h and do old school win32 gui apps? mfc even?
Our friend is on a Linux machine.
A couple of things wrong with your countdown timer.
1 - don't limit the size of your root window, widgets won't fit
2 - labels take strings
3 - root.update() is needed
Look this over:
#Gamal Crichton
#Teje's Counter
#04/02/07
from Tkinter import *
import time
class Application(Frame):
def __init__(self,master,act_name,time_):
Frame.__init__(self,master)
self.hh=time_[0]
self.mm=time_[1]
self.ss=time_[2]
self.name=act_name
self.grid()
print time_
self.disp_widgets()
self.aggregate()
def disp_widgets(self):
#Uses labels to display time.
Label(self,
text=self.name, font=("Arial, 32")
).grid(row=0,column=0,columnspan=3,sticky=W)
self.hourlbl=Label(self,
text=str(self.hh), font=("Arial, 40") # str()!!!!!!!!!!
)
self.hourlbl.grid(row=1,column=0,columnspan=1,sticky=W)
self.minutelbl=Label(self,
text=str(self.mm), font=("Arial, 40") # str()!!!!!!!!!!
)
self.minutelbl.grid(row=1,column=1,columnspan=1,sticky=W)
self.secondlbl=Label(self,
text=str(self.ss), font=("Arial, 40") # str()!!!!!!!!!!
)
self.secondlbl.grid(row=1,column=2,columnspan=1,sticky=W)
Button (self,
text="Stop",
command=self.show,
).grid(row=2,column=0,columnspan=3,sticky=EW)
def show(self):
# needs more stuff
print "Booooooooo!"
def aggregate(self): #This function is supposed to decrement the time
for hours in range(self.hh, -1, -1):
for minutes in range(self.mm, -1, -1):
for seconds in range(self.ss, -1, -1):
time.sleep(1)
root.update() # needed!!!!!
self.secondlbl["text"]=str(seconds) # str()!!!!!!!!!!
if self.ss==0:
self.ss=60
self.minutelbl["text"]=str(minutes) # str()!!!!!!!!!!
if self.mm==0:
self.mm=0
self.hourlbl["text"]=str(hours) # str()!!!!!!!!!!
#Main
root=Tk()
root.title("Timer!")
#root.geometry("250x75") # do not use, too space restrictive!!!
app= Application(root, " Timer ", [2, 4, 5])
root.mainloop()
Unless you have a huge amount of events in your loop, it could very well be your mouse.
I have learn more with you that almost six month going through several books on C programming.
Again. Thank you.
Reading the books might help.
The IT did not use C++ or she would still be working on it!
... and old code will break frequently, since division will no longer yield integers. :eek:
Jeff
This is why it hasn't been implemented yet in a large number of other languages like C, C++ either.
Here is something very simple that you can fancy up with a +/- year and a +/- month button:
# as simple monthly calendar with Tkinter
# give calendar and Tkinter abbreviated namespaces
import calendar as cd
import Tkinter as tk
# supply year and month
year = 2007
month = 2 # jan=1
# assign the month's calendar to a multiline string
str1 = cd.month(year, month)
# create the window form and call it root (typical)
root = tk.Tk()
root.title("Monthly Calendar")
# pick a fixed font like courier so spaces behave right
label1 = tk.Label(root, text=str1, font=('courier', 14, 'bold'), bg='yellow')
label1.pack(padx=3, pady=5)
# run the event loop (needed)
root.mainloop()
Welcome S.O.S to the Python crowd. We are all quite nice in Python land, just here to learn more!
Small Miss Steaks are accepted, gives the rest of us the opportunity to show off how smart we are.
That will do it Jeff! HeHe, love the word "tweakery".
Here is vegaseat's fancy Tkinter GUI "Hello World!" code:
# a simple "Hello, world!" Tkinter GUI
# add some color and a larger text font
# add buttons to change text color and fancy them up
# import Tkinter as namespace tk
import Tkinter as tk
def white_blue():
label1.config(fg='white', bg='blue')
def blue_green():
label1.config(fg='blue', bg='green')
# create the basic window, let's call it 'root'
root = tk.Tk()
# why not add a title
root.title("Hello World from DaniWeb!")
# create a label with colors in it
font1 = ('times', 36, 'bold')
label1 = tk.Label(root, text="Hello, world!", font=font1, fg='red', bg='yellow')
# let's use a grid to put the label into the window
# make it span two grid columns
label1.grid(row=0, column=0, columnspan=2)
# create 2 buttons to click for text color change
# use the two grid positions below the label
# (by default the button will take up the center of each grid space)
# give the buttons some y-axis space and a ridge style
button1 = tk.Button(root, text="white on blue", relief='ridge', command=white_blue)
button1.grid(row=1, column=0, pady=5)
button2 = tk.Button(root, text="blue on green", relief='ridge', command=blue_green)
button2.grid(row=1, column=1, pady=5)
# run the GUI event loop
root.mainloop()
Here is the same program written in wxPython, seems to be slightly more complex:
# a simple "Hello, world!" wxPython GUI
# add some color and a larger text font
# add buttons to change text color and fancy them up
import wx
def white_blue(event):
label1.SetBackgroundColour("blue")
label1.SetForegroundColour("white")
label1.SetLabel("Hello World!")
def blue_green(event):
label1.SetBackgroundColour("green")
label1.SetForegroundColour("blue")
label1.SetLabel("Hello World!")
app …
Since the data is coming from a raw source (text file, database, user input...) wouldn't it be nice if we didn't assume that the "[" will always be the first character of "txt" and "]" is not always the last character of "txt".
Given that the data can also be of the form " [ 32] " or "[32 ]". To handle such situations here is what I have come up with....
data_raw = """[20 ] [ 35 ] [40 ] [84 ] [100 ] [ 245] [ 260] [ 300 ] [ 440 ] [ 521 ] [ 650 ] """ data_list = data_raw.split() print data_list data_list2 = [x.strip(" []") for x in data_list] print data_list2
No cigars on that one s.o.s, here is the result I get:
"""
my output -->
['[20', ']', '[', '35', ']', '[40', ']', '[84', ']', ...]
['20', '', '', '35', '', '40', '', '84', '', ...]
"""
Before I forget, you can also go into the DaniWeb Code Snippets section and search the Python Snippets for Tkinter. There are a fair number of Tkinter code snippets in there at various levels of complexity.
You can also search for wxPython and get a similar response.
I am a little lost here. I assume your data comes from a file? Well, anyway, using assumptions here is some code:
def strip_brackets(txt):
if txt[0] == "[": # remove leading '['
txt = txt[1:]
if txt[-1] == "]": # remove trailing ']'
txt = txt[:-1]
return txt
# assume your data string looks like this
data_raw = """[20]
[35]
[40]
[84]
[100]
[245]
[260]
[300]
[440]
[521]
[650]
"""
data_list = data_raw.split()
# test
print data_list # ['[20]', '[35]', '[40]', '[84]', ...]
# convert to a list of numeric strings
data_list2 = [strip_brackets(x) for x in data_list]
# test
print data_list2 # ['20', '35', '40', '84', ...]
I have used this info on Tkinter:
http://infohost.nmt.edu/tcc/help/pubs/tkinter/
A liitle dry with few examples however!
This one has a nice Tkinter section and more examples:
http://bembry.org/technology/python/index.php
I have a friend who's been encouraging use of Eclipse. Any experience with that out there?
Jeff
I heard that Eclipse is a huge system originally written for Java in Java. It is supposed to be really sluggish.
I have thoroughly tested both DrPython and PyPE for my coding needs, and personally like DrPython better. DrPython has more colors and fonts, is more intuitive than PyPE, and has a much better code assistant.
However PyPE is nice too and has a number of extras like a spell checker, trigger, and macro recorder. One interesting thing is that you send selected code to the Python shell. You can also call a command shell. Both those shells have copy and paste. With large code, the folding class and function option is real nice. As far as I can see PyPE also handles unicode better.
Maybe the two of them could get together and make one super product!
Similar to Jeff's code:
# write this as a list of lists ...
matrix = [[9,8,12,15],
[0,11,15,18],
[0,0,10,13],
[0,0,0,5]]
# find the minimum value above val in each list
val = 0
for n in matrix:
print n # test
mv = min([v for v in n if v > val])
print mv
"""
my output -->
[9, 8, 12, 15]
8
[0, 11, 15, 18]
11
[0, 0, 10, 13]
10
[0, 0, 0, 5]
5
"""
With this project you need to do some "googling" to get the needed information.
If the USA would like to replace all the gasoline presently consumed here with ethanol, how many bushels of corn would US farmers have to grow to produce the ethanol.
Are there enough acres of farmland in the US to do this?
This is a project that can go from beginner to advanced level:
"Data Mining" is an increasingly popular field and Python is pretty good at it. To data-mine HTML pages on the Web you can use an HTML Scraper like "Beautiful Soup" from:
http://www.crummy.com/software/BeautifulSoup/
More involved are data scrapers like Orange from:
http://www.ailab.si/orange
"Data Mining" is an increasingly popular field and Python is pretty good at it. To data-mine HTML pages on the Web you can use an HTML Scraper like "Beautiful Soup" from:
http://www.crummy.com/software/BeautifulSoup/
More involved are data scrapers like Orange from:
http://www.ailab.si/orange
I find counter4 to be a very interesting function, thanks for putting it up vegaseat.
I have used SPE for quite a while. No, it's not the "Society of Petroleum Engineers", but "Stani's Python Editor". For some odd reason it has vanished on the net.
Now I am starting to use DrPython, that one seems to be still quite active and just released a new version. Also played with PyScripter, very promissing, but not quite there yet.
Sharky,
DrPython is not a compiler nor an interpreter, it is simply an fancy editor that allows you to run code from.
I assume from your question that you want to retain the previous outputs in your output window, so you can compare them?
Your initial problem is right here:
def main():
print "This program sorts student grade information"
filename = raw_input("Enter the name of the data file: ")
dfield = raw_input("Enter gpa, name, or credits to sort: ")
filename = raw_input("Enter a name for the output file: ")
data = readStudents(filename)
...
You are assigning the same variable 'filename' to both the input and output file.
Your next problem is here:
if dfield == gpa:
data.sort(cmpgpa)
The input function raw_input() returns a string, so this ought to be:
if dfield == 'gpa':
data.sort(cmpgpa)
Give your data file a name like in.dat, don't use .py (it is not Python code!).
Your next problem is here ( I added a test print):
def makeStudent(infoStr):
print string.split(infoStr,"\t") # test --> ['Computewell, Susan 100 400\n']
name, hours, qpoints = string.split(infoStr,"\t")
return Student(name, hours, qpoints)
The result of splitting a string is a list, not a tuple! Also the data file needs tabs at the right places to make this work!
I played wit it for a little while and came up with these obvious shortcuts:
# changed playerInitialList to pL to save on typing
# changed pL1 etc. to pL[1] etc.
# What do you do if initials of the two players match?
import random
def continents(): #<--- Visual Display of the 3 continents
"""
list pL contains the inital letters of the players
the index coincides with the number of the country
"""
print " __ ____"
print " N.A. | \ / ."
print " \__| \ 2 | ____"
print " ____________ |" + pL[2] + " / __ Eu / | |"
print " / | 1 | \ \| /13\ ___/ | |"
print "/ 0 |__" + pL[1] + "__|_/ |\ ." + pL[13] + "_// 14 / |"
print "| " + pL[0] + " | 3 | 4|__|5\ / " + pL[14] + " / |"
print " \/ \|__" + pL[3] + "_|_" + pL[4] + "__|_" + pL[5] + "_\ __ |_/|_/| 19 /"
print " / | 6 | 7 / /15\ __/ | " + pL[19] + " /"
print " |__" + pL[6] + "__|_" + pL[7] + "_/ ." + pL[15] + "_/ | 16 | /"
print " \ 8 | / _" + pL[16] + " | |"
print " \ " + pL[8] + " \ /\ / \/\ |"
print " \ \ /17|18/ ||"
print " _\_ |" + pL[17] …
Not knowing Tkinter that well, here is a somewhat simple minded approach:
from Tkinter import *
def center_window(w=300, h=200):
# get screen width and height
ws = root.winfo_screenwidth()
hs = root.winfo_screenheight()
# calculate position x, y
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
root.geometry('%dx%d+%d+%d' % (w, h, x, y))
root = Tk()
center_window(500, 300)
root.mainloop()
In case of the capital:state pair I did it this way:
def swap_dictionary(original_dict):
temp_dict = {}
dict_list = original_dict.items()
for i in dict_list:
temp_dict[i[1]] = i[0]
return temp_dict
cs = {"indianapolis":"indiana", "columbus":"ohio", "jackson":"mississippi",
"phoenix":"arizona", "honolulu":"hawaii", "richmond":"virginia",
"springfield":"illnois", "lincoln":"nebraska",
"boston":"massachuettes", "lansing":"michigan", "desmoines": "iowa",
"salem": "oregon"}
dic = swap_dictionary(cs)
print dic
"""
{'mississippi': 'jackson', 'arizona': 'phoenix', 'iowa': 'desmoines',
'massachuettes': 'boston', 'michigan': 'lansing', 'virginia': 'richmond',
'oregon': 'salem', 'hawaii': 'honolulu', 'nebraska': 'lincoln',
'indiana': 'indianapolis', 'ohio': 'columbus', 'illnois': 'springfield'}
"""
Could be your editor/IDE.
Also, a Unicode string literal is preceded with a 'u'.
I would use the state as the key just in case there could be two capitol cities with the same name:
dic = {'mississippi': 'jackson', 'arizona': 'phoenix', 'iowa': 'desmoines',
'massachuettes': 'boston', 'michigan': 'lansing', 'virginia': 'richmond',
'oregon': 'salem', 'hawaii': 'honolulu', 'nebraska': 'lincoln',
'indiana': 'indianapolis', 'ohio': 'columbus', 'illnois': 'springfield'}
while True:
state = raw_input("Enter the name of a state (enter quit to exit): ").lower()
if state == 'quit':
break
try:
print "The capitol city of %s is %s" % (state.capitalize(), dic[state].capitalize())
except KeyError:
print "%s is not in the dictionary!" % state.capitalize()