You can answer the question "What's a floppy disk".
Steven.T commented: Thankyou a million, im only a beginner at python and this was killing me. Cheers +0
woooee 814 Nearly a Posting Maven
You can answer the question "What's a floppy disk".
I've added a print statement which should clarify what you are actually doing.
p = [1, 2, 0, -1, 3, 4, 5]
smaller = 0
bigger = 0
i = 0
while i < len(p):
print "comparing", p[1], p
if p[i] >= p:
bigger += 1
print bigger
i += 1
I think you want two for loops. Note that the logic is different if the list is sorted first.
stop = len(p)
for x in range(0, stop):
greater_list = []
for y in range(0, stop):
if p[x] < p[y]:
greater_list.append(p[y])
print p[x], "greater =", greater_list
You can read the entire file into a list, process the list once appending the record number to a dictionary of lists, with the "QA" field as the key. So if record #1 has QA=123 the dictionary would then be
index_dict[123] = [1]
for record #2 QA = 12
index dict[12] = 2
record #3 QA = 123 again
index_dict[123] = [1, 3]
You can then look up a specific QA value in the dictionary and know which records in the list to print. And how are you defining "duplicate record"? If it is subsequent records with the same QA value, then you can just store the original record in the dictionary instead of the record number. Post back if you want some help with this, or want to use SQLite which is the best solution for this.
It helps to look at this pictorially.
0 1 2 3 4 5 6 7 8 9 10 11 <===== number in the list
1* 1 1
2* 2 2
3
4 4* 4
5 5 5
6 6* 6
7*
8 8 8*
9 9*
10 10* 11*
So the longest chain would be 1-2-4-6-7-9-10 = "2" from first list, "3" from 2nd list, "4" from 4th list, etc
or 1-2-4-6-7-8-11
A linked list variation would probably work with the longest chain being having the most links.
The number of groups that need to rotate and the step size is based on user input.
The OP is asking how to use a variable for range and step, based on user input, specifically
rotationarray[rotation][3] contains the whole rotation range and
rotationarray[rotation][4] contains the step size
OMG?? (this isn't high school).
You would use one separate class as a container for each item, containing the name, id, price, quantity, and any other info for that item.
class Item:
""" contains all information for an item
"""
def __init__(self, ID, name, price, start_qty):
self.ID = ID
self.name = name
self.price = price
self.quantity = start_qty
## simulate the functions
## add 5 new items
add_to_list = []
for x in range(5):
class_instance = Item("ID"+str(x), "test-"+str(x), 10.20+x, 10+x)
add_to_list.append(class_instance)
## subtract one from 'ID2'
for class_pointer in add_to_list:
if "ID2" == class_pointer.ID:
print "before", class_pointer.quantity
class_pointer.quantity -= 1
print "after", class_pointer.quantity
## print all info
print "-" * 30
for class_pointer in add_to_list:
print class_pointer.ID, class_pointer.name, \
class_pointer.price, class_pointer.quantity
You can use variables for this, if that is what you are after (untested code).
rotation_in = int(raw_input("Enter rotation "))
for el in rotationarray:
if rotation_in == el[3]:
print el
for x in range(0, el[3]+1, el[4]): ## start, stop, step
print x
"filename" should contain the complete path, not just the file name.
Note that #1 is "Create a new order". Start there. Are you going to use a GUI or the command line to enter the order?
Once you have an order, then you have to store it either in memory or on disk, or both.
Once you have the orders stored, you will have to access them in some way, so you will either have to index them or search through the entire file every time you want to find one order.
My second condition is where all the columns have numbers in them.
This would simply be an extension of your previous code.
def columns_full(x):
""" Returns True if all columns are full
Returns False if there are available spaces
"""
for col in range(5):
if x[col][0] == "x": ## Not full
return False
return True
Note that you can also store by column and not by row. Using a dictionary to do this, the key = column number, pointing to a list that contains the items in that column.
You should re-think your logic for the first snippet. And please don't use "i", "l", or "O", especially when you are displaying programing snippets. There are 23 other letters.
def scanum(x):
try:
v=float(x)
return x
except:
return False
ret_val = scanum(0)
if ret_val:
print "True"
else:
print "False"
ANNAPOLIS, Md. - Is that spring in the air — or an old gym sock on fire?
In sailing-crazy Annapolis, boaters celebrate the first day of spring with a ceremonial Burning of the Socks, signifying it will soon be warm enough to wear boat shoes without socks.
"It's a good idea to stand upwind," warned John Morgan, 77.
I guess we have now begun the clothing section of this thread.
went to the Stanford site and this looks interesting. Does anyone know if it'll work on a Mac running Win XP in Parallels?
You are running XP on a Mac? In any case, if XP is running the folding@home XP version should work. Post your results in case there is someone else in the world just as strange and wants to know the same thing.
Dictionary doesn't allow to sort the keys or values so in that case I need to transfer it to the list. Is it correct to do it this way?
That is the way that it is usually done. In fact I can't think of any other way to order keys in an existing dictionary. Note that you are re-using the same variable here
h=histogram(h)
In this case it doesn't matter but it is not a good habit to form. Also, when you start debugging code you will learn the importance of descriptive variable names.
If you are calling the programs from a Python program, you can simply pass the parameter as an arg to the program or to the function being called within the program. Subprocess works fine for this http://www.doughellmann.com/PyMOTW/subprocess/index.html#module-subprocess
Consider which of next words must be replaced if 'of' is in word list:
'''off shore switch off often "of course" of.'''
The simplest way to handle that is to use a dictionary of lists with the key being the length of the word and the list containing all words of that length, so the modified code would be
if word in words_dict[len(word)]:
Good luck on the rest of the code.
Thanks woooee!
I am beginner and dont know how to create list or dictionary. Can you give me some idea?
Here is a link to an online book explaining lists http://www.greenteapress.com/thinkpython/html/book011.html
def sort(self, x):
It is bad form to re-define reserved words like "sort" so use a more descriptive name (sort what?) and avoid the confusion. Also, you should include one function at a time and test it, then add another, etc. And why are all of the functions staticMethods? Perhaps I just don't understand the logic.
thanks... do you know how i can fix it now though?
"thanks... do you know how i can fix it now though?"
Re-post the code as a new reply with code tags around it.
Looks like there is a problem with the new page form, i.e ["QUOTE"] does not work.
Sorry, but the question has to be more specific. For one thing, you want to use a loop to deal until the user says stop, so next you want a loop and some sort of input from the user.
If you want to print one month and not keep the info, then use a list to store all of the values, monthly[0] += rainfall, etc. On the first day of a new month, print the results, zero the list, and start adding again. If you want to retain the data then consider using a dictionary with each month as the key, pointing to a list of the values you want to keep.
And you have to supply the path unless sample.txt is in your PYTHONPATH.
os.system("grep %s ./sample.txt" % variable) ## current directory
I would suggest that you print Dictionary to make sure that it is in the form you require. You only read the Search file one line at a time:
Dictionary = set(open("e:/assignment/dictionary.txt"))
print Dictionary
SearchFile = open(input("Please Enter a File Path: "))
WordList = set() ## WordList is a set not a list
for line in SearchFile:
line = line.strip()
if line not in Dictionary:
WordList.add(line)
print(WordList)
Take a look at the Python Style Guide when you have time http://www.python.org/dev/peps/pep-0008/ The variable name conventions make it easier for others to understand your code. Also include your code in code blocks the next time (the # symbol at the top) as indentation is significant in Python.
Bikinis were worn as early as 2000 BC in Sicily.
They were of course full length dresses, but 4010 years of use has cause some wear and tear shrinkage. The last part of the name comes from a South Pacific word for coconut (don't remember which island), so coconut shells were evidently used for a similar purpose.
And no one has mentioned an SQLite file on disk because? You could also use dbm or anydbm if you don't want to try SQLite, but speed of these for that many records may or may not be a drawback. Also with these, each key has to be unique, but if you just want to store/count unique addresses that should not be a problem.
I think you want to join() everything after the first sub-string if destination does indeed contain spaces, or simply split on the colon if you know that there is never more than one in the file.
for x in ["Branch: ltm_7.4\n", "Destination: Test 5\n"]:
x = x.strip()
substrs = x.split()
## Note that join() concatenates the remaining strings
print substrs[0], "----->", " ".join(substrs[1:])
It's a trick question because you don't store the values in a separate variable (that's why we have lists), you use
short_list[0].strip()
short_list[1].strip()
short_list[2].strip()
or strip all of the values in short_list if you don't want to strip() each time.
short_list = ['a\n' , 'b\n', 'c\n']
for x in range(len(short_list)):
short_list[x] = short_list[x].strip()
I tried to add more entry boxes and make them a difference size then the rest but using the width= under the if ipos: changes them all -__-.
Just use a separate block of code to add the additional entry boxes that are a different size, or add a width parameter to the info list.
For future reference, a Google for "python find from one list in another list" listed this link among others http://www.daniweb.com/code/post968722.html
Looks like you are only asking 2 questions.
=====> if (correct + incorrect) < 2: <=====
self.button = Button(win, text = 'Next Question')
self.button.config(command = self.action)
self.button.pack()
if self.action == None:
incorrect += 1
else:
correct += 1
else:
self.label.config(text = 'Number correct %i' %correct)
And, you might consider a dictionary for the cities, using the number, (1,2, etc) as the key pointing to the name.
if number ==1:
self.label.config(text = 'What is the population of Philadelphia? ')
##
## replace with something along the lines of
self.label.config(text = 'What is the population of %s? ' % (city_dict[number]))
No testing is necessary. SQLite has been up and running for years and is fully reliable. Just write your code and go.
As far as I can tell, both of these options work.
x=16
backslash = chr(92)
part1 = '\x03\xa2'
part2 = hex(x)[1:]
command2 = "%s%s%s" % (part1, backslash, part2)
command3 = part1 + backslash + part2
sorry wrong error this is the error
AttributeError: Application instance has no attribute 'toggle'
"toggle" is no longer a member of Tkinter. You re-defined it as a member of your Application class.
I've tried everything and it gives me all types of errors.
It worked find for me. I clicked button 8 and it displayed "button 8 clicked", so you'll have to include the error message(s) for any further help.
I'm not sure I quite understand this. I only want a function to display text in the field depending upon what is checked. Is there anyway to do this within the function using if/elif/elif/else/
Thank you
What you display would depend on the button number sent to the function. A convenient way would use a dictionary with the button number as key pointing to the text, so it would be
self.pp_txt = desc_dict[cb_number]
If you run the code, you will see that a different number prints for each different button checked.
Who wants to know this, why do they want to know, and what's their secret motive for collecting all of this information? By definition, no one who takes the test could be a conspiracy theorist.
set.defference() would be the easiest if record order doesn't matter, otherwise you would have to index by record number and search the next x records to determine if a record was not found, and then go back to the original point. And you could probably delete records that were just " </group>", "<user>", "</user>", etc.
file_input_1 = [ "record 1\n",
"record 2\n",
"deleted from 2nd file\n",
"record 3\n",
"record 4\n",
"record 5\n" ]
file_input_2 = [ "record 1\n",
"record 2\n",
"record 3\n",
"record 4\n",
"added to 2nd file\n",
"record 5\n" ]
set_1 = set(file_input_1)
set_2 = set(file_input_2)
diff_1_2 = set_1.difference(set_2)
diff_2_1 = set_2.difference(set_1)
print(diff_1_2)
print(diff_2_1)
You have to define "different" before you begin. Do you want to compare the first record in the first file to the first record in the second file, and the second record to second record, etc.? What happens if one of the files has one record more than the other file, or is that detail not to be considered. Generally you would read the files into lists using readlines and then check first to first, second to second, etc. for a one to one check. You could also read both files, compare the records, read both files, rinse and repeat. Linux provides this with diff (man diff) if you are running one the the Linux distros.
when moving (or tracing a line) between point A (with coordinates x1,y1) and B (with coordinates x2,y2).
If you know how to get from A to B, can't you count the number of grids as you go. Assuming that each grid is the same size, you can then multiply, or do you want to know how to trace a line between the two points as well?
I generally use a dictionary to store the buttons, but in any case you pass the button number to a callback bound to the specific button. You should also use one function to create a button, and pass the button's text, etc. to the function. Note that this does not use a grid, but you should get the idea.
def one_button(txt, var):
b = Checkbutton(self.frame, text = txt, variable=var)
b.pack()
def handler ( event, self=self, button_num=self.button_num ):
return self.cb_handler( event, button_num )
b.bind ( "<Button-1>", handler )
self.button_num += 1
return b
##-------------------------------------------------------------------
def cb_handler( self, event, cb_number ):
print cb_number, "button pressed"
You would have to test each record for the specific info you want to keep, "Ship", "start_time", etc., and store it, probably in a dictionary. If the example you posted has not been "improved" for our readability then you can start writing once you hit *END*, headers first and then each record in turn. You would probably want a comma delimited file, if there isn't any commas in the records themselves, to import in Excel. Start with reading one file, one record at a time. Next, initialize a dictionary with the keys you want to search for. It appears that you can search the dictionary using the first word in each record, (strip non-letters and split). Post back with some code for more assistance and see 10.8, Text Files, here http://openbookproject.net/thinkcs/python/english2e/ch10.html
I tried adding in where you had edited.. but it doesn't seem to work still.
Test each function individually and post what "doesn't work" means for each individual function.
You should not be using "string" as a variable name as it is used by Python. Also, "i", "l" and "o" are not good choices for single letter variable names as they can look like numbers. Test each function individuallty and see comments in the code.
def searchAuthor(dataList, string):
print"\n"
print"Search results:"
i = -1
for listIndex, subList in enumerate(dataList):
try:
ind = subList.index(string, i+1)
## test for a successful find, -1 == not found
if ind > -1:
## you are searching through subList but sending
## authorsList to the print function
## Make sure they are properly aligned
print authorNameOutput(authorsList[listIndex]),". (",papersList[i][0],"). ",papersList[i][1],". ",journalsList[i],"."
break
except ValueError:
print "\n Please search again"
break
##
##-----------------------------------------------------------------------------
def search(dataList, string):
"""This is the search function that searches the defined
string within its respective list"""
print "\n"
print "Search results:"
i = -1
for value in dataList:
try:
## while loop is not necessary and is an
## infinite loop that will only stop if string is found
while 1:
## do you want to look in dataList or value?
ind = dataList.index(string, i+1)
## same thing here
if ind > _1:
## you are searching through dataList but sending
## authorsList to the print function
print authorNameOutput(authorsList[i]),". (",papersList[i][0],"). ",papersList[i][1],". ",journalsList[i],"."
break
except ValueError:
print "\n Please search again"
break
Add some print statements to ferret out what's happening, for example:
And Idle (comes with Python) is much easier to use than the Python shell/command line.
word=str(raw_input("Please enter a string:"))
## Don't use 'string' as a variable name
input_string ="word"
word_rev =word[::-1]
print "comparing", input_string, word
if (input_string == word_rev):
print "The word your have entered is a palindrome"
else:
print"The word you have entered is not a palindrome"
And note that "banana" is not a palindrome, so you should use another word like "racecar".
My question is - should all strings be Python strings
It's always a good idea to convert to Python strings.
The idea is for the python - tk-inter window to pop up just after boot up and start its routine.
There is no GUI until X is started so no Tkinter (you may be able to use TCL or Curses depending on when you run it), so you should add the program to ~/.xinitrc or to the ~/xfce startup script. I use fluxbox so am not sure what the startup script is
What method are you using to access the office computer from home and can you sign in and get the necessary permissions so as to execute files from home?
2. Check if the latest nightly build has been successful. If it is successful, deploy it on a test environment by clicking on 'Deploy this build' link.
It should be simple to have a cron job that runs a program to test for a successful nightly build, using name, time written, or seeing a new file, and then run whatever you want to run, but I don't know what it is that determines if the build has been successful or not, so can't really say.
You are on the right track with the dictionary, but am not sure exactly what you want to do. Some input and output data might help. This code is an example of what I think you want.
SYMTAB = {"START":' ', "BYTE":" ","WORD":" ", "RESB":" ","RESW":" ","END":" ","BASE":" ","NOBASE":" "}
test_list = [ "START 1000\n", "JUNK 2000\n", "END 3000\n" ]
for rec in test_list:
rec = rec.strip()
substrs = rec.split()
## assume the keyword is always the first word
print substrs[0],
if substrs[0] in SYMTAB:
print "FOUND = xx %s" % ( " ".join(substrs[1:]) )
else:
print "NOT FOUND"
Using canvas.delete() speeds things up considerably. I have added timing to the DrawBall() function. It starts around 0.000060 seconds and takes double the amount of time after a few seconds. I would guess that this is because of the use of global variables (globals take more time than locals), but I don't really know. Try your code using a class structure, or passing one dictionary containing all of the variables to and from the functions instead of the globals.
def DrawBall():
#draws ball
start = datetime.datetime.now()
print "/ndraw ball start", start
global ballX,ballY
canvas.create_rectangle(ballX,ballY,ballX+20,ballY+20,fill="white",width=0)
print "draw ball end ", datetime.datetime.now() - start
return ball
def EraseBall(ball):
#erases ball
canvas.delete(ball)
I tried to install matplotlib/pylab to run your code but there are problems with the png dependency and I can't spend any more time on it now. Anyway, this line seems to be the problem
plot ( range(0,11),[9,4,5,2,3,5,7,12,2,3],'.-',label='sample1' )
##
## try using this and see if there is any difference
##
x_list = arange(range(0,11))
y_list = arange([9,4,5,2,3,5,7,12,2,3])
plot( x_list, y_list, 'b')
show()