text
stringlengths 2
104M
| meta
dict |
---|---|
# Kangaroo
# Can two kangaroo meet after making the same number of jumps?
#
# https://www.hackerrank.com/challenges/kangaroo/problem
#
def kangaroo(x1, v1, x2, v2):
# x1+k*v1 = x2+k*v2 => x1-x2=k*(v2-v1), k>0
if v1 == v2:
return "YES" if x1 == x2 else "NO"
q, r = divmod(x1 - x2, v2 - v1)
if r == 0 and q > 0:
return 'YES'
else:
return 'NO'
x1, v1, x2, v2 = input().strip().split(' ')
x1, v1, x2, v2 = [int(x1), int(v1), int(x2), int(v2)]
result = kangaroo(x1, v1, x2, v2)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Fair Rations
# How many loaves of bread will it take to feed your subjects?
#
# https://www.hackerrank.com/challenges/fair-rations/problem
#
# pas compliqué, le use case donne la solution :)
# on saute les nombres pairs
# il faut donner une miche au premier nombre impair et au suivant
# et on recommence à partir de ce suivant
def fairRations(B):
loaves = 0
i = 0
while i < len(B):
if B[i] % 2 == 1:
if i == len(B) - 1:
return "NO"
B[i] += 1
B[i + 1] += 1
loaves += 2
i += 1
return loaves
if __name__ == "__main__":
N = int(input().strip())
B = list(map(int, input().strip().split(' ')))
result = fairRations(B)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Taum and B'day
# Calculate the minimum cost required to buy some amounts of two types of gifts when costs of each type and the rate of conversion from one form to another is provided.
#
# https://www.hackerrank.com/challenges/taum-and-bday/problem
#
def taumBday(b, w, x, y, z):
# Complete this function
# x : cost of b
# y : cost of w
# z : cost of b <-> w
return min(x * b + y * w, # coût avec aucune transformation
(y + z) * b + y * w, # coût en transformant b en w
x * b + (x + z) * w) # coût en transformant w en b
if __name__ == "__main__":
t = int(input().strip())
for a0 in range(t):
b, w = input().strip().split(' ')
b, w = [int(b), int(w)]
x, y, z = input().strip().split(' ')
x, y, z = [int(x), int(y), int(z)]
result = taumBday(b, w, x, y, z)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Service Lane
# Calculate the maximum width of the vehicle that can pass through a service lane.
#
# https://www.hackerrank.com/challenges/service-lane/problem
#
def serviceLane(width, a, b):
# euh? comment dire...
print(min(width[a:b + 1]))
if __name__ == "__main__":
n, t = map(int, input().split())
width = list(map(int, input().split()))
for _ in range(t):
a, b = map(int, input().split())
serviceLane(width, a, b)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Algorithms > Implementation > Ema's Supercomputer
// Determine the product of the areas of two pluses on a grid.
//
// https://www.hackerrank.com/challenges/two-pluses/problem
//
#include <bits/stdc++.h>
using namespace std;
template<typename T>
typename std::vector<T>::iterator insert_sorted(std::vector<T> & vec, T const& item)
{
return vec.insert(std::upper_bound(vec.begin(), vec.end(), item,
[] (const T&a, const T& b)-> bool
{
return std::get<0>(a) > std::get<0>(b);
}), item);
}
int twoPluses(const vector<string>& grid)
{
// Complete this function
vector<tuple<int, int, int>> plus;
int n = grid.size();
int m = grid[0].length();
for (int x = 0; x < n; ++x)
{
for (int y = 0; y < m; ++y)
{
int k = 0;
while (x + k < n && y + k < m && x - k >= 0 && y - k >= 0
&& grid[x][y + k] == 'G'
&& grid[x][y - k] == 'G'
&& grid[x - k][y] == 'G'
&& grid[x + k][y] == 'G')
{
//int s = k * 4 + 1;
tuple<int, int, int> v(k, x, y);
insert_sorted(plus, v);
++k;
}
}
}
vector<string> check = grid;
char flag = '+';
int max = 0;
for (int i = 0; i < plus.size() - 1; ++i)
{
int k1, x, y;
std::tie(k1, x, y) = plus[i];
// impossible de trouver un produit supérieur
if ((k1 * 4 + 1) * (k1 * 4 + 1) <= max)
break;
for (int k = k1; k >= 0; k--)
{
check[x][y - k] = flag;
check[x][y + k] = flag;
check[x - k][y] = flag;
check[x + k][y] = flag;
}
for (int j = i + 1; j < plus.size(); ++j)
{
bool overlap = false;
int k2, x, y;
std::tie(k2, x, y) = plus[j];
for (int k = k2; k >= 0; k--)
{
if ( check[x][y - k] == flag
|| check[x][y + k] == flag
|| check[x - k][y] == flag
|| check[x + k][y] == flag)
{
overlap = true;
break;
}
}
if (overlap == false)
{
int kk = (k1 * 4 + 1) * (k2 * 4 + 1);
if (kk > max)
{
max = kk;
break; // les produits suivants seront plus petits
}
}
}
// rétablit la grille
for (int k = k1; k >= 0; k--)
{
check[x][y - k] = 'G';
check[x][y + k] = 'G';
check[x - k][y] = 'G';
check[x + k][y] = 'G';
}
}
return max;
}
int main()
{
int n;
int m;
cin >> n >> m;
vector<string> grid(n);
for(int grid_i = 0; grid_i < n; grid_i++){
cin >> grid[grid_i];
}
int result = twoPluses(grid);
cout << result << endl;
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Minimum Distances
# Find the minimum distance between two different indices containing the same integers.
#
# https://www.hackerrank.com/challenges/minimum-distances/problem
#
import sys
def minimumDistances(a):
b = [(v, i) for i, v in enumerate(a)]
b = sorted(b)
print('a=',a, file=sys.stderr)
print('b=', b, file=sys.stderr)
iprec = 0
vprec = -1
m = len(a)
for v, i in b:
if v == vprec:
m = min(m, i - iprec)
iprec = i
vprec = v
if m == len(a):
m = -1
return m
if __name__ == "__main__":
n = int(input().strip())
a = list(map(int, input().strip().split(' ')))
result = minimumDistances(a)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Sherlock and Squares
# Find the count of square numbers between A and B
#
# https://www.hackerrank.com/challenges/sherlock-and-squares/problem
#
def squares(a, b):
# Complete this function
# Il y a deux manières de faire:
# - soit on cherche tous les carrés entre a eb b
# - soit on vérifie que les nombres entre a et b sont des carrés
# La deuxième solution est trop lente, surtout avec les conditions de l'énoncé
# 1 ≤ a ≤ b ≤ 10⁹
nb = 0
r = int(a ** 0.5)
if a <= r * r <= b:
nb += 1
while True:
r += 1
if r * r <= b:
nb += 1
else:
break
return nb
if __name__ == "__main__":
q = int(input().strip())
for a0 in range(q):
a, b = input().strip().split(' ')
a, b = [int(a), int(b)]
result = squares(a, b)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Birthday Chocolate
# Given an array of integers, find the number of subarrays of length k having sum s.
#
# https://www.hackerrank.com/challenges/the-birthday-bar/problem
#
def solve(n, s, d, m):
# Complete this function
return sum(1 for i in range(len(s) - m + 1) if sum(s[i:i + m]) == d)
n = int(input().strip())
s = list(map(int, input().strip().split(' ')))
d, m = input().strip().split(' ')
d, m = [int(d), int(m)]
result = solve(n, s, d, m)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Almost Sorted
# Sort an array by either swapping or reversing a segment
#
# https://www.hackerrank.com/challenges/almost-sorted/problem
#
#!/bin/python3
import sys
def debug(*kw):
#sys.stderr.write(' '.join(map(repr, kw)) + '\n')
pass
def almostSorted(arr):
# Complete this function
l = len(arr)
# évite des tas de test de débordement
arr.insert(0, -1)
arr.append(1000001)
debug(arr, l)
def increasing(i):
while i <= l and arr[i] < arr[i + 1]:
i += 1
return i
def decreasing(i):
while i <= l and arr[i] > arr[i + 1]:
i += 1
return i
# cherche la première suite croissante
i = increasing(1)
if i == l:
print("yes")
return
# ici les éléments [1..i] sont croissants
debug("croissants", arr[1:i+1])
j = decreasing(i)
# ici [i..j] sont décroissants
debug("décroissants", arr[i:j+1])
if j == i + 1:
# un seul élément décroît:
# cherche un deuxième, nécessaire pour swap arr[i]
m = increasing(j)
debug("croissants", arr[j:m+1])
n = decreasing(m)
debug("décroissants", arr[m:n+1])
if m == l+1 and n == l+1:
if arr[i-1] < arr[j] < arr[i] < arr[j + 1]:
arr[j], arr[i] = arr[i], arr[j]
debug(arr)
print("yes")
print("swap", i, j)
return
if n == m + 1:
# un seul candidat: arr[n]
if arr[i-1] < arr[n] < arr[i+1] and arr[n-1] < arr[i] < arr[n+1]:
o = increasing(n)
if o != l + 1:
print("no")
return
arr[n], arr[i] = arr[i], arr[n]
debug(arr)
print("yes")
print("swap", i, n)
return
debug(i,j,m,n)
else:
debug('try reverse')
m = increasing(j)
debug("croissants", arr[j:m+1])
debug(i,j,m)
if m == l + 1:
print("yes")
print("reverse", i, j)
return
print("no")
return
if __name__ == "__main__":
n = int(input())
arr = list(map(int, input().split()))
almostSorted(arr)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Angry Professor
# Decide whether or not the class will be canceled based on the arrival times of its students.
#
# https://www.hackerrank.com/challenges/angry-professor/problem
#
import sys
def angryProfessor(k, a):
# Complete this function
# il faut compter le nombre de temps négatifs ou nuls
if sum(1 for i in a if i <= 0) >= k:
return "NO"
else:
return "YES"
if __name__ == "__main__":
t = int(input().strip())
for a0 in range(t):
n, k = input().strip().split(' ')
n, k = [int(n), int(k)]
a = list(map(int, input().strip().split(' ')))
result = angryProfessor(k, a)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Bigger is Greater
# Rearrange the letters of a string to construct another string such that the new string is lexicographically greater than the original.
#
# https://www.hackerrank.com/challenges/bigger-is-greater/problem
#
import sys
def biggerIsGreater(w):
# Complete this
w = list(w)
i = len(w) - 1
while i > 0 and w[i - 1] >= w[i]:
i -= 1
if i == 0: return "no answer"
# w[i - 1] est le caractère pivot
j = len(w) - 1
while w[j] <= w[i - 1]:
j -= 1
w[i - 1], w[j] = w[j], w[i - 1]
# trie le reste (qui est déjà en ordre décroissant)
w[i:] = w[len(w) - 1:i - 1:-1]
return ''.join(w)
if __name__ == "__main__":
T = int(input().strip())
for a0 in range(T):
w = input().strip()
result = biggerIsGreater(w)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Algorithms > Implementation > Larry's Array
# Larry
#
# https://www.hackerrank.com/challenges/larrys-array/problem
#
# Quelques explications:
# - la permutation ABC->BCA->CAB a une signature paire (https://en.wikipedia.org/wiki/Parity_of_a_permutation)
# - la parité d'une permutation ne change pas qq le nombre de cycle
# - la permutation identité est paire
# - donc pour que l'ensemble soit ordonnable avec le permutation donnée, il faut que la parité (i.e. le nombre d'inversions) soit paire
# Lire ici aussi: https://en.wikipedia.org/wiki/Inversion_(discrete_mathematics)
import itertools
for _ in range(int(input())):
n = input()
A = list(map(int, input().split()))
# calcule le nombre d'inversions de A[]
inversions = 0
for i in itertools.combinations(A, 2):
if i[0] > i[1]:
inversions += 1
if inversions % 2 == 0:
print("YES")
else:
print("NO")
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Strange Counter
# Print the value displayed by the counter at a given time, $t$.
#
# https://www.hackerrank.com/challenges/strange-code/problem
#
import math
def strangeCode(t):
# Complete this function
# 3 + 6 + 12 + 24 + 48 + ...
# 3 * (1 + 2 + 4 + 8 + ...)
# 3 * (2^n - 1) <= t < 3 * (2^(n+1) - 1)
# 2^n <= t / 3 + 1
# n <= log(t / 3 + 1) / log(2) < n + 1
t -= 1
n = math.floor(math.log2(t / 3 + 1))
# bornes de la colonne : ]a, b]
# a = 3 * (2 ** n - 1)
b = 3 * (2 ** (n + 1) - 1)
return b - t
if __name__ == "__main__":
t = int(input().strip())
result = strangeCode(t)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Sequence Equation
# Find some y satisfying p(p(y)) = x for each x from 1 to n.
#
# https://www.hackerrank.com/challenges/permutation-equation/problem
#
def permutationEquation(p):
# Complete this function
n = len(p)
q = [0] * n
# p(p(𝓎)) = 𝓍 (au décalage de 1 près)
for i in range(0, n):
q[p[p[i] - 1] - 1] = i + 1
return q
if __name__ == "__main__":
n = int(input())
p = list(map(int, input().split()))
result = permutationEquation(p)
print ("\n".join(map(str, result)))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Drawing Book
# How many pages does Brie need to turn to get to page p?
#
# https://www.hackerrank.com/challenges/drawing-book/problem
#
# pour résoudre ce challenge du premier coup (i.e. sans tatonner, la formule étant
# forcément une division par 2, on finira bien par tomber sur la bonne), il suffit
# de décrire tous les cas, qui ne sont pas nombreux: le seul ajustement à faire
# concerne la denière page: est-elle numérotée ou non ?
def solve(n, p):
# depuis la fin:
if n % 2 == 0:
# la dernière page est blanche
# nombre de pages à tourner:
# p=n => 0
# p=n-1 ou n-2 => 1
# p=n-3 ou n-4 => 2 => (n-p+1)//2 en partant de la fin
fin = (n - p + 1) // 2
else:
# la dernière page est numérotée
# p=n ou n-1 => 0
# p=n-2 ou n-3 => 1
# p=n-3 ou n-4 => 2 => (n-p+1)//2 en partant de la fin
fin = (n - p) // 2
# depuis le début:
# p=1 => 0
# p=2 ou 3 => 1
# p=4 ou 5 => 2 => p//2 en partant du début
debut = p // 2
return min(debut, fin)
n = int(input().strip())
p = int(input().strip())
result = solve(n, p)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Organizing Containers of Balls
# Determine if David can perform some sequence of swap operations such that each container holds one distinct type of ball.
#
# https://www.hackerrank.com/challenges/organizing-containers-of-balls/problem
#
def organizingContainers(containers):
# somme des lignes == somme des colonnes ?
return sorted(map(sum, containers)) == sorted(map(sum, zip(*containers)))
if __name__ == "__main__":
q = int(input())
for _ in range(q):
n = int(input())
containers = []
for _ in range(n):
containers.append(list(map(int, input().split())))
result = organizingContainers(containers)
print("Possible" if result else "Impossible")
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Lisa's Workbook
# A workbook with chapters. Some number of problems per page. How many problems have a number equal to a page's number?
#
# https://www.hackerrank.com/challenges/lisa-workbook/problem
#
# pas compliqué, il faut bien lire et suivre l'énoncé
def workbook(n, k, arr):
resultat = 0
page = 0
# parcourt les chapitres
for num_pb in arr:
pb = 1
# parcourt les pages
while True:
page += 1
if pb <= page < pb + min(num_pb, k):
resultat += 1
# il n'y a plus de problème dans ce chapitre
if num_pb <= k:
break
# il y en a encore: décrémente le nombre de problèmes restant
# et incrémente le numéro du premier problème de la page suivante
num_pb -= k
pb += k
return resultat
if __name__ == "__main__":
n, k = input().strip().split(' ')
n, k = [int(n), int(k)]
arr = list(map(int, input().strip().split(' ')))
result = workbook(n, k, arr)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Day of the Programmer
# Given year, determine date of the 256th day of the year.
#
# https://www.hackerrank.com/challenges/day-of-the-programmer/problem
#
def solve(year):
# Complete this function
if year == 1918:
return "26.09.1918" # cas spécial de la transition calendrier julien -> grégorien
if year >= 1918:
leap = year % 4 == 0 and (year % 400 == 0 or year % 100 != 0)
else:
leap = year % 4 == 0
if leap:
return "12.09." + str(year)
else:
return "13.09." + str(year)
year = int(input().strip())
result = solve(year)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Modified Kaprekar Numbers
# Print kaprekar numbers in the given range
#
# https://www.hackerrank.com/challenges/kaprekar-numbers/problem
#
def kaprekarNumbers(p, q):
# Complete this function
found = False
for i in range(p, q + 1):
s = str(i * i)
d = len(s) // 2
l = int(s[:d]) if d > 0 else 0
r = int(s[d:])
if l + r == i:
yield i
found = True
if not found:
yield "INVALID RANGE"
if __name__ == "__main__":
p = int(input().strip())
q = int(input().strip())
print (" ".join(map(str, kaprekarNumbers(p, q))))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Counting Valleys
// Count the valleys encountered during vacation.
//
// https://www.hackerrank.com/challenges/counting-valleys/problem
//
#include <bits/stdc++.h>
using namespace std;
int countingValleys(const string& s) {
// Complete this function
int valleys = 0;
int alt = 0;
for (auto c : s)
{
int new_alt = alt + ((c == 'U') ? +1 : -1);
if (alt == 0 && new_alt == -1) valleys ++;
alt = new_alt;
}
return valleys;
}
int main() {
int n;
cin >> n;
string s;
cin >> s;
int result = countingValleys(s);
cout << result << endl;
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Climbing the Leaderboard
# Help Alice track her progress toward the top of the leaderboard!
#
# https://www.hackerrank.com/challenges/climbing-the-leaderboard/problem
#
"""
solution 'à la mano'
on peut aussi utiliser un set() à la place de groupby(),
puis sorted() et bisect.bisect_right() pour faire la dichotomie
ce qui revient +in fine+ à la même chose
"""
import itertools
# dichotomie dans une liste décroissante
def binary_search(a, x):
first = 0
last = len(a) - 1
while first <= last:
i = (first + last) // 2
if a[i] == x:
return i
elif a[i] < x:
last = i - 1
else:
first = i + 1
return first
def climbingLeaderboard(scores, alice):
# Complete this function
leaderboard = [s for s, _ in itertools.groupby(scores)]
for a in alice:
""" version triviale
rank = 1
for s in leaderboard:
if a >= s:
break
rank += 1
"""
# version optimisée avec dichotomie
# nécessaire pour passer certains testcases
rank = binary_search(leaderboard, a) + 1
print(rank)
if __name__ == "__main__":
n = int(input())
scores = list(map(int, input().split()))
m = int(input().strip())
alice = list(map(int, input().split()))
climbingLeaderboard(scores, alice)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Cavity Map
// Depict cavities on a square map
//
// https://www.hackerrank.com/challenges/cavity-map/problem
//
#include <bits/stdc++.h>
using namespace std;
vector<string> cavityMap(size_t n, const vector<string>& grid) {
// Complete this function
vector<string> result = grid;
for (size_t i = 1; i < n - 1; ++i)
{
for (size_t j = 1; j < n - 1; ++j)
{
char v = grid[i][j];
if (v > grid[i - 1][j] && v > grid[i + 1][j] && v > grid[i][j - 1] && v > grid[i][j + 1])
{
result[i][j] = 'X';
}
}
}
return result;
}
int main() {
size_t n;
cin >> n;
vector<string> grid(n);
for (size_t grid_i = 0; grid_i < n; grid_i++) {
cin >> grid[grid_i];
}
vector<string> result = cavityMap(n, grid);
for (const auto& row : result) {
cout << row << endl;
}
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Extra Long Factorials
# Calculate a very large factorial that doesn't fit in the conventional numeric data types.
#
# https://www.hackerrank.com/challenges/extra-long-factorials/problem
#
import functools
import operator
def extraLongFactorials(n):
# Complete this function
fac = functools.reduce(operator.mul, [i for i in range(1, n + 1)], 1)
print(fac)
# ou tout simplement math.factorial(n) !!!
if __name__ == "__main__":
n = int(input().strip())
extraLongFactorials(n)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
### [Algorithms](https://www.hackerrank.com/domains/algorithms)
The true test of problem solving: when one realizes that time and memory aren't infinite.
#### [Implementation](https://www.hackerrank.com/domains/algorithms/implementation)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Grading Students](https://www.hackerrank.com/challenges/grading)|Round student grades according to Sam's rules.|[Python](grading.py)|Easy
[Apple and Orange](https://www.hackerrank.com/challenges/apple-and-orange)|Find the respective numbers of apples and oranges that fall on Sam's house.|[Python](apple-and-orange.py)|Easy
[Kangaroo](https://www.hackerrank.com/challenges/kangaroo)|Can two kangaroo meet after making the same number of jumps?|[Python](kangaroo.py)|Easy
[Between Two Sets](https://www.hackerrank.com/challenges/between-two-sets)|Find the number of integers that satisfies certain criteria relative to two sets.|[Python](between-two-sets.py)|Easy
[Breaking the Records](https://www.hackerrank.com/challenges/breaking-best-and-worst-records)|Given an array of Maria's basketball scores all season, determine the number of times she breaks her best and worst records.|[Python](breaking-best-and-worst-records.py)|Easy
[Birthday Chocolate](https://www.hackerrank.com/challenges/the-birthday-bar)|Given an array of integers, find the number of subarrays of length k having sum s.|[Python](the-birthday-bar.py)|Easy
[Divisible Sum Pairs](https://www.hackerrank.com/challenges/divisible-sum-pairs)|Count the number of pairs in an array having sums that are evenly divisible by a given number.|[Python](divisible-sum-pairs.py)|Easy
[Migratory Birds](https://www.hackerrank.com/challenges/migratory-birds)|Determine which type of bird in a flock occurs at the highest frequency.|[Python](migratory-birds.py)|Easy
[Day of the Programmer](https://www.hackerrank.com/challenges/day-of-the-programmer)|Given year, determine date of the 256th day of the year.|[Python](day-of-the-programmer.py)|Easy
[Bon Appétit](https://www.hackerrank.com/challenges/bon-appetit)|Determine whether or not Brian overcharged Anna for their split bill.|[Python](bon-appetit.py)|Easy
[Sock Merchant](https://www.hackerrank.com/challenges/sock-merchant)|How many pairs of socks John can sell?|[Python](sock-merchant.py)|Easy
[Drawing Book ](https://www.hackerrank.com/challenges/drawing-book)|How many pages does Brie need to turn to get to page p?|[Python](drawing-book.py)|Easy
[Counting Valleys](https://www.hackerrank.com/challenges/counting-valleys)|Count the valleys encountered during vacation.|[C++](counting-valleys.cpp)|Easy
[Electronics Shop](https://www.hackerrank.com/challenges/electronics-shop)|Determine the most expensive Keyboard and USB drive combination Monica can purchase within her budget.|[C++](electronics-shop.cpp)|Easy
[Cats and a Mouse](https://www.hackerrank.com/challenges/cats-and-a-mouse)|Which cat will catch the mouse first?|[Python](cats-and-a-mouse.py)|Easy
[Forming a Magic Square](https://www.hackerrank.com/challenges/magic-square-forming)|Find the minimum cost of converting a 3 by 3 matrix into a magic square.|[Python](magic-square-forming.py)|Medium
[Picking Numbers](https://www.hackerrank.com/challenges/picking-numbers)|What's the largest size subset can you choose from an array such that the difference between any two integers is not bigger than 1?|[Python](picking-numbers.py)|Easy
[Climbing the Leaderboard](https://www.hackerrank.com/challenges/climbing-the-leaderboard)|Help Alice track her progress toward the top of the leaderboard!|[Python](climbing-the-leaderboard.py)|Medium
[The Hurdle Race](https://www.hackerrank.com/challenges/the-hurdle-race)|Can you help Dan determine the minimum number of magic beverages he must drink to jump all the hurdles?|[Python](the-hurdle-race.py)|Easy
[Designer PDF Viewer](https://www.hackerrank.com/challenges/designer-pdf-viewer)|Help finding selection area in PDF Viewer.|[Python](designer-pdf-viewer.py)|Easy
[Utopian Tree](https://www.hackerrank.com/challenges/utopian-tree)|Predict the height of the tree after N growth cycles.|[Python](utopian-tree.py)|Easy
[Angry Professor](https://www.hackerrank.com/challenges/angry-professor)|Decide whether or not the class will be canceled based on the arrival times of its students.|[Python](angry-professor.py)|Easy
[Beautiful Days at the Movies](https://www.hackerrank.com/challenges/beautiful-days-at-the-movies)|Find the number of beautiful days.|[Python](beautiful-days-at-the-movies.py)|Easy
[Viral Advertising](https://www.hackerrank.com/challenges/strange-advertising)|How many people will know about the new product after n days?|[Python](strange-advertising.py)|Easy
[Save the Prisoner!](https://www.hackerrank.com/challenges/save-the-prisoner)|Given M sweets and a circular queue of N prisoners, find the ID of the last prisoner to receive a sweet.|[Python](save-the-prisoner.py)|Easy
[Circular Array Rotation](https://www.hackerrank.com/challenges/circular-array-rotation)|Print the elements in an array after 'm' right circular rotation operations.|[Python](circular-array-rotation.py)|Easy
[Sequence Equation](https://www.hackerrank.com/challenges/permutation-equation)|Find some y satisfying p(p(y)) = x for each x from 1 to n.|[Python](permutation-equation.py)|Easy
[Jumping on the Clouds: Revisited](https://www.hackerrank.com/challenges/jumping-on-the-clouds-revisited)|Determine the amount of energy Aerith has after the cloud game ends.|[Python](jumping-on-the-clouds-revisited.py)|Easy
[Find Digits](https://www.hackerrank.com/challenges/find-digits)|Calculate the number of digits in an integer that evenly divide it.|[Python](find-digits.py)|Easy
[Extra Long Factorials](https://www.hackerrank.com/challenges/extra-long-factorials)|Calculate a very large factorial that doesn't fit in the conventional numeric data types.|[Haskell](extra-long-factorials.hs) [Python](extra-long-factorials.py)|Medium
[Append and Delete](https://www.hackerrank.com/challenges/append-and-delete)|Can you convert $s$ to $t$ by performing exactly $k$ operations?|[Python](append-and-delete.py)|Easy
[Sherlock and Squares](https://www.hackerrank.com/challenges/sherlock-and-squares)|Find the count of square numbers between A and B|[Python](sherlock-and-squares.py)|Easy
[Library Fine](https://www.hackerrank.com/challenges/library-fine)|Help your library calculate fees for late books!|[Python](library-fine.py)|Easy
[Cut the sticks](https://www.hackerrank.com/challenges/cut-the-sticks)|Given the lengths of n sticks, print the number of sticks that are left before each cut operation.|[Python](cut-the-sticks.py)|Easy
[Non-Divisible Subset](https://www.hackerrank.com/challenges/non-divisible-subset)|Find the size of the maximal non-divisible subset.|[Python](non-divisible-subset.py)|Medium
[Repeated String](https://www.hackerrank.com/challenges/repeated-string)|Find and print the number of letter a's in the first n letters of an infinitely large periodic string.|[Python](repeated-string.py)|Easy
[Jumping on the Clouds](https://www.hackerrank.com/challenges/jumping-on-the-clouds)|Jumping on the clouds|[Python](jumping-on-the-clouds.py)|Easy
[Equalize the Array](https://www.hackerrank.com/challenges/equality-in-a-array)|Delete a minimal number of elements from an array so that all elements of the modified array are equal to one another.|[Python](equality-in-a-array.py)|Easy
[Queen's Attack II](https://www.hackerrank.com/challenges/queens-attack-2)|Find the number of squares the queen can attack.|[Python](queens-attack-2.py)|Medium
[ACM ICPC Team](https://www.hackerrank.com/challenges/acm-icpc-team)|Print the maximum topics a given team can cover for ACM ICPC World Finals|[Python](acm-icpc-team.py)|Easy
[Taum and B'day](https://www.hackerrank.com/challenges/taum-and-bday)|Calculate the minimum cost required to buy some amounts of two types of gifts when costs of each type and the rate of conversion from one form to another is provided.|[Python](taum-and-bday.py)|Easy
[Organizing Containers of Balls](https://www.hackerrank.com/challenges/organizing-containers-of-balls)|Determine if David can perform some sequence of swap operations such that each container holds one distinct type of ball.|[Python](organizing-containers-of-balls.py)|Medium
[Encryption](https://www.hackerrank.com/challenges/encryption)|Encrypt a string by arranging the characters of a string into a matrix and printing the resulting matrix column wise.|[Python](encryption.py)|Medium
[Bigger is Greater](https://www.hackerrank.com/challenges/bigger-is-greater)|Rearrange the letters of a string to construct another string such that the new string is lexicographically greater than the original.|[Python](bigger-is-greater.py)|Medium
[Modified Kaprekar Numbers](https://www.hackerrank.com/challenges/kaprekar-numbers)|Print kaprekar numbers in the given range|[Python](kaprekar-numbers.py)|Easy
[Beautiful Triplets](https://www.hackerrank.com/challenges/beautiful-triplets)||[Python](beautiful-triplets.py)|Easy
[Minimum Distances](https://www.hackerrank.com/challenges/minimum-distances)|Find the minimum distance between two different indices containing the same integers.|[Python](minimum-distances.py)|Easy
[Halloween Sale](https://www.hackerrank.com/challenges/halloween-sale)|How many games can you buy during the Halloween Sale?|[Python](halloween-sale.py)|Easy
[The Time in Words](https://www.hackerrank.com/challenges/the-time-in-words)|Display the time in words.|[Python](the-time-in-words.py)|Medium
[Chocolate Feast ](https://www.hackerrank.com/challenges/chocolate-feast)|Calculate the number of chocolates that can be bought following the given conditions.|[Python](chocolate-feast.py)|Easy
[Service Lane](https://www.hackerrank.com/challenges/service-lane)|Calculate the maximum width of the vehicle that can pass through a service lane.|[Python](service-lane.py)|Easy
[Lisa's Workbook](https://www.hackerrank.com/challenges/lisa-workbook)|A workbook with chapters. Some number of problems per page. How many problems have a number equal to a page's number?|[Python](lisa-workbook.py)|Easy
[Flatland Space Stations](https://www.hackerrank.com/challenges/flatland-space-stations)|Find the maximum distance an astronaut needs to travel to reach the nearest space station.|[Python](flatland-space-stations.py)|Easy
[Fair Rations](https://www.hackerrank.com/challenges/fair-rations)|How many loaves of bread will it take to feed your subjects?|[Python](fair-rations.py)|Easy
[Cavity Map](https://www.hackerrank.com/challenges/cavity-map)|Depict cavities on a square map|[C++](cavity-map.cpp)|Easy
[Manasa and Stones](https://www.hackerrank.com/challenges/manasa-and-stones)|Calculate the possible values of the last stone where consecutive values on the stones differ by a value 'a' or a value 'b'.|[Python](manasa-and-stones.py)|Easy
[The Grid Search](https://www.hackerrank.com/challenges/the-grid-search)|Given a 2D array of digits, try to find a given 2D grid pattern of digits within it.|[Python](the-grid-search.py)|Medium
[Happy Ladybugs](https://www.hackerrank.com/challenges/happy-ladybugs)|Determine whether or not all the ladybugs can be made happy.|[Python](happy-ladybugs.py)|Easy
[Strange Counter](https://www.hackerrank.com/challenges/strange-code)|Print the value displayed by the counter at a given time, $t$.|[Python](strange-code.py)|Easy
[Absolute Permutation](https://www.hackerrank.com/challenges/absolute-permutation)|Find lexicographically smallest absolute permutation.|[Python](absolute-permutation.py)|Medium
[Ema's Supercomputer](https://www.hackerrank.com/challenges/two-pluses)|Determine the product of the areas of two pluses on a grid.|[C++](two-pluses.cpp)|Medium
[Larry's Array](https://www.hackerrank.com/challenges/larrys-array)|Larry|[Python](larrys-array.py)|Medium
[Almost Sorted](https://www.hackerrank.com/challenges/almost-sorted)|Sort an array by either swapping or reversing a segment|[Python](almost-sorted.py)|Medium
[Matrix Layer Rotation ](https://www.hackerrank.com/challenges/matrix-rotation-algo)|Rotate the matrix R times and print the resultant matrix.|[Python](matrix-rotation-algo.py)|Hard
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Cats and a Mouse
# Which cat will catch the mouse first?
#
# https://www.hackerrank.com/challenges/cats-and-a-mouse/problem
#
#
# Complete the catAndMouse function below.
#
def catAndMouse(x, y, z):
#
# Write your code here.
#
if abs(x - z) == abs(y - z):
return "Mouse C"
if abs(x - z) < abs(y - z):
return "Cat A"
return "Cat B"
if __name__ == '__main__':
for _ in range(int(input())):
x, y, z = map(int, input().split())
print(catAndMouse(x, y, z))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Flatland Space Stations
# Find the maximum distance an astronaut needs to travel to reach the nearest space station.
#
# https://www.hackerrank.com/challenges/flatland-space-stations/problem
#
def flatlandSpaceStations(n, c):
# trie les space stations
sp = sorted(c)
# distence entre la première ville et la première station
# et distance entre la dernière ville et la dernière station
r = max(sp[0] - 0, n - 1 - sp[-1])
for i in range(1, len(sp)):
# le plus long chemin entre deux stations
r = max(r, (sp[i] - sp[i - 1]) // 2)
return r
if __name__ == "__main__":
n, m = map(int, input().split())
c = list(map(int, input().split()))
result = flatlandSpaceStations(n, c)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Find Digits
# Calculate the number of digits in an integer that evenly divide it.
#
# https://www.hackerrank.com/challenges/find-digits/problem
#
def findDigits(n):
# Complete this function
return sum(1 for d in str(n) if d != "0" and n % int(d) == 0)
if __name__ == "__main__":
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
result = findDigits(n)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Intro to Tutorial Challenges
# Introduction to the Tutorial Challenges
#
# https://www.hackerrank.com/challenges/tutorial-intro/problem
#
#
# dichotomie
#
def introTutorial(x, a):
first = 0
last = len(a) - 1
while first <= last:
i = (first + last) // 2
if a[i] == x:
return i
elif a[i] > x:
last = i - 1
else:
first = i + 1
return first
if __name__ == "__main__":
V = int(input())
n = int(input())
arr = list(map(int, input().split()))
result = introTutorial(V, arr)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Running Time of Algorithms
# The running time of Algorithms in general and Insertion Sort in particular.
#
# https://www.hackerrank.com/challenges/runningtime/problem
#
def runningTime(n, arr):
nb = 0
for i in range(1, n):
j = i
k = arr[i]
while j > 0 and k < arr[j - 1]:
arr[j] = arr[j - 1]
j -= 1
nb += 1
arr[j] = k
return nb
if __name__ == "__main__":
n = int(input().strip())
arr = list(map(int, input().strip().split(' ')))
result = runningTime(n, arr)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Insertion Sort - Part 1
# Insert an element into a sorted array.
#
# https://www.hackerrank.com/challenges/insertionsort1/problem
#
def insertionSort1(n, arr):
# Complete this function
e = arr[-1]
for i in range(len(arr) - 2, -1, -1):
if arr[i] < e:
arr[i + 1] = e
print(' '.join(map(str, arr)))
return
else:
arr[i + 1] = arr[i]
print(' '.join(map(str, arr)))
arr[0] = e
print(' '.join(map(str, arr)))
if __name__ == "__main__":
n = int(input())
arr = list(map(int, input().split()))
insertionSort1(n, arr)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Counting Sort 1
# Count the number of times each value appears.
#
# https://www.hackerrank.com/challenges/countingsort1/problem
#
def countingSort(arr):
# compte les occurences de arr[i] ∈ [0, 99]
counts = [0] * 100
for i in arr:
counts[i] += 1
return counts
if __name__ == "__main__":
n = int(input().strip())
arr = list(map(int, input().strip().split(' ')))
result = countingSort(arr)
print (" ".join(map(str, result)))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Insertion Sort Advanced Analysis
# How many shifts will it take Insertion Sort to sort an array?
#
# https://www.hackerrank.com/challenges/insertion-sort/problem
#
def insertionSort(arr):
bit = [0] * 10000001
bit_sum = 0
count = 0
for n in arr:
count += bit_sum
idx = n
while idx:
count -= bit[idx]
idx -= idx & -idx
idx = n
while idx < 10000001:
bit[idx] += 1
idx += idx & -idx
bit_sum += 1
return count
if __name__ == "__main__":
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
arr = list(map(int, input().strip().split(' ')))
result = insertionSort(arr)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Closest Numbers
# Find the closest numbers in a list.
#
# https://www.hackerrank.com/challenges/closest-numbers/problem
#
def closestNumbers(arr):
# Complete this function
arr = sorted(arr)
m = min(arr[i] - arr[i - 1] for i in range(1, len(arr)))
result = []
for i in range(1, len(arr)):
if arr[i] - arr[i - 1] == m:
result.append(arr[i - 1])
result.append(arr[i])
return result
if __name__ == "__main__":
n = int(input())
arr = list(map(int, input().split()))
result = closestNumbers(arr)
print(" ".join(map(str, result)))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Big Sorting
# Sort an array of very long numeric strings.
#
# https://www.hackerrank.com/challenges/big-sorting/problem
#
import functools
def entier(a, b):
la, lb = len(a), len(b)
if la < lb: return -1
if la > lb: return +1
if a < b: return -1
if a > b: return +1
return 0
if __name__ == "__main__":
n = int(input())
arr = list(input() for i in range(n))
for i in sorted(arr, key=functools.cmp_to_key(entier)):
print(i)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Quicksort 1 - Partition
# Perform the first step of Quicksort: partitioning an array.
#
# https://www.hackerrank.com/challenges/quicksort1/problem
#
def quickSort(arr):
# partitionne arr[] autour de pivot
pivot = arr[0]
left = []
right = []
for i in range(1, len(arr)):
if arr[i] < pivot:
left.append(arr[i])
elif arr[i] > pivot:
right.append(arr[i])
return left + [pivot] + right
if __name__ == "__main__":
n = int(input().strip())
arr = list(map(int, input().strip().split(' ')))
result = quickSort(arr)
print (" ".join(map(str, result)))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
add_hackerrank_py(big-sorting.py)
add_hackerrank_py(find-the-median.py)
add_hackerrank_py(insertion-sort.py)
add_hackerrank_py(countingsort1.py)
add_hackerrank_py(insertionsort2.py)
add_hackerrank_py(countingsort4.py)
add_hackerrank_py(tutorial-intro.py)
add_hackerrank_py(runningtime.py)
add_hackerrank(insertion-sort insertion-sort.cpp)
add_hackerrank_py(countingsort2.py)
add_hackerrank_py(insertionsort1.py)
add_hackerrank_py(closest-numbers.py)
add_hackerrank_py(quicksort1.py)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Insertion Sort Advanced Analysis
// How many shifts will it take Insertion Sort to sort an array?
//
// https://www.hackerrank.com/challenges/insertion-sort/problem
//
#include <iostream>
using namespace std;
const int N = 10000000;
int cnt[N + 1];
void add(int v)
{
while (v <= N)
{
cnt[v]++;
v += v & -v;
}
}
int get(int v)
{
int sum = 0;
while (v)
{
sum += cnt[v];
v -= v & -v;
}
return sum;
}
int main()
{
int T;
cin >> T;
while (T--)
{
int n;
cin >> n;
long long changes = 0;
for (int i = 0; i < n; i++)
{
int a;
cin >> a;
int cnt_larger = get(N) - get(a);
changes += cnt_larger;
add(a);
}
cout << changes << endl;
for (int i = 0; i <= N; i++)
cnt[i] = 0;
}
return 0;
} | {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Insertion Sort - Part 2
# Code Insertion Sort itself.
#
# https://www.hackerrank.com/challenges/insertionsort2/problem
#
def insertionSort2(n, arr):
for i in range(1, n):
j = i
while j > 0 and arr[i] < arr[j - 1]:
j -= 1
if j != i:
e = arr[i]
for k in range(i, j, -1):
arr[k] = arr[k - 1]
arr[j] = e
print(' '.join(map(str, arr)))
if __name__ == "__main__":
n = int(input().strip())
arr = list(map(int, input().strip().split(' ')))
insertionSort2(n, arr)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Counting Sort 2
# Simple version of counting sort.
#
# https://www.hackerrank.com/challenges/countingsort2/problem
#
def countingSort(arr):
# compte les occurences de x ∈ arr[]
counts = [0] * 100
for i in arr:
counts[i] += 1
# reconstruit arr[] en utilisant le nombre d'occurences
j = 0
for i, n in enumerate(counts):
while n > 0:
arr[j] = i
j += 1
n -= 1
return arr
if __name__ == "__main__":
n = int(input().strip())
arr = list(map(int, input().strip().split(' ')))
result = countingSort(arr)
print (" ".join(map(str, result)))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Find the Median
# Find the Median in a list of numbers.
#
# https://www.hackerrank.com/challenges/find-the-median/problem
#
def findMedian(arr):
# la valeur médiane est celle qui partage la liste triée en 2
return sorted(arr)[len(arr) // 2]
if __name__ == "__main__":
n = int(input().strip())
arr = list(map(int, input().strip().split(' ')))
result = findMedian(arr)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# The Full Counting Sort
# The real counting sort.
#
# https://www.hackerrank.com/challenges/countingsort4/problem
#
if __name__ == "__main__":
n = int(input())
# attention à la définition du tableau:
# [[]] * 100 crée un tableau de 100 fois le même objet [] !
counts = [[] for i in range(100)]
for i in range(n):
x, s = input().split()
if i < n // 2:
s = '-'
counts[int(x)].append(s)
def y():
for i in counts:
for j in i:
yield j
print(" ".join(y()))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Algorithms > Sorting > Correctness and the Loop Invariant
# How do you demonstrate the correctness of an algorithm? You can use the loop invariant.
#
# https://www.hackerrank.com/challenges/correctness-invariant/problem
#
def insertion_sort(l):
for i in range(1, len(l)):
j = i- 1
key = l[i]
while j >= 0 and l[j] > key:
l[j + 1] = l[j]
j -= 1
l[j+1] = key
# (template_tail) ----------------------------------------------------------------------
m = int(input().strip())
ar = [int(i) for i in input().strip().split()]
insertion_sort(ar)
print(" ".join(map(str,ar)))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
### [Algorithms](https://www.hackerrank.com/domains/algorithms)
The true test of problem solving: when one realizes that time and memory aren't infinite.
#### [Sorting](https://www.hackerrank.com/domains/algorithms/arrays-and-sorting)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Big Sorting](https://www.hackerrank.com/challenges/big-sorting)|Sort an array of very long numeric strings.|[Python](big-sorting.py)|Easy
[Intro to Tutorial Challenges](https://www.hackerrank.com/challenges/tutorial-intro)|Introduction to the Tutorial Challenges|[Python](tutorial-intro.py)|Easy
[Insertion Sort - Part 1](https://www.hackerrank.com/challenges/insertionsort1)|Insert an element into a sorted array.|[Python](insertionsort1.py)|Easy
[Insertion Sort - Part 2](https://www.hackerrank.com/challenges/insertionsort2)|Code Insertion Sort itself.|[Python](insertionsort2.py)|Easy
[Correctness and the Loop Invariant](https://www.hackerrank.com/challenges/correctness-invariant)|How do you demonstrate the correctness of an algorithm? You can use the loop invariant.|[Python](correctness-invariant.py)|Easy
[Running Time of Algorithms](https://www.hackerrank.com/challenges/runningtime)|The running time of Algorithms in general and Insertion Sort in particular.|[Python](runningtime.py)|Easy
[Quicksort 1 - Partition](https://www.hackerrank.com/challenges/quicksort1)|Perform the first step of Quicksort: partitioning an array.|[Python](quicksort1.py)|Easy
[Counting Sort 1](https://www.hackerrank.com/challenges/countingsort1)|Count the number of times each value appears.|[Python](countingsort1.py)|Easy
[Counting Sort 2](https://www.hackerrank.com/challenges/countingsort2)|Simple version of counting sort.|[Python](countingsort2.py)|Easy
[The Full Counting Sort](https://www.hackerrank.com/challenges/countingsort4)|The real counting sort.|[Python](countingsort4.py)|Medium
[Closest Numbers](https://www.hackerrank.com/challenges/closest-numbers)|Find the closest numbers in a list.|[Python](closest-numbers.py)|Easy
[Find the Median](https://www.hackerrank.com/challenges/find-the-median)|Find the Median in a list of numbers.|[Python](find-the-median.py)|Easy
[Insertion Sort Advanced Analysis](https://www.hackerrank.com/challenges/insertion-sort)|How many shifts will it take Insertion Sort to sort an array?|[C++](insertion-sort.cpp) [Python](insertion-sort.py)|Advanced
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Marc's Cakewalk
# Find the minimum number of miles Marc must walk to burn the calories consumed from eating cupcakes.
#
# https://www.hackerrank.com/challenges/marcs-cakewalk/problem
#
def marcsCakewalk(calorie):
# Complete this function
c = 0
p = 1
for i in sorted(calorie, reverse=True):
c += p * i
p *= 2
return c
if __name__ == "__main__":
n = int(input().strip())
calorie = list(map(int, input().strip().split(' ')))
result = marcsCakewalk(calorie)
print(result) | {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Algorithms > Greedy > Minimum Absolute Difference in an Array
# Given a list of integers, calculate their differences and find the difference with the smallest absolute value.
#
# https://www.hackerrank.com/challenges/minimum-absolute-difference-in-an-array/problem
#
def minimumAbsoluteDifference(n, arr):
# différence minimale entre deux entiers consécutifs de la liste ordonnée
arr = sorted(arr)
return min(abs(arr[i] - arr[i + 1]) for i in range(n - 1))
if __name__ == "__main__":
n = int(input().strip())
arr = list(map(int, input().strip().split(' ')))
result = minimumAbsoluteDifference(n, arr)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Beautiful Pairs
# Change an element of B and calculate the number of pairwise disjoint beautiful pairs.
#
# https://www.hackerrank.com/challenges/beautiful-pairs/problem
#
def beautifulPairs(A, B):
# compte les nombres de A
n = [0] * 1001
for i in A:
n[i] += 1
# compare avec les nombres de B et compte
pairs = 0
for i in B:
if n[i] > 0:
n[i] -= 1
pairs += 1
# si tous les nombres sont en paire (A==B)
# il faut sacrifier un nombre (cf. énoncé)
# sinon, on peut gagner une paire
if pairs == len(B):
pairs -= 1
else:
pairs += 1
return pairs
if __name__ == "__main__":
n = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
result = beautifulPairs(A, B)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Maximum Perimeter Triangle
// Find the triangle having the maximum perimeter.
//
// https://www.hackerrank.com/challenges/maximum-perimeter-triangle/problem
//
#include <bits/stdc++.h>
using namespace std;
void maximumPerimeterTriangle(vector<int> l)
{
if (l.size() >= 3)
{
std::sort(l.begin(), l.end(), [](int a, int b) -> bool { return a > b; });
// sélectionne les 3 plus grands nombres qui forment un triangle non aplati
// 1 1 3 : pas de triangle
// 1 2 3 : triangle aplati
// 1 3 3 : ok
for (size_t i = 0; i < l.size() - 2; ++i)
{
if (l[i] < l[i + 1] + l[i + 2])
{
cout << l[i + 2] << " " << l[i + 1] << " " << l[i] << endl;
return;
}
}
}
cout << "-1" << endl;
}
int main()
{
size_t n;
cin >> n;
vector<int> l(n);
for(size_t l_i = 0; l_i < n; l_i++)
{
cin >> l[l_i];
}
maximumPerimeterTriangle(l);
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
add_hackerrank_py(marcs-cakewalk.py)
add_hackerrank_py(grid-challenge.py)
add_hackerrank_py(beautiful-pairs.py)
add_hackerrank(maximum-perimeter-triangle maximum-perimeter-triangle.cpp)
add_hackerrank_py(sherlock-and-the-beast.py)
add_hackerrank_py(minimum-absolute-difference-in-an-array.py)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Sherlock and The Beast
# Find the largest number following some rules having N digits.
#
# https://www.hackerrank.com/challenges/sherlock-and-the-beast/problem
#
t = int(input())
for _ in range(t):
n = int(input())
# The number of 3's it contains is divisible by 5.
# The number of 5's it contains is divisible by 3.
# on essaie avec n chiffres 5 et on diminue
# tant que la propriété (3) n'est pas vérifiée
m = n
while m % 3 != 0:
m -= 5
if m < 0:
print("-1")
else:
print("5" * m + "3" * (n - m))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Grid Challenge
# Find if it is possible to rearrange a square grid such that every
# row and every column is lexicographically sorted.
#
# https://www.hackerrank.com/challenges/grid-challenge/problem
#
def gridChallenge(n, grid):
for i in range(n):
for j in range(n - 1):
if grid[j][i] > grid[j + 1][i]:
return "NO"
return "YES"
if __name__ == "__main__":
t = int(input())
for _ in range(t):
n = int(input())
grid = []
for _ in range(n):
grid.append(sorted(input()))
result = gridChallenge(n, grid)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
### [Algorithms](https://www.hackerrank.com/domains/algorithms)
The true test of problem solving: when one realizes that time and memory aren't infinite.
#### [Greedy](https://www.hackerrank.com/domains/algorithms/greedy)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Minimum Absolute Difference in an Array](https://www.hackerrank.com/challenges/minimum-absolute-difference-in-an-array)|Given a list of integers, calculate their differences and find the difference with the smallest absolute value.|[Python](minimum-absolute-difference-in-an-array.py)|Easy
[Marc's Cakewalk](https://www.hackerrank.com/challenges/marcs-cakewalk)|Find the minimum number of miles Marc must walk to burn the calories consumed from eating cupcakes.|[Python](marcs-cakewalk.py)|Easy
[Grid Challenge](https://www.hackerrank.com/challenges/grid-challenge)|Find if it is possible to rearrange a square grid such that every row and every column is lexicographically sorted.|[Python](grid-challenge.py)|Easy
[Maximum Perimeter Triangle](https://www.hackerrank.com/challenges/maximum-perimeter-triangle)|Find the triangle having the maximum perimeter.|[C++](maximum-perimeter-triangle.cpp)|Easy
[Beautiful Pairs](https://www.hackerrank.com/challenges/beautiful-pairs)|Change an element of B and calculate the number of pairwise disjoint beautiful pairs.|[Python](beautiful-pairs.py)|Easy
[Sherlock and The Beast](https://www.hackerrank.com/challenges/sherlock-and-the-beast)|Find the largest number following some rules having N digits.|[Python](sherlock-and-the-beast.py)|Easy
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Algorithms > Warmup > Solve Me First
// This is an easy challenge to help you start coding in your favorite languages!
//
// https://www.hackerrank.com/challenges/solve-me-first/problem
// challenge id: 2532
//
process.stdin.resume();
process.stdin.setEncoding('ascii');
var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;
process.stdin.on('data', function (data) {
input_stdin += data;
});
process.stdin.on('end', function () {
input_stdin_array = input_stdin.split("\n");
main();
});
function readLine() {
return input_stdin_array[input_currentline++];
}
function solveMeFirst(a, b) {
// Hint: Type return a+b below
return a + b;
}
function main() {
var a = parseInt(readLine());
var b = parseInt(readLine());;
var res = solveMeFirst(a, b);
console.log(res);
} | {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
"""
Mini-Max Sum
https://www.hackerrank.com/challenges/mini-max-sum/problem
"""
def miniMaxSum(arr):
# Complete this function
arr = sorted(arr)
print(sum(arr[0:4]), sum(arr[1:5]))
if __name__ == "__main__":
arr = list(map(int, input().strip().split(' ')))
miniMaxSum(arr)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Algorithms > Warmup > Solve Me First
# This is an easy challenge to help you start coding in your favorite languages!
#
# https://www.hackerrank.com/challenges/solve-me-first/problem
# challenge id: 2532
#
def solveMeFirst(a, b):
return a + b
num1 = int(input())
num2 = int(input())
res = solveMeFirst(num1, num2)
print(res)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
-- Algorithms > Warmup > Solve Me First
-- This is an easy challenge to help you start coding in your favorite languages!
--
-- https://www.hackerrank.com/challenges/solve-me-first/problem
-- challenge id: 2532
--
solveMeFirst a b = a + b
-- (template_tail) ----------------------------------------------------------------------
main = do
val1 <- readLn
val2 <- readLn
let sum = solveMeFirst val1 val2
print sum
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
"""
Diagonal Difference
https://www.hackerrank.com/challenges/diagonal-difference/problem
"""
import sys
def diagonalDifference(a):
# Complete this function
n = len(a)
return abs(sum(a[x][x] for x in range(n)) - sum(a[x][n - x - 1] for x in range(n)))
if __name__ == "__main__":
n = int(input().strip())
a = []
for a_i in range(n):
a_t = [int(a_temp) for a_temp in input().strip().split(' ')]
a.append(a_t)
result = diagonalDifference(a)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Algorithms > Warmup > Simple Array Sum
# Calculate the sum of integers in an array.
#
# https://www.hackerrank.com/challenges/simple-array-sum/problem
#
#
# Complete the simpleArraySum function below.
#
def simpleArraySum(ar):
#
# Write your code here.
#
return sum(ar)
if __name__ == '__main__':
ar_count = int(input())
ar = list(map(int, input().rstrip().split()))
result = simpleArraySum(ar)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
"""
Staircase
https://www.hackerrank.com/challenges/staircase/problem
"""
import sys
def staircase(n):
# Complete this function
for i in range(1, n + 1):
print(" " * (n - i) + "#" * i)
if __name__ == "__main__":
n = int(input().strip())
staircase(n)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
"""
A Very Big Sum
https://www.hackerrank.com/challenges/a-very-big-sum/problem
"""
def aVeryBigSum(n, ar):
return sum(ar)
n = int(input().strip())
ar = list(map(int, input().strip().split(' ')))
result = aVeryBigSum(n, ar)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
add_hackerrank(solve-me-first solve-me-first.cpp)
add_hackerrank_py(mini-max-sum.py)
add_hackerrank(simple-array-sum simple-array-sum.cpp)
add_hackerrank(compare-the-triplets compare-the-triplets.cpp)
add_hackerrank_py(plus-minus.py)
add_hackerrank_py(time-conversion.py)
add_hackerrank_py(birthday-cake-candles.py)
add_hackerrank_py(diagonal-difference.py)
add_hackerrank_py(a-very-big-sum.py)
add_hackerrank_py(staircase.py)
add_hackerrank_py(simple-array-sum.py)
add_hackerrank_py(compare-the-triplets.py)
add_hackerrank_py(solve-me-first.py)
add_hackerrank_java(solve-me-first.java)
#add_hackerrank_hs(solve-me-first.hs)
add_hackerrank_shell(solve-me-first.sh)
add_hackerrank_js(solve-me-first.js)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
"""
Birthday Cake Candles
https://www.hackerrank.com/challenges/birthday-cake-candles/problem
"""
import sys
def birthdayCakeCandles(n, ar):
# Complete this function
# en 1 passage
nb = 0
m = 0
for i in ar:
if m == i:
nb += 1
elif m < i:
nb = 1
m = i
return nb
# plus lent (2 passages)
#m = max(ar)
#return sum(1 for i in ar if i == m)
n = int(input().strip())
ar = list(map(int, input().strip().split(' ')))
result = birthdayCakeCandles(n, ar)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Algorithms > Warmup > Solve Me First
// This is an easy challenge to help you start coding in your favorite languages!
//
// https://www.hackerrank.com/challenges/solve-me-first/problem
// challenge id: 2532
//
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int solveMeFirst(int a, int b) {
// Hint: Type return a+b; below
return a + b;
}
int main() {
int num1, num2;
int sum;
cin>>num1>>num2;
sum = solveMeFirst(num1,num2);
cout<<sum;
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Algorithms > Warmup > Solve Me First
# This is an easy challenge to help you start coding in your favorite languages!
#
# https://www.hackerrank.com/challenges/solve-me-first/problem
# challenge id: 2532
#
read a
read b
echo $(($a + $b))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Algorithms > Warmup > Compare the Triplets
# Compare the elements in two triplets.
#
# https://www.hackerrank.com/challenges/compare-the-triplets/problem
#
a = map(int, input().split())
b = map(int, input().split())
alice, bob = 0, 0
for i, j in zip(a, b):
if i > j:
alice += 1
elif i < j:
bob += 1
print(alice, bob)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// https://www.hackerrank.com/challenges/compare-the-triplets/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 alice[3], bob[3];
int a = 0, b = 0;
for (int i = 0; i < 3; ++i) cin >> alice[i];
for (int i = 0; i < 3; ++i) cin >> bob[i];
for (int i = 0; i < 3; ++i) {
if (alice[i] > bob[i]) a++;
if (alice[i] < bob[i]) b++;
}
cout << a << " " << b << endl;
return 0;
} | {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Algorithms > Warmup > Solve Me First
// This is an easy challenge to help you start coding in your favorite languages!
//
// https://www.hackerrank.com/challenges/solve-me-first/problem
// challenge id: 2532
//
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static int solveMeFirst(int a, int b) {
// Hint: Type return a+b; below
return a + b;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a = in.nextInt();
int b = in.nextInt();
int sum = solveMeFirst(a, b);
System.out.println(sum);
in.close();
}
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
"""
Plus Minus
https://www.hackerrank.com/challenges/plus-minus/problem
"""
import sys
def plusMinus(arr):
# Complete this function
negatif = positif = zero = 0
for i in arr:
if i < 0:
negatif += 1
elif i > 0:
positif += 1
else:
zero += 1
print("%.06f" % (positif / len(arr)))
print("%.06f" % (negatif / len(arr)))
print("%.06f" % (zero / len(arr)))
if __name__ == "__main__":
n = int(input().strip())
arr = list(map(int, input().strip().split(' ')))
plusMinus(arr)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
### [Algorithms](https://www.hackerrank.com/domains/algorithms)
The true test of problem solving: when one realizes that time and memory aren't infinite.
#### [Warmup](https://www.hackerrank.com/domains/algorithms/warmup)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Solve Me First](https://www.hackerrank.com/challenges/solve-me-first)|This is an easy challenge to help you start coding in your favorite languages!|[C++](solve-me-first.cpp) [Haskell](solve-me-first.hs) [Java](solve-me-first.java) [Javascript](solve-me-first.js) [Python](solve-me-first.py) [bash](solve-me-first.sh)|Easy
[Simple Array Sum](https://www.hackerrank.com/challenges/simple-array-sum)|Calculate the sum of integers in an array.|[C++](simple-array-sum.cpp) [Python](simple-array-sum.py)|Easy
[Compare the Triplets](https://www.hackerrank.com/challenges/compare-the-triplets)|Compare the elements in two triplets.|[C++](compare-the-triplets.cpp) [Python](compare-the-triplets.py)|Easy
[A Very Big Sum](https://www.hackerrank.com/challenges/a-very-big-sum)|Calculate the sum of the values in an array that might exceed the range of int values.|[Python](a-very-big-sum.py)|Easy
[Diagonal Difference](https://www.hackerrank.com/challenges/diagonal-difference)|Calculate the absolute difference of sums across the two diagonals of a square matrix.|[Python](diagonal-difference.py)|Easy
[Plus Minus](https://www.hackerrank.com/challenges/plus-minus)|Calculate the fraction of positive, negative and zero values in an array.|[Python](plus-minus.py)|Easy
[Staircase](https://www.hackerrank.com/challenges/staircase)|Print a right-aligned staircase with n steps.|[Python](staircase.py)|Easy
[Mini-Max Sum](https://www.hackerrank.com/challenges/mini-max-sum)|Find the maximum and minimum values obtained by summing four of five integers.|[Python](mini-max-sum.py)|Easy
[Birthday Cake Candles](https://www.hackerrank.com/challenges/birthday-cake-candles)|Determine the number of candles that are blown out.|[Python](birthday-cake-candles.py)|Easy
[Time Conversion](https://www.hackerrank.com/challenges/time-conversion)|Convert time from an AM/PM format to a 24 hour format.|[Python](time-conversion.py)|Easy
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
"""
Time Conversion
https://www.hackerrank.com/challenges/time-conversion/problem
"""
#!/bin/python3
import sys
def timeConversion(s):
# Complete this function
if s[-2:] == "AM":
# Midnight is 12:00:00AM on a 12-hour clock
if s[0:2] == "12":
return "00" + s[2:-2]
else:
return s[:-2]
else:
if s[0:2] == "12":
# Noon is 12:00:00PM on a 12-hour clock
return s[:-2]
else:
return str(int(s[0:2]) + 12) + s[2:-2]
s = input().strip()
result = timeConversion(s)
print(result)
# https://hr-testcases-us-east-1.s3.amazonaws.com/8649/input01.txt?AWSAccessKeyId=AKIAJ4WZFDFQTZRGO3QA&Expires=1520786241&Signature=aX4vtcdHadsUyNtWQJkKmRgaOh4%3D&response-content-type=text%2Fplain
# https://hr-testcases-us-east-1.s3.amazonaws.com/8649/output01.txt?AWSAccessKeyId=AKIAJ4WZFDFQTZRGO3QA&Expires=1520786253&Signature=SaxZKgqVjMLgK2v%2BHbWTNiogr98%3D&response-content-type=text%2Fplain
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// https://www.hackerrank.com/challenges/simple-array-sum/problem
//#include <bits/stdc++.h>
#include <iostream>
#include <vector>
using namespace std;
int simpleArraySum(size_t, vector <int> ar) {
// Complete this function
int sum = 0;
for (auto i : ar) sum += i;
return sum;
}
int main() {
size_t n;
cin >> n;
vector<int> ar(n);
for(size_t ar_i = 0; ar_i < n; ar_i++){
cin >> ar[ar_i];
}
int result = simpleArraySum(n, ar);
cout << result << endl;
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Game of Stones
# A Game of Stones
#
# https://www.hackerrank.com/challenges/game-of-stones-1/problem
#
def gameOfStones(n):
# Complete this function
return "Second" if n % 7 <= 1 else "First"
if __name__ == "__main__":
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
result = gameOfStones(n)
print(result)
"""
It's proof by induction.
The hypothesis:
For n % 7 in [0, 1], the first player loses, otherwise the first player wins.
The anchor:
Clearly, for 0 or 1 stones, the first player has no move, so he loses.
For any of 2, 3, 4, 5, or 6 stones, the first player can make a move that leaves 0 or 1 stones for the second player, so the first player wins.
Induction step:
Now, for a given starting position n we assume that our hypothesis is true for all m < n.
If n % 7 in [0, 1], we can only leave the second player with positions (n - 2) % 7 in [5, 6], (n - 3) % 7 in [4, 5], or (n - 5) % 7 = [2, 3], all of which mean – by induction – that the second player will be in a winning position. Thus, for n % 7 in [0, 1], the first player loses.
If n % 7 in [2, 3, 4, 5, 6], there's always a move to leave the second player with an m % 7 in [0, 1], thus – again by induction – forcing a loss on the second player, leaving the first player to win.
That concludes the proof.
The invariant is, that once a player A can force [0, 1] on player B, A can keep forcing that position, while B cannot force it on A.
"""
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
add_hackerrank_py(game-of-stones-1.py)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
### [Algorithms](https://www.hackerrank.com/domains/algorithms)
The true test of problem solving: when one realizes that time and memory aren't infinite.
#### [Game Theory](https://www.hackerrank.com/domains/algorithms/game-theory)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Game of Stones](https://www.hackerrank.com/challenges/game-of-stones-1)|A Game of Stones|[Python](game-of-stones-1.py)|Easy
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
add_subdirectory(py-introduction)
add_subdirectory(py-date-time)
add_subdirectory(py-itertools)
add_subdirectory(py-sets)
add_subdirectory(closures-and-decorators)
add_subdirectory(py-basic-data-types)
add_subdirectory(py-classes)
add_subdirectory(py-built-ins)
add_subdirectory(py-functionals)
add_subdirectory(py-math)
add_subdirectory(py-strings)
add_subdirectory(errors-exceptions)
add_subdirectory(py-collections)
add_subdirectory(py-regex)
add_subdirectory(xml)
add_subdirectory(numpy)
add_subdirectory(py-debugging)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
### [Python](https://www.hackerrank.com/domains/python)
A step by step guide to Python, a language that is easy to pick up yet one of the most powerful.
#### [Introduction](https://www.hackerrank.com/domains/python/py-introduction)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Say "Hello, World!" With Python](https://www.hackerrank.com/challenges/py-hello-world)|Get started with Python by printing to stdout.|[Python](py-introduction/py-hello-world.py)|Easy
[Python If-Else](https://www.hackerrank.com/challenges/py-if-else)|Practice using if-else conditional statements!|[Python](py-introduction/py-if-else.py)|Easy
[Arithmetic Operators](https://www.hackerrank.com/challenges/python-arithmetic-operators)|Addition, subtraction and multiplication.|[Python](py-introduction/python-arithmetic-operators.py)|Easy
[Python: Division](https://www.hackerrank.com/challenges/python-division)|Division using __future__ module.|[Python](py-introduction/python-division.py)|Easy
[Loops](https://www.hackerrank.com/challenges/python-loops)|Practice using "for" and "while" loops in Python.|[Python](py-introduction/python-loops.py)|Easy
[Write a function](https://www.hackerrank.com/challenges/write-a-function)|Write a function to check if the given year is leap or not|[Python](py-introduction/write-a-function.py)|Medium
[Print Function](https://www.hackerrank.com/challenges/python-print)|Learn to use print as a function|[Python](py-introduction/python-print.py)|Easy
#### [Basic Data Types](https://www.hackerrank.com/domains/python/py-basic-data-types)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Lists](https://www.hackerrank.com/challenges/python-lists)|Perform different list operations.|[Python](py-basic-data-types/python-lists.py)|Easy
[Tuples ](https://www.hackerrank.com/challenges/python-tuples)|Learn about tuples and compute hash(T).|[Python](py-basic-data-types/python-tuples.py)|Easy
[List Comprehensions](https://www.hackerrank.com/challenges/list-comprehensions)|You will learn about list comprehensions.|[Python](py-basic-data-types/list-comprehensions.py)|Easy
[Find the Runner-Up Score! ](https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list)|For a given list of numbers, find the second largest number.|[Python](py-basic-data-types/find-second-maximum-number-in-a-list.py)|Easy
[Nested Lists](https://www.hackerrank.com/challenges/nested-list)|In a classroom of N students, find the student with the second lowest grade.|[Python](py-basic-data-types/nested-list.py)|Easy
[Finding the percentage](https://www.hackerrank.com/challenges/finding-the-percentage)|Store a list of students and marks in a dictionary, and find the average marks obtained by a student.|[Python](py-basic-data-types/finding-the-percentage.py)|Easy
#### [Strings](https://www.hackerrank.com/domains/python/py-strings)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[sWAP cASE](https://www.hackerrank.com/challenges/swap-case)|Swap the letter cases of a given string.|[Python](py-strings/swap-case.py)|Easy
[String Split and Join](https://www.hackerrank.com/challenges/python-string-split-and-join)|Use Python's split and join methods on the input string.|[Python](py-strings/python-string-split-and-join.py)|Easy
[What's Your Name?](https://www.hackerrank.com/challenges/whats-your-name)|Python string practice: Print your name in the console.|[Python](py-strings/whats-your-name.py)|Easy
[Mutations](https://www.hackerrank.com/challenges/python-mutations)|Understand immutable vs mutable by making changes to a given string.|[Python](py-strings/python-mutations.py)|Easy
[Find a string](https://www.hackerrank.com/challenges/find-a-string)|Find the number of occurrences of a substring in a string.|[Python](py-strings/find-a-string.py)|Easy
[String Validators](https://www.hackerrank.com/challenges/string-validators)|Identify the presence of alphanumeric characters, alphabetical characters, digits, lowercase and uppercase characters in a string.|[Python](py-strings/string-validators.py)|Easy
[Text Alignment](https://www.hackerrank.com/challenges/text-alignment)|Generate the Hackerrank logo with alignments in Python.|[Python](py-strings/text-alignment.py)|Easy
[Text Wrap](https://www.hackerrank.com/challenges/text-wrap)|Wrap the given text in a fixed width.|[Python](py-strings/text-wrap.py)|Easy
[Designer Door Mat](https://www.hackerrank.com/challenges/designer-door-mat)|Print a designer door mat.|[Python](py-strings/designer-door-mat.py)|Easy
[String Formatting](https://www.hackerrank.com/challenges/python-string-formatting)|Print the formatted decimal, octal, hexadecimal, and binary values for $n$ integers.|[Python](py-strings/python-string-formatting.py)|Easy
[Alphabet Rangoli](https://www.hackerrank.com/challenges/alphabet-rangoli)|Let's draw rangoli.|[Python](py-strings/alphabet-rangoli.py)|Easy
[Capitalize!](https://www.hackerrank.com/challenges/capitalize)|Capitalize Each Word.|[Python](py-strings/capitalize.py)|Easy
[The Minion Game](https://www.hackerrank.com/challenges/the-minion-game)|Given a string, judge the winner of the minion game.|[Python](py-strings/the-minion-game.py)|Medium
[Merge the Tools!](https://www.hackerrank.com/challenges/merge-the-tools)|Split a string into subsegments of length $k$, then print each subsegment with any duplicate characters stripped out.|[Python](py-strings/merge-the-tools.py)|Medium
#### [Sets](https://www.hackerrank.com/domains/python/py-sets)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Introduction to Sets](https://www.hackerrank.com/challenges/py-introduction-to-sets)|Use the set tool to compute the average.|[Python](py-sets/py-introduction-to-sets.py)|Easy
[Symmetric Difference](https://www.hackerrank.com/challenges/symmetric-difference)|Learn about sets as a data type.|[Python](py-sets/symmetric-difference.py)|Easy
[No Idea!](https://www.hackerrank.com/challenges/no-idea)|Compute your happiness.|[Python](py-sets/no-idea.py)|Medium
[Set .add() ](https://www.hackerrank.com/challenges/py-set-add)|Add elements to set.|[Python](py-sets/py-set-add.py)|Easy
[Set .discard(), .remove() & .pop()](https://www.hackerrank.com/challenges/py-set-discard-remove-pop)|Different ways to omit set elements.|[Python](py-sets/py-set-discard-remove-pop.py)|Easy
[Set .union() Operation](https://www.hackerrank.com/challenges/py-set-union)|Use the .union() operator to determine the number of students.|[Python](py-sets/py-set-union.py)|Easy
[Set .intersection() Operation](https://www.hackerrank.com/challenges/py-set-intersection-operation)|Use the .intersection() operator to determine the number of same students in both sets.|[Python](py-sets/py-set-intersection-operation.py)|Easy
[Set .difference() Operation](https://www.hackerrank.com/challenges/py-set-difference-operation)|Use the .difference() operator to check the differences between sets.|[Python](py-sets/py-set-difference-operation.py)|Easy
[Set .symmetric_difference() Operation](https://www.hackerrank.com/challenges/py-set-symmetric-difference-operation)|Making symmetric difference of sets.|[Python](py-sets/py-set-symmetric-difference-operation.py)|Easy
[Set Mutations](https://www.hackerrank.com/challenges/py-set-mutations)|Using various operations, change the content of a set and output the new sum.|[Python](py-sets/py-set-mutations.py)|Easy
[The Captain's Room ](https://www.hackerrank.com/challenges/py-the-captains-room)|Out of a list of room numbers, determine the number of the captain's room.|[Python](py-sets/py-the-captains-room.py)|Easy
[Check Subset](https://www.hackerrank.com/challenges/py-check-subset)|Verify if set A is a subset of set B.|[Python](py-sets/py-check-subset.py)|Easy
[Check Strict Superset](https://www.hackerrank.com/challenges/py-check-strict-superset)|Check if A is a strict superset of the other given sets.|[Python](py-sets/py-check-strict-superset.py)|Easy
#### [Math](https://www.hackerrank.com/domains/python/py-math)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Polar Coordinates](https://www.hackerrank.com/challenges/polar-coordinates)|Convert complex numbers to polar coordinates|[Python](py-math/polar-coordinates.py)|Easy
[Find Angle MBC](https://www.hackerrank.com/challenges/find-angle)|Find the desired angle in the right triangle.|[Python](py-math/find-angle.py)|Medium
[Triangle Quest 2](https://www.hackerrank.com/challenges/triangle-quest-2)|Create a palindromic triangle.|[Python](py-math/triangle-quest-2.py)|Medium
[Mod Divmod](https://www.hackerrank.com/challenges/python-mod-divmod)|Get the quotient and remainder using the divmod operator in Python.|[Python](py-math/python-mod-divmod.py)|Easy
[Power - Mod Power](https://www.hackerrank.com/challenges/python-power-mod-power)|Perform modular exponentiation in Python.|[Python](py-math/python-power-mod-power.py)|Easy
[Integers Come In All Sizes](https://www.hackerrank.com/challenges/python-integers-come-in-all-sizes)|Exercises with big integers in Python.|[Python](py-math/python-integers-come-in-all-sizes.py)|Easy
[Triangle Quest](https://www.hackerrank.com/challenges/python-quest-1)|Print a numeric triangle of height N-1 using only 2 lines.|[Python](py-math/python-quest-1.py)|Medium
#### [Itertools](https://www.hackerrank.com/domains/python/py-itertools)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[itertools.product()](https://www.hackerrank.com/challenges/itertools-product)|Find the cartesian product of 2 sets.|[Python](py-itertools/itertools-product.py)|Easy
[itertools.permutations()](https://www.hackerrank.com/challenges/itertools-permutations)|Find all permutations of a given size in a given string.|[Python](py-itertools/itertools-permutations.py)|Easy
[itertools.combinations()](https://www.hackerrank.com/challenges/itertools-combinations)|Print all the combinations of a string using itertools.|[Python](py-itertools/itertools-combinations.py)|Easy
[itertools.combinations_with_replacement()](https://www.hackerrank.com/challenges/itertools-combinations-with-replacement)|Find all the combinations of a string with replacements.|[Python](py-itertools/itertools-combinations-with-replacement.py)|Easy
[Compress the String! ](https://www.hackerrank.com/challenges/compress-the-string)|groupby()|[Python](py-itertools/compress-the-string.py)|Medium
[Iterables and Iterators](https://www.hackerrank.com/challenges/iterables-and-iterators)|Find the probability using itertools.|[Python](py-itertools/iterables-and-iterators.py)|Medium
[Maximize It!](https://www.hackerrank.com/challenges/maximize-it)|Find the maximum possible value out of the equation provided.|[Python](py-itertools/maximize-it.py)|Hard
#### [Collections](https://www.hackerrank.com/domains/python/py-collections)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[collections.Counter()](https://www.hackerrank.com/challenges/collections-counter)|Use a counter to sum the amount of money earned by the shoe shop owner.|[Python](py-collections/collections-counter.py)|Easy
[DefaultDict Tutorial](https://www.hackerrank.com/challenges/defaultdict-tutorial)|Create dictionary value fields with predefined data types.|[Python](py-collections/defaultdict-tutorial.py)|Easy
[Collections.namedtuple()](https://www.hackerrank.com/challenges/py-collections-namedtuple)|You need to turn tuples into convenient containers using collections.namedtuple().|[Python](py-collections/py-collections-namedtuple.py)|Easy
[Collections.OrderedDict()](https://www.hackerrank.com/challenges/py-collections-ordereddict)|Print a dictionary of items that retains its order.|[Python](py-collections/py-collections-ordereddict.py)|Easy
[Word Order](https://www.hackerrank.com/challenges/word-order)|List the number of occurrences of the words in order.|[Python](py-collections/word-order.py)|Medium
[Collections.deque()](https://www.hackerrank.com/challenges/py-collections-deque)|Perform multiple operations on a double-ended queue or deque.|[Python](py-collections/py-collections-deque.py)|Easy
[Piling Up!](https://www.hackerrank.com/challenges/piling-up)|Create a vertical pile of cubes.|[Python](py-collections/piling-up.py)|Medium
[Company Logo](https://www.hackerrank.com/challenges/most-commons)|Print the number of character occurrences in descending order.|[Python](py-collections/most-commons.py)|Medium
#### [Date and Time](https://www.hackerrank.com/domains/python/py-date-time)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Calendar Module](https://www.hackerrank.com/challenges/calendar-module)|Print the day of a given date.|[Python](py-date-time/calendar-module.py)|Easy
[Time Delta](https://www.hackerrank.com/challenges/python-time-delta)|Find the absolute time difference.|[Python](py-date-time/python-time-delta.py)|Medium
#### [Errors and Exceptions](https://www.hackerrank.com/domains/python/errors-exceptions)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Exceptions](https://www.hackerrank.com/challenges/exceptions)|Handle errors detected during execution.|[Python](errors-exceptions/exceptions.py)|Easy
[Incorrect Regex](https://www.hackerrank.com/challenges/incorrect-regex)|Check whether the regex is valid or not.|[Python](errors-exceptions/incorrect-regex.py)|Easy
#### [Classes](https://www.hackerrank.com/domains/python/py-classes)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Classes: Dealing with Complex Numbers](https://www.hackerrank.com/challenges/class-1-dealing-with-complex-numbers)|Create a new data type for complex numbers.|[Python](py-classes/class-1-dealing-with-complex-numbers.py)|Medium
[Class 2 - Find the Torsional Angle](https://www.hackerrank.com/challenges/class-2-find-the-torsional-angle)|Find the angle between two planes.|[Python](py-classes/class-2-find-the-torsional-angle.py)|Easy
#### [Built-Ins](https://www.hackerrank.com/domains/python/py-built-ins)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Zipped!](https://www.hackerrank.com/challenges/zipped)|Compute the average by zipping data.|[Python](py-built-ins/zipped.py)|Easy
[Input()](https://www.hackerrank.com/challenges/input)|A Python 2 challenge: Input() is equivalent to eval(raw_input(prompt)).|[Python](py-built-ins/input.py)|Easy
[Python Evaluation](https://www.hackerrank.com/challenges/python-eval)|Evaluate the expressions in Python using the expression eval().|[Python](py-built-ins/python-eval.py)|Easy
[Athlete Sort](https://www.hackerrank.com/challenges/python-sort-sort)|Sort the table on the kth attribute.|[Python](py-built-ins/python-sort-sort.py)|Medium
[Any or All](https://www.hackerrank.com/challenges/any-or-all)|Return True, if any of the iterable is true or if all of it is true using the any() and all() expressions.|[Python](py-built-ins/any-or-all.py)|Easy
[ginortS](https://www.hackerrank.com/challenges/ginorts)|An uneasy sort.|[Python](py-built-ins/ginorts.py)|Medium
#### [Python Functionals](https://www.hackerrank.com/domains/python/py-functionals)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Map and Lambda Function](https://www.hackerrank.com/challenges/map-and-lambda-expression)|This challenge covers the basic concept of maps and lambda expressions.|[Python](py-functionals/map-and-lambda-expression.py)|Easy
[Validating Email Addresses With a Filter ](https://www.hackerrank.com/challenges/validate-list-of-email-address-with-filter)|This question covers the concept of filters.|[Python](py-functionals/validate-list-of-email-address-with-filter.py)|Medium
[Reduce Function](https://www.hackerrank.com/challenges/reduce-function)|Python Practice|[Python](py-functionals/reduce-function.py)|Medium
#### [Regex and Parsing](https://www.hackerrank.com/domains/python/py-regex)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Detect Floating Point Number](https://www.hackerrank.com/challenges/introduction-to-regex)|Validate a floating point number using the regular expression module for Python.|[Python](py-regex/introduction-to-regex.py)|Easy
[Re.split()](https://www.hackerrank.com/challenges/re-split)|Split the string by the pattern occurrence using the re.split() expression.|[Python](py-regex/re-split.py)|Easy
[Group(), Groups() & Groupdict()](https://www.hackerrank.com/challenges/re-group-groups)|Using group(), groups(), and groupdict(), find the subgroup(s) of the match.|[Python](py-regex/re-group-groups.py)|Easy
[Re.findall() & Re.finditer()](https://www.hackerrank.com/challenges/re-findall-re-finditer)|Find all the pattern matches using the expressions re.findall() and re.finditer().|[Python](py-regex/re-findall-re-finditer.py)|Easy
[Re.start() & Re.end()](https://www.hackerrank.com/challenges/re-start-re-end)|Find the indices of the start and end of the substring matched by the group.|[Python](py-regex/re-start-re-end.py)|Easy
[Regex Substitution](https://www.hackerrank.com/challenges/re-sub-regex-substitution)|Substitute a string using regex tools.|[Python](py-regex/re-sub-regex-substitution.py)|Medium
[Validating Roman Numerals](https://www.hackerrank.com/challenges/validate-a-roman-number)|Use regex to validate Roman numerals.|[Python](py-regex/validate-a-roman-number.py)|Easy
[Validating phone numbers](https://www.hackerrank.com/challenges/validating-the-phone-number)|Check whether the given phone number is valid or not.|[Python](py-regex/validating-the-phone-number.py)|Easy
[Validating and Parsing Email Addresses](https://www.hackerrank.com/challenges/validating-named-email-addresses)|Print valid email addresses according to the constraints.|[Python](py-regex/validating-named-email-addresses.py)|Easy
[Hex Color Code](https://www.hackerrank.com/challenges/hex-color-code)|Validate Hex color codes in CSS.|[Python](py-regex/hex-color-code.py)|Easy
[HTML Parser - Part 1](https://www.hackerrank.com/challenges/html-parser-part-1)|Parse HTML tags, attributes and attribute values using HTML Parser.|[Python](py-regex/html-parser-part-1.py)|Easy
[HTML Parser - Part 2](https://www.hackerrank.com/challenges/html-parser-part-2)|Parse HTML comments and data using HTML Parser.|[Python](py-regex/html-parser-part-2.py)|Easy
[Detect HTML Tags, Attributes and Attribute Values](https://www.hackerrank.com/challenges/detect-html-tags-attributes-and-attribute-values)|Parse HTML tags, attributes and attribute values in this challenge.|[Python](py-regex/detect-html-tags-attributes-and-attribute-values.py)|Easy
[Validating UID ](https://www.hackerrank.com/challenges/validating-uid)|Validate all the randomly generated user identification numbers according to the constraints.|[Python](py-regex/validating-uid.py)|Easy
[Validating Credit Card Numbers](https://www.hackerrank.com/challenges/validating-credit-card-number)|Verify whether credit card numbers are valid or not.|[Python](py-regex/validating-credit-card-number.py)|Medium
[Validating Postal Codes](https://www.hackerrank.com/challenges/validating-postalcode)|Verify if the postal code is valid or invalid.|[Python](py-regex/validating-postalcode.py)|Hard
[Matrix Script](https://www.hackerrank.com/challenges/matrix-script)|Decode the Matrix.|[Python](py-regex/matrix-script.py)|Hard
#### [XML](https://www.hackerrank.com/domains/python/xml)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[XML 1 - Find the Score](https://www.hackerrank.com/challenges/xml-1-find-the-score)|Learn about XML parsing in Python.|[Python](xml/xml-1-find-the-score.py)|Easy
[XML2 - Find the Maximum Depth](https://www.hackerrank.com/challenges/xml2-find-the-maximum-depth)|Find the maximum depth in an XML document.|[Python](xml/xml2-find-the-maximum-depth.py)|Easy
#### [Closures and Decorators](https://www.hackerrank.com/domains/python/closures-and-decorators)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Standardize Mobile Number Using Decorators](https://www.hackerrank.com/challenges/standardize-mobile-number-using-decorators)|Use decorators to standardize mobile numbers.|[Python](closures-and-decorators/standardize-mobile-number-using-decorators.py)|Easy
[Decorators 2 - Name Directory](https://www.hackerrank.com/challenges/decorators-2-name-directory)|Use decorators to build a name directory.|[Python](closures-and-decorators/decorators-2-name-directory.py)|Easy
#### [Numpy](https://www.hackerrank.com/domains/python/numpy)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Arrays](https://www.hackerrank.com/challenges/np-arrays)|Convert a list to an array using the NumPy package.|[Python](numpy/np-arrays.py)|Easy
[Shape and Reshape](https://www.hackerrank.com/challenges/np-shape-reshape)|Using the shape and reshape tools available in the NumPy module, configure a list according to the guidelines.|[Python](numpy/np-shape-reshape.py)|Easy
[Transpose and Flatten](https://www.hackerrank.com/challenges/np-transpose-and-flatten)|Use the transpose and flatten tools in the NumPy module to manipulate an array.|[Python](numpy/np-transpose-and-flatten.py)|Easy
[Concatenate](https://www.hackerrank.com/challenges/np-concatenate)|Use the concatenate function on 2 arrays.|[Python](numpy/np-concatenate.py)|Easy
[Zeros and Ones](https://www.hackerrank.com/challenges/np-zeros-and-ones)|Print an array using the zeros and ones tools in the NumPy module.|[Python](numpy/np-zeros-and-ones.py)|Easy
[Eye and Identity](https://www.hackerrank.com/challenges/np-eye-and-identity)|Create an array using the identity or eye tools from the NumPy module.|[Python](numpy/np-eye-and-identity.py)|Easy
[Array Mathematics](https://www.hackerrank.com/challenges/np-array-mathematics)|Perform basic mathematical operations on arrays in NumPy.|[Python](numpy/np-array-mathematics.py)|Easy
[Floor, Ceil and Rint](https://www.hackerrank.com/challenges/floor-ceil-and-rint)|Use the floor, ceil and rint tools of NumPy on the given array.|[Python](numpy/floor-ceil-and-rint.py)|Easy
[Sum and Prod](https://www.hackerrank.com/challenges/np-sum-and-prod)|Perform the sum and prod functions of NumPy on the given 2-D array.|[Python](numpy/np-sum-and-prod.py)|Easy
[Min and Max](https://www.hackerrank.com/challenges/np-min-and-max)|Use the min and max tools of NumPy on the given 2-D array.|[Python](numpy/np-min-and-max.py)|Easy
[Mean, Var, and Std](https://www.hackerrank.com/challenges/np-mean-var-and-std)|Use the mean, var and std tools in NumPy on the given 2-D array.|[Python](numpy/np-mean-var-and-std.py)|Easy
[Dot and Cross](https://www.hackerrank.com/challenges/np-dot-and-cross)|Use NumPy to find the dot and cross products of arrays.|[Python](numpy/np-dot-and-cross.py)|Easy
[Inner and Outer](https://www.hackerrank.com/challenges/np-inner-and-outer)|Use NumPy to find the inner and outer product of arrays.|[Python](numpy/np-inner-and-outer.py)|Easy
[Polynomials](https://www.hackerrank.com/challenges/np-polynomials)|Given the coefficients, use polynomials in NumPy.|[Python](numpy/np-polynomials.py)|Easy
[Linear Algebra](https://www.hackerrank.com/challenges/np-linear-algebra)|NumPy routines for linear algebra calculations.|[Python](numpy/np-linear-algebra.py)|Easy
#### [Debugging](https://www.hackerrank.com/domains/python/py-debugging)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Words Score](https://www.hackerrank.com/challenges/words-score)|Calculate the total score of the list of words.|[Python](py-debugging/words-score.py)|Medium
[Default Arguments](https://www.hackerrank.com/challenges/default-arguments)|Debug a function which uses a default value for one of its arguments.|[Python](py-debugging/default-arguments.py)|Medium
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Python > Math > Mod Divmod
# Get the quotient and remainder using the divmod operator in Python.
#
# https://www.hackerrank.com/challenges/python-mod-divmod/problem
#
a = int(input())
b = int(input())
q, r = divmod(a, b)
print(q)
print(r)
print((q, r))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Python > Math > Polar Coordinates
# Convert complex numbers to polar coordinates
#
# https://www.hackerrank.com/challenges/polar-coordinates/problem
#
import cmath
c = complex(input())
print(abs(c)) # 𝑟
print(cmath.phase(c)) # φ
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
add_hackerrank_py(find-angle.py)
add_hackerrank_py(polar-coordinates.py)
add_hackerrank_py(triangle-quest-2.py)
add_hackerrank_py(python-mod-divmod.py)
add_hackerrank_py(python-power-mod-power.py)
add_hackerrank_py(python-integers-come-in-all-sizes.py)
add_hackerrank_py(python-quest-1.py)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Python > Math > Triangle Quest
# Print a numeric triangle of height N-1 using only 2 lines.
#
# https://www.hackerrank.com/challenges/python-quest-1/problem
#
for i in range(1,int(input())): #More than 2 lines will result in 0 score. Do not leave a blank line also
print(i * (10 ** i // 9))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
"""
Find Angle MBC
https://www.hackerrank.com/challenges/find-angle/problem
"""
from math import atan2, pi
AB = int(input())
BC = int(input())
print(u"{}°".format(round(atan2(AB, BC) * 180 / pi)))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Python > Math > Integers Come In All Sizes
# Exercises with big integers in Python.
#
# https://www.hackerrank.com/challenges/python-integers-come-in-all-sizes/problem
#
a = int(input())
b = int(input())
c = int(input())
d = int(input())
print(a ** b + c ** d) | {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Python > Math > Power - Mod Power
# Perform modular exponentiation in Python.
#
# https://www.hackerrank.com/challenges/python-power-mod-power/problem
#
def powmod(x, k, MOD):
""" fast exponentiation x^k % MOD """
p = 1
if k == 0:
return p
if k == 1:
return x
while k != 0:
if k % 2 == 1:
p = (p * x) % MOD
x = (x * x) % MOD
k //= 2
return p
a = int(input())
b = int(input())
m = int(input())
print(a ** b)
print(powmod(a, b, m))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Python > Math > Triangle Quest 2
# Create a palindromic triangle.
#
# https://www.hackerrank.com/challenges/triangle-quest-2/problem
#
# (template_tail) ----------------------------------------------------------------------
for i in range(1,int(input())+1): #More than 2 lines will result in 0 score. Do not leave a blank line also
print(123456789 // (10 ** (9-i)) * (10 ** (i - 1)) + 987654321 % (10 ** (i - 1)))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
### [Python](https://www.hackerrank.com/domains/python)
A step by step guide to Python, a language that is easy to pick up yet one of the most powerful.
#### [Math](https://www.hackerrank.com/domains/python/py-math)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Polar Coordinates](https://www.hackerrank.com/challenges/polar-coordinates)|Convert complex numbers to polar coordinates|[Python](polar-coordinates.py)|Easy
[Find Angle MBC](https://www.hackerrank.com/challenges/find-angle)|Find the desired angle in the right triangle.|[Python](find-angle.py)|Medium
[Triangle Quest 2](https://www.hackerrank.com/challenges/triangle-quest-2)|Create a palindromic triangle.|[Python](triangle-quest-2.py)|Medium
[Mod Divmod](https://www.hackerrank.com/challenges/python-mod-divmod)|Get the quotient and remainder using the divmod operator in Python.|[Python](python-mod-divmod.py)|Easy
[Power - Mod Power](https://www.hackerrank.com/challenges/python-power-mod-power)|Perform modular exponentiation in Python.|[Python](python-power-mod-power.py)|Easy
[Integers Come In All Sizes](https://www.hackerrank.com/challenges/python-integers-come-in-all-sizes)|Exercises with big integers in Python.|[Python](python-integers-come-in-all-sizes.py)|Easy
[Triangle Quest](https://www.hackerrank.com/challenges/python-quest-1)|Print a numeric triangle of height N-1 using only 2 lines.|[Python](python-quest-1.py)|Medium
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
"""
Standardize Mobile Number Using Decorators
https://www.hackerrank.com/challenges/standardize-mobile-number-using-decorators/problem
"""
def wrapper(f):
def fun(l):
# complete the function
for i, n in enumerate(l):
if len(n) == 10: n= "+91" + n
elif len(n) == 11 and n.startswith("0"): n = "+91" + n[1:]
elif len(n) == 12 and n.startswith("91"): n = "+" + n
elif len(n) == 13 and n.startswith("+91"): pass
else: continue
n = n[0:3] + " " + n[3:8] + " " + n[8:]
l[i] = n
return f(l)
return fun
@wrapper
def sort_phone(l):
print(*sorted(l), sep='\n')
if __name__ == '__main__':
l = [input() for _ in range(int(input()))]
sort_phone(l)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
add_hackerrank_py(decorators-2-name-directory.py)
add_hackerrank_py(standardize-mobile-number-using-decorators.py)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
"""
Decorators 2 - Name Directory
https://www.hackerrank.com/challenges/decorators-2-name-directory/problem
"""
import operator
def person_lister(f):
def inner(people):
# complete the function
return map(f, sorted(people, key=lambda x: int(x[2])))
return inner
@person_lister
def name_format(person):
return ("Mr. " if person[3] == "M" else "Ms. ") + person[0] + " " + person[1]
if __name__ == '__main__':
people = [input().split() for i in range(int(input()))]
print(*name_format(people), sep='\n') | {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
### [Python](https://www.hackerrank.com/domains/python)
A step by step guide to Python, a language that is easy to pick up yet one of the most powerful.
#### [Closures and Decorators](https://www.hackerrank.com/domains/python/closures-and-decorators)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Standardize Mobile Number Using Decorators](https://www.hackerrank.com/challenges/standardize-mobile-number-using-decorators)|Use decorators to standardize mobile numbers.|[Python](standardize-mobile-number-using-decorators.py)|Easy
[Decorators 2 - Name Directory](https://www.hackerrank.com/challenges/decorators-2-name-directory)|Use decorators to build a name directory.|[Python](decorators-2-name-directory.py)|Easy
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
"""
Python: Division
https://www.hackerrank.com/challenges/python-division/problem
"""
if __name__ == '__main__':
a = int(input())
b = int(input())
print(a // b)
print(round(a / b, 11))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
add_hackerrank_py(python-division.py)
add_hackerrank_py(python-loops.py)
add_hackerrank_py(python-print.py)
add_hackerrank_py(py-hello-world.py)
add_hackerrank_py(py-if-else.py)
add_hackerrank_py(write-a-function.py)
add_hackerrank_py(python-arithmetic-operators.py)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
"""
Arithmetic Operators
https://www.hackerrank.com/challenges/python-arithmetic-operators/problem
"""
if __name__ == '__main__':
a = int(input())
b = int(input())
print(a + b)
print(a - b)
print(a * b)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
"""
Write a function
https://www.hackerrank.com/challenges/write-a-function/problem
"""
def is_leap(year):
leap = False
# Write your logic here
leap = year % 4 == 0 and (year % 400 == 0 or year % 100 != 0)
return leap
year = int(input())
print(is_leap(year))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
"""
Python If-Else
https://www.hackerrank.com/challenges/py-if-else/problem
"""
if __name__ == '__main__':
n = int(input())
if n % 2 == 1 or (n >= 6 and n <= 20):
print("Weird")
else:
print("Not Weird")
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# https://www.hackerrank.com/challenges/py-hello-world/problem
if __name__ == '__main__':
print("Hello, World!")
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
"""
Loops
https://www.hackerrank.com/challenges/python-loops/problem
"""
if __name__ == '__main__':
n = int(input())
for i in range(n):
print(i ** 2)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
"""
Print Function
https://www.hackerrank.com/challenges/python-print/problem
"""
if __name__ == '__main__':
n = int(input())
print(*[i for i in range(1, n + 1)], sep='')
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
### [Python](https://www.hackerrank.com/domains/python)
A step by step guide to Python, a language that is easy to pick up yet one of the most powerful.
#### [Introduction](https://www.hackerrank.com/domains/python/py-introduction)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Say "Hello, World!" With Python](https://www.hackerrank.com/challenges/py-hello-world)|Get started with Python by printing to stdout.|[Python](py-hello-world.py)|Easy
[Python If-Else](https://www.hackerrank.com/challenges/py-if-else)|Practice using if-else conditional statements!|[Python](py-if-else.py)|Easy
[Arithmetic Operators](https://www.hackerrank.com/challenges/python-arithmetic-operators)|Addition, subtraction and multiplication.|[Python](python-arithmetic-operators.py)|Easy
[Python: Division](https://www.hackerrank.com/challenges/python-division)|Division using __future__ module.|[Python](python-division.py)|Easy
[Loops](https://www.hackerrank.com/challenges/python-loops)|Practice using "for" and "while" loops in Python.|[Python](python-loops.py)|Easy
[Write a function](https://www.hackerrank.com/challenges/write-a-function)|Write a function to check if the given year is leap or not|[Python](write-a-function.py)|Medium
[Print Function](https://www.hackerrank.com/challenges/python-print)|Learn to use print as a function|[Python](python-print.py)|Easy
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Concatenate
# Use the concatenate function on 2 arrays.
#
# https://www.hackerrank.com/challenges/np-concatenate/problem
#
import numpy
n, m, p = map(int, input().split())
N = numpy.array([list(map(int, input().split())) for _ in range(n)])
M = numpy.array([list(map(int, input().split())) for _ in range(m)])
print(numpy.concatenate((N, M), axis = 0))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Python > Numpy > Polynomials
# Given the coefficients, use polynomials in NumPy.
#
# https://www.hackerrank.com/challenges/np-polynomials/problem
#
import numpy
p = list(map(float, input().split()))
print(numpy.polyval(p, float(input())))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Python > Numpy > Transpose and Flatten
# Use the transpose and flatten tools in the NumPy module to manipulate an array.
#
# https://www.hackerrank.com/challenges/np-transpose-and-flatten/problem
#
import numpy
n, m = map(int, input().split())
M = numpy.array([input().split() for i in range(n)], numpy.int)
print(M.transpose())
print(M.flatten())
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.