help - iter & dict

2006-08-03 Thread aking


Dear Python people,

im a newbie to python and here...so hello!

Im trying to iterate through values in a dictionary so i can find the
closest value and then extract the key for that valuewhat ive done so far:

def pcloop(dictionary, exvalue):
z = dictionary.itervalues()
y = z - exvalue
v = (y*y)**1/2
if v < 0.001:
u = dictionary.get[z]
return u


ive been working off a couple of books and this is the best i can get it in
short time. I was trying to define a function (its my first!) so that i
could apply to several 'dictionary's and 'exvalue's. The best ive been able
to come up with is iterating over the dictionary values, subtracting the
exvalue, squaring then root squaring to render positive and applying an
error (0.001) which is not the ideal solution i want. Is there any easy way
to iterate through dictionary values and return the key for the minimum. Or
can someone tell me where im going wrong with this def & loop.

regards all

Ali
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help - iter & dict

2006-08-03 Thread aking
Quoting taleinat <[EMAIL PROTECTED]>:

> Ali writes:
> 
> >> Im trying to iterate through values in a dictionary so i can find the
> >> closest value and then extract the key for that valuewhat ive done
> so far:
> >> 
> >> def pcloop(dictionary, exvalue):
> >> z = dictionary.itervalues()
> >> y = z - exvalue
> >> v = (y*y)**1/2
> >> if v < 0.001:
> >> u = dictionary.get[z]
> >> return u
> 
> First of all, your code was broken everywhere...
> 
> Unlike many other languages, Python is fun! Just fire up an interpreter
> ("python" at the command line should work) and start playing around and
> trying
> stuff out. You would have quickly found that dictionary.itervalueS()
> return an
> iterator object (which must be iterated over), that dictionaries can be
> accessed
> either with brackets "[]" -or- with the .get() method, and more.
> 
> If you're learning from a book, try everything you learn out at least
> once in
> the interpreter - that way you'll make sure you understand everything,
> and
> understand the syntax much faster (since the interpreter will -explain-
> what
> your syntax errors are).
> 
> Second, Python has a built-in abs() method which returns the absolute
> value of a
> number - using it is simpler and more readable.
> 
> 
> Tim Chase  tim.thechases.com> writes:
> 
> > if closest_value:
> > if distance < closest_distance:
> > closest_key = k
> > closest_value = v
> > closest_distance = distance
> > else:
> > closest_key = k
> > closest_value = v
> > closest_distance = distance
> > return closest_key, closest_value
> 
> This has a bug - if closest_value happens to be zero at some point, it
> would be
> overriden by the next value no matter what, since "if closest_value"
> would be
> false. You must explicitly check "if closest_value is not None:".
> 
> Also the code could be simplified:
> 
>   if closest_value is None or distance < closest_distance:
>   closest_key = k
>   closest_value = v
>   closest_distance = distance
> 
> > 
> > def findClosest2(dataset, target):
>   if not dataset: # a dict is considered false if empty, true otherwise
>   return (None,None)
> > return reduce(
> > lambda x,y:
> > ((target - y[1]) ** 2 <
> > (target - x[1]) ** 2)
> > and y or x, dataset.items())
> 
> I would advise everyone still learning the basics to completely ignore
> the
> second function. Yes, it works, but this code is VERY confusing for a
> beginner,
> both because of the reduce (tough to grasp) and because of the confusing
> and
> bug-prone "and-or trick". (even though this is a classic use for reduce)
> 
> - Tal Einat
> a='[EMAIL PROTECTED]'[::-1]; print reduce(lambda m,x:[m[i]+s[-1] for i,s
> in
> enumerate(sorted(m))],[list(a)]*len(a))[3]
> 
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

I know im a little bit over my head here but have survived up until now by
books and debugging before the code runs. before last week the most lines of
code ive written are .4.

Yes i think i can stick to simplest to understand for now and work round at
a different time.


Ive tried the code:

def findClosest(dataset, target):
closest_value = None
closest_key = None
closest_distance = None
for k,v in dataset.items():
distance = (target - v) ** 2
if closest_value:
if distance < closest_distance:
closest_key = k
closest_value = v
closest_distance = distance
else:
closest_key = k
closest_value = v
closest_distance = distance
return closest_key, closest_value

Cpcb = input("\n\nPlease enter the carbon percentage value obtained from
the microanalysis. If none, enter 0: ")
print"\n\nCellulose Carbon Percentage is " + `Cpca` + "\n\nMaximum
potential monomer carbon weight is " + `Cwmax` + "\n\nMaximum potential
carbon percentage is " + `Cpcmax` + "\n\nPercentage difference between
Cellulose and Maximum is " + `Cdiff` + "\n\n"
CDS = findClosest(CDSitdict, Cpcb)
print("\nThe DS value based on carbon content is " + `CDS` + "\n\n")


here is a sample of the dictionary (normally 1000 iterations in there, all
non zero and to 15 decimal places) and the sample value:

Cpcb = 33.94

CDSitdict = {28.473823598317392: "'2.48699832'", 40.06163037274758:
"'0.2912'", 27.756248559438422: "'2.83499964'",
33.2299196586726: "'1.12499962'", 29.989685187220061:
"'1.91399677'", 31.502319473614037: "'1.4909983'",
28.487341570327612: "'2.4809983'", 30.017763818271245:

[no subject]

2006-10-30 Thread aking

J. Clifford Dyer wrote:
> Alistair King wrote:
>   
>> Hi,
>>
>> is there a simple way of creating global variables within a function?
>>
>> ive tried simply adding the variables in:
>>
>> def function(atom, Xaa, Xab):
>> Xaa = onefunction(atom)
>> Xab = anotherfunction(atom)
>>
>> if i can give something like:
>>
>> function('C')#where atom = 'C' but not necessarly include Xaa or Xab
>>
>> i would like to recieve:
>>
>> Caa = a float
>> Cab = another float
>>
>> ive tried predefining Xaa and Xab before the function but they are
>> global values and wont change within my function. Is there a simple way
>> round this, even if i call the function with the variables ('C', Caa, Cab)?
>>
...
>>
>> some actual code:
>>
>> # sample dictionaries
>> DS1v = {'C': 6}
>> pt = {'C': 12.0107}
>>
>> def monoVarcalc(atom):
>> a = atom + 'aa'
>> Xaa = a.strip('\'')
>> m = atom + 'ma'
>> Xma = m.strip('\'')
>> Xaa = DS1v.get(atom)
>> Xma = pt.get(atom)
>> print Xma
>> print Xaa
>>
>> monoVarcalc('C')
>>
>> print Caa
>> print Cma
>>
...
>> it seems to work but again i can only print the values of Xma and Xaa
>>
>> ?
>>
>> Alistair
>>
>> 
>
> I suspect you are misusing the concept of a function.  In most basic 
> cases, and I suspect your case applies just as well as most, a function 
> should take arguments and return results, with no other communication 
> between the calling code and the function itself.  When you are inside 
> your function don't worry about the names of the variables outside.  I'm 
> not sure exactly where your floats are coming from, but try something 
> like this:
>
>  >>> def monoVarCalc(relevant_data):
> ... float1 = relevant_data * 42.0
> ... float2 = relevant_data / 23.0
> ... return float1, float2
>
>  >>> C = 2001
>  >>> Caa, Cab = monoVarCalc(C)
>  >>> Caa
> 84042.0
>  >>> Cab
> 87.0
>
> Notice that you don't need to use the variable C (or much less the 
> string "C", inside monoVarCalc at all.  It gets bound to the name 
> relevant_data instead.
>
> Also, if you are going to have a lot of these little results lying 
> around, (Cab, Cac ... Czy, Czz), you might consider making them a list 
> or a dictionary instead.  I won't tell you how to do that, though.  The 
> online tutorial has plenty of information on that.
>
> http://docs.python.org/tut/tut.html
>
>
> Cheers,
> Cliff
>   
this worked a treat:

def monoVarcalc(atom):

   a = atom + 'aa'
   Xaa = a.strip('\'')
   m = atom + 'ma'
   Xma = m.strip('\'')
   Xaa = DS1v.get(atom)
   Xma = pt.get(atom)
   return Xaa, Xma


Caa, Cma = monoVarcalc('C')


thanks

Ali

-- 
Dr. Alistair King
Research Chemist,
Laboratory of Organic Chemistry,
Department of Chemistry,
Faculty of Science
P.O. Box 55 (A.I. Virtasen aukio 1)
FIN-00014 University of Helsinki
Tel. +358 9 191 50392, Mobile +358 (0)50 5279446
Fax +358 9 191 50366




-- 
http://mail.python.org/mailman/listinfo/python-list


create global variables?

2006-10-30 Thread aking


J. Clifford Dyer wrote:
> Alistair King wrote:
>   
>> Hi,
>>
>> is there a simple way of creating global variables within a function?
>>
>> ive tried simply adding the variables in:
>>
>> def function(atom, Xaa, Xab):
>> Xaa = onefunction(atom)
>> Xab = anotherfunction(atom)
>>
>> if i can give something like:
>>
>> function('C')#where atom = 'C' but not necessarly include Xaa or Xab
>>
>> i would like to recieve:
>>
>> Caa = a float
>> Cab = another float
>>
>> ive tried predefining Xaa and Xab before the function but they are
>> global values and wont change within my function. Is there a simple way
>> round this, even if i call the function with the variables ('C', Caa, Cab)?
>>
...
>>
>> some actual code:
>>
>> # sample dictionaries
>> DS1v = {'C': 6}
>> pt = {'C': 12.0107}
>>
>> def monoVarcalc(atom):
>> a = atom + 'aa'
>> Xaa = a.strip('\'')
>> m = atom + 'ma'
>> Xma = m.strip('\'')
>> Xaa = DS1v.get(atom)
>> Xma = pt.get(atom)
>> print Xma
>> print Xaa
>>
>> monoVarcalc('C')
>>
>> print Caa
>> print Cma
>>
...
>> it seems to work but again i can only print the values of Xma and Xaa
>>
>> ?
>>
>> Alistair
>>
>> 
>
> I suspect you are misusing the concept of a function.  In most basic 
> cases, and I suspect your case applies just as well as most, a function 
> should take arguments and return results, with no other communication 
> between the calling code and the function itself.  When you are inside 
> your function don't worry about the names of the variables outside.  I'm 
> not sure exactly where your floats are coming from, but try something 
> like this:
>
>  >>> def monoVarCalc(relevant_data):
> ... float1 = relevant_data * 42.0
> ... float2 = relevant_data / 23.0
> ... return float1, float2
>
>  >>> C = 2001
>  >>> Caa, Cab = monoVarCalc(C)
>  >>> Caa
> 84042.0
>  >>> Cab
> 87.0
>
> Notice that you don't need to use the variable C (or much less the 
> string "C", inside monoVarCalc at all.  It gets bound to the name 
> relevant_data instead.
>
> Also, if you are going to have a lot of these little results lying 
> around, (Cab, Cac ... Czy, Czz), you might consider making them a list 
> or a dictionary instead.  I won't tell you how to do that, though.  The 
> online tutorial has plenty of information on that.
>
> http://docs.python.org/tut/tut.html
>
>
> Cheers,
> Cliff
>   
this worked a treat:

def monoVarcalc(atom):

   a = atom + 'aa'
   Xaa = a.strip('\'')
   m = atom + 'ma'
   Xma = m.strip('\'')
   Xaa = DS1v.get(atom)
   Xma = pt.get(atom)
   return Xaa, Xma


Caa, Cma = monoVarcalc('C')


thanks

Ali

-- 
Dr. Alistair King
Research Chemist,
Laboratory of Organic Chemistry,
Department of Chemistry,
Faculty of Science
P.O. Box 55 (A.I. Virtasen aukio 1)
FIN-00014 University of Helsinki
Tel. +358 9 191 50392, Mobile +358 (0)50 5279446
Fax +358 9 191 50366



-- 
http://mail.python.org/mailman/listinfo/python-list