prefix
stringlengths 0
918k
| middle
stringlengths 0
812k
| suffix
stringlengths 0
962k
|
---|---|---|
//Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// >>> double_the_difference([1, 3, 2, 0])
// 10
// >>> double_the_difference([-1, -2, 0])
// 0
// >>> double_the_difference([9, -2])
// 81
// >>> double_the_difference([0])
// 0
// If the input array is empty, return 0.
function double_the_difference(lst){
sum = 0; | for (var i = 0; i < lst.length; i++){ | if(lst[i] % 2 == 1 && lst[i] > 0){
sum += lst[i] ** 2;
}
}
return sum;
}
|
import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Given a string s and a natural number n, you have been tasked to implement
// a function that returns an array array list of all words from string s that contain exactly
// n consonants, in order these words appear in the string s.
// If the string s is empty then the function should return an empty array list.
// Note: you may assume the input string contains only letters and spaces.
// Examples:
// >>> selectWords(("Mary had a little lamb"), (4l))
// (new ArrayList<String>(Arrays.asList((String)"little")))
// >>> selectWords(("Mary had a little lamb"), (3l))
// (new ArrayList<String>(Arrays.asList((String)"Mary", (String)"lamb")))
// >>> selectWords(("simple white space"), (2l))
// (new ArrayList<String>(Arrays.asList()))
// >>> selectWords(("Hello world"), (4l))
// (new ArrayList<String>(Arrays.asList((String)"world")))
// >>> selectWords(("Uncle sam"), (3l))
// (new ArrayList<String>(Arrays.asList((String)"Uncle")))
public static ArrayList<String> selectWords(String s, long n) {
ArrayList<String> ret = new ArrayList<String>();
String[] words = s.split(" ");
for (String word : words) {
String wordInLowerCase = word.toLowerCase();
long consonants = 0l;
for (char c : wordInLowerCase.toCharArray()) {
switch (c) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
break;
default:
consonants++;
break;
}
}
if (consonants == n) {
ret.add(word); | } | }
return ret;
}
} |
from typing import List, Optional
def prod_signs(arr: List[int]) -> Optional[int]:
"""
You are given an array arr of integers and you need to return
sum of magnitudes of integers multiplied by product of all signs
of each number in the array, represented by 1, -1 or 0.
Note: return None for empty arr.
Example:
>>> prod_signs([1, 2, 2, -4])
9
>>> prod_signs([0, 1])
0
>>> prod_signs([])
None
"""
def product(lst: List[int]) -> int:
out = 1
for item in lst:
out *= item
return out
if len(arr) == 0:
return None
else:
sign_arr = []
for num in arr:
if num > 0: | sign_arr.append(1) | elif num < 0:
sign_arr.append(-1)
else:
sign_arr.append(0)
return sum(map(abs, arr)) * product(sign_arr) |
//Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// >>> closest_integer("10")
// 10
// >>> closest_integer("15.3")
// 15
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
function closest_integer(value){
value = parseFloat(value);
if(value > 0){
if(value - Math.floor(value) < 0.5){
return Math.floor(value);
}else{
return Math.ceil(value);
}
}else{
if(value - Math.floor(value) > -0.5){
return Math.floor(value);
}else{
return Math.ceil(value); | } | }
}
|
import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Write a function that takes an array array list of numbers as input and returns
// the number of elements in the array array list that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// >>> specialFilter((new ArrayList<Long>(Arrays.asList((long)15l, (long)-73l, (long)14l, (long)-15l))))
// (1l)
// >>> specialFilter((new ArrayList<Long>(Arrays.asList((long)33l, (long)-2l, (long)-3l, (long)45l, (long)21l, (long)109l))))
// (2l)
public static long specialFilter(ArrayList<Long> nums) {
class helper { | public long getFirstDigit(long n) { | long[] digits = getDigits(n);
return digits[0];
}
public long getLastDigit(long n) {
long[] digits = getDigits(n);
return digits[digits.length - 1];
}
public long[] getDigits(long n) {
ArrayList<Long> digits = new ArrayList<Long>();
while (n != 0) {
digits.add(n % 10);
n /= 10;
}
Collections.reverse(digits);
return digits.stream().mapToLong(i -> i).toArray();
}
}
helper h = new helper();
return nums.stream().filter(x -> x > 10).filter(x -> {
long firstDigit = h.getFirstDigit(x);
long lastDigit = h.getLastDigit(x);
return firstDigit % 2 != 0 && lastDigit % 2 != 0;
}).count();
}
} |
//Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return undefined if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// >>> compare_one(1, 2.5)
// 2.5
// >>> compare_one(1, "2,3")
// "2,3"
// >>> compare_one("5,1", "6")
// "6"
// >>> compare_one("1", 1)
// undefined
function compare_one(a, b){
if (typeof a === typeof b){
if (a > b) {
return a;
} else if (a < b) {
return b;
} else {
return undefined;
}
} | else if (typeof a === "string" && typeof b === "number"){ | if (a[0] > b){
return a;
} else if (a[0] < b){
return b;
} else {
return undefined;
}
}
else if (typeof a === "number" && typeof b === "string"){
if (a > b[0]){
return a;
} else if (a < b[0]){
return b;
} else {
return undefined;
}
}
}
|
import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Filter an input array list of strings only for ones that contain given substring
// >>> filterBySubstring((new ArrayList<String>(Arrays.asList())), ("a"))
// (new ArrayList<String>(Arrays.asList()))
// >>> filterBySubstring((new ArrayList<String>(Arrays.asList((String)"abc", (String)"bacd", (String)"cde", (String)"array"))), ("a"))
// (new ArrayList<String>(Arrays.asList((String)"abc", (String)"bacd", (String)"array")))
public static ArrayList<String> filterBySubstring(ArrayList<String> strings, String substring) {
return new ArrayList<String>(strings.stream().filter(s -> s.contains(substring)).collect(Collectors.toList())); | } | } |
//This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// >>> sort_third([1, 2, 3])
// [1, 2, 3]
// >>> sort_third([5, 6, 3, 4, 8, 9, 2])
// [2, 6, 3, 4, 8, 9, 5]
function sort_third(l){
let x=[];
let y=[];
let k=0;
for(let i=0;i<l.length;i++){
if(i%3==0){
y[k]=l[i];
k=k+1;
}
else{
x[i]=l[i];
}
}
y.sort();
k=0;
for(let i=0;i<l.length;i++){
if(i%3==0){
x[i]=y[k];
k=k+1;
} | } | return x;
} |
def get_max_triples(n: int) -> int:
"""
You are given a positive integer n. You have to create an integer array a of length n.
For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
and a[i] + a[j] + a[k] is a multiple of 3.
Example :
>>> get_max_triples(5)
1
Explanation:
a = [1, 3, 7, 13, 21]
The only valid triple is (1, 7, 13).
"""
a = [i * i - i + 1 for i in range(1, n + 1)]
i = 0
j = 1
k = 2
count = 0
while (i < n - 2):
while (j < n - 1):
while (k < n):
if (a[i] + a[j] + a[k]) % 3 == 0:
count += 1
k += 1
j += 1
k = j + 1 | i += 1 | j = i + 1
k = j + 1
return count
|
//For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// >>> flip_case("Hello")
// "hELLO"
function flip_case(string){
var result = "";
for(var i = 0; i < string.length; i++){
if(string[i] == string[i].toUpperCase()){
result += string[i].toLowerCase();
}else{
result += string[i].toUpperCase();
}
}
return result; | } | |
import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return array list of integers corresponding to how many beats does each
// not last.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// >>> parseMusic(("o o| .| o| o| .| .| .| .| o o"))
// (new ArrayList<Long>(Arrays.asList((long)4l, (long)2l, (long)1l, (long)2l, (long)2l, (long)1l, (long)1l, (long)1l, (long)1l, (long)4l, (long)4l)))
public static ArrayList<Long> parseMusic(String music_string) {
ArrayList<Long> res = new ArrayList<Long>();
char[] chars = music_string.toCharArray(); | for (int i = 0; i < chars.length; i++) { | if (chars[i] == 'o') {
if (i + 1 < chars.length && chars[i + 1] == '|') {
res.add((long)2l);
i += 1;
} else {
res.add((long)4l);
}
} else if (chars[i] == '.') {
if (i + 1 < chars.length && chars[i + 1] == '|') {
res.add((long)1l);
i += 1;
}
}
}
return res;
}
} |
from typing import List
def pluck(arr: List[int]) -> List[int]:
"""
"Given an array representing a branch of a tree that has non-negative integer nodes
your task is to pluck one of the nodes and return it.
The plucked node should be the node with the smallest even value.
If multiple nodes with the same smallest even value are found return the node that has smallest index.
The plucked node should be returned in a list, [ smalest_value, its index ],
If there are no even values or the given array is empty, return [].
Example 1:
>>> pluck([4, 2, 3])
[2, 1]
Explanation: 2 has the smallest even value, and 2 has the smallest index.
Example 2:
>>> pluck([1, 2, 3])
[2, 1]
Explanation: 2 has the smallest even value, and 2 has the smallest index.
Example 3:
>>> pluck([])
[]
Example 4:
>>> pluck([5, 0, 3, 0, 4, 2])
[0, 1]
Explanation: 0 is the smallest value, but there are two zeros,
so we will choose the first zero, which has the smallest index.
Constraints:
* 1 <= nodes.length <= 10000
* 0 <= node.value
"""
| if len(arr) == 0: | return []
evens = [e for e in arr if e % 2 == 0]
if len(evens) == 0:
return []
return [min(evens), arr.index(min(evens))]
|
from typing import List
def mean_absolute_deviation(numbers: List[float]) -> float:
""" For a given list of input numbers, calculate Mean Absolute Deviation
around the mean of this dataset.
Mean Absolute Deviation is the average absolute difference between each
element and a centerpoint (mean in this case):
MAD = average | x - x_mean |
>>> mean_absolute_deviation([1.0, 2.0, 3.0, 4.0])
1.0
"""
mean = sum(numbers) / len(numbers) | absolute_deviations = [abs(x - mean) for x in numbers] | return sum(absolute_deviations) / len(absolute_deviations)
print(mean_absolute_deviation([1.0, 2.0, 3.0, 4.0])) |
//Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// >>> separate_paren_groups("( ) (( )) (( )( ))")
// ["()", "(())", "(()())"]
function separate_paren_groups(paren_string){
var count = 0;
var group = '';
var groups = [];
for (var i = 0; i < paren_string.length; i++){
if (paren_string[i] === '('){
count++;
group += paren_string[i];
} else if (paren_string[i] === ')'){
count--;
group += paren_string[i];
}
if (count === 0 && group){
groups.push(group);
group = '';
} | } | return groups;
}
|
//Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return array of integers corresponding to how many beats does each
// not last.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// >>> parse_music("o o| .| o| o| .| .| .| .| o o")
// [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
function parse_music(music_string){
let songs = music_string.split(' ');
let song = [];
songs.forEach(s => {
if(s === 'o'){ | song.push(4); | }else if(s === 'o|'){
song.push(2);
}else if(s === '.|'){
song.push(1);
}
});
return song;
}
|
//Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// >>> rescale_to_unit([1.0, 2.0, 3.0, 4.0, 5.0])
// [0.0, 0.25, 0.5, 0.75, 1.0]
function rescale_to_unit(numbers){
var min = Math.min.apply(Math, numbers);
var max = Math.max.apply(Math, numbers);
var sub = max - min;
var unit = [];
for (var i = 0; i < numbers.length; i++) {
unit.push((numbers[i] - min) / sub); | } | return unit;
}
|
//You are given a string s.
// if s[i] is a letter, reverse its case from lower to upper or vise versa,
// otherwise keep it as it is.
// If the string contains no letters, reverse the string.
// The function should return the resulted string.
// Examples
// >>> solve("1234")
// "4321"
// >>> solve("ab")
// "AB"
// >>> solve("#a@C")
// "#A@c"
function solve(s){
let letters = s.match(/[a-z]/ig);
if(letters) {
const swapped = s.split('').map(char => {
if(/[a-z]/i.test(char)) {
return char === char.toLowerCase()
? char.toUpperCase()
: char.toLowerCase();
}
return char;
});
return swapped.join(''); | } | return s.split('').reverse().join('');
}
|
import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// >>> sortNumbers(("three one five"))
// ("one three five")
public static String sortNumbers(String numbers) {
String [] nums = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
HashMap<String, Integer> indexMap = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
indexMap.put(nums[i], i);
}
String [] split = numbers.split(" ");
Arrays.sort(split, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return indexMap.get(s1) - indexMap.get(s2); | } | });
return String.join(" ", split);
}
} |
//Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// >>> maximum([-3, -4, 5], 3)
// [-4, -3, 5]
// Example 2:
// >>> maximum([4, -4, 4], 2)
// [4, 4]
// Example 3:
// >>> maximum([-3, 2, 1, 2, -1, -2, 1], 1)
// [2]
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
function maximum(arr, k){
var len = arr.length;
if(len === 0) return null;
if(len === 1) return arr;
return arr.sort((a, b) => a - b).slice(len - k); | } | |
def circular_shift(x: int, shift: int) -> str:
"""Circular shift the digits of the integer x, shift the digits right by shift
and return the result as a string.
If shift > number of digits, return digits reversed.
>>> circular_shift(12, 1)
'21'
>>> circular_shift(12, 2)
'12'
"""
temp = list(str(x))
if shift > len(temp):
return ''.join(reversed(temp))
else: | return ''.join(temp[-shift:] + temp[:-shift]) | |
//Return sorted unique elements in an array
// >>> unique([5, 3, 5, 2, 3, 3, 9, 0, 123])
// [0, 2, 3, 5, 9, 123]
function unique(l){
return l.filter(function(e, i, a){
return a.indexOf(e) === i; | }).sort(function(a, b){return a-b}); | }
|
from typing import List
def separate_paren_groups(paren_string: str) -> List[str]:
""" Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
separate those group into separate strings and return the list of those.
Separate groups are balanced (each open brace is properly closed) and not nested within each other
Ignore any spaces in the input string.
>>> separate_paren_groups('( ) (( )) (( )( ))')
['()', '(())', '(()())']
"""
paren_string = paren_string.replace(' ', '') | groups = [] | group = ''
open_count = 0
for c in paren_string:
if c == '(':
open_count += 1
elif c == ')':
open_count -= 1
group += c
if open_count == 0:
groups.append(group)
group = ''
return groups
|
import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two array array lists of scores and guesses of equal length, where each index shows a match.
// Return an array array list of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// >>> compare((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)1l))), (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)2l, (long)-2l))))
// (new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l, (long)3l, (long)3l)))
// >>> compare((new ArrayList<Long>(Arrays.asList((long)0l, (long)5l, (long)0l, (long)0l, (long)0l, (long)4l))), (new ArrayList<Long>(Arrays.asList((long)4l, (long)1l, (long)1l, (long)0l, (long)0l, (long)-2l))))
// (new ArrayList<Long>(Arrays.asList((long)4l, (long)4l, (long)1l, (long)0l, (long)0l, (long)6l)))
public static ArrayList<Long> compare(ArrayList<Long> game, ArrayList<Long> guess) {
| ArrayList<Long> result = new ArrayList<Long>(); | for (int i = 0; i < game.size(); i++) {
if (game.get(i) != guess.get(i)) {
result.add(Math.abs(game.get(i) - guess.get(i)));
} else {
result.add((long)0);
}
}
return result;
}
} |
//Return true is array elements are monotonically increasing or decreasing.
// >>> monotonic([1, 2, 4, 20])
// true
// >>> monotonic([1, 20, 4, 10])
// false
// >>> monotonic([4, 1, 0, -10])
// true
function monotonic(l){
| if(l.length <= 1){ | return true;
}
if(l[0] < l[1]){
for(var i = 1; i < l.length - 1; i++){
if(l[i] > l[i + 1]){
return false;
}
}
}
else{
for(var i = 1; i < l.length - 1; i++){
if(l[i] < l[i + 1]){
return false;
}
}
}
return true;
}
|
//Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// >>> minPath([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3)
// [1, 2, 1]
// >>> minPath([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1)
// [1]
function minPath(grid, k){
let n = grid.length;
let path = [];
let startCell = grid[0][0];
for(let i = 0; i < n; i++){
for(let j = 0; j < n; j++){
let curr = grid[i][j];
if(curr < startCell){
startCell = curr;
}
}
}
let currCell = startCell;
for(let l = 0; l < k; l++){
path.push(currCell);
let neighbours = [];
let x = null;
let y = null;
for(let i = 0; i < n; i++){
for(let j = 0; j < n; j++){ | if(grid[i][j] === currCell){ | x = i;
y = j;
}
}
}
if(x > 0){
neighbours.push(grid[x - 1][y]);
}
if(x < n - 1){
neighbours.push(grid[x + 1][y]);
}
if(y > 0){
neighbours.push(grid[x][y - 1]);
}
if(y < n - 1){
neighbours.push(grid[x][y + 1]);
}
let nextCell = neighbours[0];
for(let i = 0; i < neighbours.length; i++){
let curr = neighbours[i];
if(curr < nextCell){
nextCell = curr;
}
}
currCell = nextCell;
}
return path;
} |
import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// >>> closestInteger(("10"))
// (10l)
// >>> closestInteger(("15.3"))
// (15l)
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
public static long closestInteger(String value) {
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(0, BigDecimal.ROUND_HALF_UP);
return bd.longValue(); | } | } |
from typing import List
def odd_count(lst: List[str]) -> List[str]:
"""Given a list of strings, where each string consists of only digits, return a list.
Each element i of the output should be "the number of odd elements in the
string i of the input." where all the i's should be replaced by the number
of odd digits in the i'th string of the input.
>>> odd_count(['1234567'])
['the number of odd elements 4n the str4ng 4 of the 4nput.']
>>> odd_count(['3', '11111111'])
['the number of odd elements 1n the str1ng 1 of the 1nput.', 'the number of odd elements 8n the str8ng 8 of the 8nput.']
"""
output = []
for i in range(len(lst)):
count = 0
for j in range(len(lst[i])): | if int(lst[i][j]) % 2 != 0: | count += 1
output.append(f"the number of odd elements {count}n the str{count}ng {count} of the {count}nput.")
return output
|
//We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// >>> move_one_ball([3, 4, 5, 1, 2])
// true
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// >>> move_one_ball([3, 5, 4, 1, 2])
// false
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
function move_one_ball(arr){
var diff_count = 0;
var i = 0;
var temp = 0;
for(var i = 0; i < arr.length - 1; i++){
if(arr[i] > arr[i + 1]){
diff_count += 1;
}
}
if(diff_count > 1){
return false;
}
else{
return true;
} | } | |
import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Given an array array list arr of integers, find the minimum number of elements that
// need to be changed to make the array array list palindromic. A palindromic array array list is an array array list that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// >>> smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)5l, (long)4l, (long)7l, (long)9l, (long)6l))))
// (4l)
// >>> smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)3l, (long)2l, (long)2l))))
// (1l)
// >>> smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)2l, (long)1l))))
// (0l)
public static long smallestChange(ArrayList<Long> arr) {
int first = 0;
int last = arr.size() - 1;
int count = 0;
while (first < last) { | if (arr.get(first) != arr.get(last)) { | count++;
}
first++;
last--;
}
return count;
}
} |
//You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return undefined if there is no such element.
// >>> next_smallest([1, 2, 3, 4, 5])
// 2
// >>> next_smallest([5, 1, 4, 3, 2])
// 2
// >>> next_smallest([])
// undefined
// >>> next_smallest([1, 1])
// undefined
function next_smallest(lst){
if(lst.length<=1){
return undefined;
}
var smallest=Math.min(...lst);
var second_smallest=Number.MAX_VALUE;
for(var i in lst){
if(lst[i]>smallest&&lst[i]<second_smallest){
second_smallest=lst[i];
}
}
if(second_smallest==Number.MAX_VALUE){
return undefined;
}
return second_smallest; | } | |
//The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// >>> special_factorial(4)
// 288
// The function will receive an integer as input and should return the special
// factorial of this integer.
function special_factorial(n){
| if (n > 0) { | let fact = 1;
for (let i = 1; i <= n; i++) {
fact *= i;
}
return fact * special_factorial(n - 1);
} else {
return 1;
}
}
|
import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// >>> wordsInSentence(("This is a test"))
// ("is")
// Example 2:
// >>> wordsInSentence(("lets go for swimming"))
// ("go for")
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
public static String wordsInSentence(String sentence) {
StringBuilder ans = new StringBuilder();
String[] words = sentence.split(" ");
int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};
boolean isPrime;
for (String word : words) {
isPrime = false;
for (int prime : primes) {
if (word.length() == prime) {
isPrime = true;
break;
}
}
if (isPrime) {
ans.append(word + " ");
} | } | if (ans.length() > 0) {
ans.deleteCharAt(ans.length() - 1);
}
return ans.toString();
}
} |
//Given a string representing a space separated lowercase letters, return an object
// of the letter with the most repetition and containing the corresponding count.
// If several letters have the same occurrence, return all of them.
// Example:
// >>> histogram("a b c")
// {"a": 1, "b": 1, "c": 1}
// >>> histogram("a b b a")
// {"a": 2, "b": 2}
// >>> histogram("a b c a b")
// {"a": 2, "b": 2}
// >>> histogram("b b b b a")
// {"b": 4}
// >>> histogram("")
// {}
function histogram(test){
if (test.length === 0){
return {};
}
var lst = test.split(" ");
var count = {};
for (var i = 0; i < lst.length; i++){ | if (count[lst[i]]){ | count[lst[i]] += 1;
}
else{
count[lst[i]] = 1;
}
}
console.log(count);
var max = 0;
var result = {};
for (var key in count){
if (count[key] > max){
max = count[key];
result = {};
result[key] = max;
}
else if (count[key] === max){
result[key] = max;
}
}
return result;
}
|
def correct_bracketing(brackets: str) -> bool:
""" brackets is a string of "<" and ">".
return True if every opening bracket has a corresponding closing bracket.
>>> correct_bracketing('<')
False
>>> correct_bracketing('<>')
True
>>> correct_bracketing('<<><>>')
True
>>> correct_bracketing('><<>')
False
"""
num_left_brackets = 0 | for bracket in brackets: | if bracket == '<':
num_left_brackets += 1
elif bracket == '>':
num_left_brackets -= 1
if num_left_brackets < 0:
return False
return num_left_brackets == 0
|
import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Return array list with elements incremented by 1.
// >>> incrList((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))))
// (new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)4l)))
// >>> incrList((new ArrayList<Long>(Arrays.asList((long)5l, (long)3l, (long)5l, (long)2l, (long)3l, (long)3l, (long)9l, (long)0l, (long)123l))))
// (new ArrayList<Long>(Arrays.asList((long)6l, (long)4l, (long)6l, (long)3l, (long)4l, (long)4l, (long)10l, (long)1l, (long)124l)))
public static ArrayList<Long> incrList(ArrayList<Long> l) {
for (int i = 0; i < l.size(); i++) {
l.set(i, l.get(i) + 1l);
} | return l; | }
} |
//Return median of elements in the array l.
// >>> median([3, 1, 2, 4, 5])
// 3
// >>> median([-10, 4, 6, 1000, 10, 20])
// 15.0
function median(l){
let middle = Math.floor(l.length / 2);
let sorted = l.sort((a, b) => a - b);
if (l.length % 2 === 0) {
return (sorted[middle - 1] + sorted[middle]) / 2;
} else {
return sorted[middle]; | } | }
|
//You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// >>> match_parens(["()(", ")"])
// "Yes"
// >>> match_parens([")", ")"])
// "No"
function match_parens(lst){
const open = '(';
const close = ')'; | const is_good = (s) => { | let stack = [];
for (let p of s){
if (p === open){
stack.push(p);
} else if (p === close){
if (stack.length === 0){
return false;
}
stack.pop();
}
}
return stack.length === 0;
};
const str1 = lst[0];
const str2 = lst[1];
if (is_good(str1 + str2)){
return 'Yes';
}
if (is_good(str2 + str1)){
return 'Yes';
}
return 'No';
} |
def sort_numbers(numbers: str) -> str:
""" Input is a space-delimited string of numberals from 'zero' to 'nine'.
Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
Return the string with numbers sorted from smallest to largest
>>> sort_numbers('three one five')
'one three five'
"""
| words = numbers.split() | res = ''
mapper = {'zero': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9}
for word in sorted(words, key=lambda x: mapper[x]):
res += ' ' + word
return res.strip()
|
import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// From an array array list of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// >>> removeDuplicates((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)2l, (long)4l))))
// (new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)4l)))
public static ArrayList<Long> removeDuplicates(ArrayList<Long> numbers) {
HashMap<Long, Long> hashmap = new HashMap<Long, Long>();
for (int i = 0; i < numbers.size(); i++) { | Long key = numbers.get(i); | if (hashmap.containsKey(key)) {
hashmap.put(key, hashmap.get(key) + 1);
} else {
hashmap.put(key, 1L);
}
}
ArrayList<Long> out = new ArrayList<Long>();
for (int i = 0; i < numbers.size(); i++) {
Long key = numbers.get(i);
if (hashmap.get(key) == 1) {
out.add(key);
}
}
return out;
}
} |
import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// You are given an array array list of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// >>> matchParens((new ArrayList<String>(Arrays.asList((String)"()(", (String)")"))))
// ("Yes")
// >>> matchParens((new ArrayList<String>(Arrays.asList((String)")", (String)")"))))
// ("No")
public static String matchParens(ArrayList<String> lst) {
String s1 = lst.get(0);
String s2 = lst.get(1);
String s3 = s1+s2;
String s4 = s2+s1;
int c1 = 0;
int c2 = 0;
for (int i = 0; i < s3.length(); i++) {
if (s3.charAt(i) == '(') c1 += 1; | else c1 -= 1; | if (c1 < 0) break;
}
for (int i = 0; i < s4.length(); i++) {
if (s4.charAt(i) == '(') c2 += 1;
else c2 -= 1;
if (c2 < 0) break;
}
if (c1 == 0 || c2 == 0) return "Yes";
else return "No";
}
} |
//Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// >>> count_up_to(5)
// [2, 3]
// >>> count_up_to(11)
// [2, 3, 5, 7]
// >>> count_up_to(0)
// []
// >>> count_up_to(20)
// [2, 3, 5, 7, 11, 13, 17, 19]
// >>> count_up_to(1)
// []
// >>> count_up_to(18)
// [2, 3, 5, 7, 11, 13, 17]
function count_up_to(n){
if (n < 2) return [];
var output = [2];
for (var i = 3; i < n; i += 2){
var prime = true; | for (var j = 3; j < i; j += 2){ | if (i % j === 0){
prime = false;
break;
}
}
if (prime) output.push(i);
}
return output;
}
|
from typing import List, Optional
def prod_signs(arr: List[int]) -> Optional[int]:
"""
You are given an array arr of integers and you need to return
sum of magnitudes of integers multiplied by product of all signs
of each number in the array, represented by 1, -1 or 0.
Note: return None for empty arr.
Example:
>>> prod_signs([1, 2, 2, -4])
9
>>> prod_signs([0, 1])
0
>>> prod_signs([])
None
"""
def product(lst: List[int]) -> int:
out = 1
for item in lst:
out *= item
return out
if len(arr) == 0:
return None
else:
sign_arr = [] | for num in arr: | if num > 0:
sign_arr.append(1)
elif num < 0:
sign_arr.append(-1)
else:
sign_arr.append(0)
return sum(map(abs, arr)) * product(sign_arr) |
//You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// >>> valid_date("03-11-2000")
// true
// >>> valid_date("15-01-2012")
// false
// >>> valid_date("04-0-2040")
// false
// >>> valid_date("06-04-2020")
// true
// >>> valid_date("06/04/2020")
// false
function valid_date(date){
var date_arr = date.split("-");
if(date_arr.length == 3){
var month = parseInt(date_arr[0]);
var day = parseInt(date_arr[1]);
var year = parseInt(date_arr[2]);
if(month < 1 || month > 12){
return false;
}else if(month == 2){
if(day < 1 || day > 29){
return false;
}
}else if((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && (day < 1 || day > 31)){
return false;
}else if((month == 4 || month == 6 || month == 9 || month == 11) && (day < 1 || day > 30)){
return false;
}
return true;
} | return false; | }
|
def get_max_triples(n: int) -> int:
"""
You are given a positive integer n. You have to create an integer array a of length n.
For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
and a[i] + a[j] + a[k] is a multiple of 3.
Example :
>>> get_max_triples(5)
1
Explanation:
a = [1, 3, 7, 13, 21]
The only valid triple is (1, 7, 13).
"""
a = [i * i - i + 1 for i in range(1, n + 1)]
i = 0
j = 1
k = 2
count = 0
while (i < n - 2):
while (j < n - 1):
while (k < n): | if (a[i] + a[j] + a[k]) % 3 == 0: | count += 1
k += 1
j += 1
k = j + 1
i += 1
j = i + 1
k = j + 1
return count
|
//Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// >>> circular_shift(12, 1)
// "21"
// >>> circular_shift(12, 2)
// "12"
function circular_shift(x, shift){
var str = x.toString();
var len = str.length;
var res = '';
if(len < shift){ | for(var i = len-1; i >= 0; i--){ | res += str[i];
}
}else{
res = str.substring(len-shift) + str.substring(0, len-shift);
}
return res;
}
|
import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Return median of elements in the array list l.
// >>> median((new ArrayList<Long>(Arrays.asList((long)3l, (long)1l, (long)2l, (long)4l, (long)5l))))
// (float)3l
// >>> median((new ArrayList<Long>(Arrays.asList((long)-10l, (long)4l, (long)6l, (long)1000l, (long)10l, (long)20l))))
// (15.0f)
public static float median(ArrayList<Long> l) {
float ret = 0;
Collections.sort(l);
int size = l.size();
if (size % 2 == 0) {
ret = (l.get(size / 2) + l.get(size / 2 - 1)) / 2f; | } else { | ret = l.get(size / 2);
}
return ret;
}
} |
//Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// >>> get_odd_collatz(5)
// [1, 5]
function get_odd_collatz(n){
var collatz_sequence = []
var odd_numbers = []
var odd_count = 0
collatz_sequence.push(n)
for(var i = 0; i < collatz_sequence.length; i++){
if(collatz_sequence[i]%2 == 0){
collatz_sequence.push(collatz_sequence[i]/2)
}
else if(collatz_sequence[i]%2 == 1){
collatz_sequence.push(collatz_sequence[i]*3+1)
}
if(collatz_sequence[i]%2 == 1){
odd_numbers.push(collatz_sequence[i])
odd_count += 1
}
if(collatz_sequence[i] == 1){
break
}
}
if(odd_count != 0){ | odd_numbers.sort(function(a, b){return a-b}) | return odd_numbers
}
else{
odd_numbers.push(1)
return odd_numbers
}
}
|
import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Given a non-empty array list of integers, return the sum of all of the odd elements that are in even positions.
// Examples
// >>> solution((new ArrayList<Long>(Arrays.asList((long)5l, (long)8l, (long)7l, (long)1l))))
// (12l)
// >>> solution((new ArrayList<Long>(Arrays.asList((long)3l, (long)3l, (long)3l, (long)3l, (long)3l))))
// (9l)
// >>> solution((new ArrayList<Long>(Arrays.asList((long)30l, (long)13l, (long)24l, (long)321l))))
// (0l)
public static long solution(ArrayList<Long> lst) {
long sum = 0;
for (int i = 0; i < lst.size(); i++) {
if (i % 2 == 0 && lst.get(i) % 2 == 1) {
sum += lst.get(i);
}
}
return sum; | } | } |
import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// >>> fruitDistribution(("5 apples and 6 oranges"), (19l))
// (8l)
// >>> fruitDistribution(("0 apples and 1 oranges"), (3l))
// (2l)
// >>> fruitDistribution(("2 apples and 3 oranges"), (100l))
// (95l)
// >>> fruitDistribution(("100 apples and 1 oranges"), (120l))
// (19l)
public static long fruitDistribution(String s, long n) {
String[] splitted = s.split(" "); | long apples = Long.parseLong(splitted[0]); | long oranges = Long.parseLong(splitted[3]);
return n - apples - oranges;
}
} |
//"Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// >>> pluck([4, 2, 3])
// [2, 1]
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// >>> pluck([1, 2, 3])
// [2, 1]
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// >>> pluck([])
// []
// Example 4:
// >>> pluck([5, 0, 3, 0, 4, 2])
// [0, 1]
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
function pluck(arr){
let result = [],
index = -1;
for(let i = 0; i < arr.length; i++){ | if(arr[i] % 2 === 0){ | if(result.length === 0 || result[0] > arr[i]){
result = [arr[i], i];
}
}
}
return result;
}
|
from typing import List, Optional
def longest(strings: List[str]) -> Optional[str]:
""" Out of list of strings, return the longest one. Return the first one in case of multiple
strings of the same length. Return None in case the input list is empty.
>>> longest([])
None
>>> longest(['a', 'b', 'c'])
'a'
>>> longest(['a', 'bb', 'ccc'])
'ccc'
"""
if not strings:
return None
else:
long = strings[0] | for s in strings: | if len(s) > len(long):
long = s
return long
|
import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Write a function that takes an array array list of numbers as input and returns
// the number of elements in the array array list that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// >>> specialFilter((new ArrayList<Long>(Arrays.asList((long)15l, (long)-73l, (long)14l, (long)-15l))))
// (1l)
// >>> specialFilter((new ArrayList<Long>(Arrays.asList((long)33l, (long)-2l, (long)-3l, (long)45l, (long)21l, (long)109l))))
// (2l)
public static long specialFilter(ArrayList<Long> nums) {
class helper {
public long getFirstDigit(long n) {
long[] digits = getDigits(n);
return digits[0];
}
public long getLastDigit(long n) {
long[] digits = getDigits(n);
return digits[digits.length - 1]; | } | public long[] getDigits(long n) {
ArrayList<Long> digits = new ArrayList<Long>();
while (n != 0) {
digits.add(n % 10);
n /= 10;
}
Collections.reverse(digits);
return digits.stream().mapToLong(i -> i).toArray();
}
}
helper h = new helper();
return nums.stream().filter(x -> x > 10).filter(x -> {
long firstDigit = h.getFirstDigit(x);
long lastDigit = h.getLastDigit(x);
return firstDigit % 2 != 0 && lastDigit % 2 != 0;
}).count();
}
} |
from typing import Union
def compare_one(a: Union[int, float, str], b: Union[int, float, str]) -> Union[int, float, str, None]:
"""
Create a function that takes integers, floats, or strings representing
real numbers, and returns the larger variable in its given variable type.
Return None if the values are equal.
Note: If a real number is represented as a string, the floating point might be . or ,
>>> compare_one(1, 2.5)
2.5
>>> compare_one(1, '2,3')
'2,3'
>>> compare_one('5,1', '6')
'6'
>>> compare_one('1', 1)
None
"""
if isinstance(a, int) and isinstance(b, int):
if a > b:
return a
elif a < b:
return b
else:
return None
elif isinstance(a, float) and isinstance(b, float):
if a > b:
return a
elif a < b:
return b
else:
return None
elif isinstance(a, str) and isinstance(b, str):
a_tmp = a.replace(',', '.')
b_tmp = b.replace(',', '.')
if float(a_tmp) > float(b_tmp):
return a
elif float(a_tmp) < float(b_tmp):
return b
else:
return None
elif isinstance(a, int) and isinstance(b, float):
if a > b:
return a
elif a < b:
return b
else:
return None
elif isinstance(a, float) and isinstance(b, int):
if a > b:
return a
elif a < b:
return b
else:
return None
elif isinstance(a, str) and isinstance(b, int):
a_tmp = a.replace(',', '.')
if float(a_tmp) > b:
return a
elif float(a_tmp) < b:
return b
else:
return None
elif isinstance(a, int) and isinstance(b, str):
b_tmp = b.replace(',', '.')
if a > float(b_tmp):
return a
elif a < float(b_tmp):
return b
else:
return None
elif isinstance(a, str) and isinstance(b, float):
a_tmp = a.replace(',', '.') | if float(a_tmp) > b: | return a
elif float(a_tmp) < b:
return b |
import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Given a string representing a space separated lowercase letters, return a hash map
// of the letter with the most repetition and containing the corresponding count.
// If several letters have the same occurrence, return all of them.
// Example:
// >>> histogram(("a b c"))
// (new HashMap<String,Long>(Map.of("a", 1l, "b", 1l, "c", 1l)))
// >>> histogram(("a b b a"))
// (new HashMap<String,Long>(Map.of("a", 2l, "b", 2l)))
// >>> histogram(("a b c a b"))
// (new HashMap<String,Long>(Map.of("a", 2l, "b", 2l)))
// >>> histogram(("b b b b a"))
// (new HashMap<String,Long>(Map.of("b", 4l)))
// >>> histogram((""))
// (new HashMap<String,Long>())
public static HashMap<String,Long> histogram(String test) {
| HashMap<String,Long> s = new HashMap<String,Long>(); | if (test.length() > 0) {
HashMap<String,Long> hm = new HashMap<String,Long>();
String[] ss = test.split(" ");
for (String sss : ss) {
if (hm.containsKey(sss)) {
hm.put(sss, hm.get(sss) + 1);
} else {
hm.put(sss, 1l);
}
}
long max = 0;
for (String key : hm.keySet()) {
if (hm.get(key) > max) {
max = hm.get(key);
}
}
for (String key : hm.keySet()) {
if (hm.get(key) == max) {
s.put(key, hm.get(key));
}
}
}
return s;
}
} |
//Task
// Write a function that takes a string as input and returns the sum of the upper characters only'
// ASCII codes.
// Examples:
// >>> digitSum("")
// 0
// >>> digitSum("abAB")
// 131
// >>> digitSum("abcCd")
// 67
// >>> digitSum("helloE")
// 69
// >>> digitSum("woArBld")
// 131
// >>> digitSum("aAaaaXa")
// 153
function digitSum(s){
var sum = 0;
for(var i = 0; i < s.length; i++){
if(s[i] >= 'A' && s[i] <= 'Z'){
sum += s.charCodeAt(i);
}
} | return sum; | } |
//You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// >>> intersection([1, 2], [2, 3])
// "NO"
// >>> intersection([-1, 1], [0, 4])
// "NO"
// >>> intersection([-3, -1], [-5, 5])
// "YES"
function intersection(interval1, interval2){
let start = Math.max(interval1[0], interval2[0]);
let end = Math.min(interval1[1], interval2[1]);
if (start >= end) { | return "NO"; | }
let length = end - start;
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97];
return primes.includes(length) ? "YES" : "NO";
}
|
from typing import List, Optional
def prod_signs(arr: List[int]) -> Optional[int]:
"""
You are given an array arr of integers and you need to return
sum of magnitudes of integers multiplied by product of all signs
of each number in the array, represented by 1, -1 or 0.
Note: return None for empty arr.
Example:
>>> prod_signs([1, 2, 2, -4])
9
>>> prod_signs([0, 1])
0
>>> prod_signs([])
None
"""
def product(lst: List[int]) -> int:
out = 1
for item in lst:
out *= item
return out
if len(arr) == 0: | return None | else:
sign_arr = []
for num in arr:
if num > 0:
sign_arr.append(1)
elif num < 0:
sign_arr.append(-1)
else:
sign_arr.append(0)
return sum(map(abs, arr)) * product(sign_arr) |
import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// >>> makePalindrome((""))
// ("")
// >>> makePalindrome(("cat"))
// ("catac")
// >>> makePalindrome(("cata"))
// ("catac")
public static String makePalindrome(String string) {
StringBuilder newString = new StringBuilder(string);
String reverse = new StringBuilder(string).reverse().toString();
for (int index = 0; index < string.length(); index++) { | if (string.substring(index).equals(reverse.substring(0, string.length() - index))) { | newString.append(reverse.substring(string.length() - index));
break;
}
}
return newString.toString();
}
} |
import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// >>> correctBracketing(("("))
// (false)
// >>> correctBracketing(("()"))
// (true)
// >>> correctBracketing(("(()())"))
// (true)
// >>> correctBracketing((")(()"))
// (false)
public static boolean correctBracketing(String brackets) {
int balance = 0;
for (int i = 0; i < brackets.length(); i++) {
if (brackets.charAt(i) == '(') {
balance++;
} else { | balance--; | }
if (balance < 0) {
return false;
}
}
return balance == 0;
}
} |
from typing import List
def minPath(grid: List[List[int]], k: int) -> List[int]:
"""
Given a grid with N rows and N columns (N >= 2) and a positive integer k,
each cell of the grid contains a value. Every integer in the range [1, N * N]
inclusive appears exactly once on the cells of the grid.
You have to find the minimum path of length k in the grid. You can start
from any cell, and in each step you can move to any of the neighbor cells,
in other words, you can go to cells which share an edge with you current
cell.
Please note that a path of length k means visiting exactly k cells (not
necessarily distinct).
You CANNOT go off the grid.
A path A (of length k) is considered less than a path B (of length k) if
after making the ordered lists of the values on the cells that A and B go
through (let's call them lst_A and lst_B), lst_A is lexicographically less
than lst_B, in other words, there exist an integer index i (1 <= i <= k)
such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
lst_A[j] = lst_B[j].
It is guaranteed that the answer is unique.
Return an ordered list of the values on the cells that the minimum path go through.
Examples:
>>> minPath([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3)
[1, 2, 1]
>>> minPath([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1)
[1]
"""
min_val = float('inf')
for i in range(len(grid)): | for j in range(len(grid[0])): | if grid[i][j] < min_val:
min_val = grid[i][j]
row = i
col = j
path = [min_val]
while len(path) < k:
min_val = float('inf')
for i, j in (row - 1, col), (row + 1, col), (row, col - 1), (row, col + 1):
if 0 <= i < len(grid) and 0 <= j < len(grid[0]) and grid[i][j] < min_val:
min_val = grid[i][j]
row = i
col = j
path.append(min_val)
return path |
from typing import Tuple
def bf(planet1: str, planet2: str) -> Tuple[str, ...]:
"""
There are eight planets in our solar system: the closerst to the Sun
is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn,
Uranus, Neptune.
Write a function that takes two planet names as strings planet1 and planet2.
The function should return a tuple containing all planets whose orbits are
located between the orbit of planet1 and the orbit of planet2, sorted by
the proximity to the sun.
The function should return an empty tuple if planet1 or planet2
are not correct planet names.
Examples
>>> bf('Jupiter', 'Neptune')
('Saturn', 'Uranus')
>>> bf('Earth', 'Mercury')
'Venus'
>>> bf('Mercury', 'Uranus')
('Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn')
"""
planets = ('Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune')
if planet1 not in planets or planet2 not in planets:
return ()
start = planets.index(planet1)
end = planets.index(planet2) | if start < end: | planets = planets[start+1:end]
else:
planets = planets[end+1:start]
return tuple(planets) |
def file_name_check(file_name: str) -> str:
"""Create a function which takes a string representing a file's name, and returns
'Yes' if the the file's name is valid, and returns 'No' otherwise.
A file's name is considered to be valid if and only if all the following conditions
are met:
- There should not be more than three digits ('0'-'9') in the file's name.
- The file's name contains exactly one dot '.'
- The substring before the dot should not be empty, and it starts with a letter from
the latin alphapet ('a'-'z' and 'A'-'Z').
- The substring after the dot should be one of these: ['txt', 'exe', 'dll']
Examples:
>>> file_name_check('example.txt')
'Yes'
>>> file_name_check('1example.dll')
'No'
"""
if not file_name:
return 'No'
s_count = 0
e_count = 0
for i in file_name:
if i.isdigit():
s_count += 1
if i == '.':
e_count += 1
if s_count > 3 or e_count != 1:
return 'No'
s_name = file_name.split('.')[0]
e_name = file_name.split('.')[1]
if not s_name or not e_name or not s_name[0].isalpha(): | return 'No' | if e_name not in ['txt', 'exe', 'dll']:
return 'No'
return 'Yes'
|
import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Given a positive integer n, return a sorted array list that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array list sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// >>> getOddCollatz((5l))
// (new ArrayList<Long>(Arrays.asList((long)1l, (long)5l)))
public static ArrayList<Long> getOddCollatz(long n) {
if (n <= 0) return new ArrayList<Long>();
HashSet<Long> odds = new HashSet<Long>();
long n1 = n;
while (n1 > 1) {
if (n1 % 2 == 1) odds.add(n1);
n1 = n1 % 2 == 0 ? n1 / 2 : 3 * n1 + 1;
}
odds.add(1l);
Long[] odds_arr = odds.toArray(new Long[odds.size()]);
ArrayList<Long> ans = new ArrayList<Long>(Arrays.asList(odds_arr));
Collections.sort(ans);
return ans; | } | } |
import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// You are given a positive integer n. You have to create an integer array array list a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// >>> getMaxTriples((5l))
// (1l)
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
public static long getMaxTriples(long n) {
int count = 0;
ArrayList<Integer> arrayList = new ArrayList<Integer>();
for (int i = 1; i <= n; i++) {
arrayList.add(i * i - i + 1);
}
for (int i = 0; i < arrayList.size(); i++) {
for (int j = i + 1; j < arrayList.size(); j++) {
for (int k = j + 1; k < arrayList.size(); k++) {
if ((arrayList.get(i) + arrayList.get(j) + arrayList.get(k)) % 3 == 0) { | count++; | }
}
}
}
return count;
}
} |
import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array list) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// >>> willItFly((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l))), (5l))
// (false)
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// >>> willItFly((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l))), (1l))
// (false)
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// >>> willItFly((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l))), (9l))
// (true)
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// >>> willItFly((new ArrayList<Long>(Arrays.asList((long)3l))), (5l))
// (true)
// # 3 is less than the maximum possible weight, and it's balanced.
public static boolean willItFly(ArrayList<Long> q, long w) {
if (q.size() == 0) {
return false;
}
if (q.size() == 1) {
return true;
}
Long sum = 0l;
for (int i = 0; i < q.size(); i++) {
sum += q.get(i);
}
if (sum > w) {
return false;
}
for (int i = 0; i < q.size() / 2; i++) {
if (q.get(i) != q.get(q.size() - 1 - i)) {
return false;
}
}
return true;
} | } | |
from typing import List
def max_fill(grid: List[List[int]], capacity: int) -> int:
"""
You are given a rectangular grid of wells. Each row represents a single well,
and each 1 in a row represents a single unit of water.
Each well has a corresponding bucket that can be used to extract water from it,
and all buckets have the same capacity.
Your task is to use the buckets to empty the wells.
Output the number of times you need to lower the buckets.
Example 1:
>>> max_fill([[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], 1)
6
Example 2:
>>> max_fill([[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], 2)
5
Example 3:
>>> max_fill([[0, 0, 0], [0, 0, 0]], 5)
0
Constraints:
* all wells have the same length
* 1 <= grid.length <= 10^2
* 1 <= grid[:,1].length <= 10^2
* grid[i][j] -> 0 | 1
* 1 <= capacity <= 10
"""
times = 0
for row in grid:
for i in range(0, len(row), capacity): | if 1 in row[i:i+capacity]: | times += 1
return times
|
//You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// >>> get_max_triples(5)
// 1
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
function get_max_triples(n){
let result = 0;
let arr = [];
for(let i = 1; i<=n; i++){
arr.push(i*i-i+1);
}
for(let i = 0; i<arr.length; i++){
for(let j = i+1; j<arr.length; j++){
for(let k = j+1; k<arr.length; k++){
if((arr[i]+arr[j]+arr[k])%3 === 0){ | result++; | }
}
}
}
return result;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.