User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the Python section within the Software Development category of DaniWeb, a massive community of 456,596 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 3,423 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our Python advertiser: Programming Forums
Views: 724 | Replies: 5
Reply
Join Date: Sep 2007
Posts: 10
Reputation: rjmiller is an unknown quantity at this point 
Rep Power: 2
Solved Threads: 0
rjmiller rjmiller is offline Offline
Newbie Poster

Help with simple programming...

  #1  
Sep 8th, 2007
Alright, So I am rather new to programming and Python and I had a couple of questions that maybe you guys could help me with...

I currently have a .txt that when read in Python is a list, now i want to be able to split it up into seperate components so that i can put them all in a dictionary. I want to be able to up one part of the line and have it give me another part (obviously the purpose of having it as a dictionary).

a sample line from the file:

1 hydrogen H 1.0079

So if i were to say

>>>Print weight['Hydrogen']
1.0079


Here is a partial look at the code that I was attempting to write:

def make_atomic_weights_dict(data_lines):
d = {}
for data_line in data_lines:
parts = data_line.split()
d'[parts[3]] = float.parts [4]' # these will be added to dictionary
if len(parts) == 4:
print float.parts[4]
else print 0 '%s does not have a well defined atomic weight.' % s(parts[3])


Thanks a bunch
AddThis Social Bookmark Button
Reply With Quote  
Join Date: Dec 2006
Posts: 468
Reputation: woooee is on a distinguished road 
Rep Power: 2
Solved Threads: 65
woooee woooee is offline Offline
Posting Pro in Training

Re: Help with simple programming...

  #2  
Sep 8th, 2007
Originally Posted by rjmiller View Post
1 hydrogen H 1.0079

if len(parts) == 4:
   print float.parts[4]
else print 0 '%s does not have a well defined atomic weight.' % s(parts[3])
The elements in a list are numbered from 0 to length, so your list is [0]-->[3]. Since you didn't ask any questions, I have to assume that this is the problem.
if len(parts)==4:
   print float(parts[3])
else :
   print "no atomic weight for %s" % (parts[1])

## or
try:
   a_weight = float(parts[3])
except:
   print "no atomic weight for %s" % (parts[1])
Reply With Quote  
Join Date: Sep 2007
Posts: 10
Reputation: rjmiller is an unknown quantity at this point 
Rep Power: 2
Solved Threads: 0
rjmiller rjmiller is offline Offline
Newbie Poster

Re: Help with simple programming...

  #3  
Sep 8th, 2007
Alright, well I solved my previous problem...My next issue, is I want to be able to add up the numbers from the dictionary...how would I go about doing that?

So say I want to calculate the atomic mass of H2O I want to be able to type:

>>>print molecular_weight( 'H 2 O', atomic_weights)

some # comes out

I don't need a whole solution, just where would be a good place to start looking
Reply With Quote  
Join Date: Sep 2007
Posts: 10
Reputation: rjmiller is an unknown quantity at this point 
Rep Power: 2
Solved Threads: 0
rjmiller rjmiller is offline Offline
Newbie Poster

Re: Help with simple programming...

  #4  
Sep 8th, 2007
Ok, so should I use if statements? because 'H 2 O' will be a string, and I want to relate each individual part to my previous dictionary...

If H is in atomic_weights
print #
2
false

therefore 2*H, etc...

Would that work?
Reply With Quote  
Join Date: Jul 2006
Posts: 562
Reputation: jrcagle is on a distinguished road 
Rep Power: 4
Solved Threads: 72
jrcagle jrcagle is offline Offline
Posting Pro

Re: Help with simple programming...

  #5  
Sep 8th, 2007
Yeah, you're asking a parsing question: how do take a string representation of a chemical formula and represent it in memory?

I might do something like this, but there are smarter ways of doing it:

  1. Z = 0
  2. MASS = 1
  3. NAME = 2
  4.  
  5. ELEMENTS = {'H': (1,1.00794,'hydrogen'),
  6. 'O': (8,15.9994,'oxygen'),
  7. 'C': (6,12.001, 'carbon'),
  8. 'N': (7,14.0064, 'nitrogen')}
  9.  
  10. def get_mass(symbol):
  11.  
  12. if symbol in ELEMENTS:
  13. return ELEMENTS[symbol][MASS]
  14. else:
  15. raise ValueError, "Element not in table!"
  16.  
  17. def compute_mass(line):
  18. mass = 0.0
  19. tokens = line.split()
  20. last = ''
  21. for token in tokens:
  22. # handle numbers
  23. if token.isdigit():
  24. # correct input: number follows valid element
  25. if last:
  26. mass += get_mass(last) * int(token)
  27. last = ''
  28. # incorrect input: number follows nothing at all, or other number
  29. else:
  30. raise SyntaxError, "Illegal formula!"
  31. else:
  32. # if element follows other element, add last to mass
  33. if last:
  34. mass += get_mass(last)
  35. last = token
  36. # done with the line; don't forget the tail!
  37. if last:
  38. mass += get_mass(last)
  39. return mass
  40.  
  41. while True:
  42. formula = raw_input("Enter a formula or 'quit': ")
  43. if formula.lower() == 'quit':
  44. break
  45. else:
  46. try:
  47. m = compute_mass(formula)
  48. print "mass is", m
  49. except StandardError, e:
  50. print e

So some explanations:

* The constants defined at the beginning let me extract elements without using obscure indices that can cause trouble if I forget to count from zero.
* The problem with parsing a formula like H 2 O is that I have to remember one token back. 2 whats? Oh, yeah, 2 H's. That's the role that 'last' plays in the compute_mass function. It has the effect of creating a small pipeline: we get the current token, but compute the mass of the last token.
* Doing it like this REQUIRES that we not forget the tail end.
* Handling formulas like diethyl ether, (C 2 H 5) 2 O, requires a stack for handling parentheses. If you feel adventurous, you can probably do it.
* I used try...except and raise to handle errors. If that's weird to you, then skip it.

Jeff
Reply With Quote  
Join Date: Sep 2007
Posts: 10
Reputation: rjmiller is an unknown quantity at this point 
Rep Power: 2
Solved Threads: 0
rjmiller rjmiller is offline Offline
Newbie Poster

Re: Help with simple programming...

  #6  
Sep 10th, 2007
Ok, well I read what you gave me and I kind of put some stuff to work on my own...The beginning lines may not make sense because they relate to other parts of the code

def molecular_weight(formula, atomic_weights):
    weights = []
    formula_parts = formula.split()
    for parts in formula_parts:
        if parts in atomic_weights:
            weights.append(atomic_weights.itervalues())
        elif 0 in atomic_weights:
            print '%s does not have well-defined atomic weight' % (formula_parts)
        elif parts in formula_parts.isdigits(n): # isdigit doesn't seem to be a proper command what should I use instead....
            weights[-1] *= n # I want to be able to append this to weights, but i get an syntax error when trying to use the .append function
    return sum(weights)
Reply With Quote  
Reply

Only community members can participate in forum threads. You must register or log in to contribute.

DaniWeb Python Marketplace
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)

 

Thread Tools Display Modes

Similar Threads
Other Threads in the Python Forum

All times are GMT -4. The time now is 6:56 am.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC