.join() is more efficient than string concatenation, so I would expect to see at least one join(). Also, don't use "i", "l", or "O" in an interview.
for outer in range(1,13):
print '\t'.join(str(outer*inner) for inner in range(1, 13))
.join() is more efficient than string concatenation, so I would expect to see at least one join(). Also, don't use "i", "l", or "O" in an interview.
for outer in range(1,13):
print '\t'.join(str(outer*inner) for inner in range(1, 13))
You have to return the list that stores the textvariables and pass it to the next function. Also, you should really be using a class structure for this.
from Tkinter import *
from functools import partial
data = [
('a', 0, 'liters soda'),
('b', 0, 'liters beer'),
('c', 0, 'liters wine')
]
## Create grid, extracting infos from the data array
## Collect the text variables to list for use
def createWidgets(root, clist=[]):
L=0
# global c_w no help
first=0
while L < len(data):
cg_w=DoubleVar()
clist.append(cg_w)
l_w=Label(root, text=data[L][2])
l_w.grid(row=L)
c_w=Entry(root, textvariable=cg_w, width=3)
c_w.grid(row=L,column=1)
if L==0:
first=c_w
L+=1
first.focus_set()
return clist
## Example of simple function using values from an edited list (cl)
def Calc():
L=0
v=0
lit=0
for L,v in enumerate(cl):
lit+=v.get()
TotLiters.configure(text='%g' % lit)
def SetToZero(entries_list):
""" set all textvariables in the input list to zero
"""
for tk_var in entries_list:
tk_var.set(0.0)
root=Tk()
root.title('Bar')
##
cl=[]
list_of_entries=createWidgets(root,cl)
compute = Button(root, text=' Total liters = ', command=Calc)
compute.grid(row=0,column=3)
reset = Button(root, text=' reset ',
command=partial(SetToZero, list_of_entries))
reset.grid(row=2,column=3)
TotLiters=Label(root, width=10)
TotLiters.grid(row=0,column=4)
exit = Button(root, text='Exit', command=root.quit)
exit.grid(row=3,column=3)
root.mainloop()
So what's new? Don't we always take the round-about way to get somewhere.
The dictionary would have to contain lists as you can not duplicate keys in a dictionary, and you would then append to the list each time. So it would be
def common(dict_in, rec, update_dict):
...
new_key = dict_in[key]
## add "700" or whatever the first time it is found
if new_key not in update_dict:
update_dict[new_key]=[] ## key points to an empty list
update_dict[new_key].append(extract_string[0])
return update_dict
#
# then to write
headers = ["100a", "100c", "100d", "100q", "245a"]
for line in thelist_:
for header in headers:
# if line.has_key(header):
if header in line: ## preferred over has_key
print line[header]
list_of_recs=line[header] ## from the dictionary of lists
## added to write each one individually
for item in list_of_recs:
fileout_.write('|%s' % (item))
else:
fileout_.write('|')
fileout_.write('\n')
I'm not too sure what you want to do so it this is not quite correct, adjust it a little and post back if there are other questions. And after all of this, it occurs to me to ask if an SQL database would work better. Doh!
Let us know how this is going whether you are successful or not.
You are finding the last name to get to the end of middle name. I am finding the last space.
There isn't enough data to be exact on the extraction process, but you can use a dictionary to test for "100", "245", etc. and call a function based on the key. I have used a common function to extract the data. If this is possible on all data types then the dictionary can be used to call the common function and send the proper sub-dictionary, otherwise the unique code can be included in each function. Note that the variable "list_" is changed to "dict_" since it is a dictionary. If this is not what you want provide more test data.
def common(dict_in, rec, update_dict):
for key in dict_in:
if key in rec:
rec_as_list=rec.split(key)
## the string we want is now in rec_as_list[1]
extract_string=rec_as_list[1].split("$")
new_key=dict_in[key]
update_dict[new_key] = extract_string[0]
return update_dict
def func_100(rec, dict_):
## =100 1\$aSomeauthor, John$d1746-1818.
dict_100={"\\$a":'100a', "\\$c":'100c',"\\$q":'100q',"\\$d":'100d'}
print rec
dict_ = common(dict_100, rec, dict_)
return dict_
def func_245(rec, dict_):
## =245 13$aSome title$hmicrosomething :$bla bla /$ctranslated from some language.
dict_245={"$a":'245a', "$h":'245h',"/$b":'245b',"/$c":'245c'}
print rec
dict_ = common(dict_245, rec, dict_)
return dict_
dict_={}
match_dict={"100":func_100, "245":func_245}
records=test_data.split("\n")
for rec in records:
for key in match_dict:
if rec.startswith("="+key):
print "-"*50
dict_=match_dict[key](rec, dict_) ## call the function associated with this key
print "dict_", dict_
And intead of all of the if() statements you can use a loop and write each row if the number in the current record (=001, =100 etc.) is less than the previous record's number=new group, and then write the final row of course.
for line in thelist_:
if …
You really only need to use the first and last space, but count can be used to find how many spaces to index.
fullname = "one two three four five"
ct = fullname.count(' ')
idx=0
idx_list=[]
for ctr in range(ct):
idx=fullname.find(" ", idx)
idx_list.append(idx)
idx += 1
print idx_list
first=fullname[:idx_list[0]]
print first
middle=fullname[idx_list[0]+1:idx_list[-1]]
print middle
last=fullname[idx_list[-1]+1:]
print last
#easier
idx_first=fullname.find(" ")
idx_last=fullname.rfind(" ")
print "\n", idx_first, idx_last
first=fullname[:idx_first]
print first
middle=fullname[idx_first+1:idx_last]
print middle
last=fullname[idx_last+1:]
print last
It is explained in this tutorial. Also a web search for "python string split" will turn up more examples. You can use a split and specify the character, or replace and then split() with the default=space(s).
If you are using Python3.X input is fine. If you are using Python2.x then input captures numbers, and raw_input captures strings.
This is a common exercise where you group records based on some indicator, an empty line in this case. This code prints the contents but you can also output to a file using .join)() and append a newline, "\n".
lit="""a=1
b=2
c=3
a=4
b=5
c=6
a=7
c=8
a=9
b=10
c=11"""
test_data=lit.split("\n")
this_group=[]
for rec in test_data:
rec = rec.strip()
if len(rec): ## not an empty line
this_group.append(rec)
else: ## is empty
print_list=[]
for value in this_group:
ltr, num = value.split("=")
print_list.append(num)
print " ".join(print_list)
this_group = [] ## empty list for next group
## final group - prints differently
for value in this_group:
ltr, num = value.split("=")
print num+" ",
print
Also if the want the a=7, c=8 group to print in the first and third columns, then you will have to test for the letter and place it in the correct column.
test_group=["a=7", "c=8"]
columns=["a", "b", "c"]
print_list = ["*", "*", "*"]
for rec in test_group:
ltr, num = rec.split("=")
col=columns.index(ltr)
if col > -1: ## letter found in "columns"
print_list[col]=num
print " ".join(print_list)
You possibly add to the dictionary on line 50, although we can't tell from the code if it is adding a new key or updating an existing one.
FID_GC_dict[Cur_FID] = lr_Value
You possibly want to use a copy of the dictionary and should add some print statements to see what is happening.
The simplest is to use a dictionary
classes_taken={classlistA:["CMSC 201", "CMSC 202", "CMSC 203"],
classlistB:["MATH 151", "MATH 152"]}
etc.
If you want to use lists then you can just transfer the classes taken to the list, so you would have 3 classes_taken lists or one list with 3 sublists. You can also use one list in this way
print "This program returns a list of classes you still have to take: "
classlistA = ["CMSC 201", "CMSC 202", "CMSC 203", "CMSC 304", "CMSC 313",
"CMSC 331", "CMSC 341", "CMSC 345", "CMSC 411", "CMSC 421",
"CMSC 441"]
classlistB = ["MATH 151", "MATH 152", "MATH 221"]
classlistC = ["STAT 334" ,"STAT 451"]
# simulate this data was entered
test_data = ["CMSC 201", "CMSC 202", "STAT 334", "MATH 151", "MATH 152"]
set_test_data=set(test_data)
## print classes to be taken
letters = ["A", "B", "C"]
for ctr, classlist in enumerate([classlistA, classlistB, classlistC]):
print "You have not taken the following classes in %s" % (letters[ctr])
for this_class in classlist:
if this_class not in test_data:
print " ", this_class
print "\nEven easier with sets"
print set(classlist).difference(set_test_data), "\n"
Dive into Python has a chapter on installing Python for both the Python.org and ActiveState versions.
From your original code
name = 'francis ford coppola'
space=name.find(" ")
first=name[:space]
remaining_name=name[space+1:] ## skip the space
space=remaining_name.find(" ")
middle=remaining_name[:space]
last=remaining_name[space+1:]
print(first)
print(middle)
print(last)
Some of those codes you posted I have not learned yet. The teacher wants us to post the first middle and last names on 3 separates lines using the whitespaces as the indexes
You did not state any limitations in your question, so how are we to know what you do and do not know, and it is unreasonable to expect others to come up with solution after solution until you find one you like.
name = 'francis ford coppola'
first_name=""
middle_name=""
this_name=""
ctr=0
for ltr in range(len(name)):
print "testing letter", name[ltr]
if name[ltr]== " ":
if ctr==0:
first_name=this_name
print " ", this_name, "to first_name"
elif ctr==1:
middle_name=this_name
print " ", this_name, "to middle_name"
ctr += 1
this_name=""
else:
this_name += name[ltr]
print "this_name is now", this_name
last_name=this_name
print "-"*30
print "first_name", first_name
print "middle_name", middle_name
print "last_name", last_name
That's because of the while() loop in the function. Instead keep track of the number of times the button is clicked.
from Tkinter import *
class App:
def __init__(self,master):
self.master=master
self.returned_values = {}
frame = Frame(master)
frame.grid()
self.Answer_entry = Entry(master)
self.Answer_entry.grid(row = 0, column = 1, sticky=W)
self.Answer_entry.focus_set()
User_Answer=self.Answer_entry.get()
self.attempts = 0 #sets the attempts = to 0 to start the loop
self.exampleAnswer(master)
def exampleAnswer(self,master):
Answer = 'exampleAnswer'
self.CheckAnswerButton = Button(master, text="Check Answer", command=lambda: self.Check_Answer(Answer))
self.CheckAnswerButton.grid(row = 1, column = 3, sticky = S)
# answer defined in seperate function as it would be in prog
def Check_Answer(self,Answer):
## while 1: #starts infinite loop that will stop when break point hit
User_answer= self.Answer_entry.get()#gets users Answer entry
print User_answer
if User_answer != Answer: #checks if the user answer = the stored answer
if self.attempts >= 10:
self.returned_values['attempts'] = self.attempts
self.master.quit()
# break #breaks the loop if the user has had 10 attempts
# else:
self.attempts += 1 #adds one to attempts and repeats the loop
else: #only reaches this if there input is correct
self.returned_values['attempts'] = attempts #global variable ti give other functions access
self.master.quit()
# break #breaks the loop
root = Tk()
app = App(root)
root.mainloop()
print "returned_values", app.returned_values
Try it and see for yourself. If you have problems post the code you are using for assistance.
"When you create a new text widget, it has no contents. To insert text into the widget, use the insert method and insert text at the INSERT or END indexes:" http://effbot.org/tkinterbook/text.htm
Lists are the easiest and quickest way to work with data IMHO. You can then join the elements into one string http://www.diveintopython.net/native_data_types/joining_lists.html.
a = "01101000011001010111100100000000000000000000"
b = "011000100111100101100101"
combined_list=[]
combined_list.append(b)
combined_list.append(a[len(b):]) ## slice off length of "b"
print "".join(combined_list)
## result
01100010011110010110010100000000000000000000
Another way is to use a third class as a wrapper. The buttons in the following code print the contents of the variable from the other class. Also, it is never a good idea to create two or more instances of a GUI at the same time. It can cause confusion with the interaction from the display manager. Use one of instance of wx and separate frames.
import wx
class Test1():
def __init__(self, parent, id, title):
self.ident="Test1 Ident"
self.frame=wx.Frame(None, id, title, size=(170, 100))
self.frame.SetPosition((10, 10))
def exit_button(self, T2):
panel = wx.Panel(self.frame, -1)
exit = wx.Button(panel, -1, 'Exit 1'+T2.ident, (10, 10))
exit.Bind(wx.EVT_BUTTON, self.exit_this, id=exit.GetId())
self.frame.Show(True)
def exit_this(self, event):
self.frame.Close()
class Test2():
def __init__(self, parent, id, title, wrap):
self.ident="Test2"
self.frame=wx.Frame(None, id, title, size=(170, 100))
self.frame.SetPosition((10, 150))
panel = wx.Panel(self.frame, -1)
exit = wx.Button(panel, -1, 'Exit Two-->'+wrap.T1.ident, (10, 10))
exit.Bind(wx.EVT_BUTTON, self.exit_this, id=exit.GetId())
self.frame.Show(True)
def exit_this(self, event):
self.frame.Close()
class Wrapper():
def __init__(self):
app = wx.App()
self.T1=Test1(None, -1, '')
self.T2=Test2(None, -1, '', self)
self.T1.exit_button(self.T2)
app.MainLoop()
W = Wrapper()
Everything should go under the if statement (indents count in Python), or copy the file you want to process to a list and process the list.
def treeDir (arg, dirpath, basenames):
workspace = dirpath
roads_list = []
for f in basenames:
if f.startswith('roads.'):
fullf = os.path.join(dirpath,f)
function_to_process_this_file(fullf)
##
## or
roads_list.append(fullf)
## all files are processed
for fname in roads_list:
function_to_process_this_file(fname)
In the OnPlus function, the program will sleep for 1*5000 seconds which is about 1 1/2 hours. In the OnMinus function also, you add/subtract one from value but it has no meaning i.e is not displayed. You should test each function individually as you create it, otherwise you will be stuck with a large block of code and no idea where the error is. Finally, please read the Python Style Guide concerning naming conventions. It makes code easier to read and understand.
The error appears to be on the previous line. First, make sure that this is actually a Python3 package and not a Python2 package. There are many packages that have not been ported to Python3x.
You use "replace" so it replaces all text that is equal (duplicates), when you should slice off the word.
def split_word(word, numOfChar):
r = []
# h = len(word)/numOfChar ## not used
while True:
if len(word) == 0:
return r
else:
r.append(word[0:numOfChar])
word = word[numOfChar:] ## changed
return r
print split_word("Asentencewithduplicateduplicatewords", 5)
Put the code under the try or in a function and call the function under the try
def read_file(infile):
tex1 = infile.readline()
outfile = open ('Book11.txt', "w")
while tex1:
rfields = tex1.split()
# do something
print >> outfile, 'something'
outfile.close()
infile.close()
try:
infile = open ('Book1.txt', "r")
read_file(infile)
except IOError:
print "input file %s is missing" %'Book1.txt'
except:
print "Some other error"
Use a list http://www.greenteapress.com/thinkpython/html/book011.html
input_list = []
while True:
ID = input('> ')
if ID == 'exit': ## "is" is different from equal
break
else:
input_list.append(ID)
print input_list
or a dictionary http://www.greenteapress.com/thinkpython/html/book012.html
number = 1 ## integers remove leading zeros automatically
input_dict = {}
while True:
key = 'A%03d' % (number)
number += 1
ID = input('> ')
if ID == 'exit':
break
## technically, else is not required as break will exit the while loop
else:
input_dict[key] = ID
print "-"*70
print input_dict
print "-"*70
for key in input_dict:
print key, "----->", input_dict[key]
pow is a function in the "math" program
import math
print r"pow(2,3) returns 2^3-->", math.pow(2,3)
A simple example:
def print_grid(a_grid):
print "The Grid"
for row in a_grid:
print " |".join(row)
print "--+--+--"
print " X axis"
print "\n"
y = int(raw_input("How tall do you want the grid to be?" "(type a to exit) "))
x = int(raw_input("How long do you want the grid to be? "))
a_grid = []
for a_row in range(x):
row = [str(a_row+col) for col in range(y)] # fill with anything unique for testing
a_grid.append(row)
print a_grid ## just the container
print_grid(a_grid)
## change a cell
a_grid[1][2] = "Xx" ## assumes this grid is at least 2X3
print_grid(a_grid)
but I have no idea how I would label it
The labels would be outside of "grid" if you want to use it in a game, and so change the contents. They would be incorporated in a print_grid() function as the only time you require labels is when the grid is printed.. It is possible, but places unnecessary complexity to include the labels or any formatting characters in the container as you would no longer have a simple row and column assignment, but would have to adjust for the labels.
for number in range(a,b,c):
This prints a number starting with "a", ending at "b", and the step/increment is "c". What happens if b<a?
if len(x)== 2:
a=x[0]
b=x[1]+c ## <----- "c" does not exist at this point
c=1
Also you can just use
else:
x_str_array = x_str.split(',') # splits the string where a comma pops up
a=int(x_str_array[0]) ## length !=0 so this will be used in all cases
if len(x_str_array)==3:
b=int(x_str_array[1])
c=int(x_str_array[2])
## etc.
Vegaseat's example from this forum
# explore the ttk.Progressbar of the Tkinter module ttk
# ttk is included with Python 3.1.1
import tkinter as tk
from tkinter import ttk
def click(event):
# can be a float
increment = 4
pbar.step(increment)
root = tk.Tk()
root.title('ttk.Progressbar')
pbar = ttk.Progressbar(root, length=300)
pbar.pack(padx=5, pady=5)
btn = tk.Button(root, text="Click to advance progress bar")
# bind to left mouse button click
btn.bind("<Button-1>", click)
btn.pack(pady=10)
root.mainloop()
#now retrieve next item in list without looping again
#something like record.next()
Use readlines, which reads the file into a list.
f_data = open('file.txt').readlines()
while ctr in range(5): ## first 5 only
print "this_rec", f_data[ctr]
if ctr > 0:
print "previous_rec", f_data[ctr-1]
print "next_rec", f_data[ctr+1]
print "-"*50
There are many examples of readlines() use on the web so anything further is not necessary here.
You have to iterate over the list.
data_list=[('Geo','Elephant',['hay','peanuts']),
('Gerald','Gnu',['leaves','shoots']),
('Leo','Leopard',['meat'])]
for name,familie,feed in data_list:
print name, familie
for each_item in feed:
print " ", each_item
Yes it is. Do you get the error on the next line in the program? We don't know since you didn't include the entire error message, but it appears that the compiler has gone to the next line looking for the missing apostrophe.
## This works without any errors
data=[('Geo','Elephant',['hay','peanuts']),
('Gerald','Gnu',['leaves','shoots']),
('Leo','Leopard',['meat'])]
for name,familie,feed in data:
print name, familie, feed
Also, the following line does nothing that I can see, and you only use commit() to commit any changes to the database, not after a query.
cursor.execute("""SELECT name,feed FROM animal JOIN food ON animal.id=food.anid WHERE name=%s and feed=%s""",(name,feed))
#
# Do you want "for name,familie,feed in data:" or "for feed in data:"
for name,familie,feed in data:
cursor.execute("""SELECT name,feed FROM animal JOIN food ON animal.id=food.anid WHERE name=%s and feed=%s""",(name,feed))
for feed in data:
P.S. For future reference, if you want some one to assist you with your code, at least try the suggestions before you say that that isn't it, and explain what happens after the change/correction. We will try them, so we know if they are correct or not.
Sorry, Tony already answered. The indent is probably incorrect.
You can code your own check using Python's isdigit() function, but as we have no way of knowing what you have studied in class, you will probably just come back and say that you haven't used it in class, so it would be a further waste of time.
def int_check(str_in):
for ch in str_in:
if ch < "0" or ch > "9":
return False, str_in
return True, int(str_in)
for test_input in ["123", "AString", "123.45"]:
ret, num = int_check(test_input)
if ret:
print num, "IS an integer"
else:
print num, "is NOT an integer"
Note that this is the only code that I will post. If you come back and say "I don't like that" then I will say that you are on your own and will have to provide some code/effort yourself as your original question did not state any limitations, so don't expect us to keep coming back with option after option like a performing seal until you find one that you like,
Just test for it and eliminate the trailing period
test_text="prob=0.345."
test_text = test_text.strip()
if test_text.endswith("."):
print test_text[:-1]
print test_text[:-1].split("=")
The OP has it correct
I need to print data using if-elif statement
elif row=='muta55':
.
This post is the same as http://www.daniweb.com/software-development/python/threads/398951 Take a look at it first, and then post any further questions.
I am trying to read a text file into a 2D list.
Assuming you want each record to be one row of the 2D list, you are making your code too complicated.
infile = open(infile,"r")
old_2D =[]
for line in infile:
line = line.strip()
new_row = [] ## start with an empty list for each record
## you can also use
## for num in line:
## new_row.append(num)
## or new_row = list(line)
for ctr in range(len(line)):
new_row.append(line[ctr])
## this row is finished so append it to old_2D
old_2D.append(new_row)
print old_2D
You should read the Python style guide as it makes everyone's code easier to read (i.e. variable names are lower case, and don't use "i', "l", or "o" as variable names as they can look like number or other letters especially at first glance "i"-->"l"-->"1").
It should be
if b in line:
print line.find(b)
as the two statements are related.
You read the file into a list but write the file as one string. Instead write one tuple per record. And delete loadTextString() as that is just confusing things.
save_text(listOfOldScores, "high scores.txt")
#
def save_text(scores_list, file_name):
file_handler = open(file_name, "w")
for tup in scores_list:
file_handler.write("%s, %d\n" % (tup[0], tup[1])) ## name and score
file_handler.close()
You should not use "i", "l", or "O" for variable names as they can look like digits as well as other letters. This code is a good example of why. You will have to discover the problem yourself (the problem may be caused by being too lazy to key in the extra letters), but the following code works for some reason whereas yours does not.
list_in = range(1, 10)
total=0
ctr=0
while (ctr < len(list_in)):
total += list_in[ctr]
ctr += 1
print total
The main problem is that you don't pass board to the function, update it, and then return the new board. Consider using a list instead of a string as it makes things much easier. Also use a loop to get the input instead of 5 separate sets of statements.
import random
def compturn(board):
print 'Computer turn:'
comp = str(random.randint(1, 9))
while comp not in board: ## occupied
comp = str(random.randint(1, 9))
"""
if comp == a:
compturn()
elif comp == b:
compturn()
elif comp == c:
compturn()
elif comp == d:
compturn()
elif comp == e:
compturn()
elif comp == f:
compturn()
elif comp == g:
compturn()
elif comp == h:
compturn()
elif comp == i:
compturn()
else:
"""
board=board.replace(comp, "O")
print "computer moves to square", comp
print board
return board
print """ I have yet to make a device that tells you if you win but enjoy!"""
board = """ 1 | 2 | 3
---+---+---
4 | 5 | 6
---+---+---
7 | 8 | 9 """
print board
move1 = raw_input('Where do you want to place your X? ')
#a = b = c = d = e = f = g = h = i = move1
board = board.replace(move1, "X")
print board
board=compturn(board)
#b = comp
move2 = raw_input('Where do you want to place your X? ')
#c = d = e = f = g = h = i = move1
board = board.replace(move2, "X")
print board
board=compturn(board)
#d = comp
move3 = …
If you want to save more than one grade per student, use a dictionary of lists.
marks = {"alice" : ["A+", "B-"], "smith" : ["A", "A"], "daemon" : ["B+", "B"], "lily" : ["B", "C"] }
There are examples on Daniweb that you can use as well as on the web. This is a very simple and common question.
I am not using 'textctrl' as i will have to create a seperate frame , add buttons and add functionality to that again which is again tedious.
Laziness is not a good quality. Everything, including programming, has a tedious part. In programming you do have to do it yourself, that is why it is called "programming", and not "already programmed". So if you don't enjoy it, find something that you do enjoy.
You can do it this way, but it would be better to use a for() loop:
ctr = 0
line1 = myFile.readline()
while line1:
myOut.write(line1.strip("\n")) ## 4 records without end-of-line
ctr += 1
if ctr > 3: ## 4 records written
myOut.write("\n")
ctr = 0
line1 = myFile.readline()