-
-
Save Gerst20051/77e24c4181cfac208161279bc0273500 to your computer and use it in GitHub Desktop.
<?php | |
// Your goal is to count how many items exist that have an age equal to or greater than 50, and print this final value. | |
$ch = curl_init('https://coderbyte.com/api/challenges/json/age-counting'); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); | |
curl_setopt($ch, CURLOPT_HEADER, 0); | |
$data = curl_exec($ch); | |
curl_close($ch); | |
$json_data = json_decode($data, true); | |
$items = explode(', ', $json_data['data']); | |
$count = array_reduce($items, function ($count, $item) { | |
if (strpos($item, 'age=') !== false) { | |
$age = explode('=', $item)[1]; | |
if ($age >= 50) return $count + 1; | |
} | |
return $count; | |
}, 0); | |
print_r($count); // 128 | |
?> |
I need this code for javascript
A derivative of my regex solution.
You need to run it through a proxy service due to CORS
fetch("https://corsproxy.io/?https://coderbyte.com/api/challenges/json/age-counting")
.then(response => response.text())
.then(result => {
const pattern = /(age)=[5-9][0-9]/g;
let count = 0;
while (match = pattern.exec(result)) count++;
console.log(count);
}).catch(error => console.log('error', error));
I need this code for javascript
A derivative of my regex solution. You need to run it through a proxy service due to CORS
fetch("https://corsproxy.io/?https://coderbyte.com/api/challenges/json/age-counting") .then(response => response.text()) .then(result => { const pattern = /(age)=[5-9][0-9]/g; let count = 0; while (match = pattern.exec(result)) count++; console.log(count); }).catch(error => console.log('error', error));
You don't need to do all of that.
You can just do:
console.log(result.match(/(age)=[5-9][0-9]/g).length);
And that's it.
Here is the final inside CoderByte for NodeJS in the simpler way I found
const https = require('https');
https.get('https://coderbyte.com/api/challenges/json/age-counting', (resp) => {
let data = '';
resp.on('data', (chunk) => data += chunk);
resp.on('end', () => console.log(JSON.parse(data).data.match(/(age)=[5-9][0-9]/g).length));
});
Python solution for Age Counting problem by Coderbyte
import pandas as pd import NumPy as np import requests
r = requests.get("https://coderbyte.com/api/challenges/json/age-counting")
items = r.json()["data"].split(', ')
for data in items: splitdata = data.split("=") if splitdata[0].strip() == "age" and int(splitdata[1]) >= 50: count+=1
print(count)
Here another example using pandas
import requests
import numpy as np
import pandas as pd
r = requests.get('https://coderbyte.com/api/challenges/json/age-counting%27')
print(len(r.json()['data']))
# split data by ", "
data = r.json()['data'].split(", ")
# Load to DataFrame
df = pd.DataFrame([sub.split("=") for sub in data],columns=['key', 'age'])
# Find all age values in column "key"
dfAge = df.loc[df['key'] == 'age']
# convert column values to int
dfAge['age'] = dfAge['age'].astype(int)
# find in age column all >= 50
dfAge = dfAge.loc[dfAge['age'] >= 50]
print(len(dfAge))
Hi, Guys. I think above all solutions are not correct for the test of coderbyte.com. It is no main problem that getting the counts of age. You must be focused on this text : "Once your function is working, take the final output string and intersperse it character-by-character with your CallengeToken. Your ChallengeToken: 03h2blxr49". What is the solution?
No, it's not, I literally run my code inside CoderByte and everything is oky.
/tmp/397740317/main.py:14: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
dfAge['age'] = dfAge['age'].astype(int)
5660
128
I have tried this one to make it simple. But Lol it seems more complex but works as well.
In an interview, I couldn't answer this question answer as well but I think it's a very important and complex problem for newcomers.
<?php
$ch = curl_init('https://coderbyte.com/api/challenges/json/age-counting');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
$nedata = json_decode($data, true);
preg_match_all('/age=(\d+)/', $nedata['data'], $matches);
$count = 0;
// $matches[0] contains the full match (e.g., "age=58").
// $matches[1] = contains only the numbers, which is what you're after.
foreach($matches[1] as $age)
if($age >= 50)
$count++;
print_r($count);
?>
I need this code for javascript