In: Computer Science
Implement function get_contact(contacts, name) that returns a string. The contacts and the name parameter are both type string. This function checks for the name string in the contacts string and returns that person’s contact information. If the person is not found, the function returns, “name not in contact”. Assume input is always valid. Assume the same name is not repeated in contacts.
[You may use split(), range(), len() ONLY and no other built-in function or method]
Examples:
contacts = “Frank 703-222-2222 Sue 703-111-1111 Jane 703-333-3333”
name = “Sue”
print(get_contact(contacts, name))
returns:
703-111-1111
name = “Sam”
print(get_contact(contacts, name))
returns:
name not in contact
Below is the function that returns the number of the corresponding name provided.
Here we split the contact string into a list on the basis of spaces. Then we search for the name in the list by iterating through it. If the name is found, the next element to the name in the list is the contact number. So we return the number. If name is not found in the list, we return the string 'name not found in the list'.
def get_contact(contacts, name): # declare the function
contact_list = contacts.split(' ') #split string based on space
for i in range(len(contact_list)): #loop until length of contact list
if name == contact_list[i]: #if name matches
return contact_list[i+1] #return number of person (next element to name)
return 'name not in contact' #if out of loop return name not in list
If we supply the following input to the above function:
contacts = 'Frank 703-222-2222 Sue 703-111-1111 Jane 703-333-3333' #contact list
name = 'Sue' #name
print(get_contact(contacts, name)) #print number by calling function
what we get as output is:
when we supply input as:
contacts = 'Frank 703-222-2222 Sue 703-111-1111 Jane 703-333-3333' #contact list
name = 'Sam' #name
print(get_contact(contacts, name)) #get number
we get output as:
Complete program for your reference:
def get_contact(contacts, name): # declare the function
contact_list = contacts.split(' ') #split string based on space
for i in range(len(contact_list)): #loop until length of contact list
if name == contact_list[i]: #if name matches
return contact_list[i+1] #return number of person (next element to name)
return 'name not in contact' #if out of loop return name not in list
contacts = 'Frank 703-222-2222 Sue 703-111-1111 Jane 703-333-3333'
name = 'Sue'
print(get_contact(contacts, name))
For any doubts/clarifications, reach out in the comments section. If you find it useful, kindly upvote. Thanks.