Question: import check def compound _ to _ list ( s: str ) - > list [ str ] : Convert a chemical
import check
def compoundtolists: str liststr:
Convert a chemical compound string into a list with each element repeated
the correct number of times as indicated by its subscript.
Parameters:
s str: A string representing a chemical compound egC H O H
Returns:
liststr: A list of elements, each repeated according to its subscript.
elements
i
while i lens:
element si
i
if i lens and siislower:
element si
i
count
if i lens and siisdigit:
numstr
while i lens and siisdigit:
numstr si
i
count intnumstr
elements.extendelement count
if i lens and si:
i
return elements
check.expectethanol compoundtolistC H O H
CCHHHHHOH
check.expectsodium phosphate", compoundtolistNa P O
NaNaNaPOOOO
def sortbynumelementscompounds: liststr None:
Mutate the given list of chemical compound strings so that they are sorted
by the number of elements they expand into, using the compoundtolist function.
Parameters:
compounds liststr: A list of chemical compound strings.
Returns:
None: This function mutates the list inplace.
compounds.sortkeylambda s: strcompoundtolists s
L Na P OC H O HC
check.expectSample of above", sortbynumelementsL None
check.expectSample of above mutation", LC H O HCNa P O
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
