It's very ineffient but here goes:
a= [10, 5, 2, 7, 20]
b=[]
for i in xrange(len(a)):
b.append(min(a))
a.pop(a.index(b[-1]))
It's very ineffient but here goes:
a= [10, 5, 2, 7, 20]
b=[]
for i in xrange(len(a)):
b.append(min(a))
a.pop(a.index(b[-1]))
Consider this: last_column = [i[-1] for i in big_list]
The maximum height is where yvel = 0. In your initialization method you have:self.yvel=velocity*sin(theta)
You know that yvel goes to zero when 0.98*time equals the initial velocity, or atvelocity*sin(theta)/9.8 seconds
So you can figure out when you get to that time at your interval.
Now since xvel is presumed not to change, the xpos at that time is(velocity*sin(theta)/9.8)*velocity*cos(theta)
First a list of all the gemstones:
f=open("your file name")
gemstones=[]
for i in f: gemstones.append(i.split(',')[1])
f.close()
now a dictionary where key is gemstone and value is count
gcount={}
for g in gemstones: gcount[g]=gcount.get(g,0)+1
My description of the dictionary set-up was only notional and just to let you understand how to use objects as dictionary values.
I dont use WX but I don't think that matters. There's a lot of code there and I admit I didn't read it all. So I don't know really what you're doing already, but you have asked a specific question.
I think I would make each sensor a different obect (instance of a sensor class). The instantiation of sensors should be mediated by a dictionary (d[a]=Sensor(initdata)) so you can step through each sensor obect (dictionary entry) and call a get_data() method, appending the appropriate information to a list
To write any 2-d list as a csv formatted file, simply "join" the elements of the list with a comma and write as text:
f=open(<output file>, 'w')
for row in listname:
f.write(','.join(map(str,row))+'\n')
Your data is in a 2-d list, data_list. The first step is finding the indices of the 2 months you want. That will accomplished on data_list[0].
index1=data_list[0].index(month1), where month1 is the starting month. Likewise,
index2=data_list[0].index(month2).
Now you'll loop through the elements from 1 to the end, convert the string rainfall amounts to numbers and add them, output the first 4 elements of each row and the new sum to a new list:
newlist=[]
for row in data_list[1:]:
s=sum([float(i) for i in row[index1:index2+1]])
newlist.append(row[:4].append(s))
So what's the question? The keys are names and the values are strings.
I would need more information to answer that. What is the structure of the dictionary? Normally, I would key an address book on "name" so something like AddBook={"john doe":("8134789 Zubruzlechester", "Alpha Centauri", "999-555-1234")}. In that case I would get the telephone number, for instance, for John Doe, as: AddBook["john doe"][2]
check out the pickle module (I think it still is used with v3.x)
colorcode="#00ffaa"
strBase1="blah blah blah kjklajaskladfjlkjasdf maxMass="
strBase2="blah blah aiopweruioweruio minMass="
strBase3="blah blah iqweuiqweru890 colorCode="
strBase4="2389023489asdfjkl qwruijasdfjklha fasdfasdf"
chrDelim=","
f1=open(<input file name>)
f2=open(<output file name>,"w")
for strLine in f1:
lstLine=strLine.strip('\n').split(chrDelim)
colorcode=colorcodefunction(lstLine)
strOut=strBase1+lstLine[0]+strBase2+lstLine[1]+strBase3+colorcode+strBase4
f2.write(strOut+'\n')
f1.close()
f2.close()
My question really was after you identify a duplicate (never mind for now how you do that), then you have 2 records with the same, let's say, email field value. What next? Do you write both records to the new file? Just one (which one)?
When you identify a duplicate, let's say there are 2, do both get written to the file or just the one that wasn't first?
I think this is the culprit: Resistance.append(tuple((float(x) if x.strip() else '0.0'). On the one hand it's number, on the other, a string.
I'm afraid I don't follow. What are you trying to accomplish?
I'm not sure I follow. If it's a random number, then it won't point reliably in either direction, no? Is this maybe what you want?
There is a list of hints, lstHints. For each element of lstHints, there is a tuple, (n1,n2), where lstHints[n1] is that element and lstHints[n2] is the element you go to next. While it might seem that this is a dictionary, I don't think it is, as I am envisioning lstHints as being ordered and dictionaries are not. Basically it's two linked lists, one being lstHints and the other, say lstTuples.
Well, I'm sure with polynomial recursion you can make it as complicated as you need to but if we take every 2 points on the reference track to define a line, then you can define a parallel line that is offset from that as I described above. Then you just do that for every point pair. It's tedious but that's why we have computers.
Let's forget the altitude component for now since I don't think you're really mapping in 3-d here. So you have a series of lat/long. Let's say you know how to convert that to a more convenient x/y system. Now, if your track is a straight line, then you can easily turn it into a parametric representation: y=mx+b where m is the slope (δy/δx) and b is the y-intercept. Then a parallel line has the same m and an offset (+ or -) of b. Is your track straight? If not, is it piece-wise straight?
I don't use the csv module much (at all); I find it just as easy to manipulate csv files manually. That said, if len(timelist) is 1, that sounds a lot like the csv.reader doesn't know your delimiter is ";". Also, according to the documentation, the open() statement needs to specify "rb" (why, I don't know). So your csv.reader statement should be: r = csv.reader(open(fname),'rb'), delimiter=";")
.
But, again, I think it's easier just to parse the file yourself. What would happen if you did it this way:
r=open(fname)
for str1 in r:
timedate=str1.strip('\n').split(';')
for i in len(timedate):
time_date = time.mktime(time.strptime(timedate[i], "%d.%m.%Y
.....
You could initialize a dictionary, then use the first column as the key and accumulate a growing value separated by some character you don't expect to find in the data, like, say, "_":
>>> d={}
>>> d["test"]="_".join((d.get("test",""),"abc"))
>>> d["test"]
'_abc'
>>> d["test"]="_".join((d.get("test",""),"xyz"))
>>> d["test"]
'_abc_xyz'
>>>
where instead of "test" you'll have: line.split('\t')[0]
(it appears your data is separated by tabs) and instead of "abc" you'll have line.split('\t')[1]
You've got the right idea but I think you're doing something you don't want to do and I know you're doing something wrong.
First the wrong thing.
When you read each line, for line in f.readlines():
, "line" is a string. Strings are iterable but each character is an element. So, line[0] for instance would be "5" in the case of the Bart Simpson record. To get what you want you need to split the line into words (splitting on spaces): line=line.strip('\n').split()
, also taking off the linefeed. Now you have another problem, the "name" field is 2 words, line[1] and line[2]. If you know both names are always going to be present then you can use the constructor: Persons(line[0], line[1]+' '+line[2], line[-1])
. Otherwise you'll need to check on how many elements line has 4 or 3 and construct the object accordingly.
Now the other thing. In your loop, you keep using the same object name, "pers". Once the loop is done, you'll only have a single object. There are lots of ways to keep all the people "alive" but I think the best is to have a dictionary of people, dctPerson={}
, and instead of "pers" use dctPerson[line[0]]=Persons(line[0], line[1]+' '+line[2], line[-1])
.
oops. that should be "set_address(self,address)"
Think about it like this:
when you set "self.address=address", you are assigning a value to an attribute. If that were inside a method, say, "set_address(address)" and looked exactly the same, would that be what you wanted?
Also, your "get_name" method is wrong, I think. There is no attribute defined to be "_name".
You need to
1 - remove the linefeeds from the input line (line=line.strip('\n'))
2 - split the line into a list (lstLine=line.split(','))
Look. It's a bit presumptuous, if not rude, to ask people to do your homework without even making a token attempt, yourself. Do you have any code written? Do you understand classes/objects at all in some other context maybe?
Think of it this way:
There is a class, "patient". Objects in that class have some attributes: age, weight, sex, dob, name, ID, address, phone number.
class patient():
def __init__(self, ID, name, dob, sex, phonenumber, address):
self.ID=ID
self.address=address
bob=patient("0012","bob","8/8/88","m","888-8888","888 Oak")
Code tags are better when just the code is tagged. Still, better than no tags at all.
I don't see how the code you posted does anything at all. The lists are instantiated outside of the functions and in the case of newList(), not even used. Let's see what might work...
From your lines 44-48, I'm figuring you have a file where each line after the header is: first name space last name space id space credit space, grade point. OK. To get that into your master list, let's take your file reading program and fix it up a little:
def studentInf(file):
emptyList=[]
file.readline()
for line in file:
line = line.strip()
line = line.split()
emptyList.append(line)
return emptyList
Note that emptyList is now initialized inside the function. BTW, I don't know why you call this "emptyList" as it has whatever data is in the file.
Now you could print it line by line:
for i in emptyList: print "ID: {2} - name: {0} {1}, credits: {3}, grade point {4}".format(i)
Now, you're supposed to go through that list and update information for each student. This would be something like:
for i in len(emptyList):
emptyList[i]=updateRec(emptyList[i])
where you need a function to update the record. Note that what your doing here is updating the elements of "emptyList", not creating a new list. UpdateRec() will take your sub-list and ask the user for new data:
def updateRec(lstA):
lstA[3]=int(raw_input("new credit for " + lstA[0] + lstA[1] + ": ")) …
your question was answered in devshed
for strLine in fid:
lstLine=strLine.strip('\n').split(',')
if lstLine[0]=="ab":
for elem in lstLine[1:]:
#do your thing
#do your other thing
#do something entirely else.
I'm not entirely sure I follow but let's say you have (as in your example) 11 fields separated by commas. You're going to check if the value of the first element (index 0) has one of several values and if so, and if the value of field-x is equal to y, accumulate the value in field-z:
pcodes=(value1, value2, value3, value4)
qtys=(12,3,8,19)
prices=[0,0,0,0]
for strLine in fileobject:
lstLine=strLine.strip('\n').split(',')
if lstLine[0] in pcodes:
for i in xrange(len(qtys)):
if lstLine[2+i*2]==qtys[i]: prices[i]+=lstLine[1+i*2]
Since you title your post with "...csv file", I'll assume you're reading this table one row at a time from a comma delimited file. So, let's say you've opened the file as fid (i.e., fid=open(<file name>)). Then you read through the file, strip off the line feed, split the line on commas and process the resultant list:
for strLine in fid:
lstLine=strLine.strip('\n').split(',')
indexfield=lstLine[0]
for elem in lstLine[1:]:
#do your thing
#do your other thing
change z = setup.readline()
to z = setup.readline().strip('\n')
@crashhold:
That was just setting a string with the target pattern to demonstrate that the search would actually find it. In your case, you would be reading in the string so it's unnecessary.
@snippsat:
It's up, but empty. I had to set up a new user account to get in so I don't know if my previous "status" will be preserved. I feel like Ozimandius.
What graphics module are you using? In Tkinter, there is nothing called an input box. Rather there is a widget called an "entry". It has no title, but you can fit it with a "label". Likewise, pyGTK, has a "text" and "label". In non-GUI python, "input" is a command indicating that the user is expected to type text. There's no box and no title. So, maybe I'm just not getting something obvious about your question but I'm not.
for the first type, 21 - 27 Nov 2012:
`
import re
s="abcd efgh 44 - 88 Dec 2012 xyz"
pat=r'\d{1,2} - \d{1,2} \w{3} \d{4}'
m=re.search(pat,s)
m.group(0)
'44 - 88 Dec 2012'
'
for 1 Dec 2012 and 26 Nov 2012:pat=r'\d{1,2} \w{3} \d{4}
for 30 Nov - 2 Dec 2012:pat=r'\d{1,2} \w{3} - \d{1,2} \w{3} \d{4}
I'm not sure what you're asking. If you mean how many sidereal days in 7 24-hour days:
>>> 7.0*24/(23+56.0/60)
7.0194986072423395
Well, "map()" is going to be useful to make the strings you read from the file into numbers. I wouldn't use "reduce()" in this case but I think "sum()" qualifies as "higher order". So it looks like each line of the file has several numbers (and a linefeed). So for each line gets split, stripped, and concatenated into a list of string representations of numbers:
[edit]I guess you could use "reduce()" just show how clever you are:
lstNums=[]
f=open(<filename>)
for i in f:
lstNums+=i.strip('\n').split()
lstNums=map(int,lstNums)
average=reduce(lambda x,y: x+y,lstNums)/len(lstNums)
I think the csv module is overkill for most applications. I'm not sure I follow what the format of your data file is but let's say each line in the CSV file has n fields separated by ";". Depth is in field i (starting from 0), time is field j, and temperature is field k (you can substitute the real values (0,1,2?) as you probably know them).
depth=[]
time=[]
temp=[]
csvf=open(<filename>)
csvf.readline() #to get past the first row (headers)
for r in csvf:
lstr=r.split(";")
depth.append(lstr[i])
time.append(lstr[j])
temp.append(lstr[k])
csvf.close()
There is obviously something missing: the creation of the list, obs. Given that, the method, add(), updates the values in prior and total for each element of obs. The method, discr(), looks like it's updating something like a grade point average for each element in obs. The method, classify(), looks like it should return the highest grade point average (if that's really what discr() returns) for each element in prior, only I don't think the "[1]" is right.
A dictionary isn't really a natural implementation of a database. I suppose you could have each row be it's own dictionary such that row1={key1:value1, key2:value2,...} and likewise for all rows. Then you'd get the value in column3, row3 from row3[key3] or something like that. I think a better implementation is just to use a list of lists where the first element is a list of column headings.
You should, of course post the error but frequently the problem is that the backslash, "\", is used by Python as the escape character. You should either use the forward slash, "/" or escape the backslash, "\" in your paths.
Probably, the way you're executing the script is making the default directory other than where you have the file. Try fully qualifying the file name.