The most common answer to the 7.1.8 Citation CodeHS is:
def citation(names):
author_name = ((names))
name = str(names[2]) + ", " + str(names[0]) + " "+ str(names[1])
return name
print(citation(["Martin", "Luther", "King, Jr"]))
The function citation
is intended to format an author’s name into a citation format. However, there’s an issue with the way it handles the names array, particularly with the assumption of the array structure and the handling of names like “King, Jr., Martin Luther”.
Let’s modify the function to handle an array of names more effectively:
# Fill in the citation function to return the author's name in the correct format
"""
def citation(first, middle, last):
names = ((last,), ", ", first, middle)
print(names[0][0] + names[1] + names[2] + names[3])
"""
author_name = ("Martin", "Luther", "King, Jr.")
# Your code here...
def citation(author_name):
return str(author_name[2]) + ", " + str(author_name[0])+ " " + str(author_name[1])
# Example usage
print(citation(author_name[0], author_name[1], author_name[2]))
This function now:
- Checks the length of the
names
array to determine how to format the name. - If there are three elements, it assumes the format [first_name, middle_name, last_name].
- If there are two elements, it assumes the format [first_name, last_name].
- For one element, it just returns the name as is.
This will handle a wider variety of name formats more robustly.
Leave a comment