Question : Explanatin needed for the following code

Hi ,

I dont know Python and I need to understand the following code for something similar for a work scenario for converting an app to C sharp. It looks pretty simple but I dont want to make assumptions. Can someone help understand it step by step.

def who_knows(a, b):
     """ a and b are lists """
     c = []
     for i in a:
         if is_mem(b, i):
             c.append(i)
     return uniqify(c)
 
  def is_mem(a, elem):
     for i in a:
         if i == elem:
             return True
     return False
 
  def uniqify(arr):
     b = {}
     for i in arr:
         b[i] = 1
     return b.keys()

Answer : Explanatin needed for the following code

This is three different functions. I have commented them below.

The who_knows() function could be named "union()", it finds all items that are common to both lists. Each item may exist multiple times in each list, it is still returned only once.

The is_mem() function could be named "is_member()", it checks for membership in a list. This could have been done more efficeintly in python, the expression "i in b" returns true if the item "i" exists in the list "b".

The uniqify() function use the fact that dictionaries in python have unique keys. It could also have been written like this:

def uniqify(arr):
    result = []
    for i in arr:
        if not i in result:  # "in" is a membership operator
            result.append(i)
    return result

Big-O performance... hm... I think it's O(N**2), but I'm not sure.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
  def who_knows(a, b):
     """ a and b are lists """
     c = []                # create empty list "c"
     for i in a:           # loop over items in the a list, "i" represents each item
         if is_mem(b, i):  # calls is_mem() for each item, checks if the item exists in the b list
             c.append(i)   # if it does, append it to the c list
     return uniqify(c)     # call function uniqify() with the new c list 
 
  def is_mem(a, elem):
     for i in a:         # for each item in the list
         if i == elem:   # if the input argument "elem" exists in the list
             return True # ...return True
     return False        # otherwise return False
 
  def uniqify(arr):
     b = {}             # create dictionary (key/value mapping)
     for i in arr:      # for each item "i" in the input list "arr"
         b[i] = 1       # set b[i] = 1, duplicates overwites existing value
     return b.keys()    # return all distinct items
Open in New Window Select All
Random Solutions  
 
programming4us programming4us