"I used array to append. np.array does not have append and every np.vstack recreates object again.
import numpy as np
class Centroid:
def init(self, location, vectors):
self.location = location # (D,)
self.vectors = vectors # (N_i, D)
class KMeans:
def init(self, n_features, k):
self.nfeatures = nfeatures
self.centroids = [
Centroid(
location=np.random.randn(n_features),
vectors=[] # I"
Dinar M. - "I used array to append. np.array does not have append and every np.vstack recreates object again.
import numpy as np
class Centroid:
def init(self, location, vectors):
self.location = location # (D,)
self.vectors = vectors # (N_i, D)
class KMeans:
def init(self, n_features, k):
self.nfeatures = nfeatures
self.centroids = [
Centroid(
location=np.random.randn(n_features),
vectors=[] # I"See full answer
"--country names are UPPERCASE but the table in the in the question showing lowercase. That's why it took me a while to figure it out until I ran the country column
WITH RECURSIVE Hierarchy AS (
SELECT
e.Emp_ID,
CONCAT(e.FirstName, ' ', e.MiddleName, ' ', e.LastName) AS FullName,
e.Manager_ID,
0 AS Level,
CASE
WHEN e.Country = 'IRELAND' THEN s.Salary * 1.09
WHEN e.Country = 'INDIA' THEN s.Salary * 0.012
ELSE s.Salary
"
Victor N. - "--country names are UPPERCASE but the table in the in the question showing lowercase. That's why it took me a while to figure it out until I ran the country column
WITH RECURSIVE Hierarchy AS (
SELECT
e.Emp_ID,
CONCAT(e.FirstName, ' ', e.MiddleName, ' ', e.LastName) AS FullName,
e.Manager_ID,
0 AS Level,
CASE
WHEN e.Country = 'IRELAND' THEN s.Salary * 1.09
WHEN e.Country = 'INDIA' THEN s.Salary * 0.012
ELSE s.Salary
"See full answer
"import string
from collections import defaultdict
def mostcommonwords(text):
d = defaultdict(int)
s = text.translate(str.maketrans('', '', string.punctuation))
for w in s.lower().split():
d[w] = d[w] + 1
return sorted(sorted(d.items()), reverse=True, key=lambda x: x[1])
`"
Michael S. - "import string
from collections import defaultdict
def mostcommonwords(text):
d = defaultdict(int)
s = text.translate(str.maketrans('', '', string.punctuation))
for w in s.lower().split():
d[w] = d[w] + 1
return sorted(sorted(d.items()), reverse=True, key=lambda x: x[1])
`"See full answer
Data Structures & Algorithms
Coding
🧠Want an expert answer to a question? Saving questions lets us know what content to make next.
"Any cycle would cause the prerequisite to be greater than the course. This passes all the tests:
function canFinish(_numCourses, prerequisites) {
for (const [a, b] of prerequisites) {
if (b > a) return false
}
return true
}
`"
Jeremy D. - "Any cycle would cause the prerequisite to be greater than the course. This passes all the tests:
function canFinish(_numCourses, prerequisites) {
for (const [a, b] of prerequisites) {
if (b > a) return false
}
return true
}
`"See full answer
"The user table no longer exists as expected - I get an error that user does not contain user_id.
Note that querying the table results in only user:swuoevkivrjfta
select * FROM user
`"
Evan R. - "The user table no longer exists as expected - I get an error that user does not contain user_id.
Note that querying the table results in only user:swuoevkivrjfta
select * FROM user
`"See full answer
"Initialize left pointer: Set a left pointer left to 0.
Iterate through the array: Iterate through the array from left to right.
If the current element is not 0, swap it with the element at the left pointer and increment left.
Time complexity: O(n). The loop iterates through the entire array once, making it linear time.
Space complexity: O(1). The algorithm operates in-place, modifying the input array directly without using additional data structures.
"
Avon T. - "Initialize left pointer: Set a left pointer left to 0.
Iterate through the array: Iterate through the array from left to right.
If the current element is not 0, swap it with the element at the left pointer and increment left.
Time complexity: O(n). The loop iterates through the entire array once, making it linear time.
Space complexity: O(1). The algorithm operates in-place, modifying the input array directly without using additional data structures.
"See full answer
"Without using a recursive approach, one can perform a post-order traversal by removing the parent nodes from the stack only if children were visited:
def diameterOfTree(root):
if root is None:
return 0
diameter = 0
stack = deque([[root, False]]) # (node, visited)
node_heights = {}
while stack:
curr_node, visited = stack[-1]
if visited:
heightleft = nodeheights.get(curr_node.left, 0)
heightright = nodehe"
Gabriele G. - "Without using a recursive approach, one can perform a post-order traversal by removing the parent nodes from the stack only if children were visited:
def diameterOfTree(root):
if root is None:
return 0
diameter = 0
stack = deque([[root, False]]) # (node, visited)
node_heights = {}
while stack:
curr_node, visited = stack[-1]
if visited:
heightleft = nodeheights.get(curr_node.left, 0)
heightright = nodehe"See full answer
"In the question it says: "above the overall average total posts", which to me implying a >, yet in the solution it uses >=
Caused me 1 hr to find out. plz fix"
Peter W. - "In the question it says: "above the overall average total posts", which to me implying a >, yet in the solution it uses >=
Caused me 1 hr to find out. plz fix"See full answer
"function serialize(list) {
for (let i=0; i 0xFFFF) {
throw new Exception(String ${list[i]} is too long!);
}
const prefix = String.fromCharCode(length);
list[i] = ${prefix}${list[i]};
console.log(list[i])
}
return list.join('');
}
function deserialize(s) {
let i=0;
const length = s.length;
const output = [];
while (i < length) {
"
Tiago R. - "function serialize(list) {
for (let i=0; i 0xFFFF) {
throw new Exception(String ${list[i]} is too long!);
}
const prefix = String.fromCharCode(length);
list[i] = ${prefix}${list[i]};
console.log(list[i])
}
return list.join('');
}
function deserialize(s) {
let i=0;
const length = s.length;
const output = [];
while (i < length) {
"See full answer
"def friend_distance(friends, userA, userB):
step = 0
total_neighs = set()
llen = len(total_neighs)
total_neighs.add(userB)
while len(total_neighs)!=llen:
s = set()
step += 1
llen = len(total_neighs)
for el in total_neighs:
nes = neighbours(friends, userA, el)
if userA in nes:
return step
for p in nes:
s.add(p)
for el in s:
total_neighs.add(el)
return -1
def neighbours(A,n1, n2):
out = set()
for i in range(len(A[n2])):
if An2:
out.add(i)
return out"
Batman X. - "def friend_distance(friends, userA, userB):
step = 0
total_neighs = set()
llen = len(total_neighs)
total_neighs.add(userB)
while len(total_neighs)!=llen:
s = set()
step += 1
llen = len(total_neighs)
for el in total_neighs:
nes = neighbours(friends, userA, el)
if userA in nes:
return step
for p in nes:
s.add(p)
for el in s:
total_neighs.add(el)
return -1
def neighbours(A,n1, n2):
out = set()
for i in range(len(A[n2])):
if An2:
out.add(i)
return out"See full answer
"`select employeeid, employeename, sum(maxscore) totalscore
from (
select e.id employeeid, e.name employeename, tr.testid , max(tr.score) maxscore
from employees e
join test_results tr
on e.id = tr.employee_id
group by tr.employeeid, tr.testid
order by 1
)
group by 1,2
order by 3 desc`
`"
Abbas M. - "`select employeeid, employeename, sum(maxscore) totalscore
from (
select e.id employeeid, e.name employeename, tr.testid , max(tr.score) maxscore
from employees e
join test_results tr
on e.id = tr.employee_id
group by tr.employeeid, tr.testid
order by 1
)
group by 1,2
order by 3 desc`
`"See full answer
"-- Write your query here
select
p.id,
p.title,
p.budget,
count(e.id) as num_employees,
sum(e.salary) as total_salaries
from projects p
join employeesprojects ep on p.id = ep.projectid
join employees e on ep.employee_id = e.id
group by 1
order by 5 desc;
`"
Anonymous Roadrunner - "-- Write your query here
select
p.id,
p.title,
p.budget,
count(e.id) as num_employees,
sum(e.salary) as total_salaries
from projects p
join employeesprojects ep on p.id = ep.projectid
join employees e on ep.employee_id = e.id
group by 1
order by 5 desc;
`"See full answer