{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074515,"cells":{"text":{"kind":"string","value":"// Tutorials > 10 Days of Javascript > Day 7: Regular Expressions I\n// Get started with Regular Expressions in JavaScript.\n//\n// https://www.hackerrank.com/challenges/js10-regexp-1/problem\n// challenge id: 20996\n//\n\n'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n// (skeliton_head) ----------------------------------------------------------------------\n\nfunction regexVar() {\n /*\n * Declare a RegExp object variable named 're'\n * It must match a string that starts and ends with the same vowel (i.e., {a, e, i, o, u})\n */\n\n var re = /^([aeiou]).*\\1$/;\n\n /*\n * Do not remove the return statement\n */\n return re;\n}\n\n// (skeliton_tail) ----------------------------------------------------------------------\nfunction main() {\n const re = regexVar();\n const s = readLine();\n\n console.log(re.test(s));\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074516,"cells":{"text":{"kind":"string","value":"// Tutorials > 10 Days of Javascript > Day 6: Bitwise Operators\n// Apply everything we've learned in this bitwise AND challenge.\n//\n// https://www.hackerrank.com/challenges/js10-bitwise/problem\n// challenge id: 21854\n//\n\n'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n// (skeliton_head) ----------------------------------------------------------------------\n\nfunction getMaxLessThanK(n, k) {\n let m = 0;\n for (let a = 1; a < n; ++a) {\n for (let b = a + 1; b <= n; ++b) {\n let v = a & b;\n if (v < k && v > m) m = v;\n }\n }\n return m;\n}\n\n// (skeliton_tail) ----------------------------------------------------------------------\nfunction main() {\n const q = +(readLine());\n\n for (let i = 0; i < q; i++) {\n const [n, k] = readLine().split(' ').map(Number);\n\n console.log(getMaxLessThanK(n, k));\n }\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074517,"cells":{"text":{"kind":"string","value":"// Tutorials > 10 Days of Javascript > Day 0: Hello, World!\n// Practice printing to stdout using JavaScript.\n//\n// https://www.hackerrank.com/challenges/js10-hello-world/problem\n// challenge id: 20927\n//\n\n'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n// (skeliton_head) ----------------------------------------------------------------------\n\n/**\n* A line of code that prints \"Hello, World!\" on a new line is provided in the editor.\n* Write a second line of code that prints the contents of 'parameterVariable' on a new line.\n*\n*\tParameter:\n* parameterVariable - A string of text.\n**/\nfunction greeting(parameterVariable) {\n // This line prints 'Hello, World!' to the console:\n console.log('Hello, World!');\n\n // Write a line of code that prints parameterVariable to stdout using console.log:\n console.log(parameterVariable);\n}\n\n// (skeliton_tail) ----------------------------------------------------------------------\nfunction main() {\n const parameterVariable = readLine();\n\n greeting(parameterVariable);\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074518,"cells":{"text":{"kind":"string","value":"// Tutorials > 10 Days of Javascript > Day 3: Arrays\n// Output the 2nd largest number in an array in JavaScript.\n//\n// https://www.hackerrank.com/challenges/js10-arrays/problem\n// challenge id: 21014\n//\n\n'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n// (skeliton_head) ----------------------------------------------------------------------\n\n/**\n* Return the second largest number in the array.\n* @param {Number[]} nums - An array of numbers.\n* @return {Number} The second largest number in the array.\n**/\nfunction getSecondLargest(nums) {\n // Editorial is almost unworthy of computer science :/\n let m = 0;\n let mm = 0;\n for (const i of nums) {\n if (i > mm) { m = mm; mm = i; }\n else if (i != mm && i > m) { m = i; }\n }\n return m;\n}\n\n// (skeliton_tail) ----------------------------------------------------------------------\nfunction main() {\n const n = +(readLine());\n const nums = readLine().split(' ').map(Number);\n\n console.log(getSecondLargest(nums));\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074519,"cells":{"text":{"kind":"string","value":"// Tutorials > 10 Days of Javascript > Day 1: Functions\n// Practice writing JavaScript functions.\n//\n// https://www.hackerrank.com/challenges/js10-function/problem\n// challenge id: 21019\n//\n\n'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n// (skeliton_head) ----------------------------------------------------------------------\n\n/*\n * Create the function factorial here\n */\nfunction factorial(n)\n{\n let f = 1;\n while (n > 1)\n {\n f *= n;\n --n;\n }\n return f;\n}\n\n// (skeliton_tail) ----------------------------------------------------------------------\nfunction main() {\n const n = +(readLine());\n\n console.log(factorial(n));\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074520,"cells":{"text":{"kind":"string","value":"// Tutorials > 10 Days of Javascript > Day 3: Throw\n// Practice throwing errors` in JavaScript.\n//\n// https://www.hackerrank.com/challenges/js10-throw/problem\n// challenge id: 20998\n//\n\n'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n// (skeliton_head) ----------------------------------------------------------------------\n\n/*\n * Complete the isPositive function.\n * If 'a' is positive, return \"YES\".\n * If 'a' is 0, throw an Error with the message \"Zero Error\"\n * If 'a' is negative, throw an Error with the message \"Negative Error\"\n */\nfunction isPositive(a) {\n\n if (a == 0) throw Error(\"Zero Error\");\n if (a < 0) throw Error(\"Negative Error\");\n return \"YES\";\n}\n\n// (skeliton_tail) ----------------------------------------------------------------------\nfunction main() {\n const n = +(readLine());\n\n for (let i = 0; i < n; i++) {\n const a = +(readLine());\n\n try {\n console.log(isPositive(a));\n } catch (e) {\n console.log(e.message);\n }\n }\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074521,"cells":{"text":{"kind":"string","value":"\n\n\n \n \n \n\n \n \n \n \n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074522,"cells":{"text":{"kind":"string","value":"// Tutorials > 10 Days of Javascript > Day 2: Loops\n// Learn For, While and Do-While loops in Javascript.\n//\n// https://www.hackerrank.com/challenges/js10-loops/problem\n// challenge id: 20995\n//\n\n'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n// (skeliton_head) ----------------------------------------------------------------------\n\n/*\n * Complete the vowelsAndConsonants function.\n * Print your output using 'console.log()'.\n */\nfunction vowelsAndConsonants(s) {\n\n // syntax 1\n for (var i = 0; i < s.length; ++i)\n if (\"aeuio\".indexOf(s[i]) >= 0)\n console.log(s[i]);\n\n // syntax 2\n for (const c of s)\n if (\"aeuio\".indexOf(c) == -1)\n console.log(c);\n}\n\n// (skeliton_tail) ----------------------------------------------------------------------\nfunction main() {\n const s = readLine();\n\n vowelsAndConsonants(s);\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074523,"cells":{"text":{"kind":"string","value":"\n\n\n \n \n \n \n
\n
\n \n \n \n \n \n \n \n \n
\n \n \n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074524,"cells":{"text":{"kind":"string","value":"// Tutorials > 10 Days of Javascript > Day 2: Conditional Statements: If-Else\n// Learning about conditional statements.\n//\n// https://www.hackerrank.com/challenges/js10-if-else/problem\n// challenge id: 21009\n//\n\n'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n// (skeliton_head) ----------------------------------------------------------------------\n\nfunction getGrade(score) {\n let grade;\n // Write your code here\n\n if (score <= 30 && score >= 0)\n grade = 'FEDCBA'[Math.floor(score / 5)];\n else\n grade = '?';\n\n return grade;\n}\n\n// (skeliton_tail) ----------------------------------------------------------------------\nfunction main() {\n const score = +(readLine());\n\n console.log(getGrade(score));\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074525,"cells":{"text":{"kind":"string","value":"// Tutorials > 10 Days of Javascript > Day 1: Arithmetic Operators\n// Learn arithmetic operators in JavaScript.\n//\n// https://www.hackerrank.com/challenges/js10-arithmetic-operators/problem\n// challenge id: 21011\n//\n\n'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n// (skeliton_head) ----------------------------------------------------------------------\n\n/**\n* Calculate the area of a rectangle.\n*\n* length: The length of the rectangle.\n* width: The width of the rectangle.\n*\n*\tReturn a number denoting the rectangle's area.\n**/\nfunction getArea(length, width) {\n let area;\n\n area = length * width;\n\n return area;\n}\n\n/**\n* Calculate the perimeter of a rectangle.\n*\n*\tlength: The length of the rectangle.\n* width: The width of the rectangle.\n*\n*\tReturn a number denoting the perimeter of a rectangle.\n**/\nfunction getPerimeter(length, width) {\n let perimeter;\n\n perimeter = (length + width) * 2;\n\n return perimeter;\n}\n\n// (skeliton_tail) ----------------------------------------------------------------------\nfunction main() {\n const length = +(readLine());\n const width = +(readLine());\n\n console.log(getArea(length, width));\n console.log(getPerimeter(length, width));\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074526,"cells":{"text":{"kind":"string","value":"// Tutorials > 10 Days of Javascript > Day 2: Conditional Statements: Switch\n// Practice using Switch statements.\n//\n// https://www.hackerrank.com/challenges/js10-switch/problem\n// challenge id: 21010\n//\n\n'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n// (skeliton_head) ----------------------------------------------------------------------\n\nfunction getLetter(s) {\n let letter;\n // Write your code here\n switch (s[0]) {\n case 'a':\n case 'e':\n case 'i':\n case 'o':\n case 'u':\n letter = 'A';\n break;\n\n case 'b':\n case 'c':\n case 'd':\n case 'f':\n case 'g':\n letter = 'B';\n break;\n\n case 'h':\n case 'j':\n case 'k':\n case 'l':\n case 'm':\n letter = 'C';\n break;\n\n default:\n letter = 'D';\n break;\n }\n return letter;\n}\n\n// (skeliton_tail) ----------------------------------------------------------------------\nfunction main() {\n const s = readLine();\n\n console.log(getLetter(s));\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074527,"cells":{"text":{"kind":"string","value":"// Tutorials > 10 Days of Javascript > Day 5: Template Literals\n// JavaScript Template Strings\n//\n// https://www.hackerrank.com/challenges/js10-template-literals/problem\n// challenge id: 21886\n//\n\n'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n// (skeliton_head) ----------------------------------------------------------------------\n\n/*\n * Determine the original side lengths and return an array:\n * - The first element is the length of the shorter side\n * - The second element is the length of the longer side\n *\n * Parameter(s):\n * literals: The tagged template literal's array of strings.\n * expressions: The tagged template literal's array of expression values (i.e., [area, perimeter]).\n */\nfunction sides(literals, ...expressions) {\n\n let area = expressions[0];\n let perimeter = expressions[1];\n\n let a = (perimeter - Math.sqrt(perimeter * perimeter - 16 * area)) / 4;\n let b = (perimeter + Math.sqrt(perimeter * perimeter - 16 * area)) / 4;\n\n return [a, b];\n}\n\n// (skeliton_tail) ----------------------------------------------------------------------\nfunction main() {\n let s1 = +(readLine());\n let s2 = +(readLine());\n\n [s1, s2] = [s1, s2].sort();\n\n const [x, y] = sides`The area is: ${s1 * s2}.\\nThe perimeter is: ${2 * (s1 + s2)}.`;\n\n console.log((s1 === x) ? s1 : -1);\n console.log((s2 === y) ? s2 : -1);\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074528,"cells":{"text":{"kind":"string","value":"\n### [Tutorials](https://www.hackerrank.com/domains/tutorials)\n\n\n\n#### [10 Days of Javascript](https://www.hackerrank.com/domains/tutorials/10-days-of-javascript)\n\nName | Preview | Code | Difficulty\n---- | ------- | ---- | ----------\n[Day 0: Hello, World!](https://www.hackerrank.com/challenges/js10-hello-world)|Practice printing to stdout using JavaScript.|[Javascript](js10-hello-world.js)|Easy\n[Day 0: Data Types](https://www.hackerrank.com/challenges/js10-data-types)|Get started with JavaScript data types and practice using the + operator.|[Javascript](js10-data-types.js)|Easy\n[Day 1: Arithmetic Operators](https://www.hackerrank.com/challenges/js10-arithmetic-operators)|Learn arithmetic operators in JavaScript.|[Javascript](js10-arithmetic-operators.js)|Easy\n[Day 1: Functions](https://www.hackerrank.com/challenges/js10-function)|Practice writing JavaScript functions.|[Javascript](js10-function.js)|Easy\n[Day 1: Let and Const](https://www.hackerrank.com/challenges/js10-let-and-const)|The const declaration creates a read-only reference to a value.|[Javascript](js10-let-and-const.js)|Easy\n[Day 2: Conditional Statements: If-Else](https://www.hackerrank.com/challenges/js10-if-else)|Learning about conditional statements.|[Javascript](js10-if-else.js)|Easy\n[Day 2: Conditional Statements: Switch](https://www.hackerrank.com/challenges/js10-switch)|Practice using Switch statements.|[Javascript](js10-switch.js)|Easy\n[Day 2: Loops](https://www.hackerrank.com/challenges/js10-loops)|Learn For, While and Do-While loops in Javascript.|[Javascript](js10-loops.js)|Easy\n[Day 3: Arrays](https://www.hackerrank.com/challenges/js10-arrays)|Output the 2nd largest number in an array in JavaScript.|[Javascript](js10-arrays.js)|Easy\n[Day 3: Try, Catch, and Finally](https://www.hackerrank.com/challenges/js10-try-catch-and-finally)|Learn to use `try`, `catch`, and 'finally' in JavaScript.|[Javascript](js10-try-catch-and-finally.js)|Easy\n[Day 3: Throw](https://www.hackerrank.com/challenges/js10-throw)|Practice throwing errors` in JavaScript.|[Javascript](js10-throw.js)|Easy\n[Day 4: Create a Rectangle Object](https://www.hackerrank.com/challenges/js10-objects)|Create an object with certain properties in JavaScript.|[Javascript](js10-objects.js)|Easy\n[Day 4: Count Objects](https://www.hackerrank.com/challenges/js10-count-objects)|Iterate over the elements in an array and perform an action based on each element's properties.|[Javascript](js10-count-objects.js)|Easy\n[Day 4: Classes](https://www.hackerrank.com/challenges/js10-class)|Practice using JavaScript classes.|[Javascript](js10-class.js)|Easy\n[Day 5: Inheritance](https://www.hackerrank.com/challenges/js10-inheritance)|Practice using prototypes and implementing inheritance in JavaScript.|[Javascript](js10-inheritance.js)|Easy\n[Day 5: Template Literals](https://www.hackerrank.com/challenges/js10-template-literals)|JavaScript Template Strings|[Javascript](js10-template-literals.js)|Easy\n[Day 5: Arrow Functions](https://www.hackerrank.com/challenges/js10-arrows)|Practice using Arrow Functions in JavaScript.|[Javascript](js10-arrows.js)|Easy\n[Day 6: Bitwise Operators](https://www.hackerrank.com/challenges/js10-bitwise)|Apply everything we've learned in this bitwise AND challenge.|[Javascript](js10-bitwise.js)|Easy\n[Day 6: JavaScript Dates](https://www.hackerrank.com/challenges/js10-date)|Write a JavaScript function that retrieves the day of the week from a given date.|[Javascript](js10-date.js)|Easy\n[Day 7: Regular Expressions I](https://www.hackerrank.com/challenges/js10-regexp-1)|Get started with Regular Expressions in JavaScript.|[Javascript](js10-regexp-1.js)|Easy\n[Day 7: Regular Expressions II](https://www.hackerrank.com/challenges/js10-regexp-2)|Write a JavaScript RegExp to match a name satisfying certain criteria.|[Javascript](js10-regexp-2.js)|Easy\n[Day 7: Regular Expressions III](https://www.hackerrank.com/challenges/js10-regexp-3)|Regex|[Javascript](js10-regexp-3.js)|Easy\n[Day 8: Create a Button](https://www.hackerrank.com/challenges/js10-create-a-button)|Create a button.|[HTML](js10-create-a-button.html)|Easy\n[Day 8: Buttons Container](https://www.hackerrank.com/challenges/js10-buttons-container)|Arrange buttons in a grid.|[HTML](js10-buttons-container.html)|Easy\n[Day 9: Binary Calculator](https://www.hackerrank.com/challenges/js10-binary-calculator)|Create a calculator for base 2 arithmetic.|[HTML](js10-binary-calculator.html)|Medium\n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074529,"cells":{"text":{"kind":"string","value":"\n\n\n \n \n Binary Calculator\n \n \n \n
\n
\n \n \n \n \n \n \n \n \n
\n \t\n \n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074530,"cells":{"text":{"kind":"string","value":"body {\n width: 33%;\n}\n\n#res {\n background-color: lightgray;\n border: solid;\n height: 48px;\n font-size: 20px;\n}\n\n.btns button {\n width: 25%;\n height: 36px;\n font-size: 18px;\n margin: 0px;\n float: left;\n}\n\n.dgt {\n background-color: lightgreen;\n color: brown;\n}\n\n.ctl {\n background-color: darkgreen;\n color: white;\n}\n\n.op {\n background-color: black;\n color: red;\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074531,"cells":{"text":{"kind":"string","value":"btnClr.onclick = function() {\n res.innerHTML = \"\";\n}\n\nbtnEql.onclick = function() {\n let s = res.innerHTML;\n s = Math.floor(eval(s.replace(/([01]+)/g, '0b$1'))).toString(2);\n res.innerHTML = s;\n}\n\nbtn0.onclick = function() {\n res.innerHTML += \"0\";\n}\nbtn1.onclick = function() {\n res.innerHTML += \"1\";\n}\nbtnSum.onclick = function() {\n res.innerHTML += \"+\";\n}\nbtnSub.onclick = function() {\n res.innerHTML += \"-\";\n}\nbtnMul.onclick = function() {\n res.innerHTML += \"*\";\n}\nbtnDiv.onclick = function() {\n res.innerHTML += \"/\";\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074532,"cells":{"text":{"kind":"string","value":"\n\n \n \n \n\n \n \n \n \n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074533,"cells":{"text":{"kind":"string","value":"#btn {\n width: 96px;\n height: 48px;\n font-size: 24px;\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074534,"cells":{"text":{"kind":"string","value":"var btn = document.getElementById('btn');\n\nbtn.innerHTML = 0;\nbtn.onclick = function() { ++btn.innerHTML; }\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074535,"cells":{"text":{"kind":"string","value":"\n\n\n \n \n Buttons Grid\n \n \n \n
\n

\n \n \n \n

\n

\n \n \n \n

\n

\n \n \n \n

\n
\n \n \n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074536,"cells":{"text":{"kind":"string","value":"#btns {\n width: 75%;\n}\n\nbutton {\n width: 30%;\n height: 48px;\n font-size: 24px;\n}"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074537,"cells":{"text":{"kind":"string","value":"var btn1 = document.getElementById('btn1');\nvar btn2 = document.getElementById('btn2');\nvar btn3 = document.getElementById('btn3');\nvar btn4 = document.getElementById('btn4');\nvar btn5 = document.getElementById('btn5');\nvar btn6 = document.getElementById('btn6');\nvar btn7 = document.getElementById('btn7');\nvar btn8 = document.getElementById('btn8');\nvar btn9 = document.getElementById('btn9');\n\nbtn5.onclick = function() { \n let tmp = btn1.innerHTML;\n btn1.innerHTML = btn4.innerHTML;\n btn4.innerHTML = btn7.innerHTML;\n btn7.innerHTML = btn8.innerHTML;\n btn8.innerHTML = btn9.innerHTML;\n btn9.innerHTML = btn6.innerHTML;\n btn6.innerHTML = btn3.innerHTML;\n btn3.innerHTML = btn2.innerHTML;\n btn2.innerHTML = tmp; \n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074538,"cells":{"text":{"kind":"string","value":"# Tutorials > 10 Days of Statistics > Day 5: Normal Distribution I\n# Problems based on basic statistical distributions.\n#\n# https://www.hackerrank.com/challenges/s10-normal-distribution-1/problem\n# challenge id: 21229\n#\n\nimport math\n\nπ = math.pi\n\n\ndef N(x, µ, σ):\n \"\"\" Normal Distribution \"\"\"\n return math.exp(- (x - µ) ** 2 / (2 * σ * σ)) / (σ * math.sqrt(2 * π))\n\n\ndef Φ(x, µ, σ):\n \"\"\" Cumulative Probability \"\"\"\n return 1 / 2 * (1 + math.erf((x - µ) / σ / math.sqrt(2)))\n\n\nµ = 20\nσ = 2\n\nprint(\"{:.3f}\".format(Φ(19.5, µ, σ)))\n\nprint(\"{:.3f}\".format(Φ(22, µ, σ) - Φ(20, µ, σ)))"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074539,"cells":{"text":{"kind":"string","value":"# Tutorials > 10 Days of Statistics > Day 5: Poisson Distribution I\n# Basic problem on Poisson Distribution.\n#\n# https://www.hackerrank.com/challenges/s10-poisson-distribution-1/problem\n# challenge id: 21227\n#\n\nimport math\n\ndef poisson(λ, k):\n return λ ** k * math.e ** (-λ) / math.factorial(k)\n\nλ = float(input())\nk = int(input())\n\nprint(\"{:.3f}\".format(poisson(λ, k)))\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074540,"cells":{"text":{"kind":"string","value":"# Tutorials > 10 Days of Statistics > Day 0: Weighted Mean\n# Compute the weighted mean.\n#\n# https://www.hackerrank.com/challenges/s10-weighted-mean/problem\n# challenge id: 21217\n#\n\nn = int(input())\nX = list(map(int, input().split()))\nW = list(map(int, input().split()))\n\nm = sum(x * w for x, w in zip(X, W)) / sum(W)\nprint(\"{:.1f}\".format(m))\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074541,"cells":{"text":{"kind":"string","value":"# Tutorials > 10 Days of Statistics > Day 6: The Central Limit Theorem II\n# Basic problems on the Central Limit Theorem.\n#\n# https://www.hackerrank.com/challenges/s10-the-central-limit-theorem-2/problem\n# challenge id: 21225\n#\n\nimport math\n\ndef Φ(x, µ, σ):\n \"\"\" Cumulative Probability \"\"\"\n return 1 / 2 * (1 + math.erf((x - µ) / σ / math.sqrt(2)))\n\ntickets = int(input()) # 250\nstudents = int(input()) # 100\nµ = float(input()) # 2.4 mean\nσ = float(input()) # 2.0 standard deviation\n\np = Φ(tickets, students * µ, math.sqrt(students) * σ)\n\nprint(\"{:.4f}\".format(p))\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074542,"cells":{"text":{"kind":"string","value":"# Tutorials > 10 Days of Statistics > Day 9: Multiple Linear Regression\n# Learn multiple linear regression\n#\n# https://www.hackerrank.com/challenges/s10-multiple-linear-regression/problem\n# challenge id: 21158\n#\n\nfrom sklearn import linear_model\nimport numpy as np\n\n# suppress a annoying warning on macOS\nimport warnings\nwarnings.filterwarnings(action=\"ignore\", module=\"sklearn\", message=\"^internal gelsd\")\n\nm, n = map(int, input().split())\n\nX = []\nY = []\nfor _ in range(n):\n f_y = np.array(input().split(), np.float)\n X.append(f_y[:-1])\n Y.append(f_y[-1])\n\nlm = linear_model.LinearRegression()\nlm.fit(X, Y)\na = lm.intercept_\nb = lm.coef_\n\nfor _ in range(int(input())):\n f = np.array(input().split(), np.float)\n y = a + np.sum(f * b)\n print(np.ceil(y * 100) / 100) # the rounding in the testcases it not good...\n # print('{:.2f}'.format(y)) # this is more accurate\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074543,"cells":{"text":{"kind":"string","value":"# Tutorials > 10 Days of Statistics > Day 5: Poisson Distribution II\n# Basic problem on Poisson Distribution.\n#\n# https://www.hackerrank.com/challenges/s10-poisson-distribution-2/problem\n# challenge id: 21228\n#\n\nimport math\n\ndef poisson(λ, k):\n return λ ** k * math.e ** (-λ) / math.factorial(k)\n\ndef E(λ):\n return λ + λ ** 2\n\nλ1, λ2 = map(float, input().split())\n\nprint(\"{:.3f}\".format(160 + 40 * E(λ1)))\nprint(\"{:.3f}\".format(128 + 40 * E(λ2)))\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074544,"cells":{"text":{"kind":"string","value":"# Tutorials > 10 Days of Statistics > Day 7: Pearson Correlation Coefficient I\n# Computing Pearson correlation coefficient.\n#\n# https://www.hackerrank.com/challenges/s10-pearson-correlation-coefficient/problem\n# challenge id: 21178\n#\n\n# Pearson: measure of the linear correlation between two variables X and Y\n\ndef pearson(n, X, Y):\n mx = sum(X) / n # moyenne de la série X\n my = sum(Y) / n\n\n sx = 0\n sy = 0\n p = 0\n\n for x, y in zip(X, Y):\n sx += (x - mx) ** 2 # calcule l'écart-type de X\n sy += (y - my) ** 2 # calcule l'écart-type de Y\n p += (x - mx) * (y - my) # calcule la covariance de (X,Y)\n\n sx = (sx / n) ** 0.5\n sy = (sy / n) ** 0.5\n\n p = p / (n * sx * sy)\n return p\n\n\nn = int(input())\nX = list(map(float, input().split()))\nY = list(map(float, input().split()))\n\nprint('{:.3f}'.format(pearson(n, X, Y)))\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074545,"cells":{"text":{"kind":"string","value":"# Tutorials > 10 Days of Statistics > Day 4: Geometric Distribution I\n# Problems based on basic statistical distributions.\n#\n# https://www.hackerrank.com/challenges/s10-geometric-distribution-1/problem\n# challenge id: 21244\n#\n\n\ndef g(n, p):\n return p * (1 - p) ** (n - 1)\n\nko, total = map(int, input().split())\nn = int(input())\n\nr = g(n, ko / total)\nprint(\"%.3f\" % r)\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074546,"cells":{"text":{"kind":"string","value":"# Tutorials > 10 Days of Statistics > Day 0: Mean, Median, and Mode\n# Compute the mean, median, mode, and standard deviation.\n#\n# https://www.hackerrank.com/challenges/s10-basic-statistics/problem\n# challenge id: 21180\n#\n\nfrom itertools import groupby\n\nn = int(input())\nx = list(map(int, input().split()))\n\n# la moyenne arithmétique\nm = sum(x) / len(x)\nprint(\"{:.1f}\".format(m))\n\n# la valeur médiane\nx = sorted(x)\nif n % 2 == 1:\n m = x[n // 2]\n print(m)\nelse:\n m = (x[n // 2 - 1] + x[n // 2]) / 2\n print(\"{:.1f}\".format(m))\n\n# la classe modale\n# on trie les paires par longueur décroissante: la première sera la plus grande en valeur absolue\nm = sorted([-len(list(g)), int(k)] for k, g in groupby(x))\nprint(m[0][1])\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074547,"cells":{"text":{"kind":"string","value":"# Tutorials > 10 Days of Statistics > Day 2: Basic Probability\n# Calculate the probability that two dice will have a maximum sum of 9.\n#\n# https://www.hackerrank.com/challenges/s10-mcq-1/problem\n# challenge id: 21607\n#\n\nfrom fractions import Fraction\n\nn = 0\nfor i in range(1, 7):\n for j in range(1, 7):\n if i + j <= 9:\n n += 1\n\nprint(Fraction(n, 6 * 6))\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074548,"cells":{"text":{"kind":"string","value":"# Tutorials > 10 Days of Statistics > Day 3: Cards of the Same Suit\n# Find the probability that 2 cards drawn from a deck (without replacement) are of the same suit.\n#\n# https://www.hackerrank.com/challenges/s10-mcq-5/problem\n# challenge id: 21611\n#\n\n12 / 51\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074549,"cells":{"text":{"kind":"string","value":"# Tutorials > 10 Days of Statistics > Day 7: Spearman's Rank Correlation Coefficient\n# Computing Spearman's rank correlation coefficient.\n#\n# https://www.hackerrank.com/challenges/s10-spearman-rank-correlation-coefficient/problem\n# challenge id: 21707\n#\n\ndef spearman(n, X, Y):\n \"\"\" calcul du coefficient de Spearman pour des échantillons avec des valeurs uniques \"\"\"\n\n def rank(X):\n r = [0] * len(X)\n xs = sorted((x, i) for i, x in enumerate(X))\n for j, xi in enumerate(xs):\n r[xi[1]] = j + 1\n return r\n\n # somme de la différence des ranks au carré\n r = sum((rx - ry) ** 2 for rx, ry in zip(rank(X), rank(Y)))\n r = 1 - 6 * r / n / (n ** 2 - 1)\n\n return r\n\n\nn = int(input())\nX = list(map(float, input().split()))\nY = list(map(float, input().split()))\n\nc = spearman(n, X, Y)\nprint('{:.3f}'.format(c))\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074550,"cells":{"text":{"kind":"string","value":"# Tutorials > 10 Days of Statistics > Day 8: Least Square Regression Line\n# Find the line of best fit.\n#\n# https://www.hackerrank.com/challenges/s10-least-square-regression-line/problem\n# challenge id: 21177\n#\n\ndef pearson(n, X, Y):\n mx = sum(X) / n # moyenne de la série X\n my = sum(Y) / n\n\n sx = 0.\n sy = 0.\n p = 0.\n\n for x, y in zip(X, Y):\n sx += (x - mx) ** 2 # calcule l'écart-type de X\n sy += (y - my) ** 2 # calcule l'écart-type de Y\n p += (x - mx) * (y - my) # calcule la covariance de (X,Y)\n\n sx = (sx / n) ** 0.5\n sy = (sy / n) ** 0.5\n\n p = p / (n * sx * sy)\n\n b = p * sy / sx # Y = a + b X\n a = my - b * mx\n\n return p, a, b\n\n\nX, Y = [0] * 5, [0] * 5\nfor i in range(5):\n X[i], Y[i] = map(int, input().split())\n\n_, a, b = pearson(5, X, Y)\n\nprint(\"{:.3f}\".format(a + b * 80))\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074551,"cells":{"text":{"kind":"string","value":"include(FindPythonInterp)\n\nadd_hackerrank_py(s10-basic-statistics.py)\nadd_hackerrank_py(s10-weighted-mean.py)\nadd_hackerrank_py(s10-quartiles.py)\nadd_hackerrank_py(s10-standard-deviation.py)\nadd_hackerrank_py(s10-interquartile-range.py)\nadd_hackerrank_py(s10-mcq-1.py)\nadd_hackerrank_py(s10-mcq-2.py)\nadd_hackerrank_py(s10-mcq-3.py)\nadd_hackerrank_py(s10-binomial-distribution-1.py)\nadd_hackerrank_py(s10-binomial-distribution-2.py)\nadd_hackerrank_py(s10-geometric-distribution-1.py)\nadd_hackerrank_py(s10-geometric-distribution-2.py)\nadd_hackerrank_py(s10-poisson-distribution-1.py)\nadd_hackerrank_py(s10-poisson-distribution-2.py)\nadd_hackerrank_py(s10-normal-distribution-1.py)\nadd_hackerrank_py(s10-normal-distribution-2.py)\nadd_hackerrank_py(s10-the-central-limit-theorem-1.py)\nadd_hackerrank_py(s10-the-central-limit-theorem-2.py)\nadd_hackerrank_py(s10-the-central-limit-theorem-3.py)\nadd_hackerrank_py(s10-pearson-correlation-coefficient.py)\nadd_hackerrank_py(s10-spearman-rank-correlation-coefficient.py)\nadd_hackerrank_py(s10-least-square-regression-line.py)\n\n# scikit-learn does not work with Python 3.7\nif(PYTHON_VERSION_STRING VERSION_LESS 3.7)\nadd_hackerrank_py(s10-multiple-linear-regression.py)\nendif()\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074552,"cells":{"text":{"kind":"string","value":"# Tutorials > 10 Days of Statistics > Day 5: Normal Distribution II\n# Problems based on basic statistical distributions.\n#\n# https://www.hackerrank.com/challenges/s10-normal-distribution-2/problem\n# challenge id: 21230\n#\n\nimport math\n\n\ndef N(x, µ, σ):\n \"\"\" Normal Distribution \"\"\"\n π = math.pi\n return math.exp(- (x - µ) ** 2 / (2 * σ * σ)) / (σ * math.sqrt(2 * π))\n\n\ndef Φ(x, µ, σ):\n \"\"\" Cumulative Probability \"\"\"\n return 1 / 2 * (1 + math.erf((x - µ) / σ / math.sqrt(2)))\n\n\nµ, σ = map(float, input().split())\nq1 = float(input())\nq2 = float(input())\n\n# percentage of students having grade > q1\nprint(\"{:.2f}\".format(100 - Φ(q1, µ, σ) * 100))\n\n# percentage of students having grade ≥ q2\nprint(\"{:.2f}\".format(100 - Φ(q2, µ, σ) * 100))\n\n# percentage of students having grade < q2\nprint(\"{:.2f}\".format(Φ(q2, µ, σ) * 100))\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074553,"cells":{"text":{"kind":"string","value":"# Tutorials > 10 Days of Statistics > Day 8: Pearson Correlation Coefficient II\n# Find the Pearson correlation coefficient\n#\n# https://www.hackerrank.com/challenges/s10-mcq-7/problem\n# challenge id: 21709\n#\n\n# explication:\n# 3*x + 4*y + 8 = 0 ⟹ y = -3/4 * x - 2 ⟹ b = -3/4 = ρ σy/σx\n# 4*x + 3*y + 7 = 0 ⟹ x = -3/4 * y - 7/4 ⟹ b = -3/4 = ρ σx/σy\n# (-3/4)² = ρ² ⟹ ρ = ± 3/4\n# b < 0 ⟹ ρ = - 3/4\n\n-3 / 4\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074554,"cells":{"text":{"kind":"string","value":"# Tutorials > 10 Days of Statistics > Day 1: Interquartile Range\n# Calculate the interquartile range.\n#\n# https://www.hackerrank.com/challenges/s10-interquartile-range/problem\n# challenge id: 21249\n#\n\ndef median(x):\n n = len(x)\n if n % 2 == 1:\n return x[n // 2]\n else:\n return (x[n // 2 - 1] + x[n // 2]) / 2\n\n\nn = int(input())\nX = list(map(int, input().split()))\nF = list(map(int, input().split()))\n\nS = []\nfor x, f in zip(X, F):\n S.extend([x] * f)\nS = sorted(S)\n\nn = len(S)\nif n % 2 == 1:\n Q1 = median(S[:(n // 2)])\n Q3 = median(S[(n // 2) + 1:])\nelse:\n Q1 = median(S[:(n // 2)])\n Q3 = median(S[(n // 2):])\n\nprint(\"{:.1f}\".format(Q3 - Q1))\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074555,"cells":{"text":{"kind":"string","value":"# Tutorials > 10 Days of Statistics > Day 4: Binomial Distribution II\n# Problems based on basic statistical distributions.\n#\n# https://www.hackerrank.com/challenges/s10-binomial-distribution-2/problem\n# challenge id: 21232\n#\n\nfrom math import factorial\n\n# b(x,n,p) = C(n,p) * p^x * (1-p)^(n-x)\n\n# x: number of successes\n# n: total number of trials\n# p: probability of success of 1 trial\n\ndef b(n, x, p):\n return factorial(n) // factorial(n - x) // factorial(x) * (p ** x) * (1 - p) ** (n - x)\n\np, n = map(int, input().split())\n\np = p / 100 # proba qu'un piston soit ko\n\nr = b(n, 0, p) + b(n, 1, p) + b(n, 2, p) # 0 ou 1 ou 2 rejets\nprint(\"%.3f\" % r)\n\nr = sum(b(n, i, p) for i in range(2, n + 1)) # 2 à 12 rejets\nprint(\"%.3f\" % r)\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074556,"cells":{"text":{"kind":"string","value":"# Tutorials > 10 Days of Statistics > Day 1: Standard Deviation\n# Compute the standard deviation\n#\n# https://www.hackerrank.com/challenges/s10-standard-deviation/problem\n# challenge id: 21237\n#\n\nn = int(input())\nx = list(map(int, input().split()))\n\nΣ = sum\n\n# moyenne (mean)\nµ = Σ(x) / n\n\n# écart-type (standard deviation)\n𝜎 = (Σ((i - µ) ** 2 for i in x) / n) ** 0.5\n\nprint(\"{:.1f}\".format(𝜎))\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074557,"cells":{"text":{"kind":"string","value":"# Tutorials > 10 Days of Statistics > Day 2: Compound Event Probability\n#\n#\n# https://www.hackerrank.com/challenges/s10-mcq-3/problem\n# challenge id: 21609\n#\n\nfrom fractions import Fraction\n\nn, t = 0, 0\nfor i in range(1, 8):\n for j in range(1, 10):\n for k in range(1, 9):\n red, black = 0, 0\n\n if i <= 4:\n red += 1\n else:\n black += 1\n\n if j <= 5:\n red += 1\n else:\n black += 1\n\n if k <= 4:\n red += 1\n else:\n black += 1\n\n if red == 2 and black == 1:\n n += 1\n t += 1\n\nprint(Fraction(n, t))\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074558,"cells":{"text":{"kind":"string","value":"# Tutorials > 10 Days of Statistics > Day 3: Conditional Probability\n# Find the probability that both children are boys, given that one is a boy.\n#\n# https://www.hackerrank.com/challenges/s10-mcq-4/problem\n# challenge id: 21610\n#\n\n1 / 3\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074559,"cells":{"text":{"kind":"string","value":"# Tutorials > 10 Days of Statistics > Day 6: The Central Limit Theorem I\n# Basic problems on the Central Limit Theorem.\n#\n# https://www.hackerrank.com/challenges/s10-the-central-limit-theorem-1/problem\n# challenge id: 21224\n#\n\nimport math\n\ndef Φ(x, µ, σ):\n \"\"\" Cumulative Probability \"\"\"\n return 1 / 2 * (1 + math.erf((x - µ) / σ / math.sqrt(2)))\n\ncapacity = float(input()) # 9800 maximum load\nn = int(input()) # 49 number of boxes\nµ = float(input()) # 205 mean\nσ = float(input()) # 15 standard deviation\n\np = Φ(capacity, n * µ, math.sqrt(n) * σ)\n\nprint(\"{:.4f}\".format(p))\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074560,"cells":{"text":{"kind":"string","value":"# Tutorials > 10 Days of Statistics > Day 2: More Dice\n# Calculate the probability that two dice will roll two unique values having a sum of 6.\n#\n# https://www.hackerrank.com/challenges/s10-mcq-2/problem\n# challenge id: 21608\n#\n\nfrom fractions import Fraction\n\nn = 0\nfor i in range(1, 7):\n for j in range(1, 7):\n if i + j == 6 and i != j:\n n += 1\n\nprint(Fraction(n, 6 * 6))"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074561,"cells":{"text":{"kind":"string","value":"# Tutorials > 10 Days of Statistics > Day 4: Geometric Distribution II\n# Problems based on basic statistical distributions.\n#\n# https://www.hackerrank.com/challenges/s10-geometric-distribution-2/problem\n# challenge id: 21245\n#\n\ndef g(n, p):\n return p * (1 - p) ** (n - 1)\n\nko, total = map(int, input().split())\nn = int(input())\n\nr = sum(g(n, ko / total) for n in range(1, 6))\nprint(\"%.3f\" % r)\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074562,"cells":{"text":{"kind":"string","value":"# Tutorials > 10 Days of Statistics > Day 4: Binomial Distribution I\n# Problems based on basic statistical distributions.\n#\n# https://www.hackerrank.com/challenges/s10-binomial-distribution-1/problem\n# challenge id: 21231\n#\n\nfrom math import factorial\n\n# b(x,n,p) = C(n,p) * p^x * (1-p)^(n-x)\n\n# x: number of successes\n# n: total number of trials\n# p: probability of success of 1 trial\n\ndef b(n, x, p):\n return factorial(n) // factorial(n - x) // factorial(x) * (p ** x) * (1 - p) ** (n - x)\n\n\nboys, girls = map(float, input().split())\n\np = boys / (boys + girls)\n\nr = b(6, 3, p) + b(6, 4, p) + b(6, 5, p) + b(6, 6, p)\n\nprint(\"%.3f\" % r)\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074563,"cells":{"text":{"kind":"string","value":"# Tutorials > 10 Days of Statistics > Day 6: The Central Limit Theorem III\n# Basic problems on the Central Limit Theorem.\n#\n# https://www.hackerrank.com/challenges/s10-the-central-limit-theorem-3/problem\n# challenge id: 21226\n#\n\nimport math\n\nn = int(input()) # 100 sample size\nµ = float(input()) # 500 mean\nσ = float(input()) # 80 standard deviation\npercent = float(input()) # 0.95 distribution percentage we want to cover\nz = float(input()) # 1.96 z-score : Φ(1.96) - Φ(-1.96) ≈ 95%\n\ne = z * σ / math.sqrt(n)\nprint('{:2f}'.format(µ - e))\nprint('{:2f}'.format(µ + e))\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074564,"cells":{"text":{"kind":"string","value":"\n### [Tutorials](https://www.hackerrank.com/domains/tutorials)\n\n\n\n#### [10 Days of Statistics](https://www.hackerrank.com/domains/tutorials/10-days-of-statistics)\n\nName | Preview | Code | Difficulty\n---- | ------- | ---- | ----------\n[Day 0: Mean, Median, and Mode](https://www.hackerrank.com/challenges/s10-basic-statistics)|Compute the mean, median, mode, and standard deviation.|[Python](s10-basic-statistics.py)|Easy\n[Day 0: Weighted Mean](https://www.hackerrank.com/challenges/s10-weighted-mean)|Compute the weighted mean.|[Python](s10-weighted-mean.py)|Easy\n[Day 1: Quartiles](https://www.hackerrank.com/challenges/s10-quartiles)|Calculate quartiles for an array of integers|[Python](s10-quartiles.py)|Easy\n[Day 1: Interquartile Range](https://www.hackerrank.com/challenges/s10-interquartile-range)|Calculate the interquartile range.|[Python](s10-interquartile-range.py)|Easy\n[Day 1: Standard Deviation](https://www.hackerrank.com/challenges/s10-standard-deviation)|Compute the standard deviation|[Python](s10-standard-deviation.py)|Easy\n[Day 2: Basic Probability](https://www.hackerrank.com/challenges/s10-mcq-1)|Calculate the probability that two dice will have a maximum sum of 9.|[Python](s10-mcq-1.py)|Easy\n[Day 2: More Dice](https://www.hackerrank.com/challenges/s10-mcq-2)|Calculate the probability that two dice will roll two unique values having a sum of 6.|[Python](s10-mcq-2.py)|Easy\n[Day 2: Compound Event Probability](https://www.hackerrank.com/challenges/s10-mcq-3)||[Python](s10-mcq-3.py)|Easy\n[Day 3: Conditional Probability](https://www.hackerrank.com/challenges/s10-mcq-4)|Find the probability that both children are boys, given that one is a boy.|[text](s10-mcq-4.txt)|Easy\n[Day 3: Cards of the Same Suit](https://www.hackerrank.com/challenges/s10-mcq-5)|Find the probability that 2 cards drawn from a deck (without replacement) are of the same suit.|[text](s10-mcq-5.txt)|Easy\n[Day 3: Drawing Marbles](https://www.hackerrank.com/challenges/s10-mcq-6)|Find the probability that the second marble drawn is blue.|[text](s10-mcq-6.txt)|Easy\n[Day 4: Binomial Distribution I](https://www.hackerrank.com/challenges/s10-binomial-distribution-1)|Problems based on basic statistical distributions.|[Python](s10-binomial-distribution-1.py)|Easy\n[Day 4: Binomial Distribution II](https://www.hackerrank.com/challenges/s10-binomial-distribution-2)|Problems based on basic statistical distributions.|[Python](s10-binomial-distribution-2.py)|Easy\n[Day 4: Geometric Distribution I](https://www.hackerrank.com/challenges/s10-geometric-distribution-1)|Problems based on basic statistical distributions.|[Python](s10-geometric-distribution-1.py)|Easy\n[Day 4: Geometric Distribution II](https://www.hackerrank.com/challenges/s10-geometric-distribution-2)|Problems based on basic statistical distributions.|[Python](s10-geometric-distribution-2.py)|Easy\n[Day 5: Poisson Distribution I](https://www.hackerrank.com/challenges/s10-poisson-distribution-1)|Basic problem on Poisson Distribution.|[Python](s10-poisson-distribution-1.py)|Easy\n[Day 5: Poisson Distribution II](https://www.hackerrank.com/challenges/s10-poisson-distribution-2)|Basic problem on Poisson Distribution.|[Python](s10-poisson-distribution-2.py)|Easy\n[Day 5: Normal Distribution I](https://www.hackerrank.com/challenges/s10-normal-distribution-1)|Problems based on basic statistical distributions.|[Python](s10-normal-distribution-1.py)|Easy\n[Day 5: Normal Distribution II](https://www.hackerrank.com/challenges/s10-normal-distribution-2)|Problems based on basic statistical distributions.|[Python](s10-normal-distribution-2.py)|Easy\n[Day 6: The Central Limit Theorem I](https://www.hackerrank.com/challenges/s10-the-central-limit-theorem-1)|Basic problems on the Central Limit Theorem.|[Python](s10-the-central-limit-theorem-1.py)|Easy\n[Day 6: The Central Limit Theorem II](https://www.hackerrank.com/challenges/s10-the-central-limit-theorem-2)|Basic problems on the Central Limit Theorem.|[Python](s10-the-central-limit-theorem-2.py)|Easy\n[Day 6: The Central Limit Theorem III](https://www.hackerrank.com/challenges/s10-the-central-limit-theorem-3)|Basic problems on the Central Limit Theorem.|[Python](s10-the-central-limit-theorem-3.py)|Easy\n[Day 7: Pearson Correlation Coefficient I](https://www.hackerrank.com/challenges/s10-pearson-correlation-coefficient)|Computing Pearson correlation coefficient.|[Python](s10-pearson-correlation-coefficient.py)|Easy\n[Day 7: Spearman's Rank Correlation Coefficient](https://www.hackerrank.com/challenges/s10-spearman-rank-correlation-coefficient)|Computing Spearman's rank correlation coefficient.|[Python](s10-spearman-rank-correlation-coefficient.py)|Easy\n[Day 8: Least Square Regression Line](https://www.hackerrank.com/challenges/s10-least-square-regression-line)|Find the line of best fit.|[Python](s10-least-square-regression-line.py)|Easy\n[Day 8: Pearson Correlation Coefficient II](https://www.hackerrank.com/challenges/s10-mcq-7)|Find the Pearson correlation coefficient|[text](s10-mcq-7.txt)|Medium\n[Day 9: Multiple Linear Regression](https://www.hackerrank.com/challenges/s10-multiple-linear-regression)|Learn multiple linear regression|[Python](s10-multiple-linear-regression.py)|Medium\n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074565,"cells":{"text":{"kind":"string","value":"# Tutorials > 10 Days of Statistics > Day 1: Quartiles\n# Calculate quartiles for an array of integers\n#\n# https://www.hackerrank.com/challenges/s10-quartiles/problem\n# challenge id: 21248\n#\n\ndef median(x):\n n = len(x)\n if n % 2 == 1:\n return x[n // 2]\n else:\n return (x[n // 2 - 1] + x[n // 2]) // 2\n\n\nn = int(input())\nx = list(map(int, input().split()))\n\nx = sorted(x)\n\nQ2 = median(x)\nif n % 2 == 1:\n Q1 = median(x[0:(n // 2)])\n Q3 = median(x[(n // 2) + 1:])\nelse:\n Q1 = median(x[0:(n // 2)])\n Q3 = median(x[(n // 2):])\n\nprint(Q1)\nprint(Q2)\nprint(Q3)\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074566,"cells":{"text":{"kind":"string","value":"# Tutorials > 10 Days of Statistics > Day 3: Drawing Marbles\n# Find the probability that the second marble drawn is blue.\n#\n# https://www.hackerrank.com/challenges/s10-mcq-6/problem\n# challenge id: 21612\n#\n\n2 / 3\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074567,"cells":{"text":{"kind":"string","value":"# Tutorials > 30 Days of Code > Day 13: Abstract Classes\n# Build on what you've already learned about Inheritance with this Abstract Classes challenge\n#\n# https://www.hackerrank.com/challenges/30-abstract-classes/problem\n#\n\nfrom abc import ABCMeta, abstractmethod\nclass Book(object, metaclass=ABCMeta):\n def __init__(self,title,author):\n self.title=title\n self.author=author\n @abstractmethod\n def display(): pass\n# (skeliton_head) ----------------------------------------------------------------------\n\n\nclass MyBook(Book):\n\n def __init__(self, title, author, price):\n super().__init__(title, author)\n self.price = price\n\n def display(self):\n print(\"Title:\", self.title)\n print(\"Author:\", self.author)\n print(\"Price:\", self.price)\n\n\n# (skeliton_tail) ----------------------------------------------------------------------\ntitle=input()\nauthor=input()\nprice=int(input())\nnew_novel=MyBook(title,author,price)\nnew_novel.display()\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074568,"cells":{"text":{"kind":"string","value":"// Tutorials > 30 Days of Code > Day 12: Inheritance\n// Learn about inheritance.\n//\n// https://www.hackerrank.com/challenges/30-inheritance/problem\n//\n\n#include \n#include \n\nusing namespace std;\n\n\nclass Person{\n\tprotected:\n\t\tstring firstName;\n\t\tstring lastName;\n\t\tint id;\n\tpublic:\n\t\tPerson(string firstName, string lastName, int identification){\n\t\t\tthis->firstName = firstName;\n\t\t\tthis->lastName = lastName;\n\t\t\tthis->id = identification;\n\t\t}\n\t\tvoid printPerson(){\n\t\t\tcout<< \"Name: \"<< lastName << \", \"<< firstName <<\"\\nID: \"<< id << \"\\n\";\n\t\t}\n\n};\n// (skeliton_head) ----------------------------------------------------------------------\n\n\n#include \n\nclass Student : public Person{\n\tprivate:\n\t\tvector testScores;\n\tpublic:\n /*\n * Class Constructor\n *\n * Parameters:\n * firstName - A string denoting the Person's first name.\n * lastName - A string denoting the Person's last name.\n * id - An integer denoting the Person's ID number.\n * scores - An array of integers denoting the Person's test scores.\n */\n // Write your constructor here\n Student(const string& firstName, const string& lastName, int identification, const vector& scores) :\n Person(firstName, lastName, identification),\n testScores(scores)\n {}\n\n /*\n * Function Name: calculate\n * Return: A character denoting the grade.\n */\n // Write your function here\n\t\tchar calculate() const\n {\n int sum = std::accumulate(testScores.begin(), testScores.end(), 0);\n\n float avg = sum / testScores.size();\n\n if (avg >= 90) return 'O';\n if (avg >= 80) return 'E';\n if (avg >= 70) return 'A';\n if (avg >= 55) return 'P';\n if (avg >= 40) return 'D';\n return 'T';\n }\n};\n\n// (skeliton_tail) ----------------------------------------------------------------------\nint main() {\n\tstring firstName;\n \tstring lastName;\n\tint id;\n \tint numScores;\n\tcin >> firstName >> lastName >> id >> numScores;\n \tvector scores;\n \tfor(int i = 0; i < numScores; i++){\n\t \tint tmpScore;\n\t \tcin >> tmpScore;\n\t\tscores.push_back(tmpScore);\n\t}\n\tStudent* s = new Student(firstName, lastName, id, scores);\n\ts->printPerson();\n\tcout << \"Grade: \" << s->calculate() << \"\\n\";\n\treturn 0;\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074569,"cells":{"text":{"kind":"string","value":"# Day 0: Hello, World.\n# Tutorials > 30 Days of Code\n# Practice reading from stdin and printing to stdout.\n#\n# https://www.hackerrank.com/challenges/30-hello-world/problem\n#\n\n# Read a full line of input from stdin and save it to our dynamically typed variable, input_string.\ninput_string = input()\n\n# Print a string literal saying \"Hello, World.\" to stdout.\nprint('Hello, World.')\n\n# TODO: Write a line of code here that prints the contents of input_string to stdout.\nprint(input_string)\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074570,"cells":{"text":{"kind":"string","value":"// Tutorials > 30 Days of Code > Day 21: Generics\n// Welcome to Day 21! Review generics in this challenge!\n//\n// https://www.hackerrank.com/challenges/30-generics/problem\n//\n\n#include \n#include \n#include \n\nusing namespace std;\n// (skeliton_head) ----------------------------------------------------------------------\n\n/**\n* Name: printArray\n* Print each element of the generic vector on a new line. Do not return anything.\n* @param A generic vector\n**/\n\ntemplate\nvoid printArray(const vector& a)\n{\n for (auto i : a)\n cout << i << endl;\n}\n\n// (skeliton_tail) ----------------------------------------------------------------------\nint main() {\n\tint n;\n\n\tcin >> n;\n\tvector int_vector(n);\n\tfor (int i = 0; i < n; i++) {\n\t\tint value;\n\t\tcin >> value;\n\t\tint_vector[i] = value;\n\t}\n\n\tcin >> n;\n\tvector string_vector(n);\n\tfor (int i = 0; i < n; i++) {\n\t\tstring value;\n\t\tcin >> value;\n\t\tstring_vector[i] = value;\n\t}\n\n\tprintArray(int_vector);\n\tprintArray(string_vector);\n\n\treturn 0;\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074571,"cells":{"text":{"kind":"string","value":"# Tutorials > 30 Days of Code > Day 14: Scope\n# Learn about the scope of an identifier.\n#\n# https://www.hackerrank.com/challenges/30-scope/problem\n#\n\nclass Difference:\n def __init__(self, a):\n self.__elements = a\n# (skeliton_head) ----------------------------------------------------------------------\n\n def __init__(self, a):\n self.a = a\n\n def computeDifference(self):\n self.maximumDifference = max(self.a) - min(self.a)\n\n# (skeliton_tail) ----------------------------------------------------------------------\n# End of Difference class\n\n_ = input()\na = [int(e) for e in input().split(' ')]\n\nd = Difference(a)\nd.computeDifference()\n\nprint(d.maximumDifference)\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074572,"cells":{"text":{"kind":"string","value":"// Tutorials > 30 Days of Code > Day 14: Scope\n// Learn about the scope of an identifier.\n//\n// https://www.hackerrank.com/challenges/30-scope/problem\n//\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nclass Difference {\n private:\n vector elements;\n\n \tpublic:\n \tint maximumDifference;\n// (skeliton_head) ----------------------------------------------------------------------\n\n Difference(const vector& a)\n {\n maximumDifference = *std::max_element(a.begin(), a.end()) - *std::min_element(a.begin(), a.end());\n }\n\n void computeDifference() const\n {}\n\n// (skeliton_tail) ----------------------------------------------------------------------\n}; // End of Difference class\n\nint main() {\n int N;\n cin >> N;\n\n vector a;\n\n for (int i = 0; i < N; i++) {\n int e;\n cin >> e;\n\n a.push_back(e);\n }\n\n Difference d(a);\n\n d.computeDifference();\n\n cout << d.maximumDifference;\n\n return 0;\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074573,"cells":{"text":{"kind":"string","value":"// Tutorials > 30 Days of Code > Day 15: Linked List\n// Complete the body of a function that adds a new node to the tail of a Linked List.\n//\n// https://www.hackerrank.com/challenges/30-linked-list/problem\n//\n\n#include \n#include \nusing namespace std;\nclass Node\n{\n public:\n int data;\n Node *next;\n Node(int d){\n data=d;\n next=NULL;\n }\n};\nclass Solution{\n public:\n// (skeliton_head) ----------------------------------------------------------------------\n\n Node* insert(Node *head,int data)\n {\n //Complete this method\n if (head == NULL)\n {\n return new Node(data);\n }\n Node *node = head;\n while (node->next)\n {\n node = node->next;\n }\n node->next = new Node(data);\n return head;\n }\n\n// (skeliton_tail) ----------------------------------------------------------------------\nvoid display(Node *head)\n {\n Node *start=head;\n while(start)\n {\n cout<data<<\" \";\n start=start->next;\n }\n }\n};\nint main()\n{\n\tNode* head=NULL;\n \tSolution mylist;\n int T,data;\n cin>>T;\n while(T-->0){\n cin>>data;\n head=mylist.insert(head,data);\n }\n\tmylist.display(head);\n\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074574,"cells":{"text":{"kind":"string","value":"# Tutorials > 30 Days of Code > Day 27: Testing\n# Welcome to Day 27! Review testing in this challenge!\n#\n# https://www.hackerrank.com/challenges/30-testing/problem\n#\n\nfrom random import randint\n\nprint(5)\n\n# YES (cancelled, il faut au plus k-1 nombres <= 0)\ndef yes():\n n = randint(50, 200)\n k = randint(10, n - 5)\n print(n, k)\n A = [0]\n for i in range(k - 2):\n A.append(randint(-1000, -1))\n while len(A) < n:\n A.append(randint(1, 1000))\n print(' '.join(map(str, A)))\n\n# NO (il faut au moins k nombres <= 0)\ndef no():\n n = randint(50, 200)\n k = randint(10, n - 5)\n print(n, k)\n A = [0]\n for i in range(k + 2):\n A.append(randint(-1000, -1))\n while len(A) < n:\n A.append(randint(1, 1000))\n print(' '.join(map(str, A)))\n\nyes()\nno()\nyes()\nno()\nyes()\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074575,"cells":{"text":{"kind":"string","value":"// Tutorials > 30 Days of Code > Day 24: More Linked Lists\n// Welcome to Day 24! Review everything we've learned so far and learn more about Linked Lists in this challenge.\n//\n// https://www.hackerrank.com/challenges/30-linked-list-deletion/problem\n//\n\n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\nclass Node\n{\n public:\n int data;\n Node *next;\n Node(int d){\n data=d;\n next=NULL;\n }\n};\nclass Solution{\n public:\n// (skeliton_head) ----------------------------------------------------------------------\n\n Node* removeDuplicates(Node *head)\n {\n //Write your code here\n if (head == nullptr) return head;\n\n Node *node = head;\n while (node->next != nullptr)\n {\n if (node->data == node->next->data)\n {\n Node *old = node->next;\n node->next = node->next->next;\n delete old;\n }\n else\n {\n node = node->next;\n }\n }\n\n return head;\n }\n\n// (skeliton_tail) ----------------------------------------------------------------------\nNode* insert(Node *head,int data)\n {\n Node* p=new Node(data);\n if(head==NULL){\n head=p;\n\n }\n else if(head->next==NULL){\n head->next=p;\n\n }\n else{\n Node *start=head;\n while(start->next!=NULL){\n start=start->next;\n }\n start->next=p;\n\n }\n return head;\n\n\n }\n void display(Node *head)\n {\n Node *start=head;\n while(start)\n {\n cout<data<<\" \";\n start=start->next;\n }\n }\n};\n\nint main()\n{\n\tNode* head=NULL;\n \tSolution mylist;\n int T,data;\n cin>>T;\n while(T-->0){\n cin>>data;\n head=mylist.insert(head,data);\n }\n head=mylist.removeDuplicates(head);\n\n\tmylist.display(head);\n\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074576,"cells":{"text":{"kind":"string","value":"# Day 4: Class vs. Instance\n# Learn the difference between class variables and instance variables.\n#\n# https://www.hackerrank.com/challenges/30-class-vs-instance/problem\n#\n\nclass Person:\n def __init__(self,initialAge):\n # Add some more code to run some checks on initialAge\n if initialAge < 0:\n print(\"Age is not valid, setting age to 0.\")\n initialAge = 0\n self.age = initialAge\n\n def amIOld(self):\n # Do some computations in here and print out the correct statement to the console\n if self.age < 13:\n print(\"You are young.\")\n elif self.age < 18:\n print(\"You are a teenager.\")\n else:\n print(\"You are old.\")\n\n def yearPasses(self):\n # Increment the age of the person in here\n self.age += 1\n\n\n# (skeliton_tail) ----------------------------------------------------------------------\nt = int(input())\nfor i in range(0, t):\n age = int(input())\n p = Person(age)\n p.amIOld()\n for j in range(0, 3):\n p.yearPasses()\n p.amIOld()\n print(\"\")\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074577,"cells":{"text":{"kind":"string","value":"# Tutorials > 30 Days of Code > Day 23: BST Level-Order Traversal\n# Implement a breadth-first search!\n#\n# https://www.hackerrank.com/challenges/30-binary-trees/problem\n#\n\nimport sys\n\nclass Node:\n def __init__(self,data):\n self.right=self.left=None\n self.data = data\nclass Solution:\n def insert(self,root,data):\n if root==None:\n return Node(data)\n else:\n if data<=root.data:\n cur=self.insert(root.left,data)\n root.left=cur\n else:\n cur=self.insert(root.right,data)\n root.right=cur\n return root\n# (skeliton_head) ----------------------------------------------------------------------\n\n def levelOrder(self,root):\n queue = []\n result = []\n\n queue.append(root)\n while queue:\n n = queue.pop(0)\n if n:\n result.append(n.data)\n queue.append(n.left)\n queue.append(n.right)\n\n print(*result)\n\n# (skeliton_tail) ----------------------------------------------------------------------\nT=int(input())\nmyTree=Solution()\nroot=None\nfor i in range(T):\n data=int(input())\n root=myTree.insert(root,data)\nmyTree.levelOrder(root)\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074578,"cells":{"text":{"kind":"string","value":"// Day 6: Let's Review\n// Characters and Strings\n//\n// https://www.hackerrank.com/challenges/30-review-loop/problem\n//\n\n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\n\nint main()\n{\n int t;\n cin >> t;\n\n while (t--)\n {\n string s;\n cin >> s;\n\n for (size_t i = 0; i < s.length(); ++i)\n if (i % 2 == 0) cout << s[i];\n cout << ' ';\n for (size_t i = 0; i < s.length(); ++i)\n if (i % 2 == 1) cout << s[i];\n cout << endl;\n }\n\n return 0;\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074579,"cells":{"text":{"kind":"string","value":"// Tutorials > 30 Days of Code > Day 29: Bitwise AND\n// Apply everything we've learned in this bitwise AND challenge.\n//\n// https://www.hackerrank.com/challenges/30-bitwise-and/problem\n//\n\n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\n\nint main()\n{\n /* Enter your code here. Read input from STDIN. Print output to STDOUT */\n int t;\n cin >> t;\n while (t--)\n {\n int n, k;\n cin >> n >> k;\n\n int max = 0;\n for (int i = 2; i < n; ++i)\n {\n for (int j = i + 1; j <= n; ++j)\n {\n int ij = i & j;\n if (ij < k && ij > max) max = ij;\n }\n }\n\n cout << max << endl;\n }\n return 0;\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074580,"cells":{"text":{"kind":"string","value":"// Day 0: Hello, World.\n// Practice reading from stdin and printing to stdout.\n// \n// https://www.hackerrank.com/challenges/30-hello-world/problem\n// \n\n#include \n#include \n#include \n#include \n// (skeliton_head) ----------------------------------------------------------------------\n\nint main() {\n // Declare a variable named 'input_string' to hold our input.\n char input_string[105]; \n \n // Read a full line of input from stdin and save it to our variable, input_string.\n scanf(\"%[^\\n]\", input_string); \n \n // Print a string literal saying \"Hello, World.\" to stdout using printf.\n printf(\"Hello, World.\\n\");\n \n // TODO: Write a line of code here that prints the contents of input_string to stdout.\n printf(\"%s\\n\", input_string);\n\n return 0;\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074581,"cells":{"text":{"kind":"string","value":"# Tutorials > 30 Days of Code > Day 22: Binary Search Trees\n# Given a binary tree, print its height.\n#\n# https://www.hackerrank.com/challenges/30-binary-search-trees/problem\n#\n\nclass Node:\n def __init__(self,data):\n self.right=self.left=None\n self.data = data\nclass Solution:\n def insert(self,root,data):\n if root==None:\n return Node(data)\n else:\n if data<=root.data:\n cur=self.insert(root.left,data)\n root.left=cur\n else:\n cur=self.insert(root.right,data)\n root.right=cur\n return root\n# (skeliton_head) ----------------------------------------------------------------------\n\n def getHeight(self,root,height=0):\n #Write your code here\n\n h = height\n if root.left is not None:\n h = max(h, self.getHeight(root.left, height + 1))\n if root.right is not None:\n h = max(h, self.getHeight(root.right, height + 1))\n return h\n\n# (skeliton_tail) ----------------------------------------------------------------------\nT=int(input())\nmyTree=Solution()\nroot=None\nfor i in range(T):\n data=int(input())\n root=myTree.insert(root,data)\nheight=myTree.getHeight(root)\nprint(height)\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074582,"cells":{"text":{"kind":"string","value":"# Tutorials > 30 Days of Code > Day 16: Exceptions - String to Integer\n# Can you determine if a string can be converted to an integer?\n#\n# https://www.hackerrank.com/challenges/30-exceptions-string-to-integer/problem\n#\n\nS = input().strip()\n\ntry:\n print(int(S))\nexcept ValueError:\n print(\"Bad String\")\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074583,"cells":{"text":{"kind":"string","value":"// Tutorials > 30 Days of Code > Day 26: Nested Logic\n// Test your understanding of layered logic by calculating a library fine!\n//\n// https://www.hackerrank.com/challenges/30-nested-logic/problem\n//\n\n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\n\nint main()\n{\n int d1, m1, y1, d2, m2, y2;\n cin >> d1 >> m1 >> y1;\n cin >> d2 >> m2 >> y2;\n\n int fine = 0;\n if (y1 > y2)\n fine = 10000; // plus d'un an de retard\n else if (y1 == y2)\n {\n if (m1 > m2)\n {\n fine = (m1 - m2) * 500; // plus d'un mois de retard\n }\n else if (m1 == m2 && d1 > d2)\n {\n fine = (d1 - d2) * 15; // retard dans le même mois\n }\n }\n\n cout << fine << endl;\n\n return 0;\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074584,"cells":{"text":{"kind":"string","value":"# Tutorials > 30 Days of Code > Day 15: Linked List\n# Complete the body of a function that adds a new node to the tail of a Linked List.\n#\n# https://www.hackerrank.com/challenges/30-linked-list/problem\n#\n\nclass Node:\n def __init__(self,data):\n self.data = data\n self.next = None\nclass Solution:\n def display(self,head):\n current = head\n while current:\n print(current.data,end=' ')\n current = current.next\n# (skeliton_head) ----------------------------------------------------------------------\n\n def insert(self,head,data):\n #Complete this method\n\n if head is None:\n return Node(data)\n node = head\n while node.next is not None:\n node = node.next\n node.next = Node(data)\n return head\n\n# (skeliton_tail) ----------------------------------------------------------------------\nmylist= Solution()\nT=int(input())\nhead=None\nfor i in range(T):\n data=int(input())\n head=mylist.insert(head,data)\nmylist.display(head);\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074585,"cells":{"text":{"kind":"string","value":"// Tutorials > 30 Days of Code > Day 13: Abstract Classes\n// Build on what you've already learned about Inheritance with this Abstract Classes challenge\n//\n// https://www.hackerrank.com/challenges/30-abstract-classes/problem\n//\n\n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\nclass Book{\n protected:\n string title;\n string author;\n public:\n Book(string t,string a){\n title=t;\n author=a;\n }\n virtual void display()=0;\n\n};\n// (skeliton_head) ----------------------------------------------------------------------\n\nclass MyBook : public Book\n{\n int price;\npublic:\n // Class Constructor\n //\n // Parameters:\n // title - The book's title.\n // author - The book's author.\n // price - The book's price.\n //\n MyBook(const string& t, const string& a, int p) : Book(t, a), price(p)\n {\n }\n\n // Function Name: display\n // Print the title, author, and price in the specified format.\n //\n virtual void display() override\n {\n cout << \"Title: \" << this->Book::title << endl;\n cout << \"Author: \" << this->Book::author << endl;\n cout << \"Price: \" << price << endl;\n }\n};\n\n// (skeliton_tail) ----------------------------------------------------------------------\nint main() {\n string title,author;\n int price;\n getline(cin,title);\n getline(cin,author);\n cin>>price;\n MyBook novel(title,author,price);\n novel.display();\n return 0;\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074586,"cells":{"text":{"kind":"string","value":"# Day 7: Arrays\n# Getting started with Arrays.\n#\n# https://www.hackerrank.com/challenges/30-arrays/problem\n#\n\ninput()\nprint(\" \".join(map(str, reversed(list(map(int, input().split()))))))\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074587,"cells":{"text":{"kind":"string","value":"// Day 2: Operators\n// Start using arithmetic operators.\n//\n// https://www.hackerrank.com/challenges/30-operators/problem\n//\n\n#include \n\nusing namespace std;\n\nint main() {\n double meal_cost;\n cin >> meal_cost;\n int tip_percent;\n cin >> tip_percent;\n int tax_percent;\n cin >> tax_percent;\n\n cout << \"The total meal cost is \"\n << round(meal_cost * (1 + tip_percent / 100. + tax_percent / 100.))\n << \" dollars.\" << endl;\n\n return 0;\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074588,"cells":{"text":{"kind":"string","value":"// Day 3: Intro to Conditional Statements\n// Get started with conditional statements.\n//\n// https://www.hackerrank.com/challenges/30-conditional-statements/problem\n//\n\n#include \nusing namespace std;\n\nint main()\n{\n int n;\n cin >> n;\n\n if (n % 2 == 1 or (n >= 6 and n <= 20))\n cout << \"Weird\" << endl;\n else\n cout << \"Not Weird\" << endl;\n\n return 0;\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074589,"cells":{"text":{"kind":"string","value":"# Tutorials > 30 Days of Code > Day 25: Running Time and Complexity\n# Determine if a number is prime in optimal time!\n#\n# https://www.hackerrank.com/challenges/30-running-time-and-complexity/problem\n#\n\n\ndef est_premier(n):\n \"\"\" teste si le nombre est premier \"\"\"\n if n <= 1:\n return False\n elif n == 2:\n return True\n elif n % 2 == 0:\n return False\n else:\n i = 3\n while i * i <= n:\n if n % i == 0:\n return False\n i = i + 2\n return True\n\n\nfor _ in range(int(input())):\n print(\"Prime\" if est_premier(int(input())) else \"Not prime\")\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074590,"cells":{"text":{"kind":"string","value":"add_hackerrank(30-arrays 30-arrays.cpp)\nadd_hackerrank(30-conditional-statements 30-conditional-statements.cpp)\nadd_hackerrank(30-data-types 30-data-types.cpp)\nadd_hackerrank(30-hello-world 30-hello-world.c)\nadd_hackerrank(30-operators 30-operators.cpp)\nadd_hackerrank(30-review-loop 30-review-loop.cpp)\nadd_hackerrank_py(30-arrays.py)\nadd_hackerrank_py(30-class-vs-instance.py)\nadd_hackerrank_py(30-data-types.py)\nadd_hackerrank_py(30-dictionaries-and-maps.py)\nadd_hackerrank_py(30-hello-world.py)\nadd_hackerrank_py(30-loops.py)\nadd_hackerrank_py(30-operators.py)\nadd_hackerrank_py(30-review-loop.py)\nadd_hackerrank_py(30-binary-numbers.py)\nadd_hackerrank(30-binary-numbers 30-binary-numbers.cpp)\nadd_hackerrank_py(30-2d-arrays.py)\nadd_hackerrank(30-2d-arrays 30-2d-arrays.cpp)\nadd_hackerrank(30-inheritance 30-inheritance.cpp)\nadd_hackerrank(30-generics 30-generics.cpp)\nadd_hackerrank(30-bitwise-and 30-bitwise-and.cpp)\nadd_hackerrank_py(30-scope.py)\nadd_hackerrank(30-scope 30-scope.cpp)\nadd_hackerrank_py(30-abstract-classes.py)\nadd_hackerrank(30-abstract-classes 30-abstract-classes.cpp)\nadd_hackerrank_py(30-linked-list.py)\nadd_hackerrank(30-linked-list 30-linked-list.cpp)\nadd_hackerrank_py(30-exceptions-string-to-integer.py)\nadd_hackerrank(30-exceptions-string-to-integer 30-exceptions-string-to-integer.cpp)\nadd_hackerrank(30-more-exceptions 30-more-exceptions.cpp)\nadd_hackerrank_py(30-queues-stacks.py)\nadd_hackerrank(30-running-time-and-complexity 30-running-time-and-complexity.cpp)\nadd_hackerrank_py(30-running-time-and-complexity.py)\nadd_hackerrank_py(30-binary-search-trees.py)\nadd_hackerrank(30-interfaces 30-interfaces.cpp)\nadd_hackerrank_py(30-binary-trees.py)\nadd_hackerrank(30-binary-trees 30-binary-trees.cpp)\nadd_hackerrank(30-sorting 30-sorting.cpp)\nadd_hackerrank(30-linked-list-deletion 30-linked-list-deletion.cpp)\nadd_hackerrank(30-nested-logic 30-nested-logic.cpp)\nadd_hackerrank_py(30-regex-patterns.py)\n\ndirty_cpp(30-sorting)\ndirty_cpp(30-arrays)\ndirty_cpp(30-2d-arrays)\ndirty_cpp(30-generics)\ndirty_cpp(30-inheritance)\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074591,"cells":{"text":{"kind":"string","value":"# Day 8: Dictionaries and Maps\n# Mapping Keys to Values using a Map or Dictionary.\n#\n# https://www.hackerrank.com/challenges/30-dictionaries-and-maps/problem\n#\n\nn = int(input())\nd = {}\n\nfor _ in range(n):\n k, v = input().split()\n d[k] = v\n\nfor _ in range(n):\n k = input()\n if k in d:\n print(\"{}={}\".format(k, d[k]))\n else:\n print(\"Not found\")\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074592,"cells":{"text":{"kind":"string","value":"# Tutorials > 30 Days of Code > Day 10: Binary Numbers\n# Find the maximum number of consecutive 1's in the base-2 representation of a base-10 number.\n#\n# https://www.hackerrank.com/challenges/30-binary-numbers/problem\n#\n\nn = int(input())\n\nnb = 0\nresult = 0\n\nwhile n != 0:\n n, r = divmod(n, 2)\n if r == 1:\n nb += 1\n if nb > result:\n result = nb\n else:\n nb = 0\n\nprint(result)\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074593,"cells":{"text":{"kind":"string","value":"# Tutorials > 30 Days of Code > Day 9: Recursion\n# Use recursion to compute the factorial of number.\n#\n# https://www.hackerrank.com/challenges/30-recursion/problem\n#\n\ndef factorial(n):\n if n < 2:\n return 1\n return n * factorial(n - 1)\n\nif __name__ == \"__main__\":\n n = int(input().strip())\n result = factorial(n)\n print(result)\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074594,"cells":{"text":{"kind":"string","value":"# Tutorials > 30 Days of Code > Day 11: 2D Arrays\n# Find the maximum sum of any hourglass in a 2D-Array.\n#\n# https://www.hackerrank.com/challenges/30-2d-arrays/problem\n#\n\n\ndef array2D(arr):\n resulat = -100\n for i in range(0, 4):\n for j in range(0, 4):\n s = sum(arr[i][j:j + 3])\n s += arr[i + 1][j + 1]\n s += sum(arr[i + 2][j:j + 3])\n if s > resulat:\n resulat = s\n return resulat\n\n\nif __name__ == '__main__':\n arr = []\n for _ in range(6):\n arr.append(list(map(int, input().split())))\n result = array2D(arr)\n print(result)\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074595,"cells":{"text":{"kind":"string","value":"# Day 1: Data Types\n# Get started with data types.\n#\n# https://www.hackerrank.com/challenges/30-data-types/problem\n#\n\ni = 4\nd = 4.0\ns = 'HackerRank '\n# (skeliton_head) ----------------------------------------------------------------------\n\n# Declare second integer, double, and String variables.\n\n# Read and save an integer, double, and String to your variables.\ni2 = int(input())\nd2 = float(input())\ns2 = input()\n\n# Print the sum of both integer variables on a new line.\nprint(i + i2)\n\n# Print the sum of the double variables on a new line.\nprint(d + d2)\n\n# Concatenate and print the String variables on a new line\n# The 's' variable above should be printed first.\nprint(s + s2)\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074596,"cells":{"text":{"kind":"string","value":"// Tutorials > 30 Days of Code > Day 17: More Exceptions\n// Throw an exception when user sends wrong parameters to a method.\n//\n// https://www.hackerrank.com/challenges/30-more-exceptions/problem\n//\n\n#include \n#include \n#include \n#include \nusing namespace std;\n// (skeliton_head) ----------------------------------------------------------------------\n\n//Write your code here\nclass Calculator\n{\npublic:\n int power(int n, int p)\n {\n if (n < 0 || p < 0)\n throw invalid_argument(\"n and p should be non-negative\");\n\n return (int) pow(n, p);\n }\n};\n\n// (skeliton_tail) ----------------------------------------------------------------------\nint main()\n{\n Calculator myCalculator=Calculator();\n int T,n,p;\n cin>>T;\n while(T-->0){\n if(scanf(\"%d %d\",&n,&p)==2){\n try{\n int ans=myCalculator.power(n,p);\n cout<\n#include \n#include \n\nusing namespace std;\n\nint main() {\n int i = 4;\n double d = 4.0;\n string s = \"HackerRank \";\n// (skeliton_head) ----------------------------------------------------------------------\n\n // Declare second integer, double, and String variables.\n int i2;\n double d2;\n string s2;\n\n // Read and save an integer, double, and String to your variables.\n cin >> i2 >> d2; getline(cin, s2);\n getline(cin, s2);\n\n // Print the sum of both integer variables on a new line.\n cout << i + i2 << endl;\n\n // Print the sum of the double variables on a new line.\n cout << fixed << setprecision(1) << d + d2 << endl;\n\n // Concatenate and print the String variables on a new line\n // The 's' variable above should be printed first.\n cout << s << s2 << endl;\n\n// (skeliton_tail) ----------------------------------------------------------------------\n return 0;\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074598,"cells":{"text":{"kind":"string","value":"// Day 7: Arrays\n// Getting started with Arrays.\n//\n// https://www.hackerrank.com/challenges/30-arrays/problem\n//\n\n#include \n\nusing namespace std;\n\n\nint main()\n{\n int n;\n cin >> n;\n vector arr(n);\n for(int arr_i = 0;arr_i < n;arr_i++)\n {\n cin >> arr[arr_i];\n }\n\n for(int arr_i = n;arr_i > 0;)\n {\n cout << arr[--arr_i] << \" \";\n }\n cout << endl;\n\n return 0;\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1074599,"cells":{"text":{"kind":"string","value":"# Tutorials > 30 Days of Code > Day 18: Queues and Stacks\n# Use stacks and queues to determine if a string is a palindrome.\n#\n# https://www.hackerrank.com/challenges/30-queues-stacks/problem\n#\n\nimport sys\n# (skeliton_head) ----------------------------------------------------------------------\n\nclass Solution:\n\n def __init__(self):\n self.queue = []\n self.stack = []\n\n def pushCharacter(self, ch):\n self.stack.append(ch)\n\n def popCharacter(self):\n return self.stack.pop()\n\n def enqueueCharacter(self, ch):\n self.queue.append(ch)\n\n def dequeueCharacter(self):\n return self.queue.pop(0)\n\n# (skeliton_tail) ----------------------------------------------------------------------\n# read the string s\ns=input()\n#Create the Solution class object\nobj=Solution()\n\nl=len(s)\n# push/enqueue all the characters of string s to stack\nfor i in range(l):\n obj.pushCharacter(s[i])\n obj.enqueueCharacter(s[i])\n\nisPalindrome=True\n'''\npop the top character from stack\ndequeue the first character from queue\ncompare both the characters\n'''\nfor i in range(l // 2):\n if obj.popCharacter()!=obj.dequeueCharacter():\n isPalindrome=False\n break\n#finally print whether string s is palindrome or not.\nif isPalindrome:\n print(\"The word, \"+s+\", is a palindrome.\")\nelse:\n print(\"The word, \"+s+\", is not a palindrome.\")\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"rene-d/hackerrank\",\n \"stars\": \"65\",\n \"repo_language\": \"Python\",\n \"file_name\": \"README.md\",\n \"mime_type\": \"text/plain\"\n}"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":10745,"numItemsPerPage":100,"numTotalItems":1076617,"offset":1074500,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NjE5MDM1Miwic3ViIjoiL2RhdGFzZXRzL0tvYWxhQUkvR2l0SHViLUNDMCIsImV4cCI6MTc1NjE5Mzk1MiwiaXNzIjoiaHR0cHM6Ly9odWdnaW5nZmFjZS5jbyJ9.RDoShuFtqupNvDGPzL0OKtHT9AlSdLIWlWsOeeUMUL3i9lDwrJixb5cfhS7EoCwU01uJ6rDRRZp21j2S0vNcBA","displayUrls":true},"discussionsStats":{"closed":0,"open":0,"total":0},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
text
stringlengths
2
104M
meta
dict
### [Tutorials](https://www.hackerrank.com/domains/tutorials) #### [Cracking the Coding Interview](https://www.hackerrank.com/domains/tutorials/cracking-the-coding-interview) Name | Preview | Code | Difficulty ---- | ------- | ---- | ---------- [Arrays: Left Rotation](https://www.hackerrank.com/challenges/ctci-array-left-rotation)|Given an array and a number, d, perform d left rotations on the array.|[Python](ctci-array-left-rotation.py)|Easy [Strings: Making Anagrams](https://www.hackerrank.com/challenges/ctci-making-anagrams)|How many characters should one delete to make two given strings anagrams of each other?|[Python](ctci-making-anagrams.py)|Easy [Hash Tables: Ransom Note](https://www.hackerrank.com/challenges/ctci-ransom-note)|Given two sets of dictionaries, tell if one of them is a subset of the other.|[C++](ctci-ransom-note.cpp)|Easy [Linked Lists: Detect a Cycle](https://www.hackerrank.com/challenges/ctci-linked-list-cycle)|Given a pointer to the head of a linked list, determine whether the list has a cycle.|[C++](ctci-linked-list-cycle.cpp)|Easy [Stacks: Balanced Brackets](https://www.hackerrank.com/challenges/ctci-balanced-brackets)|Given a string containing three types of brackets, determine if it is balanced.|[C++](ctci-balanced-brackets.cpp)|Medium [Queues: A Tale of Two Stacks](https://www.hackerrank.com/challenges/ctci-queue-using-two-stacks)|Create a queue data structure using two stacks.|[C++](ctci-queue-using-two-stacks.cpp)|Medium [Trees: Is This a Binary Search Tree?](https://www.hackerrank.com/challenges/ctci-is-binary-search-tree)|Given the root of a binary tree, determine if it's a binary search tree.|[Python](ctci-is-binary-search-tree.py)|Medium [Heaps: Find the Running Median](https://www.hackerrank.com/challenges/ctci-find-the-running-median)|Find the median of the elements after inputting each element.|[C++](ctci-find-the-running-median.cpp)|Hard [Tries: Contacts](https://www.hackerrank.com/challenges/ctci-contacts)|Create a Contacts application with the two basic operations: add and find.|[Python](ctci-contacts.py)|Hard [Sorting: Bubble Sort](https://www.hackerrank.com/challenges/ctci-bubble-sort)|Find the minimum number of conditional checks taking place in Bubble Sort|[Python](ctci-bubble-sort.py)|Easy [Sorting: Comparator](https://www.hackerrank.com/challenges/ctci-comparator-sorting)|Write a Comparator for sorting elements in an array.|[C++](ctci-comparator-sorting.cpp)|Medium [Merge Sort: Counting Inversions](https://www.hackerrank.com/challenges/ctci-merge-sort)|How many shifts will it take to Merge Sort an array?|[Python](ctci-merge-sort.py)|Hard [Hash Tables: Ice Cream Parlor](https://www.hackerrank.com/challenges/ctci-ice-cream-parlor)|Help Sunny and Johnny spend all their money during each trip to the Ice Cream Parlor.|[Python](ctci-ice-cream-parlor.py)|Medium [DFS: Connected Cell in a Grid](https://www.hackerrank.com/challenges/ctci-connected-cell-in-a-grid)|Find the largest connected region in a 2D Matrix.|[C++](ctci-connected-cell-in-a-grid.cpp)|Hard [BFS: Shortest Reach in a Graph](https://www.hackerrank.com/challenges/ctci-bfs-shortest-reach)|Implement a Breadth First Search (BFS).|[C++](ctci-bfs-shortest-reach.cpp)|Hard [Time Complexity: Primality](https://www.hackerrank.com/challenges/ctci-big-o)|Determine whether or not a number is prime in optimal time.|[C++](ctci-big-o.cpp)|Medium [Recursion: Fibonacci Numbers](https://www.hackerrank.com/challenges/ctci-fibonacci-numbers)|Compute the $n^{th}$ Fibonacci number.|[C++](ctci-fibonacci-numbers.cpp)|Easy [Recursion: Davis' Staircase](https://www.hackerrank.com/challenges/ctci-recursive-staircase)|Find the number of ways to get from the bottom of a staircase to the top if you can jump 1, 2, or 3 stairs at a time.|[C++](ctci-recursive-staircase.cpp)|Medium [DP: Coin Change](https://www.hackerrank.com/challenges/ctci-coin-change)|Given $m$ distinct dollar coins in infinite quantities, how many ways can you make change for $n$ dollars?|[C++](ctci-coin-change.cpp)|Hard [Bit Manipulation: Lonely Integer](https://www.hackerrank.com/challenges/ctci-lonely-integer)|Find the unique element in an array of integer pairs.|[C++](ctci-lonely-integer.cpp)|Easy
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Queues: A Tale of Two Stacks // Create a queue data structure using two stacks. // // https://www.hackerrank.com/challenges/ctci-queue-using-two-stacks/problem // #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <stack> #include <queue> using namespace std; class MyQueue { public: stack<int> stack_newest_on_top, stack_oldest_on_top; void push(int x) { // dans cette stack, les éléments sont ordonnés selon leur ordre d'arrivée stack_newest_on_top.push(x); } void pop() { // dans l'autre stack, les éléments sont ordonnés selon leur ordre INVERSE d'arrivée if (stack_oldest_on_top.empty()) { while (! stack_newest_on_top.empty()) { int x = stack_newest_on_top.top(); stack_newest_on_top.pop(); stack_oldest_on_top.push(x); } } stack_oldest_on_top.pop(); } int front() { int x = -1; if (stack_oldest_on_top.empty()) { while (! stack_newest_on_top.empty()) { x = stack_newest_on_top.top(); stack_newest_on_top.pop(); stack_oldest_on_top.push(x); } } else { x = stack_oldest_on_top.top(); } return x; } }; int main() { MyQueue q1; int q, type, x; cin >> q; for(int i = 0; i < q; i++) { cin >> type; if(type == 1) { cin >> x; q1.push(x); } else if(type == 2) { q1.pop(); } else cout << q1.front() << endl; } /* Enter your code here. Read input from STDIN. Print output to STDOUT */ return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tutorials > 10 Days of Javascript > Day 7: Regular Expressions II // Write a JavaScript RegExp to match a name satisfying certain criteria. // // https://www.hackerrank.com/challenges/js10-regexp-2/problem // challenge id: 21850 // 'use strict'; process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', inputStdin => { inputString += inputStdin; }); process.stdin.on('end', _ => { inputString = inputString.trim().split('\n').map(string => { return string.trim(); }); main(); }); function readLine() { return inputString[currentLine++]; } // (skeliton_head) ---------------------------------------------------------------------- function regexVar() { /* * Declare a RegExp object variable named 're' * It must match a string that starts with 'Mr.', 'Mrs.', 'Ms.', 'Dr.', or 'Er.', * followed by one or more letters. */ const re = /^(Mr\.|Mrs\.|Ms\.|Dr\.|Er\.)[a-zA-Z]+$/; /* * Do not remove the return statement */ return re; } // (skeliton_tail) ---------------------------------------------------------------------- function main() { const re = regexVar(); const s = readLine(); console.log(!!s.match(re)); }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tutorials > 10 Days of Javascript > Day 5: Inheritance // Practice using prototypes and implementing inheritance in JavaScript. // // https://www.hackerrank.com/challenges/js10-inheritance/problem // challenge id: 21000 // class Rectangle { constructor(w, h) { this.w = w; this.h = h; } } // (skeliton_head) ---------------------------------------------------------------------- /* * Write code that adds an 'area' method to the Rectangle class' prototype */ Rectangle.prototype.area = function() { return this.w * this.h; } /* * Create a Square class that inherits from Rectangle and implement its class constructor */ class Square extends Rectangle { constructor(w) { super(w, w); } } // (skeliton_tail) ---------------------------------------------------------------------- if (JSON.stringify(Object.getOwnPropertyNames(Square.prototype)) === JSON.stringify([ 'constructor' ])) { const rec = new Rectangle(3, 4); const sqr = new Square(3); console.log(rec.area()); console.log(sqr.area()); } else { console.log(-1); console.log(-1); }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tutorials > 10 Days of Javascript > Day 7: Regular Expressions III // Regex // // https://www.hackerrank.com/challenges/js10-regexp-3/problem // challenge id: 21896 // 'use strict'; process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', inputStdin => { inputString += inputStdin; }); process.stdin.on('end', _ => { inputString = inputString.trim().split('\n').map(string => { return string.trim(); }); main(); }); function readLine() { return inputString[currentLine++]; } // (skeliton_head) ---------------------------------------------------------------------- function regexVar() { /* * Declare a RegExp object variable named 're' * It must match ALL occurrences of numbers in a string. */ const re = /(\d+)/g; /* * Do not remove the return statement */ return re; } // (skeliton_tail) ---------------------------------------------------------------------- function main() { const re = regexVar(); const s = readLine(); const r = s.match(re); for (const e of r) { console.log(e); } }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tutorials > 10 Days of Javascript > Day 4: Create a Rectangle Object // Create an object with certain properties in JavaScript. // // https://www.hackerrank.com/challenges/js10-objects/problem // challenge id: 21012 // 'use strict'; process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', inputStdin => { inputString += inputStdin; }); process.stdin.on('end', _ => { inputString = inputString.trim().split('\n').map(string => { return string.trim(); }); main(); }); function readLine() { return inputString[currentLine++]; } // (skeliton_head) ---------------------------------------------------------------------- /* * Complete the Rectangle function */ function Rectangle(a, b) { return { length: a, width: b, perimeter: (a + b) * 2, area: a * b }; } // (skeliton_tail) ---------------------------------------------------------------------- function main() { const a = +(readLine()); const b = +(readLine()); const rec = new Rectangle(a, b); console.log(rec.length); console.log(rec.width); console.log(rec.perimeter); console.log(rec.area); }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tutorials > 10 Days of Javascript > Day 3: Try, Catch, and Finally // Learn to use `try`, `catch`, and 'finally' in JavaScript. // // https://www.hackerrank.com/challenges/js10-try-catch-and-finally/problem // challenge id: 20997 // 'use strict'; process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', inputStdin => { inputString += inputStdin; }); process.stdin.on('end', _ => { inputString = inputString.trim().split('\n').map(string => { return string.trim(); }); main(); }); function readLine() { return inputString[currentLine++]; } // (skeliton_head) ---------------------------------------------------------------------- /* * Complete the reverseString function * Use console.log() to print to stdout. */ function reverseString(s) { try { s = s.split("").reverse().join(""); } catch (e) { console.log(e.message); } finally { console.log(s); } } // (skeliton_tail) ---------------------------------------------------------------------- function main() { const s = eval(readLine()); reverseString(s); }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tutorials > 10 Days of Javascript > Day 5: Arrow Functions // Practice using Arrow Functions in JavaScript. // // https://www.hackerrank.com/challenges/js10-arrows/problem // challenge id: 21891 // 'use strict'; process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', inputStdin => { inputString += inputStdin; }); process.stdin.on('end', _ => { inputString = inputString.trim().split('\n').map(string => { return string.trim(); }); main(); }); function readLine() { return inputString[currentLine++]; } // (skeliton_head) ---------------------------------------------------------------------- /* * Modify and return the array so that all even elements are doubled and all odd elements are tripled. * * Parameter(s): * nums: An array of numbers. */ function modifyArray(nums) { let ans = nums.map(x => (x % 2 == 0) ? x * 2 : x * 3); return ans; } // (skeliton_tail) ---------------------------------------------------------------------- function main() { const n = +(readLine()); const a = readLine().split(' ').map(Number); console.log(modifyArray(a).toString().split(',').join(' ')); }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tutorials > 10 Days of Javascript > Day 1: Let and Const // The const declaration creates a read-only reference to a value. // // https://www.hackerrank.com/challenges/js10-let-and-const/problem // challenge id: 21020 // 'use strict'; process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', inputStdin => { inputString += inputStdin; }); process.stdin.on('end', _ => { inputString = inputString.trim().split('\n').map(string => { return string.trim(); }); main(); }); function readLine() { return inputString[currentLine++]; } // (skeliton_head) ---------------------------------------------------------------------- function main() { // Write your code here. Read input using 'readLine()' and print output using 'console.log()'. let radius = Number(readLine()); const PI = Math.PI; // Print the area of the circle: let area = PI * radius * radius; console.log(area); // Print the perimeter of the circle: let perimeter = PI * radius * 2; console.log(perimeter); // (skeliton_tail) ---------------------------------------------------------------------- try { // Attempt to redefine the value of constant variable PI PI = 0; // Attempt to print the value of PI console.log(PI); } catch(error) { console.error("You correctly declared 'PI' as a constant."); } }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tutorials > 10 Days of Javascript > Day 6: JavaScript Dates // Write a JavaScript function that retrieves the day of the week from a given date. // // https://www.hackerrank.com/challenges/js10-date/problem // challenge id: 21015 // 'use strict'; process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', inputStdin => { inputString += inputStdin; }); process.stdin.on('end', _ => { inputString = inputString.trim().split('\n').map(string => { return string.trim(); }); main(); }); function readLine() { return inputString[currentLine++]; } // (skeliton_head) ---------------------------------------------------------------------- // The days of the week are: "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" function getDayName(dateString) { let dayName; // Write your code here let d = new Date(dateString); const dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; dayName = dayNames[d.getDay()]; return dayName; } // (skeliton_tail) ---------------------------------------------------------------------- function main() { const d = +(readLine()); for (let i = 0; i < d; i++) { const date = readLine(); console.log(getDayName(date)); } }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tutorials > 10 Days of Javascript > Day 4: Count Objects // Iterate over the elements in an array and perform an action based on each element's properties. // // https://www.hackerrank.com/challenges/js10-count-objects/problem // challenge id: 21013 // 'use strict'; process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', inputStdin => { inputString += inputStdin; }); process.stdin.on('end', _ => { inputString = inputString.trim().split('\n').map(string => { return string.trim(); }); main(); }); function readLine() { return inputString[currentLine++]; } // (skeliton_head) ---------------------------------------------------------------------- /* * Return a count of the total number of objects 'o' satisfying o.x == o.y. * * Parameter(s): * objects: an array of objects with integer properties 'x' and 'y' */ function getCount(objects) { var count = 0; for (const o of objects) if (o.x == o.y) count++; return count; } // (skeliton_tail) ---------------------------------------------------------------------- function main() { const n = +(readLine()); let objects = []; for (let i = 0; i < n; i++) { const [a, b] = readLine().split(' '); objects.push({x: +(a), y: +(b)}); } console.log(getCount(objects)); }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tutorials > 10 Days of Javascript > Day 0: Data Types // Get started with JavaScript data types and practice using the + operator. // // https://www.hackerrank.com/challenges/js10-data-types/problem // challenge id: 20939 // 'use strict'; process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', inputStdin => { inputString += inputStdin; }); process.stdin.on('end', _ => { inputString = inputString.trim().split('\n').map(string => { return string.trim(); }); main(); }); function readLine() { return inputString[currentLine++]; } // (skeliton_head) ---------------------------------------------------------------------- /** * The variables 'firstInteger', 'firstDecimal', and 'firstString' are declared for you -- do not modify them. * Print three lines: * 1. The sum of 'firstInteger' and the Number representation of 'secondInteger'. * 2. The sum of 'firstDecimal' and the Number representation of 'secondDecimal'. * 3. The concatenation of 'firstString' and 'secondString' ('firstString' must be first). * * Parameter(s): * secondInteger - The string representation of an integer. * secondDecimal - The string representation of a floating-point number. * secondString - A string consisting of one or more space-separated words. **/ function performOperation(secondInteger, secondDecimal, secondString) { // Declare a variable named 'firstInteger' and initialize with integer value 4. const firstInteger = 4; // Declare a variable named 'firstDecimal' and initialize with floating-point value 4.0. const firstDecimal = 4.0; // Declare a variable named 'firstString' and initialize with the string "HackerRank". const firstString = 'HackerRank '; // Write code that uses console.log to print the sum of the 'firstInteger' and 'secondInteger' (converted to a Number type) on a new line. console.log(firstInteger + Number(secondInteger)); // Write code that uses console.log to print the sum of 'firstDecimal' and 'secondDecimal' (converted to a Number type) on a new line. console.log(firstDecimal + Number(secondDecimal)); // Write code that uses console.log to print the concatenation of 'firstString' and 'secondString' on a new line. The variable 'firstString' must be printed first. console.log(firstString + secondString); } // (skeliton_tail) ---------------------------------------------------------------------- function main() { const secondInteger = readLine(); const secondDecimal = readLine(); const secondString = readLine(); performOperation(secondInteger, secondDecimal, secondString); }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
add_hackerrank_js(js10-hello-world.js) add_hackerrank_js(js10-data-types.js) add_hackerrank_js(js10-arithmetic-operators.js) add_hackerrank_js(js10-function.js) add_hackerrank_js(js10-let-and-const.js) add_hackerrank_js(js10-if-else.js) add_hackerrank_js(js10-switch.js) add_hackerrank_js(js10-loops.js) add_hackerrank_js(js10-arrays.js) add_hackerrank_js(js10-try-catch-and-finally.js) add_hackerrank_js(js10-throw.js) add_hackerrank_js(js10-objects.js) add_hackerrank_js(js10-count-objects.js) add_hackerrank_js(js10-class.js) add_hackerrank_js(js10-inheritance.js) add_hackerrank_js(js10-template-literals.js) add_hackerrank_js(js10-arrows.js) add_hackerrank_js(js10-bitwise.js) add_hackerrank_js(js10-date.js) add_hackerrank_js(js10-regexp-1.js) add_hackerrank_js(js10-regexp-2.js) add_hackerrank_js(js10-regexp-3.js)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tutorials > 10 Days of Javascript > Day 4: Classes // Practice using JavaScript classes. // // https://www.hackerrank.com/challenges/js10-class/problem // challenge id: 21855 // /* * Implement a Polygon class with the following properties: * 1. A constructor that takes an array of integer side lengths. * 2. A 'perimeter' method that returns the sum of the Polygon's side lengths. */ class Polygon { constructor(sides) { this.sides = sides; } perimeter() { let sum = 0; for (const s of this.sides) sum += s; return sum; } } // (skeliton_tail) ---------------------------------------------------------------------- const rectangle = new Polygon([10, 20, 10, 20]); const square = new Polygon([10, 10, 10, 10]); const pentagon = new Polygon([10, 20, 30, 40, 43]); console.log(rectangle.perimeter()); console.log(square.perimeter()); console.log(pentagon.perimeter());
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
<!DOCTYPE html> <!-- # Tutorials > 10 Days of Javascript > Day 8: Buttons Container # Arrange buttons in a grid. # # https://www.hackerrank.com/challenges/js10-buttons-container/problem # challenge id: 21007 # --> <html> <head> <style> .btnContainer { width: 75%; } .btnContainer > .btn { width: 30%; height: 48px; font-size: 24px; } </style> </head> <body> <div id="btns" class="btnContainer"> <button id="btn1" class="btn">1</button> <button id="btn2" class="btn">2</button> <button id="btn3" class="btn">3</button> <button id="btn4" class="btn">4</button> <button id="btn5" class="btn">5</button> <button id="btn6" class="btn">6</button> <button id="btn7" class="btn">7</button> <button id="btn8" class="btn">8</button> <button id="btn9" class="btn">9</button> </div> <script type="text/javascript"> var btn1 = document.getElementById('btn1'); var btn2 = document.getElementById('btn2'); var btn3 = document.getElementById('btn3'); var btn4 = document.getElementById('btn4'); var btn5 = document.getElementById('btn5'); var btn6 = document.getElementById('btn6'); var btn7 = document.getElementById('btn7'); var btn8 = document.getElementById('btn8'); var btn9 = document.getElementById('btn9'); btn5.onclick = function() { let tmp = btn1.innerHTML; btn1.innerHTML = btn4.innerHTML; btn4.innerHTML = btn7.innerHTML; btn7.innerHTML = btn8.innerHTML; btn8.innerHTML = btn9.innerHTML; btn9.innerHTML = btn6.innerHTML; btn6.innerHTML = btn3.innerHTML; btn3.innerHTML = btn2.innerHTML; btn2.innerHTML = tmp; }; </script> </body> </html>
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tutorials > 10 Days of Javascript > Day 7: Regular Expressions I // Get started with Regular Expressions in JavaScript. // // https://www.hackerrank.com/challenges/js10-regexp-1/problem // challenge id: 20996 // 'use strict'; process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', inputStdin => { inputString += inputStdin; }); process.stdin.on('end', _ => { inputString = inputString.trim().split('\n').map(string => { return string.trim(); }); main(); }); function readLine() { return inputString[currentLine++]; } // (skeliton_head) ---------------------------------------------------------------------- function regexVar() { /* * Declare a RegExp object variable named 're' * It must match a string that starts and ends with the same vowel (i.e., {a, e, i, o, u}) */ var re = /^([aeiou]).*\1$/; /* * Do not remove the return statement */ return re; } // (skeliton_tail) ---------------------------------------------------------------------- function main() { const re = regexVar(); const s = readLine(); console.log(re.test(s)); }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tutorials > 10 Days of Javascript > Day 6: Bitwise Operators // Apply everything we've learned in this bitwise AND challenge. // // https://www.hackerrank.com/challenges/js10-bitwise/problem // challenge id: 21854 // 'use strict'; process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', inputStdin => { inputString += inputStdin; }); process.stdin.on('end', _ => { inputString = inputString.trim().split('\n').map(string => { return string.trim(); }); main(); }); function readLine() { return inputString[currentLine++]; } // (skeliton_head) ---------------------------------------------------------------------- function getMaxLessThanK(n, k) { let m = 0; for (let a = 1; a < n; ++a) { for (let b = a + 1; b <= n; ++b) { let v = a & b; if (v < k && v > m) m = v; } } return m; } // (skeliton_tail) ---------------------------------------------------------------------- function main() { const q = +(readLine()); for (let i = 0; i < q; i++) { const [n, k] = readLine().split(' ').map(Number); console.log(getMaxLessThanK(n, k)); } }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tutorials > 10 Days of Javascript > Day 0: Hello, World! // Practice printing to stdout using JavaScript. // // https://www.hackerrank.com/challenges/js10-hello-world/problem // challenge id: 20927 // 'use strict'; process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', inputStdin => { inputString += inputStdin; }); process.stdin.on('end', _ => { inputString = inputString.trim().split('\n').map(string => { return string.trim(); }); main(); }); function readLine() { return inputString[currentLine++]; } // (skeliton_head) ---------------------------------------------------------------------- /** * A line of code that prints "Hello, World!" on a new line is provided in the editor. * Write a second line of code that prints the contents of 'parameterVariable' on a new line. * * Parameter: * parameterVariable - A string of text. **/ function greeting(parameterVariable) { // This line prints 'Hello, World!' to the console: console.log('Hello, World!'); // Write a line of code that prints parameterVariable to stdout using console.log: console.log(parameterVariable); } // (skeliton_tail) ---------------------------------------------------------------------- function main() { const parameterVariable = readLine(); greeting(parameterVariable); }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tutorials > 10 Days of Javascript > Day 3: Arrays // Output the 2nd largest number in an array in JavaScript. // // https://www.hackerrank.com/challenges/js10-arrays/problem // challenge id: 21014 // 'use strict'; process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', inputStdin => { inputString += inputStdin; }); process.stdin.on('end', _ => { inputString = inputString.trim().split('\n').map(string => { return string.trim(); }); main(); }); function readLine() { return inputString[currentLine++]; } // (skeliton_head) ---------------------------------------------------------------------- /** * Return the second largest number in the array. * @param {Number[]} nums - An array of numbers. * @return {Number} The second largest number in the array. **/ function getSecondLargest(nums) { // Editorial is almost unworthy of computer science :/ let m = 0; let mm = 0; for (const i of nums) { if (i > mm) { m = mm; mm = i; } else if (i != mm && i > m) { m = i; } } return m; } // (skeliton_tail) ---------------------------------------------------------------------- function main() { const n = +(readLine()); const nums = readLine().split(' ').map(Number); console.log(getSecondLargest(nums)); }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tutorials > 10 Days of Javascript > Day 1: Functions // Practice writing JavaScript functions. // // https://www.hackerrank.com/challenges/js10-function/problem // challenge id: 21019 // 'use strict'; process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', inputStdin => { inputString += inputStdin; }); process.stdin.on('end', _ => { inputString = inputString.trim().split('\n').map(string => { return string.trim(); }); main(); }); function readLine() { return inputString[currentLine++]; } // (skeliton_head) ---------------------------------------------------------------------- /* * Create the function factorial here */ function factorial(n) { let f = 1; while (n > 1) { f *= n; --n; } return f; } // (skeliton_tail) ---------------------------------------------------------------------- function main() { const n = +(readLine()); console.log(factorial(n)); }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tutorials > 10 Days of Javascript > Day 3: Throw // Practice throwing errors` in JavaScript. // // https://www.hackerrank.com/challenges/js10-throw/problem // challenge id: 20998 // 'use strict'; process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', inputStdin => { inputString += inputStdin; }); process.stdin.on('end', _ => { inputString = inputString.trim().split('\n').map(string => { return string.trim(); }); main(); }); function readLine() { return inputString[currentLine++]; } // (skeliton_head) ---------------------------------------------------------------------- /* * Complete the isPositive function. * If 'a' is positive, return "YES". * If 'a' is 0, throw an Error with the message "Zero Error" * If 'a' is negative, throw an Error with the message "Negative Error" */ function isPositive(a) { if (a == 0) throw Error("Zero Error"); if (a < 0) throw Error("Negative Error"); return "YES"; } // (skeliton_tail) ---------------------------------------------------------------------- function main() { const n = +(readLine()); for (let i = 0; i < n; i++) { const a = +(readLine()); try { console.log(isPositive(a)); } catch (e) { console.log(e.message); } } }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
<!DOCTYPE html> <!-- # Tutorials > 10 Days of Javascript > Day 8: Create a Button # Create a button. # # https://www.hackerrank.com/challenges/js10-create-a-button/problem # challenge id: 21006 # --> <html> <head> <style> #btn { width: 96px; height: 48px; font-size: 24px; } </style> </head> <body> <button id="btn">0</button> <script type="text/javascript"> var btn = document.getElementById('btn'); btn.onclick = function() { ++btn.innerHTML; }; </script> </body> </html>
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tutorials > 10 Days of Javascript > Day 2: Loops // Learn For, While and Do-While loops in Javascript. // // https://www.hackerrank.com/challenges/js10-loops/problem // challenge id: 20995 // 'use strict'; process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', inputStdin => { inputString += inputStdin; }); process.stdin.on('end', _ => { inputString = inputString.trim().split('\n').map(string => { return string.trim(); }); main(); }); function readLine() { return inputString[currentLine++]; } // (skeliton_head) ---------------------------------------------------------------------- /* * Complete the vowelsAndConsonants function. * Print your output using 'console.log()'. */ function vowelsAndConsonants(s) { // syntax 1 for (var i = 0; i < s.length; ++i) if ("aeuio".indexOf(s[i]) >= 0) console.log(s[i]); // syntax 2 for (const c of s) if ("aeuio".indexOf(c) == -1) console.log(c); } // (skeliton_tail) ---------------------------------------------------------------------- function main() { const s = readLine(); vowelsAndConsonants(s); }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
<!DOCTYPE html> <!-- # Tutorials > 10 Days of Javascript > Day 9: Binary Calculator # Create a calculator for base 2 arithmetic. # # https://www.hackerrank.com/challenges/js10-binary-calculator/problem # challenge id: 21008 # --> <html> <head> <style> body { width: 33%; } #res { background-color: lightgray; border: solid; height: 48px; font-size: 20px; } .btns button { width: 25%; height: 36px; font-size: 18px; margin: 0px; float: left; } .dgt { background-color: lightgreen; color: brown; } .ctl { background-color: darkgreen; color: white; } .op { background-color: black; color: red; } </style> </head> <body> <div id="res"></div> <div id="btns" class="btns"> <button id="btn0" class="dgt">0</button> <button id="btn1" class="dgt">1</button> <button id="btnClr" class="ctl">C</button> <button id="btnEql" class="ctl">=</button> <button id="btnSum" class="op">+</button> <button id="btnSub" class="op">-</button> <button id="btnMul" class="op">*</button> <button id="btnDiv" class="op">/</button> </div> <script type="text/javascript"> btnClr.onclick = function() { res.innerHTML = ""; }; btnEql.onclick = function() { let s = res.innerHTML; s = Math.floor(eval(s.replace(/([01]+)/g, '0b$1'))).toString(2); res.innerHTML = s; }; btn0.onclick = function() { res.innerHTML += "0"; }; btn1.onclick = function() { res.innerHTML += "1"; }; btnSum.onclick = function() { res.innerHTML += "+"; }; btnSub.onclick = function() { res.innerHTML += "-"; }; btnMul.onclick = function() { res.innerHTML += "*"; }; btnDiv.onclick = function() { res.innerHTML += "/"; }; </script> </body> </html>
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tutorials > 10 Days of Javascript > Day 2: Conditional Statements: If-Else // Learning about conditional statements. // // https://www.hackerrank.com/challenges/js10-if-else/problem // challenge id: 21009 // 'use strict'; process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', inputStdin => { inputString += inputStdin; }); process.stdin.on('end', _ => { inputString = inputString.trim().split('\n').map(string => { return string.trim(); }); main(); }); function readLine() { return inputString[currentLine++]; } // (skeliton_head) ---------------------------------------------------------------------- function getGrade(score) { let grade; // Write your code here if (score <= 30 && score >= 0) grade = 'FEDCBA'[Math.floor(score / 5)]; else grade = '?'; return grade; } // (skeliton_tail) ---------------------------------------------------------------------- function main() { const score = +(readLine()); console.log(getGrade(score)); }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tutorials > 10 Days of Javascript > Day 1: Arithmetic Operators // Learn arithmetic operators in JavaScript. // // https://www.hackerrank.com/challenges/js10-arithmetic-operators/problem // challenge id: 21011 // 'use strict'; process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', inputStdin => { inputString += inputStdin; }); process.stdin.on('end', _ => { inputString = inputString.trim().split('\n').map(string => { return string.trim(); }); main(); }); function readLine() { return inputString[currentLine++]; } // (skeliton_head) ---------------------------------------------------------------------- /** * Calculate the area of a rectangle. * * length: The length of the rectangle. * width: The width of the rectangle. * * Return a number denoting the rectangle's area. **/ function getArea(length, width) { let area; area = length * width; return area; } /** * Calculate the perimeter of a rectangle. * * length: The length of the rectangle. * width: The width of the rectangle. * * Return a number denoting the perimeter of a rectangle. **/ function getPerimeter(length, width) { let perimeter; perimeter = (length + width) * 2; return perimeter; } // (skeliton_tail) ---------------------------------------------------------------------- function main() { const length = +(readLine()); const width = +(readLine()); console.log(getArea(length, width)); console.log(getPerimeter(length, width)); }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tutorials > 10 Days of Javascript > Day 2: Conditional Statements: Switch // Practice using Switch statements. // // https://www.hackerrank.com/challenges/js10-switch/problem // challenge id: 21010 // 'use strict'; process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', inputStdin => { inputString += inputStdin; }); process.stdin.on('end', _ => { inputString = inputString.trim().split('\n').map(string => { return string.trim(); }); main(); }); function readLine() { return inputString[currentLine++]; } // (skeliton_head) ---------------------------------------------------------------------- function getLetter(s) { let letter; // Write your code here switch (s[0]) { case 'a': case 'e': case 'i': case 'o': case 'u': letter = 'A'; break; case 'b': case 'c': case 'd': case 'f': case 'g': letter = 'B'; break; case 'h': case 'j': case 'k': case 'l': case 'm': letter = 'C'; break; default: letter = 'D'; break; } return letter; } // (skeliton_tail) ---------------------------------------------------------------------- function main() { const s = readLine(); console.log(getLetter(s)); }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tutorials > 10 Days of Javascript > Day 5: Template Literals // JavaScript Template Strings // // https://www.hackerrank.com/challenges/js10-template-literals/problem // challenge id: 21886 // 'use strict'; process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', inputStdin => { inputString += inputStdin; }); process.stdin.on('end', _ => { inputString = inputString.trim().split('\n').map(string => { return string.trim(); }); main(); }); function readLine() { return inputString[currentLine++]; } // (skeliton_head) ---------------------------------------------------------------------- /* * Determine the original side lengths and return an array: * - The first element is the length of the shorter side * - The second element is the length of the longer side * * Parameter(s): * literals: The tagged template literal's array of strings. * expressions: The tagged template literal's array of expression values (i.e., [area, perimeter]). */ function sides(literals, ...expressions) { let area = expressions[0]; let perimeter = expressions[1]; let a = (perimeter - Math.sqrt(perimeter * perimeter - 16 * area)) / 4; let b = (perimeter + Math.sqrt(perimeter * perimeter - 16 * area)) / 4; return [a, b]; } // (skeliton_tail) ---------------------------------------------------------------------- function main() { let s1 = +(readLine()); let s2 = +(readLine()); [s1, s2] = [s1, s2].sort(); const [x, y] = sides`The area is: ${s1 * s2}.\nThe perimeter is: ${2 * (s1 + s2)}.`; console.log((s1 === x) ? s1 : -1); console.log((s2 === y) ? s2 : -1); }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
### [Tutorials](https://www.hackerrank.com/domains/tutorials) #### [10 Days of Javascript](https://www.hackerrank.com/domains/tutorials/10-days-of-javascript) Name | Preview | Code | Difficulty ---- | ------- | ---- | ---------- [Day 0: Hello, World!](https://www.hackerrank.com/challenges/js10-hello-world)|Practice printing to stdout using JavaScript.|[Javascript](js10-hello-world.js)|Easy [Day 0: Data Types](https://www.hackerrank.com/challenges/js10-data-types)|Get started with JavaScript data types and practice using the + operator.|[Javascript](js10-data-types.js)|Easy [Day 1: Arithmetic Operators](https://www.hackerrank.com/challenges/js10-arithmetic-operators)|Learn arithmetic operators in JavaScript.|[Javascript](js10-arithmetic-operators.js)|Easy [Day 1: Functions](https://www.hackerrank.com/challenges/js10-function)|Practice writing JavaScript functions.|[Javascript](js10-function.js)|Easy [Day 1: Let and Const](https://www.hackerrank.com/challenges/js10-let-and-const)|The const declaration creates a read-only reference to a value.|[Javascript](js10-let-and-const.js)|Easy [Day 2: Conditional Statements: If-Else](https://www.hackerrank.com/challenges/js10-if-else)|Learning about conditional statements.|[Javascript](js10-if-else.js)|Easy [Day 2: Conditional Statements: Switch](https://www.hackerrank.com/challenges/js10-switch)|Practice using Switch statements.|[Javascript](js10-switch.js)|Easy [Day 2: Loops](https://www.hackerrank.com/challenges/js10-loops)|Learn For, While and Do-While loops in Javascript.|[Javascript](js10-loops.js)|Easy [Day 3: Arrays](https://www.hackerrank.com/challenges/js10-arrays)|Output the 2nd largest number in an array in JavaScript.|[Javascript](js10-arrays.js)|Easy [Day 3: Try, Catch, and Finally](https://www.hackerrank.com/challenges/js10-try-catch-and-finally)|Learn to use `try`, `catch`, and 'finally' in JavaScript.|[Javascript](js10-try-catch-and-finally.js)|Easy [Day 3: Throw](https://www.hackerrank.com/challenges/js10-throw)|Practice throwing errors` in JavaScript.|[Javascript](js10-throw.js)|Easy [Day 4: Create a Rectangle Object](https://www.hackerrank.com/challenges/js10-objects)|Create an object with certain properties in JavaScript.|[Javascript](js10-objects.js)|Easy [Day 4: Count Objects](https://www.hackerrank.com/challenges/js10-count-objects)|Iterate over the elements in an array and perform an action based on each element's properties.|[Javascript](js10-count-objects.js)|Easy [Day 4: Classes](https://www.hackerrank.com/challenges/js10-class)|Practice using JavaScript classes.|[Javascript](js10-class.js)|Easy [Day 5: Inheritance](https://www.hackerrank.com/challenges/js10-inheritance)|Practice using prototypes and implementing inheritance in JavaScript.|[Javascript](js10-inheritance.js)|Easy [Day 5: Template Literals](https://www.hackerrank.com/challenges/js10-template-literals)|JavaScript Template Strings|[Javascript](js10-template-literals.js)|Easy [Day 5: Arrow Functions](https://www.hackerrank.com/challenges/js10-arrows)|Practice using Arrow Functions in JavaScript.|[Javascript](js10-arrows.js)|Easy [Day 6: Bitwise Operators](https://www.hackerrank.com/challenges/js10-bitwise)|Apply everything we've learned in this bitwise AND challenge.|[Javascript](js10-bitwise.js)|Easy [Day 6: JavaScript Dates](https://www.hackerrank.com/challenges/js10-date)|Write a JavaScript function that retrieves the day of the week from a given date.|[Javascript](js10-date.js)|Easy [Day 7: Regular Expressions I](https://www.hackerrank.com/challenges/js10-regexp-1)|Get started with Regular Expressions in JavaScript.|[Javascript](js10-regexp-1.js)|Easy [Day 7: Regular Expressions II](https://www.hackerrank.com/challenges/js10-regexp-2)|Write a JavaScript RegExp to match a name satisfying certain criteria.|[Javascript](js10-regexp-2.js)|Easy [Day 7: Regular Expressions III](https://www.hackerrank.com/challenges/js10-regexp-3)|Regex|[Javascript](js10-regexp-3.js)|Easy [Day 8: Create a Button](https://www.hackerrank.com/challenges/js10-create-a-button)|Create a button.|[HTML](js10-create-a-button.html)|Easy [Day 8: Buttons Container](https://www.hackerrank.com/challenges/js10-buttons-container)|Arrange buttons in a grid.|[HTML](js10-buttons-container.html)|Easy [Day 9: Binary Calculator](https://www.hackerrank.com/challenges/js10-binary-calculator)|Create a calculator for base 2 arithmetic.|[HTML](js10-binary-calculator.html)|Medium
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
<!-- Enter your HTML code here --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Binary Calculator</title> <link rel="stylesheet" href="css/binaryCalculator.css" type="text/css"> </head> <body> <div id="res"></div> <div id="btns" class="btns"> <button id="btn0" class="dgt">0</button> <button id="btn1" class="dgt">1</button> <button id="btnClr" class="ctl">C</button> <button id="btnEql" class="ctl">=</button> <button id="btnSum" class="op">+</button> <button id="btnSub" class="op">-</button> <button id="btnMul" class="op">*</button> <button id="btnDiv" class="op">/</button> </div> <script src="js/binaryCalculator.js" type="text/javascript"></script> </body> </html>
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
body { width: 33%; } #res { background-color: lightgray; border: solid; height: 48px; font-size: 20px; } .btns button { width: 25%; height: 36px; font-size: 18px; margin: 0px; float: left; } .dgt { background-color: lightgreen; color: brown; } .ctl { background-color: darkgreen; color: white; } .op { background-color: black; color: red; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
btnClr.onclick = function() { res.innerHTML = ""; } btnEql.onclick = function() { let s = res.innerHTML; s = Math.floor(eval(s.replace(/([01]+)/g, '0b$1'))).toString(2); res.innerHTML = s; } btn0.onclick = function() { res.innerHTML += "0"; } btn1.onclick = function() { res.innerHTML += "1"; } btnSum.onclick = function() { res.innerHTML += "+"; } btnSub.onclick = function() { res.innerHTML += "-"; } btnMul.onclick = function() { res.innerHTML += "*"; } btnDiv.onclick = function() { res.innerHTML += "/"; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="css/button.css" type="text/css"> </head> <body> <button id="btn">0</button> <script src="js/button.js" type="text/javascript"></script> </body> </html>
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
#btn { width: 96px; height: 48px; font-size: 24px; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
var btn = document.getElementById('btn'); btn.innerHTML = 0; btn.onclick = function() { ++btn.innerHTML; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
<!-- Enter your HTML code here --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Buttons Grid</title> <link rel="stylesheet" href="css/buttonsGrid.css" type="text/css"> </head> <body> <div id="btns"> <p> <button id="btn1">1</button> <button id="btn2">2</button> <button id="btn3">3</button> </p> <p> <button id="btn4">4</button> <button id="btn5">5</button> <button id="btn6">6</button> </p> <p> <button id="btn7">7</button> <button id="btn8">8</button> <button id="btn9">9</button> </p> </div> <script src="js/buttonsGrid.js" type="text/javascript"></script> </body> </html>
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
#btns { width: 75%; } button { width: 30%; height: 48px; font-size: 24px; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
var btn1 = document.getElementById('btn1'); var btn2 = document.getElementById('btn2'); var btn3 = document.getElementById('btn3'); var btn4 = document.getElementById('btn4'); var btn5 = document.getElementById('btn5'); var btn6 = document.getElementById('btn6'); var btn7 = document.getElementById('btn7'); var btn8 = document.getElementById('btn8'); var btn9 = document.getElementById('btn9'); btn5.onclick = function() { let tmp = btn1.innerHTML; btn1.innerHTML = btn4.innerHTML; btn4.innerHTML = btn7.innerHTML; btn7.innerHTML = btn8.innerHTML; btn8.innerHTML = btn9.innerHTML; btn9.innerHTML = btn6.innerHTML; btn6.innerHTML = btn3.innerHTML; btn3.innerHTML = btn2.innerHTML; btn2.innerHTML = tmp; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 10 Days of Statistics > Day 5: Normal Distribution I # Problems based on basic statistical distributions. # # https://www.hackerrank.com/challenges/s10-normal-distribution-1/problem # challenge id: 21229 # import math π = math.pi def N(x, µ, σ): """ Normal Distribution """ return math.exp(- (x - µ) ** 2 / (2 * σ * σ)) / (σ * math.sqrt(2 * π)) def Φ(x, µ, σ): """ Cumulative Probability """ return 1 / 2 * (1 + math.erf((x - µ) / σ / math.sqrt(2))) µ = 20 σ = 2 print("{:.3f}".format(Φ(19.5, µ, σ))) print("{:.3f}".format(Φ(22, µ, σ) - Φ(20, µ, σ)))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 10 Days of Statistics > Day 5: Poisson Distribution I # Basic problem on Poisson Distribution. # # https://www.hackerrank.com/challenges/s10-poisson-distribution-1/problem # challenge id: 21227 # import math def poisson(λ, k): return λ ** k * math.e ** (-λ) / math.factorial(k) λ = float(input()) k = int(input()) print("{:.3f}".format(poisson(λ, k)))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 10 Days of Statistics > Day 0: Weighted Mean # Compute the weighted mean. # # https://www.hackerrank.com/challenges/s10-weighted-mean/problem # challenge id: 21217 # n = int(input()) X = list(map(int, input().split())) W = list(map(int, input().split())) m = sum(x * w for x, w in zip(X, W)) / sum(W) print("{:.1f}".format(m))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 10 Days of Statistics > Day 6: The Central Limit Theorem II # Basic problems on the Central Limit Theorem. # # https://www.hackerrank.com/challenges/s10-the-central-limit-theorem-2/problem # challenge id: 21225 # import math def Φ(x, µ, σ): """ Cumulative Probability """ return 1 / 2 * (1 + math.erf((x - µ) / σ / math.sqrt(2))) tickets = int(input()) # 250 students = int(input()) # 100 µ = float(input()) # 2.4 mean σ = float(input()) # 2.0 standard deviation p = Φ(tickets, students * µ, math.sqrt(students) * σ) print("{:.4f}".format(p))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 10 Days of Statistics > Day 9: Multiple Linear Regression # Learn multiple linear regression # # https://www.hackerrank.com/challenges/s10-multiple-linear-regression/problem # challenge id: 21158 # from sklearn import linear_model import numpy as np # suppress a annoying warning on macOS import warnings warnings.filterwarnings(action="ignore", module="sklearn", message="^internal gelsd") m, n = map(int, input().split()) X = [] Y = [] for _ in range(n): f_y = np.array(input().split(), np.float) X.append(f_y[:-1]) Y.append(f_y[-1]) lm = linear_model.LinearRegression() lm.fit(X, Y) a = lm.intercept_ b = lm.coef_ for _ in range(int(input())): f = np.array(input().split(), np.float) y = a + np.sum(f * b) print(np.ceil(y * 100) / 100) # the rounding in the testcases it not good... # print('{:.2f}'.format(y)) # this is more accurate
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 10 Days of Statistics > Day 5: Poisson Distribution II # Basic problem on Poisson Distribution. # # https://www.hackerrank.com/challenges/s10-poisson-distribution-2/problem # challenge id: 21228 # import math def poisson(λ, k): return λ ** k * math.e ** (-λ) / math.factorial(k) def E(λ): return λ + λ ** 2 λ1, λ2 = map(float, input().split()) print("{:.3f}".format(160 + 40 * E(λ1))) print("{:.3f}".format(128 + 40 * E(λ2)))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 10 Days of Statistics > Day 7: Pearson Correlation Coefficient I # Computing Pearson correlation coefficient. # # https://www.hackerrank.com/challenges/s10-pearson-correlation-coefficient/problem # challenge id: 21178 # # Pearson: measure of the linear correlation between two variables X and Y def pearson(n, X, Y): mx = sum(X) / n # moyenne de la série X my = sum(Y) / n sx = 0 sy = 0 p = 0 for x, y in zip(X, Y): sx += (x - mx) ** 2 # calcule l'écart-type de X sy += (y - my) ** 2 # calcule l'écart-type de Y p += (x - mx) * (y - my) # calcule la covariance de (X,Y) sx = (sx / n) ** 0.5 sy = (sy / n) ** 0.5 p = p / (n * sx * sy) return p n = int(input()) X = list(map(float, input().split())) Y = list(map(float, input().split())) print('{:.3f}'.format(pearson(n, X, Y)))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 10 Days of Statistics > Day 4: Geometric Distribution I # Problems based on basic statistical distributions. # # https://www.hackerrank.com/challenges/s10-geometric-distribution-1/problem # challenge id: 21244 # def g(n, p): return p * (1 - p) ** (n - 1) ko, total = map(int, input().split()) n = int(input()) r = g(n, ko / total) print("%.3f" % r)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 10 Days of Statistics > Day 0: Mean, Median, and Mode # Compute the mean, median, mode, and standard deviation. # # https://www.hackerrank.com/challenges/s10-basic-statistics/problem # challenge id: 21180 # from itertools import groupby n = int(input()) x = list(map(int, input().split())) # la moyenne arithmétique m = sum(x) / len(x) print("{:.1f}".format(m)) # la valeur médiane x = sorted(x) if n % 2 == 1: m = x[n // 2] print(m) else: m = (x[n // 2 - 1] + x[n // 2]) / 2 print("{:.1f}".format(m)) # la classe modale # on trie les paires par longueur décroissante: la première sera la plus grande en valeur absolue m = sorted([-len(list(g)), int(k)] for k, g in groupby(x)) print(m[0][1])
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 10 Days of Statistics > Day 2: Basic Probability # Calculate the probability that two dice will have a maximum sum of 9. # # https://www.hackerrank.com/challenges/s10-mcq-1/problem # challenge id: 21607 # from fractions import Fraction n = 0 for i in range(1, 7): for j in range(1, 7): if i + j <= 9: n += 1 print(Fraction(n, 6 * 6))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 10 Days of Statistics > Day 3: Cards of the Same Suit # Find the probability that 2 cards drawn from a deck (without replacement) are of the same suit. # # https://www.hackerrank.com/challenges/s10-mcq-5/problem # challenge id: 21611 # 12 / 51
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 10 Days of Statistics > Day 7: Spearman's Rank Correlation Coefficient # Computing Spearman's rank correlation coefficient. # # https://www.hackerrank.com/challenges/s10-spearman-rank-correlation-coefficient/problem # challenge id: 21707 # def spearman(n, X, Y): """ calcul du coefficient de Spearman pour des échantillons avec des valeurs uniques """ def rank(X): r = [0] * len(X) xs = sorted((x, i) for i, x in enumerate(X)) for j, xi in enumerate(xs): r[xi[1]] = j + 1 return r # somme de la différence des ranks au carré r = sum((rx - ry) ** 2 for rx, ry in zip(rank(X), rank(Y))) r = 1 - 6 * r / n / (n ** 2 - 1) return r n = int(input()) X = list(map(float, input().split())) Y = list(map(float, input().split())) c = spearman(n, X, Y) print('{:.3f}'.format(c))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 10 Days of Statistics > Day 8: Least Square Regression Line # Find the line of best fit. # # https://www.hackerrank.com/challenges/s10-least-square-regression-line/problem # challenge id: 21177 # def pearson(n, X, Y): mx = sum(X) / n # moyenne de la série X my = sum(Y) / n sx = 0. sy = 0. p = 0. for x, y in zip(X, Y): sx += (x - mx) ** 2 # calcule l'écart-type de X sy += (y - my) ** 2 # calcule l'écart-type de Y p += (x - mx) * (y - my) # calcule la covariance de (X,Y) sx = (sx / n) ** 0.5 sy = (sy / n) ** 0.5 p = p / (n * sx * sy) b = p * sy / sx # Y = a + b X a = my - b * mx return p, a, b X, Y = [0] * 5, [0] * 5 for i in range(5): X[i], Y[i] = map(int, input().split()) _, a, b = pearson(5, X, Y) print("{:.3f}".format(a + b * 80))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
include(FindPythonInterp) add_hackerrank_py(s10-basic-statistics.py) add_hackerrank_py(s10-weighted-mean.py) add_hackerrank_py(s10-quartiles.py) add_hackerrank_py(s10-standard-deviation.py) add_hackerrank_py(s10-interquartile-range.py) add_hackerrank_py(s10-mcq-1.py) add_hackerrank_py(s10-mcq-2.py) add_hackerrank_py(s10-mcq-3.py) add_hackerrank_py(s10-binomial-distribution-1.py) add_hackerrank_py(s10-binomial-distribution-2.py) add_hackerrank_py(s10-geometric-distribution-1.py) add_hackerrank_py(s10-geometric-distribution-2.py) add_hackerrank_py(s10-poisson-distribution-1.py) add_hackerrank_py(s10-poisson-distribution-2.py) add_hackerrank_py(s10-normal-distribution-1.py) add_hackerrank_py(s10-normal-distribution-2.py) add_hackerrank_py(s10-the-central-limit-theorem-1.py) add_hackerrank_py(s10-the-central-limit-theorem-2.py) add_hackerrank_py(s10-the-central-limit-theorem-3.py) add_hackerrank_py(s10-pearson-correlation-coefficient.py) add_hackerrank_py(s10-spearman-rank-correlation-coefficient.py) add_hackerrank_py(s10-least-square-regression-line.py) # scikit-learn does not work with Python 3.7 if(PYTHON_VERSION_STRING VERSION_LESS 3.7) add_hackerrank_py(s10-multiple-linear-regression.py) endif()
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 10 Days of Statistics > Day 5: Normal Distribution II # Problems based on basic statistical distributions. # # https://www.hackerrank.com/challenges/s10-normal-distribution-2/problem # challenge id: 21230 # import math def N(x, µ, σ): """ Normal Distribution """ π = math.pi return math.exp(- (x - µ) ** 2 / (2 * σ * σ)) / (σ * math.sqrt(2 * π)) def Φ(x, µ, σ): """ Cumulative Probability """ return 1 / 2 * (1 + math.erf((x - µ) / σ / math.sqrt(2))) µ, σ = map(float, input().split()) q1 = float(input()) q2 = float(input()) # percentage of students having grade > q1 print("{:.2f}".format(100 - Φ(q1, µ, σ) * 100)) # percentage of students having grade ≥ q2 print("{:.2f}".format(100 - Φ(q2, µ, σ) * 100)) # percentage of students having grade < q2 print("{:.2f}".format(Φ(q2, µ, σ) * 100))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 10 Days of Statistics > Day 8: Pearson Correlation Coefficient II # Find the Pearson correlation coefficient # # https://www.hackerrank.com/challenges/s10-mcq-7/problem # challenge id: 21709 # # explication: # 3*x + 4*y + 8 = 0 ⟹ y = -3/4 * x - 2 ⟹ b = -3/4 = ρ σy/σx # 4*x + 3*y + 7 = 0 ⟹ x = -3/4 * y - 7/4 ⟹ b = -3/4 = ρ σx/σy # (-3/4)² = ρ² ⟹ ρ = ± 3/4 # b < 0 ⟹ ρ = - 3/4 -3 / 4
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 10 Days of Statistics > Day 1: Interquartile Range # Calculate the interquartile range. # # https://www.hackerrank.com/challenges/s10-interquartile-range/problem # challenge id: 21249 # def median(x): n = len(x) if n % 2 == 1: return x[n // 2] else: return (x[n // 2 - 1] + x[n // 2]) / 2 n = int(input()) X = list(map(int, input().split())) F = list(map(int, input().split())) S = [] for x, f in zip(X, F): S.extend([x] * f) S = sorted(S) n = len(S) if n % 2 == 1: Q1 = median(S[:(n // 2)]) Q3 = median(S[(n // 2) + 1:]) else: Q1 = median(S[:(n // 2)]) Q3 = median(S[(n // 2):]) print("{:.1f}".format(Q3 - Q1))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 10 Days of Statistics > Day 4: Binomial Distribution II # Problems based on basic statistical distributions. # # https://www.hackerrank.com/challenges/s10-binomial-distribution-2/problem # challenge id: 21232 # from math import factorial # b(x,n,p) = C(n,p) * p^x * (1-p)^(n-x) # x: number of successes # n: total number of trials # p: probability of success of 1 trial def b(n, x, p): return factorial(n) // factorial(n - x) // factorial(x) * (p ** x) * (1 - p) ** (n - x) p, n = map(int, input().split()) p = p / 100 # proba qu'un piston soit ko r = b(n, 0, p) + b(n, 1, p) + b(n, 2, p) # 0 ou 1 ou 2 rejets print("%.3f" % r) r = sum(b(n, i, p) for i in range(2, n + 1)) # 2 à 12 rejets print("%.3f" % r)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 10 Days of Statistics > Day 1: Standard Deviation # Compute the standard deviation # # https://www.hackerrank.com/challenges/s10-standard-deviation/problem # challenge id: 21237 # n = int(input()) x = list(map(int, input().split())) Σ = sum # moyenne (mean) µ = Σ(x) / n # écart-type (standard deviation) 𝜎 = (Σ((i - µ) ** 2 for i in x) / n) ** 0.5 print("{:.1f}".format(𝜎))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 10 Days of Statistics > Day 2: Compound Event Probability # # # https://www.hackerrank.com/challenges/s10-mcq-3/problem # challenge id: 21609 # from fractions import Fraction n, t = 0, 0 for i in range(1, 8): for j in range(1, 10): for k in range(1, 9): red, black = 0, 0 if i <= 4: red += 1 else: black += 1 if j <= 5: red += 1 else: black += 1 if k <= 4: red += 1 else: black += 1 if red == 2 and black == 1: n += 1 t += 1 print(Fraction(n, t))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 10 Days of Statistics > Day 3: Conditional Probability # Find the probability that both children are boys, given that one is a boy. # # https://www.hackerrank.com/challenges/s10-mcq-4/problem # challenge id: 21610 # 1 / 3
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 10 Days of Statistics > Day 6: The Central Limit Theorem I # Basic problems on the Central Limit Theorem. # # https://www.hackerrank.com/challenges/s10-the-central-limit-theorem-1/problem # challenge id: 21224 # import math def Φ(x, µ, σ): """ Cumulative Probability """ return 1 / 2 * (1 + math.erf((x - µ) / σ / math.sqrt(2))) capacity = float(input()) # 9800 maximum load n = int(input()) # 49 number of boxes µ = float(input()) # 205 mean σ = float(input()) # 15 standard deviation p = Φ(capacity, n * µ, math.sqrt(n) * σ) print("{:.4f}".format(p))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 10 Days of Statistics > Day 2: More Dice # Calculate the probability that two dice will roll two unique values having a sum of 6. # # https://www.hackerrank.com/challenges/s10-mcq-2/problem # challenge id: 21608 # from fractions import Fraction n = 0 for i in range(1, 7): for j in range(1, 7): if i + j == 6 and i != j: n += 1 print(Fraction(n, 6 * 6))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 10 Days of Statistics > Day 4: Geometric Distribution II # Problems based on basic statistical distributions. # # https://www.hackerrank.com/challenges/s10-geometric-distribution-2/problem # challenge id: 21245 # def g(n, p): return p * (1 - p) ** (n - 1) ko, total = map(int, input().split()) n = int(input()) r = sum(g(n, ko / total) for n in range(1, 6)) print("%.3f" % r)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 10 Days of Statistics > Day 4: Binomial Distribution I # Problems based on basic statistical distributions. # # https://www.hackerrank.com/challenges/s10-binomial-distribution-1/problem # challenge id: 21231 # from math import factorial # b(x,n,p) = C(n,p) * p^x * (1-p)^(n-x) # x: number of successes # n: total number of trials # p: probability of success of 1 trial def b(n, x, p): return factorial(n) // factorial(n - x) // factorial(x) * (p ** x) * (1 - p) ** (n - x) boys, girls = map(float, input().split()) p = boys / (boys + girls) r = b(6, 3, p) + b(6, 4, p) + b(6, 5, p) + b(6, 6, p) print("%.3f" % r)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 10 Days of Statistics > Day 6: The Central Limit Theorem III # Basic problems on the Central Limit Theorem. # # https://www.hackerrank.com/challenges/s10-the-central-limit-theorem-3/problem # challenge id: 21226 # import math n = int(input()) # 100 sample size µ = float(input()) # 500 mean σ = float(input()) # 80 standard deviation percent = float(input()) # 0.95 distribution percentage we want to cover z = float(input()) # 1.96 z-score : Φ(1.96) - Φ(-1.96) ≈ 95% e = z * σ / math.sqrt(n) print('{:2f}'.format(µ - e)) print('{:2f}'.format(µ + e))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
### [Tutorials](https://www.hackerrank.com/domains/tutorials) #### [10 Days of Statistics](https://www.hackerrank.com/domains/tutorials/10-days-of-statistics) Name | Preview | Code | Difficulty ---- | ------- | ---- | ---------- [Day 0: Mean, Median, and Mode](https://www.hackerrank.com/challenges/s10-basic-statistics)|Compute the mean, median, mode, and standard deviation.|[Python](s10-basic-statistics.py)|Easy [Day 0: Weighted Mean](https://www.hackerrank.com/challenges/s10-weighted-mean)|Compute the weighted mean.|[Python](s10-weighted-mean.py)|Easy [Day 1: Quartiles](https://www.hackerrank.com/challenges/s10-quartiles)|Calculate quartiles for an array of integers|[Python](s10-quartiles.py)|Easy [Day 1: Interquartile Range](https://www.hackerrank.com/challenges/s10-interquartile-range)|Calculate the interquartile range.|[Python](s10-interquartile-range.py)|Easy [Day 1: Standard Deviation](https://www.hackerrank.com/challenges/s10-standard-deviation)|Compute the standard deviation|[Python](s10-standard-deviation.py)|Easy [Day 2: Basic Probability](https://www.hackerrank.com/challenges/s10-mcq-1)|Calculate the probability that two dice will have a maximum sum of 9.|[Python](s10-mcq-1.py)|Easy [Day 2: More Dice](https://www.hackerrank.com/challenges/s10-mcq-2)|Calculate the probability that two dice will roll two unique values having a sum of 6.|[Python](s10-mcq-2.py)|Easy [Day 2: Compound Event Probability](https://www.hackerrank.com/challenges/s10-mcq-3)||[Python](s10-mcq-3.py)|Easy [Day 3: Conditional Probability](https://www.hackerrank.com/challenges/s10-mcq-4)|Find the probability that both children are boys, given that one is a boy.|[text](s10-mcq-4.txt)|Easy [Day 3: Cards of the Same Suit](https://www.hackerrank.com/challenges/s10-mcq-5)|Find the probability that 2 cards drawn from a deck (without replacement) are of the same suit.|[text](s10-mcq-5.txt)|Easy [Day 3: Drawing Marbles](https://www.hackerrank.com/challenges/s10-mcq-6)|Find the probability that the second marble drawn is blue.|[text](s10-mcq-6.txt)|Easy [Day 4: Binomial Distribution I](https://www.hackerrank.com/challenges/s10-binomial-distribution-1)|Problems based on basic statistical distributions.|[Python](s10-binomial-distribution-1.py)|Easy [Day 4: Binomial Distribution II](https://www.hackerrank.com/challenges/s10-binomial-distribution-2)|Problems based on basic statistical distributions.|[Python](s10-binomial-distribution-2.py)|Easy [Day 4: Geometric Distribution I](https://www.hackerrank.com/challenges/s10-geometric-distribution-1)|Problems based on basic statistical distributions.|[Python](s10-geometric-distribution-1.py)|Easy [Day 4: Geometric Distribution II](https://www.hackerrank.com/challenges/s10-geometric-distribution-2)|Problems based on basic statistical distributions.|[Python](s10-geometric-distribution-2.py)|Easy [Day 5: Poisson Distribution I](https://www.hackerrank.com/challenges/s10-poisson-distribution-1)|Basic problem on Poisson Distribution.|[Python](s10-poisson-distribution-1.py)|Easy [Day 5: Poisson Distribution II](https://www.hackerrank.com/challenges/s10-poisson-distribution-2)|Basic problem on Poisson Distribution.|[Python](s10-poisson-distribution-2.py)|Easy [Day 5: Normal Distribution I](https://www.hackerrank.com/challenges/s10-normal-distribution-1)|Problems based on basic statistical distributions.|[Python](s10-normal-distribution-1.py)|Easy [Day 5: Normal Distribution II](https://www.hackerrank.com/challenges/s10-normal-distribution-2)|Problems based on basic statistical distributions.|[Python](s10-normal-distribution-2.py)|Easy [Day 6: The Central Limit Theorem I](https://www.hackerrank.com/challenges/s10-the-central-limit-theorem-1)|Basic problems on the Central Limit Theorem.|[Python](s10-the-central-limit-theorem-1.py)|Easy [Day 6: The Central Limit Theorem II](https://www.hackerrank.com/challenges/s10-the-central-limit-theorem-2)|Basic problems on the Central Limit Theorem.|[Python](s10-the-central-limit-theorem-2.py)|Easy [Day 6: The Central Limit Theorem III](https://www.hackerrank.com/challenges/s10-the-central-limit-theorem-3)|Basic problems on the Central Limit Theorem.|[Python](s10-the-central-limit-theorem-3.py)|Easy [Day 7: Pearson Correlation Coefficient I](https://www.hackerrank.com/challenges/s10-pearson-correlation-coefficient)|Computing Pearson correlation coefficient.|[Python](s10-pearson-correlation-coefficient.py)|Easy [Day 7: Spearman's Rank Correlation Coefficient](https://www.hackerrank.com/challenges/s10-spearman-rank-correlation-coefficient)|Computing Spearman's rank correlation coefficient.|[Python](s10-spearman-rank-correlation-coefficient.py)|Easy [Day 8: Least Square Regression Line](https://www.hackerrank.com/challenges/s10-least-square-regression-line)|Find the line of best fit.|[Python](s10-least-square-regression-line.py)|Easy [Day 8: Pearson Correlation Coefficient II](https://www.hackerrank.com/challenges/s10-mcq-7)|Find the Pearson correlation coefficient|[text](s10-mcq-7.txt)|Medium [Day 9: Multiple Linear Regression](https://www.hackerrank.com/challenges/s10-multiple-linear-regression)|Learn multiple linear regression|[Python](s10-multiple-linear-regression.py)|Medium
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 10 Days of Statistics > Day 1: Quartiles # Calculate quartiles for an array of integers # # https://www.hackerrank.com/challenges/s10-quartiles/problem # challenge id: 21248 # def median(x): n = len(x) if n % 2 == 1: return x[n // 2] else: return (x[n // 2 - 1] + x[n // 2]) // 2 n = int(input()) x = list(map(int, input().split())) x = sorted(x) Q2 = median(x) if n % 2 == 1: Q1 = median(x[0:(n // 2)]) Q3 = median(x[(n // 2) + 1:]) else: Q1 = median(x[0:(n // 2)]) Q3 = median(x[(n // 2):]) print(Q1) print(Q2) print(Q3)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 10 Days of Statistics > Day 3: Drawing Marbles # Find the probability that the second marble drawn is blue. # # https://www.hackerrank.com/challenges/s10-mcq-6/problem # challenge id: 21612 # 2 / 3
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 30 Days of Code > Day 13: Abstract Classes # Build on what you've already learned about Inheritance with this Abstract Classes challenge # # https://www.hackerrank.com/challenges/30-abstract-classes/problem # from abc import ABCMeta, abstractmethod class Book(object, metaclass=ABCMeta): def __init__(self,title,author): self.title=title self.author=author @abstractmethod def display(): pass # (skeliton_head) ---------------------------------------------------------------------- class MyBook(Book): def __init__(self, title, author, price): super().__init__(title, author) self.price = price def display(self): print("Title:", self.title) print("Author:", self.author) print("Price:", self.price) # (skeliton_tail) ---------------------------------------------------------------------- title=input() author=input() price=int(input()) new_novel=MyBook(title,author,price) new_novel.display()
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tutorials > 30 Days of Code > Day 12: Inheritance // Learn about inheritance. // // https://www.hackerrank.com/challenges/30-inheritance/problem // #include <iostream> #include <vector> using namespace std; class Person{ protected: string firstName; string lastName; int id; public: Person(string firstName, string lastName, int identification){ this->firstName = firstName; this->lastName = lastName; this->id = identification; } void printPerson(){ cout<< "Name: "<< lastName << ", "<< firstName <<"\nID: "<< id << "\n"; } }; // (skeliton_head) ---------------------------------------------------------------------- #include <bits/stdc++.h> class Student : public Person{ private: vector<int> testScores; public: /* * Class Constructor * * Parameters: * firstName - A string denoting the Person's first name. * lastName - A string denoting the Person's last name. * id - An integer denoting the Person's ID number. * scores - An array of integers denoting the Person's test scores. */ // Write your constructor here Student(const string& firstName, const string& lastName, int identification, const vector<int>& scores) : Person(firstName, lastName, identification), testScores(scores) {} /* * Function Name: calculate * Return: A character denoting the grade. */ // Write your function here char calculate() const { int sum = std::accumulate(testScores.begin(), testScores.end(), 0); float avg = sum / testScores.size(); if (avg >= 90) return 'O'; if (avg >= 80) return 'E'; if (avg >= 70) return 'A'; if (avg >= 55) return 'P'; if (avg >= 40) return 'D'; return 'T'; } }; // (skeliton_tail) ---------------------------------------------------------------------- int main() { string firstName; string lastName; int id; int numScores; cin >> firstName >> lastName >> id >> numScores; vector<int> scores; for(int i = 0; i < numScores; i++){ int tmpScore; cin >> tmpScore; scores.push_back(tmpScore); } Student* s = new Student(firstName, lastName, id, scores); s->printPerson(); cout << "Grade: " << s->calculate() << "\n"; return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Day 0: Hello, World. # Tutorials > 30 Days of Code # Practice reading from stdin and printing to stdout. # # https://www.hackerrank.com/challenges/30-hello-world/problem # # Read a full line of input from stdin and save it to our dynamically typed variable, input_string. input_string = input() # Print a string literal saying "Hello, World." to stdout. print('Hello, World.') # TODO: Write a line of code here that prints the contents of input_string to stdout. print(input_string)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tutorials > 30 Days of Code > Day 21: Generics // Welcome to Day 21! Review generics in this challenge! // // https://www.hackerrank.com/challenges/30-generics/problem // #include <iostream> #include <vector> #include <string> using namespace std; // (skeliton_head) ---------------------------------------------------------------------- /** * Name: printArray * Print each element of the generic vector on a new line. Do not return anything. * @param A generic vector **/ template<typename T> void printArray(const vector<T>& a) { for (auto i : a) cout << i << endl; } // (skeliton_tail) ---------------------------------------------------------------------- int main() { int n; cin >> n; vector<int> int_vector(n); for (int i = 0; i < n; i++) { int value; cin >> value; int_vector[i] = value; } cin >> n; vector<string> string_vector(n); for (int i = 0; i < n; i++) { string value; cin >> value; string_vector[i] = value; } printArray<int>(int_vector); printArray<string>(string_vector); return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 30 Days of Code > Day 14: Scope # Learn about the scope of an identifier. # # https://www.hackerrank.com/challenges/30-scope/problem # class Difference: def __init__(self, a): self.__elements = a # (skeliton_head) ---------------------------------------------------------------------- def __init__(self, a): self.a = a def computeDifference(self): self.maximumDifference = max(self.a) - min(self.a) # (skeliton_tail) ---------------------------------------------------------------------- # End of Difference class _ = input() a = [int(e) for e in input().split(' ')] d = Difference(a) d.computeDifference() print(d.maximumDifference)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tutorials > 30 Days of Code > Day 14: Scope // Learn about the scope of an identifier. // // https://www.hackerrank.com/challenges/30-scope/problem // #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; class Difference { private: vector<int> elements; public: int maximumDifference; // (skeliton_head) ---------------------------------------------------------------------- Difference(const vector<int>& a) { maximumDifference = *std::max_element(a.begin(), a.end()) - *std::min_element(a.begin(), a.end()); } void computeDifference() const {} // (skeliton_tail) ---------------------------------------------------------------------- }; // End of Difference class int main() { int N; cin >> N; vector<int> a; for (int i = 0; i < N; i++) { int e; cin >> e; a.push_back(e); } Difference d(a); d.computeDifference(); cout << d.maximumDifference; return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tutorials > 30 Days of Code > Day 15: Linked List // Complete the body of a function that adds a new node to the tail of a Linked List. // // https://www.hackerrank.com/challenges/30-linked-list/problem // #include <iostream> #include <cstddef> using namespace std; class Node { public: int data; Node *next; Node(int d){ data=d; next=NULL; } }; class Solution{ public: // (skeliton_head) ---------------------------------------------------------------------- Node* insert(Node *head,int data) { //Complete this method if (head == NULL) { return new Node(data); } Node *node = head; while (node->next) { node = node->next; } node->next = new Node(data); return head; } // (skeliton_tail) ---------------------------------------------------------------------- void display(Node *head) { Node *start=head; while(start) { cout<<start->data<<" "; start=start->next; } } }; int main() { Node* head=NULL; Solution mylist; int T,data; cin>>T; while(T-->0){ cin>>data; head=mylist.insert(head,data); } mylist.display(head); }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 30 Days of Code > Day 27: Testing # Welcome to Day 27! Review testing in this challenge! # # https://www.hackerrank.com/challenges/30-testing/problem # from random import randint print(5) # YES (cancelled, il faut au plus k-1 nombres <= 0) def yes(): n = randint(50, 200) k = randint(10, n - 5) print(n, k) A = [0] for i in range(k - 2): A.append(randint(-1000, -1)) while len(A) < n: A.append(randint(1, 1000)) print(' '.join(map(str, A))) # NO (il faut au moins k nombres <= 0) def no(): n = randint(50, 200) k = randint(10, n - 5) print(n, k) A = [0] for i in range(k + 2): A.append(randint(-1000, -1)) while len(A) < n: A.append(randint(1, 1000)) print(' '.join(map(str, A))) yes() no() yes() no() yes()
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tutorials > 30 Days of Code > Day 24: More Linked Lists // Welcome to Day 24! Review everything we've learned so far and learn more about Linked Lists in this challenge. // // https://www.hackerrank.com/challenges/30-linked-list-deletion/problem // #include <cstddef> #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; class Node { public: int data; Node *next; Node(int d){ data=d; next=NULL; } }; class Solution{ public: // (skeliton_head) ---------------------------------------------------------------------- Node* removeDuplicates(Node *head) { //Write your code here if (head == nullptr) return head; Node *node = head; while (node->next != nullptr) { if (node->data == node->next->data) { Node *old = node->next; node->next = node->next->next; delete old; } else { node = node->next; } } return head; } // (skeliton_tail) ---------------------------------------------------------------------- Node* insert(Node *head,int data) { Node* p=new Node(data); if(head==NULL){ head=p; } else if(head->next==NULL){ head->next=p; } else{ Node *start=head; while(start->next!=NULL){ start=start->next; } start->next=p; } return head; } void display(Node *head) { Node *start=head; while(start) { cout<<start->data<<" "; start=start->next; } } }; int main() { Node* head=NULL; Solution mylist; int T,data; cin>>T; while(T-->0){ cin>>data; head=mylist.insert(head,data); } head=mylist.removeDuplicates(head); mylist.display(head); }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Day 4: Class vs. Instance # Learn the difference between class variables and instance variables. # # https://www.hackerrank.com/challenges/30-class-vs-instance/problem # class Person: def __init__(self,initialAge): # Add some more code to run some checks on initialAge if initialAge < 0: print("Age is not valid, setting age to 0.") initialAge = 0 self.age = initialAge def amIOld(self): # Do some computations in here and print out the correct statement to the console if self.age < 13: print("You are young.") elif self.age < 18: print("You are a teenager.") else: print("You are old.") def yearPasses(self): # Increment the age of the person in here self.age += 1 # (skeliton_tail) ---------------------------------------------------------------------- t = int(input()) for i in range(0, t): age = int(input()) p = Person(age) p.amIOld() for j in range(0, 3): p.yearPasses() p.amIOld() print("")
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 30 Days of Code > Day 23: BST Level-Order Traversal # Implement a breadth-first search! # # https://www.hackerrank.com/challenges/30-binary-trees/problem # import sys class Node: def __init__(self,data): self.right=self.left=None self.data = data class Solution: def insert(self,root,data): if root==None: return Node(data) else: if data<=root.data: cur=self.insert(root.left,data) root.left=cur else: cur=self.insert(root.right,data) root.right=cur return root # (skeliton_head) ---------------------------------------------------------------------- def levelOrder(self,root): queue = [] result = [] queue.append(root) while queue: n = queue.pop(0) if n: result.append(n.data) queue.append(n.left) queue.append(n.right) print(*result) # (skeliton_tail) ---------------------------------------------------------------------- T=int(input()) myTree=Solution() root=None for i in range(T): data=int(input()) root=myTree.insert(root,data) myTree.levelOrder(root)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Day 6: Let's Review // Characters and Strings // // https://www.hackerrank.com/challenges/30-review-loop/problem // #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { int t; cin >> t; while (t--) { string s; cin >> s; for (size_t i = 0; i < s.length(); ++i) if (i % 2 == 0) cout << s[i]; cout << ' '; for (size_t i = 0; i < s.length(); ++i) if (i % 2 == 1) cout << s[i]; cout << endl; } return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tutorials > 30 Days of Code > Day 29: Bitwise AND // Apply everything we've learned in this bitwise AND challenge. // // https://www.hackerrank.com/challenges/30-bitwise-and/problem // #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int t; cin >> t; while (t--) { int n, k; cin >> n >> k; int max = 0; for (int i = 2; i < n; ++i) { for (int j = i + 1; j <= n; ++j) { int ij = i & j; if (ij < k && ij > max) max = ij; } } cout << max << endl; } return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Day 0: Hello, World. // Practice reading from stdin and printing to stdout. // // https://www.hackerrank.com/challenges/30-hello-world/problem // #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> // (skeliton_head) ---------------------------------------------------------------------- int main() { // Declare a variable named 'input_string' to hold our input. char input_string[105]; // Read a full line of input from stdin and save it to our variable, input_string. scanf("%[^\n]", input_string); // Print a string literal saying "Hello, World." to stdout using printf. printf("Hello, World.\n"); // TODO: Write a line of code here that prints the contents of input_string to stdout. printf("%s\n", input_string); return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 30 Days of Code > Day 22: Binary Search Trees # Given a binary tree, print its height. # # https://www.hackerrank.com/challenges/30-binary-search-trees/problem # class Node: def __init__(self,data): self.right=self.left=None self.data = data class Solution: def insert(self,root,data): if root==None: return Node(data) else: if data<=root.data: cur=self.insert(root.left,data) root.left=cur else: cur=self.insert(root.right,data) root.right=cur return root # (skeliton_head) ---------------------------------------------------------------------- def getHeight(self,root,height=0): #Write your code here h = height if root.left is not None: h = max(h, self.getHeight(root.left, height + 1)) if root.right is not None: h = max(h, self.getHeight(root.right, height + 1)) return h # (skeliton_tail) ---------------------------------------------------------------------- T=int(input()) myTree=Solution() root=None for i in range(T): data=int(input()) root=myTree.insert(root,data) height=myTree.getHeight(root) print(height)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 30 Days of Code > Day 16: Exceptions - String to Integer # Can you determine if a string can be converted to an integer? # # https://www.hackerrank.com/challenges/30-exceptions-string-to-integer/problem # S = input().strip() try: print(int(S)) except ValueError: print("Bad String")
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tutorials > 30 Days of Code > Day 26: Nested Logic // Test your understanding of layered logic by calculating a library fine! // // https://www.hackerrank.com/challenges/30-nested-logic/problem // #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { int d1, m1, y1, d2, m2, y2; cin >> d1 >> m1 >> y1; cin >> d2 >> m2 >> y2; int fine = 0; if (y1 > y2) fine = 10000; // plus d'un an de retard else if (y1 == y2) { if (m1 > m2) { fine = (m1 - m2) * 500; // plus d'un mois de retard } else if (m1 == m2 && d1 > d2) { fine = (d1 - d2) * 15; // retard dans le même mois } } cout << fine << endl; return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 30 Days of Code > Day 15: Linked List # Complete the body of a function that adds a new node to the tail of a Linked List. # # https://www.hackerrank.com/challenges/30-linked-list/problem # class Node: def __init__(self,data): self.data = data self.next = None class Solution: def display(self,head): current = head while current: print(current.data,end=' ') current = current.next # (skeliton_head) ---------------------------------------------------------------------- def insert(self,head,data): #Complete this method if head is None: return Node(data) node = head while node.next is not None: node = node.next node.next = Node(data) return head # (skeliton_tail) ---------------------------------------------------------------------- mylist= Solution() T=int(input()) head=None for i in range(T): data=int(input()) head=mylist.insert(head,data) mylist.display(head);
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tutorials > 30 Days of Code > Day 13: Abstract Classes // Build on what you've already learned about Inheritance with this Abstract Classes challenge // // https://www.hackerrank.com/challenges/30-abstract-classes/problem // #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <string> using namespace std; class Book{ protected: string title; string author; public: Book(string t,string a){ title=t; author=a; } virtual void display()=0; }; // (skeliton_head) ---------------------------------------------------------------------- class MyBook : public Book { int price; public: // Class Constructor // // Parameters: // title - The book's title. // author - The book's author. // price - The book's price. // MyBook(const string& t, const string& a, int p) : Book(t, a), price(p) { } // Function Name: display // Print the title, author, and price in the specified format. // virtual void display() override { cout << "Title: " << this->Book::title << endl; cout << "Author: " << this->Book::author << endl; cout << "Price: " << price << endl; } }; // (skeliton_tail) ---------------------------------------------------------------------- int main() { string title,author; int price; getline(cin,title); getline(cin,author); cin>>price; MyBook novel(title,author,price); novel.display(); return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Day 7: Arrays # Getting started with Arrays. # # https://www.hackerrank.com/challenges/30-arrays/problem # input() print(" ".join(map(str, reversed(list(map(int, input().split()))))))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Day 2: Operators // Start using arithmetic operators. // // https://www.hackerrank.com/challenges/30-operators/problem // #include <bits/stdc++.h> using namespace std; int main() { double meal_cost; cin >> meal_cost; int tip_percent; cin >> tip_percent; int tax_percent; cin >> tax_percent; cout << "The total meal cost is " << round(meal_cost * (1 + tip_percent / 100. + tax_percent / 100.)) << " dollars." << endl; return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Day 3: Intro to Conditional Statements // Get started with conditional statements. // // https://www.hackerrank.com/challenges/30-conditional-statements/problem // #include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; if (n % 2 == 1 or (n >= 6 and n <= 20)) cout << "Weird" << endl; else cout << "Not Weird" << endl; return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 30 Days of Code > Day 25: Running Time and Complexity # Determine if a number is prime in optimal time! # # https://www.hackerrank.com/challenges/30-running-time-and-complexity/problem # def est_premier(n): """ teste si le nombre est premier """ if n <= 1: return False elif n == 2: return True elif n % 2 == 0: return False else: i = 3 while i * i <= n: if n % i == 0: return False i = i + 2 return True for _ in range(int(input())): print("Prime" if est_premier(int(input())) else "Not prime")
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
add_hackerrank(30-arrays 30-arrays.cpp) add_hackerrank(30-conditional-statements 30-conditional-statements.cpp) add_hackerrank(30-data-types 30-data-types.cpp) add_hackerrank(30-hello-world 30-hello-world.c) add_hackerrank(30-operators 30-operators.cpp) add_hackerrank(30-review-loop 30-review-loop.cpp) add_hackerrank_py(30-arrays.py) add_hackerrank_py(30-class-vs-instance.py) add_hackerrank_py(30-data-types.py) add_hackerrank_py(30-dictionaries-and-maps.py) add_hackerrank_py(30-hello-world.py) add_hackerrank_py(30-loops.py) add_hackerrank_py(30-operators.py) add_hackerrank_py(30-review-loop.py) add_hackerrank_py(30-binary-numbers.py) add_hackerrank(30-binary-numbers 30-binary-numbers.cpp) add_hackerrank_py(30-2d-arrays.py) add_hackerrank(30-2d-arrays 30-2d-arrays.cpp) add_hackerrank(30-inheritance 30-inheritance.cpp) add_hackerrank(30-generics 30-generics.cpp) add_hackerrank(30-bitwise-and 30-bitwise-and.cpp) add_hackerrank_py(30-scope.py) add_hackerrank(30-scope 30-scope.cpp) add_hackerrank_py(30-abstract-classes.py) add_hackerrank(30-abstract-classes 30-abstract-classes.cpp) add_hackerrank_py(30-linked-list.py) add_hackerrank(30-linked-list 30-linked-list.cpp) add_hackerrank_py(30-exceptions-string-to-integer.py) add_hackerrank(30-exceptions-string-to-integer 30-exceptions-string-to-integer.cpp) add_hackerrank(30-more-exceptions 30-more-exceptions.cpp) add_hackerrank_py(30-queues-stacks.py) add_hackerrank(30-running-time-and-complexity 30-running-time-and-complexity.cpp) add_hackerrank_py(30-running-time-and-complexity.py) add_hackerrank_py(30-binary-search-trees.py) add_hackerrank(30-interfaces 30-interfaces.cpp) add_hackerrank_py(30-binary-trees.py) add_hackerrank(30-binary-trees 30-binary-trees.cpp) add_hackerrank(30-sorting 30-sorting.cpp) add_hackerrank(30-linked-list-deletion 30-linked-list-deletion.cpp) add_hackerrank(30-nested-logic 30-nested-logic.cpp) add_hackerrank_py(30-regex-patterns.py) dirty_cpp(30-sorting) dirty_cpp(30-arrays) dirty_cpp(30-2d-arrays) dirty_cpp(30-generics) dirty_cpp(30-inheritance)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Day 8: Dictionaries and Maps # Mapping Keys to Values using a Map or Dictionary. # # https://www.hackerrank.com/challenges/30-dictionaries-and-maps/problem # n = int(input()) d = {} for _ in range(n): k, v = input().split() d[k] = v for _ in range(n): k = input() if k in d: print("{}={}".format(k, d[k])) else: print("Not found")
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 30 Days of Code > Day 10: Binary Numbers # Find the maximum number of consecutive 1's in the base-2 representation of a base-10 number. # # https://www.hackerrank.com/challenges/30-binary-numbers/problem # n = int(input()) nb = 0 result = 0 while n != 0: n, r = divmod(n, 2) if r == 1: nb += 1 if nb > result: result = nb else: nb = 0 print(result)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 30 Days of Code > Day 9: Recursion # Use recursion to compute the factorial of number. # # https://www.hackerrank.com/challenges/30-recursion/problem # def factorial(n): if n < 2: return 1 return n * factorial(n - 1) if __name__ == "__main__": n = int(input().strip()) result = factorial(n) print(result)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 30 Days of Code > Day 11: 2D Arrays # Find the maximum sum of any hourglass in a 2D-Array. # # https://www.hackerrank.com/challenges/30-2d-arrays/problem # def array2D(arr): resulat = -100 for i in range(0, 4): for j in range(0, 4): s = sum(arr[i][j:j + 3]) s += arr[i + 1][j + 1] s += sum(arr[i + 2][j:j + 3]) if s > resulat: resulat = s return resulat if __name__ == '__main__': arr = [] for _ in range(6): arr.append(list(map(int, input().split()))) result = array2D(arr) print(result)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Day 1: Data Types # Get started with data types. # # https://www.hackerrank.com/challenges/30-data-types/problem # i = 4 d = 4.0 s = 'HackerRank ' # (skeliton_head) ---------------------------------------------------------------------- # Declare second integer, double, and String variables. # Read and save an integer, double, and String to your variables. i2 = int(input()) d2 = float(input()) s2 = input() # Print the sum of both integer variables on a new line. print(i + i2) # Print the sum of the double variables on a new line. print(d + d2) # Concatenate and print the String variables on a new line # The 's' variable above should be printed first. print(s + s2)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tutorials > 30 Days of Code > Day 17: More Exceptions // Throw an exception when user sends wrong parameters to a method. // // https://www.hackerrank.com/challenges/30-more-exceptions/problem // #include <cmath> #include <iostream> #include <exception> #include <stdexcept> using namespace std; // (skeliton_head) ---------------------------------------------------------------------- //Write your code here class Calculator { public: int power(int n, int p) { if (n < 0 || p < 0) throw invalid_argument("n and p should be non-negative"); return (int) pow(n, p); } }; // (skeliton_tail) ---------------------------------------------------------------------- int main() { Calculator myCalculator=Calculator(); int T,n,p; cin>>T; while(T-->0){ if(scanf("%d %d",&n,&p)==2){ try{ int ans=myCalculator.power(n,p); cout<<ans<<endl; } catch(exception& e){ cout<<e.what()<<endl; } } } }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Day 1: Data Types // Get started with data types. // // https://www.hackerrank.com/challenges/30-data-types/problem // #include <iostream> #include <iomanip> #include <limits> using namespace std; int main() { int i = 4; double d = 4.0; string s = "HackerRank "; // (skeliton_head) ---------------------------------------------------------------------- // Declare second integer, double, and String variables. int i2; double d2; string s2; // Read and save an integer, double, and String to your variables. cin >> i2 >> d2; getline(cin, s2); getline(cin, s2); // Print the sum of both integer variables on a new line. cout << i + i2 << endl; // Print the sum of the double variables on a new line. cout << fixed << setprecision(1) << d + d2 << endl; // Concatenate and print the String variables on a new line // The 's' variable above should be printed first. cout << s << s2 << endl; // (skeliton_tail) ---------------------------------------------------------------------- return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Day 7: Arrays // Getting started with Arrays. // // https://www.hackerrank.com/challenges/30-arrays/problem // #include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; vector<int> arr(n); for(int arr_i = 0;arr_i < n;arr_i++) { cin >> arr[arr_i]; } for(int arr_i = n;arr_i > 0;) { cout << arr[--arr_i] << " "; } cout << endl; return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tutorials > 30 Days of Code > Day 18: Queues and Stacks # Use stacks and queues to determine if a string is a palindrome. # # https://www.hackerrank.com/challenges/30-queues-stacks/problem # import sys # (skeliton_head) ---------------------------------------------------------------------- class Solution: def __init__(self): self.queue = [] self.stack = [] def pushCharacter(self, ch): self.stack.append(ch) def popCharacter(self): return self.stack.pop() def enqueueCharacter(self, ch): self.queue.append(ch) def dequeueCharacter(self): return self.queue.pop(0) # (skeliton_tail) ---------------------------------------------------------------------- # read the string s s=input() #Create the Solution class object obj=Solution() l=len(s) # push/enqueue all the characters of string s to stack for i in range(l): obj.pushCharacter(s[i]) obj.enqueueCharacter(s[i]) isPalindrome=True ''' pop the top character from stack dequeue the first character from queue compare both the characters ''' for i in range(l // 2): if obj.popCharacter()!=obj.dequeueCharacter(): isPalindrome=False break #finally print whether string s is palindrome or not. if isPalindrome: print("The word, "+s+", is a palindrome.") else: print("The word, "+s+", is not a palindrome.")
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }