Комментарии:
I dont quite get why he chose python and then wrote code like that.
ОтветитьIs any way to improve this?
from itertools import combinations
def find_pairs (values , target):
if target > 1 and len(values) > 1:
comb = combinations(values, 2)
try:
print('{} and {}'.format(*next(filter(lambda x : sum(x) == target, comb)))))
except StopIteration:
print('None Found')
best solution :
1. use set (because the question didnt ask for the index, else you need to use a hashmap)
2. complete it in one iteration - O(n) by checking whether the complement exists in the set then and there.
java solution:
static int[] getMatchingPairs(int[] nums, int target){
HashSet<Integer> set = new HashSet<>();
for(int num : nums){
int complement = target - num;
if(set.contains(complement)) return new int[] {complement, num};
set.add(num);
}
return new int[] {-1, -1};
}
Literally just needed a extra check before the inner return to see if it's the same number
ОтветитьRather confusing interview. We write python to literally provide micro services in numerous docker containers reading/writing to Qs/Topics/S3 buckets/Lambdas/FTP servers/RSDBs/plotting graphs and you spend this entire interview on find the sum of two numbers in a list?? This is a bash interview! If this was my interview I would fail it. If you asked me to write 1000 lines to contact a server reliably and download a terabyte of data, I am good.
Ответитьc = [14,13,6,7,8,10,1,2]
from itertools import combinations
def comb(a,target):
solution = 'No valid pairs'
comb = combinations(a,2)
for i in list(comb):
if sum(i) == target:
solution = '{0} and {1}'.format(i[0],i[1])
print(solution)
comb(c,27)
Code for this question:
x=[12,14,8,6,1,2]
y=x
for i in x:
for j in y:
if i+j==3:
result=f"{i},{j}"
break
print(result)
lol @ actually getting two sum in an interview
ОтветитьIf only real job interviews were this easy. It's always "code a solution to the cure for cancer with O(log n)
Ответитьmy solution
num_list = [14, 13, 6, 7, 8, 10, 1, 2]
target = 3
num_set = []
filtered_num_list = [i for i in num_list if i <= target]
for num in filtered_num_list:
for n in filtered_num_list[1:]:
if num + n == target:
if (num, n) not in num_set and (n, num) not in num_set:
num_set.append((num, n))
Just one for loop needed and I guess it'd be more efficient to exclude values > target.
def find_pair(values, target):
val_dict = {}
for val in values:
if val < target:
if val_dict.get(val) in values:
print(f"pairs found {val} {val_dict[val]}")
return 0
val_dict[val] = target - val
print("None found")
return 1
The criticism in the comments are ridiculous. The whole purpose of this is to practice, learn, get better, and gather feedback. This is why young software developers have a hard time because of the rude personalities that's in the area. Golden rule is to treat others the way you want to be treated. Let's not act like day one geniuses and have never improved in this line of work. smh
ОтветитьPlease change title to - Python interview with a LinkedIn engineer: Two Sum
ОтветитьThis is literally Two Sums 😱 you need to study more my friend
Ответитьml1 = [14, 3, 6, 7, 8, 10, 1, 2]
def find_target(x, t):
v = x.copy()
for i in x:
for j in v:
if i + j == t:
return i, j, t
print(find_target(ml1, 17))
waiting for the day when interviewers asks me such questions lol
ОтветитьTypical hash map question. It can be solved with O(N) complexity.
ОтветитьHere is my solution for this problem; No need for second loop:
def find_pair(values, target):
value_dict = {}
for value in values:
if (target - value) in value_dict:
return "{} and {}".format(target - value, value)
value_dict[value] = value
return "No Valid Pair"
Found a simpler way to do it.
def find_pairs(values,target):
for x in values:
for e in values[1:-1]:
if x + e == target:
print(x,"and",e)
print(True)
else:
print("not valid")
x = find_pairs([14,13,6,7,8,10,1,2],3)
arr = [14, 13, 6, 7, 8, 10, 1, 2 ]
target = 3
for i in arr:
for j in arr:
if j + i == target:
print(f'{i} and {j}')
break
This works right?
Leetcode easy problems for noobs 101.
Ответитьdef find_pairs(values, target):
num_list = []
for value in values:
if value < target:
num_list.append(value)
for num in num_list:
for x in num_list:
if target == num + x:
return str(num) + " and " + str(x)
def solution(l,n):
for i in l :
if n-i in l:
return str(i) + " and " + str(n-i)
else :
return "none!"
How about this:
def find(nums, target):
comp = { }
for num in nums:
try:
if comp[num] == num:
return [num, target - num]
except:
comp[target - num] = target - num
return []
time complexity O(log N)
worst case O(N) when no matching pairs
def find_pairs(arr, target):
d = {arr[i] : False for i in range(len(arr))}
ans = []
for num in arr:
reminder = target - num
if d[num] == False and reminder in d and num and num != reminder:
ans.append(f"{num} and {reminder}")
d[num] = True
d[target - num] = True
return ans if ans else "no valid pairs."
I am confused
How this is faster than a "nested for loop"?
""for tagert_compliment in val_dict"" --- The in operator also uses a for loop btw.
def find_pairs(a,target):
dic = {i: target-i for i in a if target-i>=0}
for i in dic.keys():
if dic[i] in dic:
return i,dic[i]
return 'no pairs'
@13.55 that excitement when 'interviewer' finally 'understands' that -2 and says "its because 0 - 2 = -2 , True is 0" :( , man please in what language True is 0 man its 1 - 3
ОтветитьI don’t understand why he is using dict[value] - target, (@ ; @) dict[value] = True which also = 1 and 1-3= -2 that’s why it’s constant -2 in print. It’s so easy and how could this question get fucked up....
Ответитьcan not believe he accepted using hash table, he just cut the corner, the actual answer is using sort then step through elements from start and end end to find the pair.
Ответитьdan the solution could have done much more easily, like looping through the array 2 levels and compare each some 2 values with the target, the store them in a array
Ответитьdef pairs(nums, target):
for num in range(len(nums)):
if (target-nums[num]) in nums[num+1:]:
return(str(nums[num])+ " and " + str((target-nums[num])))
return("can't be done")
my solution:
target_num = 9 # change target_num to whatever you want
list = [1, 10, 4, 5] # change numbers in list to whatever you want
def find_pair(temp, ind1):
ind2 = 0
for num in list:
if ind2 != ind1:
if num + temp == target_num:
print(f"#'s that add up to {target_num}: ( {temp}, {num} ) ")
return True
ind2 += 1
ind = 0
for num_ in list:
if find_pair(num_, ind) == True:
break
elif ind == len(list)-1:
print(f"No pairs add up to {target_num}");
ind += 1
['{0} and {1}'.format(n, target - n) for n in values if target - n in values][0]
'Howboudat!'
the solution he found is extremely complicated and unecessary, this can be easily done with a double for interation, and then testing the sum of the numbers: for i in values:
for j in values:
if i+j==target:
list1.append(i)
list1.append(j)
a=sorted(set(list1))
list2.append(a)
list1.clear()
then wth a litlle tupple and sets adjustment, you can easily extract the numbers, without duplicates, i don;t understand why the long complicated coding, programers need to be simple and efficient.
how about this (nice, simple and short):
# Program to give valid pairs which add up to target
def get_pairs(nums, target):
sublist = list(filter(lambda x: x <= target, sorted(nums)))
for i in sublist:
for j in sublist:
if i + j == target:
return((i, j))
return 'No valid pairs'
nums = [14, 13, 6, 7, 8, 10, 1, 2]
target = 24
pairs = get_pairs(nums, target)
print(pairs)
I haven't gone through the whole video but thought of this solution.
def find_pairs(values, target):
pairs = {}
for index, x in enumerate(values):
if x not in pairs:
pairs[target-x] = x
else:
return [pairs[x], x]
return 'No Valid Pairs'
- Pairs will store (target-number) as the key and number of number as the value
Rest is easy to figure out.
this audio was pretty bad
ОтветитьThis interviewer needs to stop eating...
ОтветитьHi,all.
Whar about
a = [14,13,6,7,8,10,1,2]
def foo(a,v):
dct = {}
[dct.update({x:v-x}) for x in a if x<v and x*2!=v]
for i in dct.keys():
if i in dct.values(): return (i,v-i)
print(foo(a,3))
“Hello”
ОтветитьThe 2sum solution was truly horrendous. From the misspelled "complement" to using a dictionary as a set, to concatenating integers with strings, to using two loops when one would do, to returning a string that describes an exceptional situation. Sorry for the negative comment.
Ответитьdef find_pairs(values,target):
for num,x in enumerate(values):
if x > target:
pass
else:
solution = target - x
if solution in values[num+1:]:
return str(solution) + '&' + str(x)
return ('No pairs')
“Python is generally easy for interviews” you got that right. Lmao
Ответитьdef getpairs(values, target):
for i in values:
target_diff = target - i
for j in values:
if target_diff == j:
return str(i) + " and " + str(j)
return "No valid pairs."