Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- example_input="John is connected to Bryant, Debra, Walter.\
- John likes to play The Movie: The Game, The Legend of Corgi, Dinosaur Diner.\
- Bryant is connected to Olive, Ollie, Freda, Mercedes.\
- Bryant likes to play City Comptroller: The Fiscal Dilemma, Super Mushroom Man.\
- Mercedes is connected to Walter, Robin, Bryant.\
- Mercedes likes to play The Legend of Corgi, Pirates in Java Island, Seahorse Adventures.\
- Olive is connected to John, Ollie.\
- Olive likes to play The Legend of Corgi, Starfleet Commander.\
- Debra is connected to Walter, Levi, Jennie, Robin.\
- Debra likes to play Seven Schemers, Pirates in Java Island, Dwarves and Swords.\
- Walter is connected to John, Levi, Bryant.\
- Walter likes to play Seahorse Adventures, Ninja Hamsters, Super Mushroom Man.\
- Levi is connected to Ollie, John, Walter.\
- Levi likes to play The Legend of Corgi, Seven Schemers, City Comptroller: The Fiscal Dilemma.\
- Ollie is connected to Mercedes, Freda, Bryant.\
- Ollie likes to play Call of Arms, Dwarves and Swords, The Movie: The Game.\
- Jennie is connected to Levi, John, Freda, Robin.\
- Jennie likes to play Super Mushroom Man, Dinosaur Diner, Call of Arms.\
- Robin is connected to Ollie.\
- Robin likes to play Call of Arms, Dwarves and Swords.\
- Freda is connected to Olive, John, Debra.\
- Freda likes to play Starfleet Commander, Ninja Hamsters, Seahorse Adventures."
- # -----------------------------------------------------------------------------
- # create_data_structure(string_input):
- # Parses a block of text (such as the one above) and stores relevant
- # information into a data structure. You are free to choose and design any
- # data structure you would like to use to manage the information.
- #
- # Arguments:
- # string_input: block of text containing the network information
- #
- # You may assume that for all the test cases we will use, you will be given the
- # connections and games liked for all users listed on the right-hand side of an
- # 'is connected to' statement. For example, we will not use the string
- # "A is connected to B.A likes to play X, Y, Z.C is connected to A.C likes to play X."
- # as a test case for create_data_structure because the string does not
- # list B's connections or liked games.
- #
- # The procedure should be able to handle an empty string (the string '') as input, in
- # which case it should return a network with no users.
- #
- # Return:
- # The newly created network data structure
- def create_data_structure(string_input):
- """ This create the dictionary net from lists: users, connection, gaming"""
- network= {}
- net = []
- users= []
- connection= []
- gaming=[]
- word = "connected"
- game = "play"
- lines = example_input.split(".") #splits example_input into lines based on "."
- for line in lines: #loops through lines splits into words based on spaces
- words = line.split(" ")
- name = words[0] #get the first word in line
- if name == "": #if name is empty skip to next;if the name is in user skip
- break #to next work; append if name is not in users list
- if name in users:
- pass
- else:
- users.append(name)
- if word in words: #if word-connect is in words, get the position of word
- if word == "connected": #plus 2, this removes "is connected to";
- pos = words.index(word)+2 #join the words starting afte position of pos
- friend = ''.join(words[pos:]) #and split at the comma, append each element into connection list.
- friends = friend.split(',')
- connection.append(friends)
- else:
- if word =="": # if word is empty move to next block
- break
- if line.find(" "+'play'+ " ") != -1: #find play in line, checking position is not -1(not there)
- foundit= line.index(game) # get the postion of game add 5 to position to
- newline= line[foundit+5:] #remove "likes to play",events splits word at the comma
- events = newline.split(', ') # appends events to gaming list
- gaming.append(events)
- else:
- if game =="": # if game is empty move to next block
- break
- for i in range(len(users)): #loops through users, builds dictionary, appending
- network[users[i]] = connection[i], gaming[i] # each users their connection and gaming. Users is the key
- return network #return dictionary named network
- # ----------------------------------------------------------------------------- #
- # Note that the first argument to all procedures below is 'network' This is the #
- # data structure that you created with your create_data_structure procedure, #
- # though it may be modified as you add new users or new connections. Each #
- # procedure below will then modify or extract information from 'network' #
- # ----------------------------------------------------------------------------- #
- # -----------------------------------------------------------------------------
- # get_connections(network, user):
- # Returns a list of all the connections that user has
- #
- # Arguments:
- # network: the gamer network data structure
- # user: a string containing the name of the user
- #
- # Return:
- # A list of all connections the user has.
- # - If the user has no connections, return an empty list.
- # - If the user is not in network, return None.
- def get_connections(network, user):
- """ return a users connnections, if no connections return [] if users doesn't exist return none"""
- for users in network: #loops through dictionary, if user is dictionary and
- try: # users connections is not empty, retrieve the connects
- if user == users:
- if len(network[users][0])> 0:
- connect= network[users][0]
- return connect
- else:
- return [] #return empty list if no connections
- except KeyError: #error handling if user does exist
- return None
- def get_gamer(network, user):
- """MYOP - return user connection and games like in network if they exist; if they dont return None"""
- for users in network:
- try: #loop through network,if user in network, return
- if user == users: #users their connection and games liked
- if len(network[users])>0:
- record = network[users], network[users][0], network[users][1]
- return record
- else:
- return []
- except KeyError: #error handling if user doesnt exist
- print "No record found"
- # -----------------------------------------------------------------------------
- # get_games_liked(network, user):
- # Returns a list of all the games a user likes
- #
- # Arguments:
- # network: the gamer network data structure
- # user: a string containing the name of the user
- #
- # Return:
- # A list of all games the user likes.
- # - If the user likes no games, return an empty list.
- # - If the user is not in network, return None.
- def get_games_liked(network,user):
- """ return a users games liked, if no games liked return [] if users doesn't exist return none"""
- video= []
- for users in network: #loops through network, if user exist, and have some games
- try: # returns the liked games in list video
- if user == users:
- if len(network[users][1])> 0:
- video= network[users][1]
- return video
- else:
- return [] # return empty list if no games
- except KeyError: #error handling
- return None
- # -----------------------------------------------------------------------------
- # add_connection(network, user_A, user_B):
- # Adds a connection from user_A to user_B. Make sure to check that both users
- # exist in network.
- #
- # Arguments:
- # network: the gamer network data structure
- # user_A: a string with the name of the user the connection is from
- # user_B: a string with the name of the user the connection is to
- #
- # Return:
- # The updated network with the new connection added.
- # - If a connection already exists from user_A to user_B, return network unchanged.
- # - If user_A or user_B is not in network, return False.
- def add_connection(network, user_A, user_B):
- """ Adds a connection if one does not exist; if either user is not in network return false, if connection
- already exist does nothing"""
- if user_A in network== False: #if user A or B do not exist return false
- return network
- elif user_B in network==False:
- return network
- else:
- if user_B in network[user_A][0]: #if the user B is in user A connections return the dictionary
- return network
- else:
- network[user_A][0].append(user_B) #if user B is not in user A connections append it
- return network
- # -----------------------------------------------------------------------------
- # add_new_user(network, user, games):
- # Creates a new user profile and adds that user to the network, along with
- # any game preferences specified in games. Assume that the user has no
- # connections to begin with.
- #
- # Arguments:
- # network: the gamer network data structure
- # user: a string containing the name of the user to be added to the network
- # games: a list of strings containing the user's favorite games, e.g.:
- # ['Ninja Hamsters', 'Super Mushroom Man', 'Dinosaur Diner']
- #
- # Return:
- # The updated network with the new user and game preferences added. The new user
- # should have no connections.
- # - If the user already exists in network, return network *UNCHANGED* (do not change
- # the user's game preferences)
- def add_new_user(network, user, games):
- """Adds new user and games liked to the network. If user existed return network unchanged"""
- gaming=(games)
- if user in network: #if user already exist return network
- return network
- else:
- users = user
- network[users]=([],games) #if user doesn't exist add user and games liked
- return network
- # -----------------------------------------------------------------------------
- # get_secondary_connections(network, user):
- # Finds all the secondary connections (i.e. connections of connections) of a
- # given user.
- #
- # Arguments:
- # network: the gamer network data structure
- # user: a string containing the name of the user
- #
- # Return:
- # A list containing the secondary connections (connections of connections).
- # - If the user is not in the network, return None.
- # - If a user has no primary connections to begin with, return an empty list.
- #
- # NOTE:
- # It is OK if a user's list of secondary connections includes the user
- # himself/herself. It is also OK if the list contains a user's primary
- # connection that is a secondary connection as well.
- def get_secondary_connections(network, user):
- """return secondary connections from user's direct line connections"""
- if user in network== False: #if user is not in network return empty list
- return []
- try:
- if len(network[user][0])==0: #if user connection is 0 return empty list
- return []
- if user in network: # is user in network
- for ntuser in network[user][0]: #loop through list of connection
- n= get_connections(network, ntuser) #calls get_connections function to get secondary connections
- return n # subconnections
- else:
- return [] #return empty if no secondary connections
- except KeyError: #error handling if user doesnt exist
- return None
- # -----------------------------------------------------------------------------
- # connections_in_common(network, user_A, user_B):
- # Finds the number of people that user_A and user_B have in common.
- #
- # Arguments:
- # network: the gamer network data structure
- # user_A: a string containing the name of user_A
- # user_B: a string containing the name of user_B
- #
- # Return:
- # The number of connections in common (as an integer).
- # - If user_A or user_B is not in network, return False.
- def connections_in_common(network, user_A, user_B):
- """Return the number of common connections two users have; if either user is not in network return false"""
- #a_conn =
- # b_conn=
- common=[]
- i= 0
- if user_A in network:
- a = get_connections(network, user_A) #if both user_A and user_B are in network, call get_connections
- #a_conn.append(a) #and return their connections append to list a_conn or b_conn
- if user_B in network:
- b = get_connections(network, user_B)
- #b_conn.append(b)
- #print b_conn
- for friend in a:
- #print friend #go through each friend in list a_conn if that friend is in
- if friend in b: #b_conn add 1 to i print i which gives nbr of common friends
- i=i+1
- return i
- return False
- # -----------------------------------------------------------------------------
- # path_to_friend(network, user_A, user_B):
- # Finds a connections path from user_A to user_B. It has to be an existing
- # path but it DOES NOT have to be the shortest path.
- #
- # Arguments:
- # network: The network you created with create_data_structure.
- # user_A: String holding the starting username ("Abe")
- # user_B: String holding the ending username ("Zed")
- #
- # Return:
- # A list showing the path from user_A to user_B.
- # - If such a path does not exist, return None.
- # - If user_A or user_B is not in network, return None.
- #
- # Sample output:
- # >>> print path_to_friend(network, "Abe", "Zed")
- # >>> ['Abe', 'Gel', 'Sam', 'Zed']
- # This implies that Abe is connected with Gel, who is connected with Sam,
- # who is connected with Zed.
- #
- # NOTE:
- # You must solve this problem using recursion!
- #
- # Hints:
- # - Be careful how you handle connection loops, for example, A is connected to B.
- # B is connected to C. C is connected to B. Make sure your code terminates in
- # that case.
- # - If you are comfortable with default parameters, you might consider using one
- # in this procedure to keep track of nodes already visited in your search. You
- # may safely add default parameters since all calls used in the grading script
- # will only include the arguments network, user_A, and user_B.
- def path_to_friend(network, user_A, user_B):
- dr= []
- if get_gamer(network, user_A) ==False: #calls get_gamer function see if user in dictionary
- return False
- if get_gamer(network, user_B) == False:
- return False
- else:
- return find_path(network, user_A, user_B, path=[]) # call recursive to find path
- def find_path(network, begin, end, path=[]):
- """ finds the path of connection if level is deeper than first connection"""
- path= path + [begin] #create list to hold variablespatg
- if begin == end: # if user_A equal user_B return the path
- return [path]
- if end in network[begin][0]:
- return path +[end]
- #for name in network[begin][0]:
- #for person in network: #look in path to make sure person exist in network
- # if person not in path: #if person not in path
- # ext_paths= find_path(network, person, end, path) #cycle through calling find_path
- # if ext_paths: #once path is found return the extendedpath
- # return ext_paths
- # your RECURSIVE solution here!
- # Make-Your-Own-Procedure (MYOP)
- # -----------------------------------------------------------------------------
- # Your MYOP should either perform some manipulation of your network data
- # structure (like add_new_user) or it should perform some valuable analysis of
- # your network (like path_to_friend). Don't forget to comment your MYOP. You
- # may give this procedure any name you want.
- # Replace this with your own procedure! You can also uncomment the lines below
- # to see how your code behaves. Have fun!
- net = create_data_structure(example_input)
- network = create_data_structure(example_input)
- #print net
- #print path_to_friend(net, "John", "Ollie")
- #print get_connections(net, "Debra")
- #print add_new_user(net, "Debra", [])
- #print add_new_user(net, "Nick", ["Seven Schemers", "The Movie: The Game"]) # True
- #print add_new_user(network, 'Alice',[])
- #print add_connection(network,'Alice','Bob')
- #print get_connections(net, "Mercedes")
- #print get_games_liked(net, "John")
- #print add_connection(net, "John", "Freda")
- #print get_secondary_connections(net, "Mercedes")
- #print connections_in_common(net, "Mercedes", "John")
- print network
- print path_to_friend(net, 'Alice', 'Bob')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement