Question: import check def compound _ to _ list ( s: str ) - > list [ str ] : Convert a chemical

import check
def compound_to_list(s: str)-> list[str]:
"""
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 (e.g.,"C2 H5 O H")
Returns:
list[str]: A list of elements, each repeated according to its subscript.
"""
elements =[]
i =0
while i < len(s):
element = s[i]
i +=1
if i < len(s) and s[i].islower():
element += s[i]
i +=1
count =1
if i < len(s) and s[i].isdigit():
num_str =""
while i < len(s) and s[i].isdigit():
num_str += s[i]
i +=1
count = int(num_str)
elements.extend([element]* count)
if i < len(s) and s[i]=='':
i +=1
return elements
check.expect("ethanol", compound_to_list("C2 H5 O H"),
["C","C","H","H","H","H","H","O","H"])
check.expect("sodium phosphate", compound_to_list("Na3 P O4"),
["Na","Na","Na","P","O","O","O","O"])
def sort_by_num_elements(compounds: list[str])-> None:
"""
Mutate the given list of chemical compound strings so that they are sorted
by the number of elements they expand into, using the compound_to_list function.
Parameters:
compounds (list[str]): A list of chemical compound strings.
Returns:
None: This function mutates the list in-place.
"""
compounds.sort(key=lambda s: (str(compound_to_list(s)), s))
L =["Na3 P O4","C2 H5 O H","C9"]
check.expect("Sample of above", sort_by_num_elements(L), None)
check.expect("Sample of above mutation", L,['C2 H5 O H','C9','Na3 P O4'])

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!