I have code for the chart but I just don't know how to insert the data into it.
ASCII "data" is just integers from 0-255
I have code for the chart but I just don't know how to insert the data into it.
ASCII "data" is just integers from 0-255
Check out the difference between copy and deepcopy as well. You probably want deepcopy (not a copy, and not a reference pointer to the list) since b is a list of tuples
a=[[(34,5),(34,6)],[(35,5),(35,6)]]
b=[(36,5),(36,6)]
a.append(copy.deepcopy(b))
You can pass the acceptable values to the checkInput() function and let it do the work. For the getFloat() function, use a try/except to test for correct input.
def checkInput(prompt, values_list):
print "\n"
while True:
result = input(prompt).strip()
if result.lower() in values_list:
return result
print("Please enter an appropriate value --> " + ", ".join(values_list))
deg = checkInput("Do you have Celsius, Fahrenheit, or Kelvin? ", \
['c', 'celsius', 'f', 'fahrenheit', 'k', 'kelvin'])
cdeg = checkInput("Convert to: Fahrenheit or Kelvin? ", \
['f', 'fahrenheit', 'k', 'kelvin'])
print deg, cdeg
def getFloat(prompt):
while True:
result = input(prompt)
try:
return float(result)
except:
print("Enter a number only\n")
fcel = getFloat("What is the degrees in Celsius? ")
print fcel
and then i have to write down the programm to get dictionary of people that know each other depending on the pictures they were on together
The index would be the photo, pointing to a list or set of all people in the photo.
now i would have to edit my program to get all the pairs of people that ever apeared on the picture together
If you mean pairs that have been in more than one photo, you would take each photo/key in the dictionary, loop through the items to get one pair at a time, and see if both of the people in the pair are in any other of the dictionary's items.
# pseudo-code
keys_list = dictionary.keys()
for ctr, key in enumerate(keys_list):
## assume split into pairs to create tuple, each_pair
for each_pair in dictionary[key]:
# search the remainder of the dictionary
for key_2 in key_list[ctr:]:
if pair[0] in dictionary[key_2] and pair[1] in dictionary[key_2]:
print "found", pair, "in", key, key_2
A class does not exist, it is a prototype for actual objects. Only a class instance exists. That is why we declare an instance for each class object desired.
class Person(object):
def __init__(self, name, health=100):
self.name=name
self.health=100
def hurt(self, amount):
print("%s health = %d - %d" % (self.name, self.health, amount))
self.health-=amount
class Killer(object):
def __init__(self):
import random
power= random.randint(10, 21)
self.power=power
print("power:", self.power)
def stab(self,Person):
Person.hurt(self.power)
K = Killer()
James=Person('James')
Karen=Person('Karen')
K.stab(James)
K.stab(Karen)
K.stab(James)
Did you commit() afterwards? All of my links are pretty old http://eringary.com/python/pysqlite.html
The online books cover dictionaries extensively https://secure.wikimedia.org/wikibooks/en/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Dictionaries.
For storing a few values, like phone number and e-mail address, you can use a list which is easier to understand and use.
AB={'Joshua' : ['sho0uk0m0o@gmail.com', '(802) 3-5-2206'],
'Ashley': ['a000@gmail.com', '(802) 820-0000']}
print "%s, e-mail=%s, phone=%s" % ("Joshua", AB["Joshua"][0], AB["Joshua"][1])
new_name = "Bill"
new_email= "bill@domain.com"
new_phone= "(802) 123-4567"
AB[new_name] = [new_phone, new_email]
print AB
I would suggest something like the following. I am no SQL expert, but using a dictionary to hold the variables eliminates SQL injection problems, or so we think.
cur.execute('SELECT * FROM inventario WHERE codigo==:dic_var', \
{"dic_var":resultado})
recs_list=cur.fetchall()
#
#-----take a look at the contents of recs_list FYI
print recs_list
Also, this code
def OnBuscar(self, event):
con = lite.connect("MiBase.sqlite")
cur = con.cursor()
establishes a connection every time the function is called. You should establish a connection once, and store as an instance variable of the class, or pass "cur" to the function (and "con" if using a commit). An example:
class InsertarDato(wx.Frame):
def __init__(self, parent, id, title):
self.con = lite.connect("MiBase.sqlite")
self.cur = self.con.cursor()
def OnBuscar(self, event):
resultado = self.tc1.GetValue()
self.cur.execute('SELECT * FROM inventario WHERE codigo==:dic_var', \
{"dic_var":resultado})
recs_list=self.cur.fetchall()
print recs_list
You can multiply the number by 100 and use integers, or truncate to 2 decimal places when printing floats. On most modern computers a float is a binary number as defined by the IEEE Floating Point Arithmetic Standard and represents numbers 1,000,000,000,000 to 0.0000000000000001 (at a minimum). Floats (actually a C double) have plenty of precision for 2 decimal monetary numbers.
x = 0.1+0.2
print repr(x)
y = "%3.2f" % (x)
print y
x = 0.1+0.2+0.005
print repr(x)
y = "%3.2f" % (x)
print y
SQLite is separate from wxPython, so the two are independent of each other. You can enter a value in wxPython, retrieve the value from the wxPython entry box, and then add it to a SQLite database, or vice-versa. I would suggest starting with a simple program that asks for a name, for example, and adds the name to a database. It doesn't matter what it is as long as it is simple . Use one class only for all of the wx statements, and another class for the SQLite statements. Next you can add another function to ask for a name to look up in the database and display the results. You have posted 99 lines of code, and have not stated clearly what the problem is. Start with a smaller program that makes it easy to understand what it does, and state any problems, i.e. what was expected and what actually happened. For example, the wx class would instantiate the SQLite class, which would open the file when the __init__ function is called. You would then retrieve the name or whatever, still in the wx class, and pass it to an "add" function in the SQLite class which would add the record, etc.
Also you should check the value of this statement
out = out + key1[key1.index(i)+3]
to make sure that key1.index(i)+3 isn't greater than the length of the list, key1.
while look () == Void:
will loop indefinitely when they are not equal because the contents of the variable Void and the function look() don't change. You might want to send some variable to look() and return something other than the value of the Void when you want to exit. Functions explained http://greenteapress.com/thinkpython/html/book004.html#toc28
You should also be able to use the list as is, something like this:
for i, record in enumerate(reader):
if (i > 0) and (len(record) > 7): #skip headers & record has all the fields
print "date =", record[0]
print "hk =", record[1]
print "ba =", record[2]
## etc.
(Reuters) - A mine awareness team in Uganda was horrified to find an unexploded bomb being used as a bell when they visited a school to teach children how to spot bombs, a local newspaper reported.
The Anti-Mine Network organization saw teachers banging the bomb with stones to call children to lessons in a 700-pupil school in a rural area, the Daily Monitor said.
"Its head was still active, which means that if it is hit by a stronger force, it would explode instantly and cause untold destruction in the area," Wilson Bwambale, coordinator of the organization, told the newspaper.
+1 for HTML. People are familiar with web browsers and you can generate the code via Python if you want.
Meaning that if user A asked to perform some task X, which took 10 minutes, user B will not be able to perform a new task Y until X would have ended.
That is usually done via a lock file, which each process checks before it begins.
First, my personal opinion is that "in" is more straight forward than "-1"
#elif self._wordAt[w][-1] != linenum: # occurring on a new line for this word
elif linenum not in self._wordAt[w]
self._wordAt[w].append(linenum)
To get the number of times it occurs, I would suggest that you print 10 items of the dictionary. This should give you an idea of how to get the number of occurrences for each word; {"the":1, 3, 7} = "the" occurs in 3 lines.
You perhaps want something along the lines of:
class someclass:
def __init__(self):
self.somevariable='somevalue'
def somefunction(self):
print('gotta get here')
def someotherfunction(class_instance):
print "somevariable -->", class_instance.somevariable
print "somefunction -->",
class_instance.somefunction()
myclass=someclass()
someotherfunction(myclass)
Generally, you would store the next time you want to execute, i.e. now+10 seconds,
using a loop,
call the function,
upon the return get the time and calculate the difference between it and the next time and sleep that amount of time,
update the next time, (+10 seconds), and loop again.
Also, Python has a schedule module, as do most operating systems. On Linux you can use cron to execute the program every 10 seconds, if you want to continue forever.
I would not be concerned about the differences between 2.6 and 2.7. Using 2.7 is only slightly different than 2.6. There are some third party packages that are not yet available for 2.7 though.
The original problem is that the OP is iterating through the list
l=list(s) #['j', 'a', 'n', 'k', 'o', 's', 'i', 'e', 'n', 'a', 'p', 'i', 'v', 'o']
f=[]
for i in l: ## <-- iterating through the input list
f.append(l.count(i)) # [1, 2, 2, 1, 2, 1
instead of through a list of letters, which would eliminate the duplicate problem.
l=list(s) #['j', 'a', 'n', 'k', 'o', 's', 'i', 'e', 'n', 'a', 'p', 'i', 'v', 'o']
f=[]
##for i in l:
for i in string.lowercase: ## "abcdef...etc" --> count each letter once
f.append(l.count(i)) # [1, 2, 2, 1, 2, 1
but since this is homework, no one wants to give out a complete solution/
Dictionary keys are stored in "hash" order, not the order they were entered (a dictionary is an indexed container, not a sequential one). You should either sort the keys, and then use the sorted list to lookup in the dictionary, or use "ordered dictionary", which usually requires importing "collections" depending on your version of Python.
Why are you going through the following gyrations instead of using "t". Also, please do not use "i", "l", or "O" as variable names as they can look like letters.
t=s.split()
delimiter= ''
s=delimiter.join(t)
l=list(s)
Match up the parens on the previous, raw_input, statement. Also, the welcome() function does nothing.
I am guessing that the window doesn't contain anything visible, just containers. (This just displays a button.)
import sys
from PyQt4 import QtCore, QtGui
class UI_CMDTester:
def __init__(self):
self.__app = None
self.__win = None
def init(self, \
w_title, \
w_width, \
w_height):
self.__app = QtGui.QApplication(sys.argv)
self.__create_win(w_title, w_width, w_height)
sys.exit(self.__app.exec_())
def __create_win(self, w_title, w_width, w_height):
self.__win = QtGui.QWidget()
self.__win.resize(w_width, w_height)
self.__win.setWindowTitle(w_title)
close_button = QtGui.QPushButton("&Quit")
layout = QtGui.QGridLayout()
layout.addWidget(close_button, 1, 0)
self.__win.setLayout(layout)
self.__win.show()
if __name__ == "__main__":
obj_ct = UI_CMDTester()
obj_ct.init("Window", 800, 600)
The result is correct since you open it for reading before anything is written to it.
text = "aim low and reach it"
fname = "test7.txt"
with open(fname, 'w') as foutp:
# write text to file
foutp.write(text)
# read text from file
with open(fname, 'r') as finp:
mytext = finp.read()
print("to file --> %s" % text)
print('-'*30)
print("from file --> %s" % mytext)
If it is easier to understand, reduce the lists first and then create the dictionary.
list_1= ['0 ', '512 ', '1 ', '513 ', '2 ', '514 ', '3 ', '515 ', '4 ', '516 ', '5 ', '517 ', '6 ', '518 ', '7 ', '519 ', '8 ', '520 ', '9 ', '521 ', '10 ', '522 ', '11 ', '523 ', '12 ', '524 ', '13 ', '525 ', '14 ', '526 ', '15 ', '527 ', '16 ', '528 ', '17 ', '529 ', '168 ', '530 ', '169 ', '531 ', '170 ', '532 ', '171 ', '596 ', '172 ', '597 ', '173 ', '598 ', '174 ', '599 ', '175 ', '600 ', '176 ', '601 ', '177 ', '602 ', '178 ', '603 ', '179 ', '604 ', '180 ', '605 ', '181 ', '606 ', '182 ', '607 ', '183 ', '608 ', '184 ', '609 ', '185 ', '610 ']
list_2 = ['0', '344', '1', '345', '2', '346', '3', '347', '4', '348', '5', '349', '6', '350', '7', '351', '8', '352', '9', '353', '10', '354', '11', '355', '12', '356', '13', '357', '14', '358', '15', '359', '16', '360', '17', '361', '18', '512', '19', '513', '20', '514', '168', '515', '169', '516', '170', '517', '171', '518', '172', '519', '173', '520', '174', '521', '175', '522', '176', '523', '177', '524', '178', '525', '179', '526', '180', '527', '181', '528', '182', '529']
print [[list_1[y], list_2[y]] for y in range(1, len(list_1), 2)]
It works for me on Slackware Linux as well. Are you behind a firewall?
Generally speaking, a dictionary should be used instead of several if/elif/else statements. It is easier to read and understand, and easier to modify since entries can be added or deleted from the dictionary. You will probably use dictionaries quite often so try to become more familiar with the object over time.
The pointer is positioned at the end of the file so nothing is read.
import tempfile
if __name__ == '__main__':
test = tempfile.NamedTemporaryFile()
test.write('asdfsadfsadfsadfasdfasdfsadfsdfsadfsadfs')
test.seek(0) ## offset=0 --> beginning of file
print "\n test read", test.read()
print test.name
wx has a CallAfter method. It will require some implementation of multiprocessing/threads however you do it since you want to do two things at once: 1) wait for a button press, 2) keep track of the time that has passed. This programs waits for 5 seconds, simulating waiting for a button press, and after 5 seconds exits.
import time
from multiprocessing import Process
class TestClass():
def test_f(self, name):
ctr = 0
while True:
ctr += 1
print ctr, name
time.sleep(0.5)
if __name__ == '__main__':
CT=TestClass()
p = Process(target=CT.test_f, args=('Simulation of MessageBox',))
p.start()
## sleep for 5 seconds and terminate
time.sleep(5.0)
p.terminate()
p.join()
print "\n\ndestroy here"
Lists are passed by reference, so the tuple contains the memory address of the list, not the list itself, and that doesn't change. Both of these statements will fail
my_tuple = (1, 2, 3, [4, 5, 6])
new_list = [4, 5, 6]
my_tuple[3] = new_list ## new memory address
my_tuple[1] = "a"
The program has to take as input a .csv file and manipulate it and plot it accordingly.
The Python wiki contains a section on plotting tools. Other than that your question is impossible to answer as we have no idea if it is a 2D or 3D, bar or graph, etc. At the very least you should include code to read the file into a data container, and a sample of the data you want to plot.
Using the datetime module is an easy way to subtract one time value from another IMHO.
import datetime
# subtract 10:02:59 from 12:01:02
difference = datetime.datetime(2011, 5, 11, 12, 1, 2) - \
datetime.datetime(2011, 5, 11, 10, 2, 59)
print "the difference is %s" % (str(difference))
#
# also note that split(":") is a better way to split the input
# and you can also check for len == 3
time_input = "2:03:05"
print time_input, "-->", time_input.split(":")
First, there are two types of variables in classes, attributes and instance variables. I think you want instance variables, so you can have more than one human for example, with separate values for each one.
class Human:
def __init__(self):
self.isplayer = False
self.nhealth = 20.0
def health_add_one(self):
self.nhealth += 1
## 2 separate humans
instance_1 = Human()
instance_2 = Human()
instance_1.health_add_one()
print instance_1.nhealth
print instance_2.nhealth
Next, store each instance in a dictionary or list that you can pass around the program.
You can just code a while() instead of the if() and while().
hours = 0
while int(hours) > 60 or int(hours) < 1:
hours=raw_input('Hours worked:')
#
# the following is poor syle; use if statement instead
#if hours == 'DONE':
#break
#else
#
if hours.upper() != 'DONE':
hwage = 0
while int(hwage) > 20 or int(hwage) < 5:
hwage=raw_input('Enter hourly wage:')
#
#etc. for the rest of the input
I try to remove the wx.GridSizer and replace it with another one.
The wxpython docs list Detach, Remove, and RemoveSizer for a Sizer widger (GridSizer is a subclass of Sizer). So it would be something like (sorry, 186 lines of code is more than I want to wade through, though someone else may do it)
sizer = self.mainPanel.GetSizer()
sizer.Detach(0)
#
# or
sub_sizer = wxGridSizer(vgap=10, hgap=10)
sizer.Remove(sub_sizer)
#
# Not a good example, but it works
#
import wx
class Test:
def __init__(self):
app = wx.App(False)
self.app = app
frame = wx.Frame(None, wx.ID_ANY, "Test App")
panel = wx.Panel(frame)
vboxsizer = wx.BoxSizer(wx.VERTICAL)
self.frame = frame
self.panel = panel
self.grid = wx.GridSizer(rows=0, cols=3)
self.button_dict = {}
x = 10
y = 20
for j in range(5):
print j, x, y
b = wx.Button(panel, label="Remove Button %d" % (j), id=j, pos=(x, y))
self.grid.Add(b)
b.Bind(wx.EVT_BUTTON, self.removeButton)
self.button_dict[j] = b
x += 50
if j == 2:
x = 10
y = 30
exit = wx.Button(panel, -1, 'Exit', (10, 200))
exit.Bind(wx.EVT_BUTTON, self.exit_this)
vboxsizer.Add(self.grid, 1, border=2, flag=wx.EXPAND|wx.ALL)
panel.SetSizer(vboxsizer)
frame.Show(True)
app.MainLoop()
def removeButton(self,e):
button_num = e.GetId()
print "ID =", button_num, type(button_num)
if button_num in self.button_dict:
self.button_dict[button_num].Destroy()
def exit_this(self, event):
self.frame.Destroy()
if __name__ == "__main__":
t = Test()
You can't mention drinking without some of W.C. Fields' sayings
"A woman drove me to drink and I didn't even have the decency to thank her."
"Always carry a flagon of whiskey in case of snakebite and furthermore always carry a small snake."
Not drinking related, but one of my favorites
"Ah, the patter of little feet around the house. There's nothing like having a midget for a butler."
To associate name and score you would use a list, tuple or dictionary of pairs, so as to keep them together. The name and score that you print do not necessarily go together. The Python sorting HowTo is here.
import operator
name_score = []
## example data
name = "Joe"
score = 5
name_score.append([name, score])
name = 'Steve'
score = 2
name_score.append([name, score])
name = 'Mike'
score = 7
name_score.append([name, score])
print name_score
name_score.sort() ## in name order
print "\nname order", name_score
## itemgetter[1] = memory offset X 1 = second item = score
score_sorted = sorted(name_score, key=operator.itemgetter(1))
print "\nscore order", score_sorted
Line 41 = Line 32 in your code. It is an infinite loop;
while channels < prevchannels:
randint(0,15)
Also the variable "channels" has not been defined for the findchannel scope.
def findchannel(state):
if state==1:
prevchannels=channels <--- channels not yet defined
I would suggest that you add a test function to test each function as there are other errors. You will get scope errors because variables have not been declared in many functions as well as from those function calls. Test the code and get it to the point where it will at least run and then post back with the test results that are incorrect, or the __complete__ error message if there is an error.
Is python int by default a 32 bit- signed int?
Python uses the system's, so 32 bit on a 32bit system and 64 bit on a 64 bit system. Note that there is no difference in length between a signed integer and an unsigned integer. A signed integer just uses one of the bits as a sign, so an 8 bit unsigned can store 0-->255, and an 8 bit signed -127-->127 because one bit is used as a sign.
There is bitstring, bitbuffer and bitarray, Also, check PyPi for existing packages whenever you run into a problem like this .
recreate the script from class
We don't have the script from class and don't do your homework for you.
Anyone up for this coding challenge? I'm interested to see who can get the code the fastest
That's just calling us stupid.
You should probably ask this on the Qt forum as this doesn't have anything to do with Python. I would suspect, but don't have any idea, that it has to do with the 2 separate installations for the two versions of Python.
Your picker code
word = picker(picker(combine))
first picks a tuple, then a word from the picked tuple. While this works, our "debug sensors" were alerted as this would not be obvious down the road when someone is debugging the code. A more accepted version is to combine all of the tuples and pick a random word from the combination by calling picker() once.
terms = ('designing', 'programming', 'development', 'analysis', 'coding')
company = ('Microsoft', 'IBM', 'Apple', 'Intel', 'Google', 'AMD', 'DELL')
language = ('Java', 'Ruby', 'Python', 'Jython', 'Javascript', 'Perl', )
sub_systems = ('software', 'hardware')
inventor = ('Gates', 'Jobs', 'yang', 'Torvalds', 'filo')
combine = terms + company + language + sub_systems + inventor
print combine
I thought you wanted a goose (but it won't come from me). Why do you call "picker" twice?
def run():
"""this function runs the program"""
word = picker(picker(combine))
Also, you can reach the maximum recursion level since run() calls decision() which calls run(), etc. And there is more recursion in decision()
def decision():
"""prompts user for decision after program execution"""
decide = input('Do you want to try again (Y/N)')
decide = decide.upper()
if decide == 'Y':
run()
elif decide == 'N':
quit()
else:
print('It\s either Y or N')
decision()
#
#--------------------------------------------------------------------
decide = input('Do you want to try again (Y/N)')
decide = decide.upper()
while decide not in ["N", "Y"]:
print("It's either Y or N")
decide = input('Do you want to try again (Y/N)')
decide = decide.upper()
return decide ## to run, decide is now "N" or "Y"
Then return the "decide" variable to run(), which will use it to test a while loop for "Y".
You have to use the absolute or full path.
##--------------------------------------------------------------------
def get_files(parent):
files_list = os.listdir(parent)
for a in files_list:
full_name = os.path.join( parent, a )
if os.path.isdir(full_name):
get_files(full_name)
else:
print full_name
get_files("/home")
I used a for loop just for a little variety. And I would also think it should be (but that is just my opinion)
p p
l l
aa <-- not reversed
cc <-- reversed
e e
s s
One advantage of using a dictionary is that it is simple to add or delete options, so a similar method is used for menus. An example (not tested):
def conv(g):
grade_dict = {'A':5, 'B':4, 'C':3, 'D':2, 'E':1, 'F':0}
if g in grade_dict:
return grade_dict[g]
else:
print(g, "is not a valid letter grade")