Skip to content

Commit cd69fa5

Browse files
authored
simplified valency_checker()
Using regex. Now branched chain development can happen.
1 parent 80662d1 commit cd69fa5

File tree

1 file changed

+23
-31
lines changed

1 file changed

+23
-31
lines changed

Carbonpy.py

Lines changed: 23 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
# TODO: Identify branched chains, functional groups and somehow represent the compound in the same way you would draw it
77

88
import re
9+
from typing import Union
10+
911

1012
class Namer(object): # IUPAC Names for now only
1113
symbol = '\u2261' # The triple bond symbol ≡
@@ -48,36 +50,26 @@ def analyser(self) -> str:
4850

4951
return f"{prefixes[self.carbons].capitalize()}{compound_name}" # returns final name
5052

51-
def valency_checker(self):
52-
"""Checks if valencies of carbon are satisfied the same way you would do in real life, by counting no. of
53-
atoms and bonds before and after the carbon."""
54-
55-
values = {'H': 1, '-': 1, '=': 2, '~': 3}
56-
# use these as examples to understand code below 'CH3-CH=C=CH2', 'CH~CH':
57-
for index, atom in enumerate(self.structure):
58-
if atom == 'C':
59-
valency = 0 # Valency of each carbon before calculating
60-
try:
61-
if self.structure[index + 2].isdigit(): # If atoms after carbon
62-
valency += int(self.structure[index + 2]) # Adds those atoms
63-
valency += values[self.structure[index + 3]] # And the bond (if it isn't terminal carbon)
64-
65-
elif self.structure[index + 2] in values.keys(): # If single H / bonds present
66-
valency += values[self.structure[index + 2]] # Add that bond value
67-
valency += values[self.structure[index + 1]] # Add that atom
68-
else:
69-
valency += values[self.structure[index + 1]] # Add either atom or bond value
70-
71-
except (IndexError, KeyError):
72-
if self.structure[-1] == 'H': # If last carbon has atom
73-
valency += 1 # Add that
74-
75-
if valency != 4 and index != 0: # If valency isn't 4 yet
76-
previous_bond = self.structure[index - 1]
77-
valency += values[previous_bond] # Add previous bond value
78-
79-
if valency != 4: # If it still isn't four!!!
80-
raise ValencyError("Check valencies of your compound!")
53+
def valency_checker(self) -> None:
54+
"""Checks if valencies of carbon are satisfied and raises error if not satisfied. """
55+
56+
valency = 0
57+
hydros_bonds = {'H': 1, "H2": 1, "H3": 2, "H4": 3, '-': 1, '=': 2, '~': 3}
58+
splitted = re.split('([-=~])', self.structure) # Splits the bonds and elements
59+
60+
for index, element in enumerate(splitted): # Adds the bonds to the string of atoms
61+
if element == "-" or element == "=" or element == "~":
62+
splitted[index - 1] += element
63+
splitted[index + 1] += element
64+
splitted.pop(index) # Removes those bonds from the list. Final list example: ['CH3-', 'CH2-', 'CH3-']
65+
66+
for element in splitted: # Counts the bonds and hydrogens to see if valency is satisfied
67+
for hyd_bonds in hydros_bonds.keys(): # Iterating through dict
68+
if hyd_bonds in element:
69+
valency += hydros_bonds[hyd_bonds] * element.count(hyd_bonds)
70+
if valency != 4:
71+
raise ValencyError("Check valencies of your compound!")
72+
valency = 0
8173

8274
def atom_counter(self, element):
8375
if element == "C":
@@ -127,7 +119,7 @@ def suffix_namer(self) -> str:
127119
elif '=' in self.processing: # Only double bond present
128120
return f"{lowest_db}{db_suffix}ene" # Return with di,tri,etc
129121

130-
def lowest_position(self) -> dict:
122+
def lowest_position(self) -> Union[None, dict]:
131123
"""First point of difference rule used"""
132124
lowest_front = {}
133125
lowest_back = {}

0 commit comments

Comments
 (0)