Your second wife calls your first wife “ma’am”
I wish.
A night out means sitting on the patio.
Your second wife calls your first wife “ma’am”
I wish.
A night out means sitting on the patio.
-m 1 (--max-count=one) = find the first occurrence only, so something like:
found = [line.strip() for line in open('myfile.txt') if "this string" in line.lower()]
print found[0]
#
# or if you like debuging hell
print [line.strip() for line in open('test1') if "my game" in line.lower()][0]
Use 'quotes as outer quotes or double the " inside quotes.
What space?
str_out = 'cat /home/myfile.txt |grep -m 1 "my game" '
## ^<-- this space???
proc = subprocess.Popen([str_out], stdout=subprocess.PIPE, shell=True)
#
# in Python
found = False
for rec in open("/home/myfile.txt", "r"):
if (not found) and ("my game" in rec.lower()):
print rec.strip()
found = True ## first record only
Split() each record. Don't use the first element of the list, join([1:]), in the first file. And, similarly, don't use the last element in the second file.
Try it the other way around?
inCur = gp.SearchCursor(myFeatureClass2,'COLLECTED_BY = "%s"' % (str(Name)), \
"", "", "DATE_COLLECTED A")
Generally, the name is also stored as "obrien" so you can find O'Brien, O'brien, Obrien, etc. I don't know if this is possible here or not.
I'm glad this thread has some occasional life still. Some old jokes: you know you are old when you go to smooth the wrinkles in you socks and realize you aren't wearing any. You know you are old when a night out is sitting on the patio.
What does the function normDistProb return? The first attempt to debug this should be to print it
for i in range(0,12):
listProbFog.append(normDistProb(dayValues[i], fogAve[i], fogVar[i]))
print normDistProb(dayValues[i], fogAve[i], fogVar[i])
print listProbFog
# the other lists are just extra cruft until you get this problem solved
I tried using the ordered dict, but its still giving the memory error
That is too vague to be of any value. Post the actual error. Also this line
if tuple(line[:2]) in od.keys():
should just be
if tuple(line[:2]) in od:
".keys" returns a list of the keys which means there is double the amount of memory for the number of keys. If you can not do this with the memory available, then you want to use an SQLite database on disk instead.
You must install the version of PIL for the Python version that you have on your system. You are trying to install PIL for Python2.6. Python2.6 can not be found on your system. Keying "python -V" (capital V, not lower case) on the command line will give you the Python version found on your system. PIL is available for Python versions 2.4, 2.5, 2.6. and 2.7, but does not yet run on any of the Python3 versions.
Also, form the habit of using a list instead of if/elif. It is more straightforward as all of the conditions are on one line. And verb[-2:] is just shorthand for verb[-2:len(verb)], just as verb[:-2] is shorthand for verb[0:-2].
verb = input("Write the verb here: ")
if verb[-2:] in ['ar', 'er', 'ir']:
#
else:
#
# or
found = False
for ending in ['ar', 'er', 'ir']:
if verb.endswith(ending):
found = True
If you are confident that the string is not wrap-
ped around (on 2 lines), then reading the file one record at a time and searching it is the accepted way to go. You have to look at every character in the file no matter how you do it.
An example for splitting a sentence http://www.java2s.com/Code/Python/String/Asentenceissplitupintoalistofwords.htm
A second dictionary is not required. Create a tuple containing item1 and item2 and look up in the dictionary. If found, you have a match. If you want to keep the keys in the same order as the file, use the ordered dictionary. For Python 2.7 it is in "collections".
"while True" serves no purpose in this program.
You never exit the "while True" so it is an infinite loop. Once you eliminate that, you should be able to print the final word_list list which will be a series of numbers. Sort the list and count each of the sequences of the same number. You should also get an error on this statement
text = text.join().strip()
What are you trying to do? Take a look at this doc to see what join() does http://docs.python.org/library/stdtypes.html
You want to start testing at the third element & checking the prior two. What you have will error because when the last element is reached, there is no +1 (also do not use "i", "l", or "O" as single digit variables as they can look like numbers).
## convert to integer
numbers = [int(x) for x in numbers]
for ctr in range(2, len(numbers)):
if numbers[ctr] == 1:
if numbers[ctr] == numbers[ctr-1] == numbers[ctr-2]:
print numbers[ctr], "occurs three times at positions",
for x in range(3):
print numbers[ctr-x],
print
Only one function is necessary as they both do the same thing. And I remember reading about "__main__" being necessary for a certain type of code on Windows, but don't remember what is was. Anyway, try running this code from a file, not from the command line, as see if it works ("__main__" is in the correct place--it just means that the calling program is this one, as opposed to the program being called from another program).
from multiprocessing import Process, Lock
def countodd(l, x):
while (x <= 10):
x = x+2
l.acquire()
print x
l.release()
def call(l):
p1 = Process(target = countodd, args = (l, x))
p2 = Process(target = countodd, args = (l, y))
p1.start()
p2.start()
p1.join()
p2.join()
if __name__ == "__main__":
x = 1
y = 0
lock = Lock()
call(lock)
Seems to work OK for me. What OS are you using? Is this a typo
def counteven(l, y):
if __name__ == '__main__':
while (y <= 10):
A mosquito has 47 teeth.
I had to look that up.
Mosquitoes have four knife-like tools of serrated teeth that surround a pair of fine tubes — one for dripping a pain suppressor and one for sucking blood.
A common house mosquito (Culex sp.) stabs the skin with her sharp snout and saws in with her four knife tools to draw blood. She shoots in saliva laced with anesthetic (to escape notice) and an anticoagulant (to keep blood flowing). Then she sucks blood.
In 90 seconds, she sucks enough blood to nourish 100 eggs or more — and is too heavy to fly. She makes a controlled descent to a close safe spot where she squeezes in on her abdomen. Water oozes out of the blood, filtered through the abdominal wall, and forms a large drop. Light again, she takes off.
During her short adult life (two weeks to a month) she bites one to three times, says Larry Weber, naturalist and author of Spiders of the North Woods. (Males feed on nectar and plant juices.)
I am aware of 2 existing packages, parallel python and coreit, but haven't tried either. Let us know how it goes.
You should state what it is you want to do. No offense but there are other solutions and perhaps someone here can come up with a workable solution. Generally you would use (although I can't really understand what you are asking):
class myClass:
def __init__(self, methodName="This is the result"):
self.methodName = methodName
MC = myClass()
print MC.methodName
If you want to associate 2 or more items, a dictionary is generally used. But again, if you state the problem, there will probably be better solutions presented.
See if this code example helps.
class Node:
def __init__(self):
infinity = 1000000
invalid_node = -1
self.distFromSource = infinity
self.previous = invalid_node
self.visited = False
def print_variables(class_instance):
print class_instance.distFromSource, \
class_instance.previous, class_instance.visited
def print_distance(from_node, to_node, distances, instances):
this_nodes_distances = distances[from_node]
print "node distance list for ", from_node, this_nodes_distances
to_node_distance = this_nodes_distances[to_node]
print "\nthe distance from %d to %d = %d" % \
(from_node, to_node, to_node_distance)
instances[from_node].previous = to_node
print "from_node class =",
print_variables(instances[from_node])
print "to_node class =",
print_variables(instances[to_node])
if __name__ == "__main__":
distances = [ [0,2,4,1,6,0,0],
[2,0,0,0,5,0,0],
[4,0,0,0,5,5,0],
[1,0,0,0,1,1,0],
[6,5,0,1,0,5,5],
[0,0,5,1,5,0,0],
[0,0,0,0,5,0,0] ]
## a list of Node class instances.
## the same number as the list 'distances'
class_instances = []
for x in range(len(distances)):
class_instances.append(Node())
print_distance(0, 3, distances, class_instances)
print_distance(3, 0, distances, class_instances)
The variable definitions come under the __init__ function (double underscores). If there is no __init__ function, then the code was never executed.
Isn't nodeTable a list of classes? So you would access it like this:
for node in nodeTable:
#if node != 0 and Node.visited == False:
#nearestNode = node[theNetwork]
#listOfNeighbours.append(nearestNode)
print node.distFromSource, node.previous. node.visited
That is if your class is constructed correctly, which it is not, so that is where you want to start (it has to be self.previous to be a member of the class which can be accessed outside the class). Try to simplify this and start with 2 nodes, which will be a 2x2 matrix and see it that is easier to understand. Also what happens if there is more than one node that is the same distance.
class TestIt():
def __init__(self):
self.x = 1
y = 2 ## no 'self'
if __name__ == "__main__":
X = TestIt()
print X.x
X.x = 3
print X.x
Y = TestIt()
Y.z = 5 ## new 'self.z' variable declared
print Y.z, Y.x
print Y.y
You have to define current distance from source, or distance for pairs, i.e. from node1 to node2 = x, node2 to node3 = y, etc.
1) change the button sizes to be all the same size (buttons are labeled decrease, surrender, remain, etc...)
You can use width and height on buttons the same way as done with Text in your program. Reference sites here and here
from Tkinter import *
class PreferencesWindow(object):
def __init__(self, master):
master.geometry("200x100+10+10")
row = 1
self.preferences_button = Button(master, text='Preferences', \
width=9, height=2, \
command=self.edit_preferences)
self.preferences_button.grid(row=row, column=0)
self.make_report_button = Button(master, text='Make reports', \
width=7, height=5, \
command=self.generate_reports)
self.make_report_button.grid(row=row, column=1)
def edit_preferences(self):
print "preferences callback"
def generate_reports(self):
print "generate_reports callback"
if __name__ == "__main__":
root = Tk()
app = PreferencesWindow(root)
root.mainloop()
Take a look at the "buttons" function in this code, as it should help with the StringVar, and with creating several buttons using a for loop. In this case the buttons are stored in a dictionary.
from Tkinter import *
from functools import partial
class TicTacToe:
def __init__(self, top):
self.top = top
self.button_dic = {} ## pointer to buttons and StringVar()
self.X_O_dict = {"X":[], "O":[]} ## list of "X" and "O" moves
self.top.title('Buttons TicTacToe Test')
self.top_frame = Frame(self.top, width =500, height=500)
self.buttons()
self.top_frame.grid(row=0, column=1)
exit = Button(self.top_frame, text='Exit', \
command=self.top.quit).grid(row=10,column=0, columnspan=5)
self.player = True ## True = "X", False = "O"
##-------------------------------------------------------------------
def buttons(self):
""" create 9 buttons, a 3x3 grid
"""
b_row=1
b_col=0
for j in range(1, 10):
## point the button number to a Tkinter StringVar()
self.button_dic[j] = StringVar()
## set the StringVar() to the button number
self.button_dic[j].set(str(j))
## set textvariable to the StringVar()
b = Button(self.top_frame, textvariable = self.button_dic[j], \
command=partial(self.cb_handler, j))
b.grid(row=b_row, column=b_col)
b_col += 1
if b_col > 2:
b_col = 0
b_row += 1
##----------------------------------------------------------------
def cb_handler( self, square_number ):
print "cb_handler", square_number
if self.player: ## True = "X", False = "O"
player = "X"
else:
player = "O"
##--- square not already occupied
if square_number not in self.X_O_dict["X"] and \
square_number not in self.X_O_dict["O"]:
## change the StringVar() to "X" or "O"
self.button_dic[square_number].set(player)
self.X_O_dict[player].append(square_number)
print player,
self.check_for_winner(self.X_O_dict[player])
self.player = not self.player
else:
print "Occupied, pick another"
##----------------------------------------------------------------
def check_for_winner( self, list_in ):
set_in = set(list_in)
winner_list = [[1, 2, 3], [4, 5, …
Split on "study", or a normal split on space(s) will also work as the number.txt will be -1, or the study's description will be everything except the last element.
A second way is to use a StringVar(). See the "textvariable" write up at http://infohost.nmt.edu/tcc/help/pubs/tkinter/button.html
You will have to put trace points in your program to see where it is hanging. I doubt it is here. Also, do not use "list" as a variable name as it is already used to name a function that returns a list, and that could be the problem because references to "list" are destroyed upon exiting the function, but it is impossible to tell from the code posted.
Since you did not state the problem, it is difficult to answer. After adding a colon on this line (was it an "illegal snytax error"?)
"for x in v"
it worked fine for me.
Code tags added.
I want to create a function wich prints all numbers over 1000000.
So the user can input for example 500 and that dosent print but if you input 1005000 it prints.My code far is.
v = [600,6300330,47, 1000001]
for x in v
if x >1000000:
print x
You can't combine grid() and pack() but must use one or the other. Also, AFAIK, one radio button must be selected (a default selection or you can't choose 'none' when using radio buttons), and the others can be deselected.
from Tkinter import *
class App:
def __init__(self, parent):
self.my_parent = parent
self.my_parent.geometry("200x100+10+10")
# self.fm = Frame(parent, width=400, height=300)
# self.fm.pack_propagate(0) # to keep the frame size
# self.fm.pack()
self.R1 = Radiobutton(self.my_parent, text="Red", value=1, command=self.make_Red)
self.R1.grid(row =2 , column = 1)
self.R1.select()
self.R2 = Radiobutton(self.my_parent, text="Blue", value=2, command=self.make_Blue)
self.R2.grid(row =2 , column = 2)
self.R2.deselect()
self.R3 = Radiobutton(self.my_parent, text="Green", value=3, command=self.make_Green)
self.R3.deselect()
self.R3.grid(row =2 , column = 3)
def change_buttons(self, color):
self.my_parent.configure(bg=color)
self.R1.configure(bg=color)
self.R2.configure(bg=color)
self.R3.configure(bg=color)
def make_Red(self):
self.change_buttons("Red")
def make_Blue(self):
self.change_buttons("BLUE")
def make_Green(self):
self.change_buttons("GREEN")
root = Tk()
root.title ("Color Option")
app = App(root)
root.mainloop()
The health variable would be the same as the location and inventory variables. Using a class makes this simple. Instead of "money", "rope", "shiny_stone", etc. I would suggest using a dictionary.
vars_dict = ["money":[0, "5 dollars sits upon the dresser."],
"rope":[0, "a pile of tangles rope is in the corner."],
"shiny_stone",[0, "A brilliant looking stone. It looks like it could be worth some money."]}
for var in vars_dict:
print var, vars_dict[var][0], vars_dict[var][1]
vars_dict[var][0] = text_game.Entity(var, vars_dict[var][1])
print var, vars_dict[var][0], vars_dict[var][1], "\n"
Use a for() loop with step=3.
DNA= "ATCGATCGATCGATC"
for ctr in range(0, len(DNA), 3):
print DNA[ctr:ctr+3]
The difference between
name1,number1;name2,number2;name3,number3
and
name1,number1
name2,number2
name3,number3
is a newline. Use rstrip() to strip the newline before you write to the output file.
out.write(line.rstrip())
You don't have a callback or any way to execute curselection. An example:
import Tkinter
class TestCallback:
def __init__(self, top):
self.top = top
self.top.geometry( "100x100+10+10" )
self.top.minsize( 200, 175 )
self.listbox = Tkinter.Listbox( self.top, height=6, width=20, font=('Fixed', 14) )
lit = [ "aaa", "bbbbb", "ccccccc", "dd", "e", \
"fff", "ggggg", "hhhhhhh", "jj", "m", \
"nn", "ooo", "ppp", "rr" "s" ]
for item in range( len(lit) ):
new_item = "%2d %-10s" % (item, lit[item])
self.listbox.insert(Tkinter.END, new_item)
exit = Tkinter.Button(self.top, text='Exit',
command=self.top.quit, bg='blue', fg='yellow' )
exit.pack(side="bottom", fill=Tkinter.X, expand=1)
self.listbox.pack(side="left")
self.listbox.see(2)
self.listbox.bind("<Double-Button-1>", self.test_callback)
def test_callback(self, event):
print self.listbox.curselection()
root = Tkinter.Tk()
TC = TestCallback(root)
root.mainloop()
I'm not sure I understand your question but if you want to use multiple class instances, one per dog, try something like this.
if __name__ == "__main__":
dogs = list()
dog_name = ""
first_inp = "Name: ('quit' to exit) "
second_inp = "Breed: "
while dog_name.lower() != "quit":
dog_name = input(first_inp).strip()
dog_breed = input(second_inp).strip()
this_instance = Dog(dog_name, dog_breed)
dogs.append(this_instance)
for each_instance in dogs:
print(each_instance.name, each_instance.breed)
However,i only can not figure out.....am I stupid??stupid logic??
can anyone help me?It is urgent..
No one cares if you are stupid or are stupid twice and have waited 'till the last minute. Ask a specific question.
For starters, break this into functions. For example, use one function to choose a square. If the player is the user, ask for an input from the squares available, and if it is the computer, do a random choice and return the selection.
Also, this line
cc=random.randint(0,len(AL)-1)
returns an integer in the range, but the squares will not all be available. Use
random.choice(AL) instead (and print these things while testing so you know if it is working).
Finally, you should have a separate function to check for a winner and can use
def winner_check(L):
winner_list = [ [0, 1, 2], [3, 4, 5], [6, 7, 8] ] ## etc
for each_list in winner_list:
print "checking", each_list[0], each_list[1], each_list[2]
if L[each_list[0]] == L[each_list[1]] == L[each_list[2]]:
print("Congraduation!You have won the game!")
return True
return False
def tie_check(L, AL):
## no squares left and no winner
if (len(AL)==0) and (not winner_check(AL)):
print "Tie"
## exit program
If you break the code up into functions and use variable names that are descriptive, (available_squares instead of AL), so the code is readable you will probably get more help. No on wants to clean up your mess.
Run the input files one at a time, i.e. run the program using the first file and check the output, then run the program again using the second file and check the output file, etc.
Use curselection to return the item number selected. Note that the title of this thread indicates that this is a "HowTo", a code snippet on how to do something, and not a question. You will possibly get more views=more responses when it is clear that this is a question.
Sorry, I don't have must experience with that. I only use SetBackgroundColour, etc.
try and convert the value from the numctrl to a decimal
You can not convert a float to decimal.Decimal because floats are inaccurate past a certain number of digits. You will have to get/enter the value as a string and convert.
Use a while() loop that checks for the answer. Also, you should print what options are available as an answer instead of making the enterer guess. This is not intended as a complete answer.
while intro not in ["yes", "no"]:
intro = input("Want to play a game of number guess? ('yes' or 'no'")
available_guesses = [str(x) for x in range(1, 11)]
while intro == 'yes':
guess = "0"
while guess not in available guesses:
guess = input("\nOkay. Just guess the number I am thinking of from 1 to 10. ")
while intro not in ["yes", "no"]:
intro = input("Want to play a game of number guess? ('yes' or 'no'")
(sorry i didn't know how to explain it well)
That is why you can't code it. You have to first explain it in words, in detail, in order to explain it in code?
getRow = "// " + ligne[0] + " " + ligne[2] + "\n\n" + ligne[1]
TypeError: 'NoneType' object is unsubscriptable
says that "ligne" is empty. You have to check for a successful lookup.
Many of us have an SQL generator in our tool box for quick and dirty apps. This is output from the generator and should help. It may require some tweaking because it is always a work in progress, but should give you some working code to start with, so run the program and take a look at the output from the tests and go from there.
import os
import sqlite3 as sqlite
##======================================================================
class DummyClass:
def __init__( self ) :
self.SQL_filename = './SQL_test_dbf'
self.open_files()
## END __init__()
##----------------------------------------------------------------------
def add_rec( self ) :
val_tuple=(int(self.id), str(self.titre), str(self.code), str(self.date))
self.cur.execute('INSERT INTO SQL_test_dbf values (?,?,?,?)', val_tuple)
self.con.commit()
## END AddRec()
##----------------------------------------------------------------------
def copy_to_struct( self, rec ) :
self.id = rec[0]
self.titre = rec[1]
self.code = rec[2]
self.date = rec[3]
## END copy_to_struct()
##----------------------------------------------------------------------
def del_rec( self, value_to_delete ) :
self.cur.execute("DELETE FROM SQL_test_dbf WHERE SQL_field=:name_dict", {"name_dict":value_to_delete})
## END del_rec()
##----------------------------------------------------------------------
def list_all_recs( self ) :
self.cur.execute("select * from SQL_test_dbf")
recs_list = self.cur.fetchall()
for rec in recs_list:
print rec
## END list_all_recs
##----------------------------------------------------------------------
def lookup_first_field( self, lookup_int ) :
self.cur.execute("select * from SQL_test_dbf where id==:dic_lookup", {"dic_lookup":int(lookup_int)})
recs_list = self.cur.fetchall()
print
print "lookup_first_field"
if len(recs_list):
for rec in recs_list:
self.copy_to_struct(rec)
self.print_rec()
else:
print "No records found for", lookup_int
## END lookup_first_field()
##----------------------------------------------------------------------
def lookup_first_2_fields( self, lookup_dic ) :
self.cur.execute("select * …
A cross platform solution is os.path.join(). The only gottcha is it sometimes gets confused when a "/" or "\" is included with the right-most string
print os.path.join("dir_1", "dir_2", "image"+str(12)+".png")
I am getting "syntax error - unindent does not match any outer indentation level"
Look at the line number of the error message (you didn't post it) and check that it, or sometimes the previous line, lines up correctly.
join() interleaves a list with a constant so
self.currentOutDir.join(self.counterStr)
would produce
self.counterStr[0]+self.currentOutDir+self.counterStr[1]+self.currentOutDir+self.counterStr[2]...etc.
A simple example:
x = ["1", "2", "3"]
print "a".join(x)
#
x = "123"
print "b".join(x)
res = self.dbUse.readRow(getidrow)
File "/home/steph/scripts/phpy/bdd.py", line 37, in readRow
getRow = "// " + ligne[0] + " " + ligne[2] + "\n\n" + ligne[1]
TypeError: 'NoneType' object is unsubscriptable
Should you be using "res" instead of "ligne", and does ligne/res contain at least 3 elements? For any further progress, you should submit a simple, complete example for the SQL portion, as there is too much guessing and that always compounds the errors. The wx part of the program can wait until this is solved.