This is a question Im trying to figure out for a job pre-interview questioniar. and i dont know python that well so im struggling with this problem.
the real questions for the job are big-o performance and making it better but i can do that i just need to understand this code
question A: in is_bar they compare the iterator to the array (if i == b). is this the equivalent of (if i == b.length)?
question B: so following the flow of the function and assuming the above and (a = [1,2,3] b=[3,4,5]) is true the first comparison is comparing two iterators????
so it would be:
- is_bar(b, 0)
- for i in b (says a but its b from above)
- if 0 == 0
- so it evaluates to true and does c.append(0)
- does this 3 more times and since its comparing iterators it would append 1,2 than unique (c) 6.which makes a new array the same size as c and makes every values = 1
but that wouldnt make sense. Appearently there is somthing im missing because a function that takes 2 arrays, then creates an array of equal size of the second array and makes all values = 1 would be stupid.
question C: what does b.keys() return exactly (i looked up the function but it says "list of all the keys used" but that doesnt make sense since it is a one-dimension array)
def foo(a, b):
""" a and b are both lists """
c = []
for i in a:
if is_bar(b, i):
c.append(i)
return unique(c)
def is_bar(a, b):
for i in a:
if i == b:
return True
return False
def unique(arr):
b = {}
for i in arr:
b[i] = 1
return b.keys()
A: No. It compares each element of a
to b
. So if b
is an element of a
it returns True
.
B: Change based on the above.
C: b
is not an array. It's a dictionary (the b = {}
).
the function can be simplified to:
def foo(a, b):
""" a and b are both lists """
return list(set(a)&set(b))
精彩评论