"If 0's aren't a concern, couldn't we just
multiply all numbers.
and then divide product by each number in the list ?
if there's more than one zero, then we just return an array of 0s
if there's one zero, then we just replace 0 with product and rest 0s.
what am i missing?"
Sachin R. - "If 0's aren't a concern, couldn't we just
multiply all numbers.
and then divide product by each number in the list ?
if there's more than one zero, then we just return an array of 0s
if there's one zero, then we just replace 0 with product and rest 0s.
what am i missing?"See full answer
"SELECT
items.item_category,
SUM(orders.orderquantity) AS totalunitsorderedlast7days
FROM orders
JOIN items
ON orders.itemid = items.itemid
WHERE orders.order_date BETWEEN DATE('now', '-6 days') AND DATE('now')
GROUP BY items.item_category
`"
Salome L. - "SELECT
items.item_category,
SUM(orders.orderquantity) AS totalunitsorderedlast7days
FROM orders
JOIN items
ON orders.itemid = items.itemid
WHERE orders.order_date BETWEEN DATE('now', '-6 days') AND DATE('now')
GROUP BY items.item_category
`"See full answer
"WITH discount AS (
SELECT
name,
type,
CASE
WHEN type = 'Electronic' THEN price * 0.90
WHEN type = 'Clothing' THEN price * 0.80
WHEN type = 'Grocery' THEN price * 0.95
WHEN type = 'Book' THEN price * 0.85
ELSE price
END AS discounted_price
FROM products
)
SELECT
name,
type,
ROUND(discountedprice, 2) AS discountedprice
FROM discount;
`"
Salome L. - "WITH discount AS (
SELECT
name,
type,
CASE
WHEN type = 'Electronic' THEN price * 0.90
WHEN type = 'Clothing' THEN price * 0.80
WHEN type = 'Grocery' THEN price * 0.95
WHEN type = 'Book' THEN price * 0.85
ELSE price
END AS discounted_price
FROM products
)
SELECT
name,
type,
ROUND(discountedprice, 2) AS discountedprice
FROM discount;
`"See full answer
"def find_first(array: List[int], num: int) -> int:
lo = 0
hi = len(array)-1
while lo = num:
hi = mid - 1
if lo == mid and array[mid] == num:
return mid
else:
array[mid] < num
lo = mid + 1
return -1
`"
Gabriele G. - "def find_first(array: List[int], num: int) -> int:
lo = 0
hi = len(array)-1
while lo = num:
hi = mid - 1
if lo == mid and array[mid] == num:
return mid
else:
array[mid] < num
lo = mid + 1
return -1
`"See full answer
"Even more faster and vectorized version, using np.linalg.norm - to avoid loop and np.argpartition to select lowest k. We dont need to sort whole array - we need to be sure that first k elements are lower than the rest.
import numpy as np
def knn(Xtrain, ytrain, X_new, k):
distances = np.linalg.norm(Xtrain - Xnew, axis=1)
k_indices = np.argpartition(distances, k)[:k] # O(N) selection instead of O(N log N) sort
return int(np.sum(ytrain[kindices]) > k / 2.0)
`"
Dinar M. - "Even more faster and vectorized version, using np.linalg.norm - to avoid loop and np.argpartition to select lowest k. We dont need to sort whole array - we need to be sure that first k elements are lower than the rest.
import numpy as np
def knn(Xtrain, ytrain, X_new, k):
distances = np.linalg.norm(Xtrain - Xnew, axis=1)
k_indices = np.argpartition(distances, k)[:k] # O(N) selection instead of O(N log N) sort
return int(np.sum(ytrain[kindices]) > k / 2.0)
`"See full answer
Machine Learning Engineer
Coding
+1 more
🧠 Want an expert answer to a question? Saving questions lets us know what content to make next.
"function findPrimes(n) {
if (n < 2) return [];
const primes = [];
for (let i=2; i <= n; i++) {
const half = Math.floor(i/2);
let isPrime = true;
for (let prime of primes) {
if (i % prime === 0) {
isPrime = false;
break;
}
}
if (isPrime) {
primes.push(i);
}
}
return primes;
}
`"
Tiago R. - "function findPrimes(n) {
if (n < 2) return [];
const primes = [];
for (let i=2; i <= n; i++) {
const half = Math.floor(i/2);
let isPrime = true;
for (let prime of primes) {
if (i % prime === 0) {
isPrime = false;
break;
}
}
if (isPrime) {
primes.push(i);
}
}
return primes;
}
`"See full answer
"I might be missing something but the solution, seems to be incorrect.
...
, post_pairings AS (
SELECT
ps.user_id,
ps.postseqid AS failpostid,
ps.postseqid + 1 AS nextpostid
FROM post_seq AS ps
WHERE ps.issuccessfulpost IS TRUE
)
-- here ps.issuccessfulpost IS TRUE the condition should be FALSE
-- in that way ps.postseqid is the actual failed post(failpostid)
-- Additionally, at the end the join is assumming that the sequence id is going to match the post_id, wh"
Jaime A. - "I might be missing something but the solution, seems to be incorrect.
...
, post_pairings AS (
SELECT
ps.user_id,
ps.postseqid AS failpostid,
ps.postseqid + 1 AS nextpostid
FROM post_seq AS ps
WHERE ps.issuccessfulpost IS TRUE
)
-- here ps.issuccessfulpost IS TRUE the condition should be FALSE
-- in that way ps.postseqid is the actual failed post(failpostid)
-- Additionally, at the end the join is assumming that the sequence id is going to match the post_id, wh"See full answer
"
from typing import List
def getnumberof_islands(binaryMatrix: List[List[int]]) -> int:
if not binaryMatrix: return 0
rows = len(binaryMatrix)
cols = len(binaryMatrix[0])
islands = 0
for r in range(rows):
for c in range(cols):
if binaryMatrixr == 1:
islands += 1
dfs(binaryMatrix, r, c)
return islands
def dfs(grid, r, c):
if (
r = len(grid)
"
Rick E. - "
from typing import List
def getnumberof_islands(binaryMatrix: List[List[int]]) -> int:
if not binaryMatrix: return 0
rows = len(binaryMatrix)
cols = len(binaryMatrix[0])
islands = 0
for r in range(rows):
for c in range(cols):
if binaryMatrixr == 1:
islands += 1
dfs(binaryMatrix, r, c)
return islands
def dfs(grid, r, c):
if (
r = len(grid)
"See full answer
"from typing import List
def three_sum(nums: List[int]) -> List[List[int]]:
nums.sort()
triplets = set()
for i in range(len(nums) - 2):
firstNum = nums[i]
l = i + 1
r = len(nums) - 1
while l 0:
r -= 1
elif potentialSum < 0:
l += 1
"
Anonymous Roadrunner - "from typing import List
def three_sum(nums: List[int]) -> List[List[int]]:
nums.sort()
triplets = set()
for i in range(len(nums) - 2):
firstNum = nums[i]
l = i + 1
r = len(nums) - 1
while l 0:
r -= 1
elif potentialSum < 0:
l += 1
"See full answer
"SELECT u.userid, a.marketingchannel
FROM
attribution a
JOIN
user_sessions u
ON u.sessionid = a.sessionid
GROUP BY u.userid, a.marketingchannel
HAVING SUM(a.purchase_value) > 100
ORDER BY MIN(u.adclicktimestamp) ASC;
`"
Derrick M. - "SELECT u.userid, a.marketingchannel
FROM
attribution a
JOIN
user_sessions u
ON u.sessionid = a.sessionid
GROUP BY u.userid, a.marketingchannel
HAVING SUM(a.purchase_value) > 100
ORDER BY MIN(u.adclicktimestamp) ASC;
`"See full answer
"I'm pretty sure Exponent's answer is wrong.
In the snippet below, they use "pl.name = 'Telephones' to attempt to filter down to the Telephone transactions, but they do this within a LEFT JOIN which means all product_lines rows are returned.
> LEFT JOIN product_lines pl
> ON p.productlineid = pl.id
> AND pl.name = 'Telephones'
Below is my solution. Also, I didn't see anywhere that said the "amount" column was in cents instead of dollars, but I still divided by 100 to be consistent with Exp"
Bradley E. - "I'm pretty sure Exponent's answer is wrong.
In the snippet below, they use "pl.name = 'Telephones' to attempt to filter down to the Telephone transactions, but they do this within a LEFT JOIN which means all product_lines rows are returned.
> LEFT JOIN product_lines pl
> ON p.productlineid = pl.id
> AND pl.name = 'Telephones'
Below is my solution. Also, I didn't see anywhere that said the "amount" column was in cents instead of dollars, but I still divided by 100 to be consistent with Exp"See full answer
"class ListNode:
def init(self, val=0, next=None):
self.val = val
self.next = next
def has_cycle(head: ListNode) -> bool:
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
debug your code below
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)
creates a linked list with a cycle: 1 -> 2 -> 3 -> 4"
Anonymous Roadrunner - "class ListNode:
def init(self, val=0, next=None):
self.val = val
self.next = next
def has_cycle(head: ListNode) -> bool:
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
debug your code below
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)
creates a linked list with a cycle: 1 -> 2 -> 3 -> 4"See full answer
"
with youngsuccrate as(
select
strftime('%m', postdate) AS postmonth,
round(sum(issuccessfulpost)*1.0/count(issuccessfulpost),2)as yascrate
from
post
where
userid in (select userid from post_user where age between 0 and 18)
group by
post_month
),
nonyoungsucc_rate as(
select
strftime('%m', postdate) AS postmonth,
round(sum(issuccessfulpost)*1.0/count(issuccessfulpost),2)as nonyasc_rate
from
post
where
user_id in (select"
Bhavna S. - "
with youngsuccrate as(
select
strftime('%m', postdate) AS postmonth,
round(sum(issuccessfulpost)*1.0/count(issuccessfulpost),2)as yascrate
from
post
where
userid in (select userid from post_user where age between 0 and 18)
group by
post_month
),
nonyoungsucc_rate as(
select
strftime('%m', postdate) AS postmonth,
round(sum(issuccessfulpost)*1.0/count(issuccessfulpost),2)as nonyasc_rate
from
post
where
user_id in (select"See full answer
"
from typing import Dict, List, Optional
def max_profit(prices: Dict[str, int]) -> Optional[List[str]]:
pass # your code goes here
max = [None, 0]
min = [None, float("inf")]
for city, price in prices.items():
if price > max[1]:
max[0], max[1] = city, price
if price 0:
return [min[0], max[0]]
return None
debug your code below
prices = {'"
Rick E. - "
from typing import Dict, List, Optional
def max_profit(prices: Dict[str, int]) -> Optional[List[str]]:
pass # your code goes here
max = [None, 0]
min = [None, float("inf")]
for city, price in prices.items():
if price > max[1]:
max[0], max[1] = city, price
if price 0:
return [min[0], max[0]]
return None
debug your code below
prices = {'"See full answer
"const ops = {
'+': (a, b) => a+b,
'-': (a, b) => a-b,
'/': (a, b) => a/b,
'': (a, b) => ab,
};
function calc(expr) {
// Search for + or -
for (let i=expr.length-1; i >= 0; i--) {
const char = expr.charAt(i);
if (['+', '-'].includes(char)) {
return opschar), calc(expr.slice(i+1)));
}
}
// Search for / or *
for (let i=expr.length-1; i >= 0; i--) {
const char = expr.charAt(i);
if"
Tiago R. - "const ops = {
'+': (a, b) => a+b,
'-': (a, b) => a-b,
'/': (a, b) => a/b,
'': (a, b) => ab,
};
function calc(expr) {
// Search for + or -
for (let i=expr.length-1; i >= 0; i--) {
const char = expr.charAt(i);
if (['+', '-'].includes(char)) {
return opschar), calc(expr.slice(i+1)));
}
}
// Search for / or *
for (let i=expr.length-1; i >= 0; i--) {
const char = expr.charAt(i);
if"See full answer
"
import pandas as pd
def findaveragedistance(gps_data: pd.DataFrame) -> pd.DataFrame:
#0. IMPORTANT: get the unordered pairs
gpsdata['city1']=gpsdata[['origin','destination']].min(axis=1)
gpsdata['city2']=gpsdata[['origin','destination']].max(axis=1)
#1. get the mean distance by cities
avgdistance=gpsdata.groupby(['city1','city2'], as_index=False)['distance'].mean().round(2)
avgdistance.rename(columns={'distance':"averagedistance"}, inplace=True)
"
Sean L. - "
import pandas as pd
def findaveragedistance(gps_data: pd.DataFrame) -> pd.DataFrame:
#0. IMPORTANT: get the unordered pairs
gpsdata['city1']=gpsdata[['origin','destination']].min(axis=1)
gpsdata['city2']=gpsdata[['origin','destination']].max(axis=1)
#1. get the mean distance by cities
avgdistance=gpsdata.groupby(['city1','city2'], as_index=False)['distance'].mean().round(2)
avgdistance.rename(columns={'distance':"averagedistance"}, inplace=True)
"See full answer