text
stringlengths
2
104M
meta
dict
# Python > Numpy > Inner and Outer # Use NumPy to find the inner and outer product of arrays. # # https://www.hackerrank.com/challenges/np-inner-and-outer/problem # import numpy u = numpy.array(input().split(), numpy.int) v = numpy.array(input().split(), numpy.int) print(numpy.inner(u, v)) print(numpy.outer(u, v))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Numpy > Sum and Prod # Perform the sum and prod functions of NumPy on the given 2-D array. # # https://www.hackerrank.com/challenges/np-sum-and-prod/problem # import numpy n, m = map(int, input().split()) A = numpy.array([input().split() for i in range(n)], numpy.int) print(numpy.prod(numpy.sum(A, axis=0)))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Numpy > Dot and Cross # Use NumPy to find the dot and cross products of arrays. # # https://www.hackerrank.com/challenges/np-dot-and-cross/problem # import numpy n = int(input()) A = numpy.array([input().split() for i in range(n)], numpy.int) B = numpy.array([input().split() for i in range(n)], numpy.int) print(A.dot(B))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Numpy > Zeros and Ones # Print an array using the zeros and ones tools in the NumPy module. # # https://www.hackerrank.com/challenges/np-zeros-and-ones/problem # import numpy shape = tuple(map(int, input().split())) print(numpy.zeros(shape, dtype=numpy.int)) print(numpy.ones(shape, dtype=numpy.int))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Numpy > Eye and Identity # Create an array using the identity or eye tools from the NumPy module. # # https://www.hackerrank.com/challenges/np-eye-and-identity/problem # import numpy if numpy.version.version >= '1.14.': numpy.set_printoptions(legacy='1.13') n, m = map(int, input().split()) print(numpy.eye(n, m))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Numpy > Min and Max # Use the min and max tools of NumPy on the given 2-D array. # # https://www.hackerrank.com/challenges/np-min-and-max/problem # import numpy n, m = map(int, input().split()) A = numpy.array([input().split() for i in range(n)], numpy.int) print(numpy.max(numpy.min(A, axis=1)))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Numpy > Shape and Reshape # Using the shape and reshape tools available in the NumPy module, configure a list according to the guidelines. # # https://www.hackerrank.com/challenges/np-shape-reshape/problem # import numpy v = numpy.array(input().split(), numpy.integer) m = numpy.reshape(v, (3, 3)) print(m)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
add_hackerrank_py(np-concatenate.py) add_hackerrank_py(np-arrays.py) add_hackerrank_py(np-linear-algebra.py) add_hackerrank_py(np-dot-and-cross.py) add_hackerrank_py(np-inner-and-outer.py) add_hackerrank_py(np-polynomials.py) add_hackerrank_py(np-shape-reshape.py) add_hackerrank_py(np-transpose-and-flatten.py) add_hackerrank_py(np-zeros-and-ones.py) add_hackerrank_py(np-eye-and-identity.py) add_hackerrank_py(np-array-mathematics.py) add_hackerrank_py(floor-ceil-and-rint.py) add_hackerrank_py(np-sum-and-prod.py) add_hackerrank_py(np-min-and-max.py) add_hackerrank_py(np-mean-var-and-std.py)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Arrays # Convert a list to an array using the NumPy package. # # https://www.hackerrank.com/challenges/np-arrays/problem # import numpy # (template_head) ---------------------------------------------------------------------- def arrays(arr): # complete this function # use numpy.array arr.reverse() return numpy.array(arr, float) # (template_tail) ---------------------------------------------------------------------- arr = input().strip().split(' ') result = arrays(arr) print(result)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Numpy > Mean, Var, and Std # Use the mean, var and std tools in NumPy on the given 2-D array. # # https://www.hackerrank.com/challenges/np-mean-var-and-std/problem # import numpy if numpy.version.version >= '1.14.': numpy.set_printoptions(legacy='1.13') n, m = map(int, input().split()) A = numpy.array([input().split() for i in range(n)], numpy.int) print(numpy.mean(A, axis=1)) print(numpy.var(A, axis=0)) print(numpy.std(A, axis=None))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Numpy > Array Mathematics # Perform basic mathematical operations on arrays in NumPy. # # https://www.hackerrank.com/challenges/np-array-mathematics/problem # import numpy n, m = map(int, input().split()) A = numpy.array([input().split() for i in range(n)], numpy.int) B = numpy.array([input().split() for i in range(n)], numpy.int) print(A + B) print(A - B) print(A * B) 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" }
# Python > Numpy > Linear Algebra # NumPy routines for linear algebra calculations. # # https://www.hackerrank.com/challenges/np-linear-algebra/problem # import numpy if numpy.version.version >= '1.14.': numpy.set_printoptions(legacy='1.13') m = numpy.array([input().split() for i in range(int(input()))], numpy.float) print(numpy.linalg.det(m))
{ "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. #### [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](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](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](np-transpose-and-flatten.py)|Easy [Concatenate](https://www.hackerrank.com/challenges/np-concatenate)|Use the concatenate function on 2 arrays.|[Python](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](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](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](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](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](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](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](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](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](np-inner-and-outer.py)|Easy [Polynomials](https://www.hackerrank.com/challenges/np-polynomials)|Given the coefficients, use polynomials in NumPy.|[Python](np-polynomials.py)|Easy [Linear Algebra](https://www.hackerrank.com/challenges/np-linear-algebra)|NumPy routines for linear algebra calculations.|[Python](np-linear-algebra.py)|Easy
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Numpy > Floor, Ceil and Rint # Use the floor, ceil and rint tools of NumPy on the given array. # # https://www.hackerrank.com/challenges/floor-ceil-and-rint/problem # import numpy if numpy.version.version >= '1.14.': numpy.set_printoptions(legacy='1.13') a = numpy.array(input().split(), numpy.float) print(numpy.floor(a)) print(numpy.ceil(a)) print(numpy.rint(a))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Classes > Classes: Dealing with Complex Numbers # Create a new data type for complex numbers. # # https://www.hackerrank.com/challenges/class-1-dealing-with-complex-numbers/problem # import math # (skeliton_head) ---------------------------------------------------------------------- class Complex(object): def __init__(self, real, imaginary): self.a = real self.b = imaginary def __add__(self, no): return Complex(self.a + no.a, self.b + no.b) def __sub__(self, no): return Complex(self.a - no.a, self.b - no.b) def __mul__(self, no): # (a+ib)(c+id) = (ac-bd) + (ad+bc)i return Complex(self.a * no.a - self.b * no.b, self.a * no.b + self.b * no.a) def __truediv__(self, no): # (a+ib)/(c+id) = (a+ib)*(c-id) /((c+id)(c-id)) # = (ac+bd+(bc-ad)i)/(c*c+d*d) x = no.a ** 2 + no.b ** 2 return Complex((self.a * no.a + self.b * no.b) / x, (self.b * no.a - self.a * no.b) / x) def mod(self): return Complex(math.sqrt(self.a ** 2 + self.b ** 2), 0) def __str__(self): if self.b == 0: result = "%.2f+0.00i" % (self.a) elif self.a == 0: if self.b >= 0: result = "0.00+%.2fi" % (self.b) else: result = "0.00-%.2fi" % (abs(self.b)) elif self.b > 0: result = "%.2f+%.2fi" % (self.a, self.b) else: result = "%.2f-%.2fi" % (self.a, abs(self.b)) return result # (skeliton_tail) ---------------------------------------------------------------------- if __name__ == '__main__': c = map(float, input().split()) d = map(float, input().split()) x = Complex(*c) y = Complex(*d) print(*map(str, [x+y, x-y, x*y, x/y, x.mod(), y.mod()]), sep='\n')
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
add_hackerrank_py(class-1-dealing-with-complex-numbers.py) add_hackerrank_py(class-2-find-the-torsional-angle.py)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Classes > Class 2 - Find the Torsional Angle # Find the angle between two planes. # # https://www.hackerrank.com/challenges/class-2-find-the-torsional-angle/problem # import math # (skeliton_head) ---------------------------------------------------------------------- class Points(object): def __init__(self, x, y, z): self.x, self.y, self.z = x, y, z def __sub__(self, no): return Points(self.x - no.x, self.y - no.y, self.z - no.z) def dot(self, no): """ produit scalaire """ return self.x * no.x + self.y * no.y + self.z * no.z def cross(self, no): """ produit vectoriel """ return Points(self.y * no.z - self.z * no.y, self.z * no.x - self.x * no.z, self.x * no.y - self.y * no.x) def absolute(self): return pow((self.x ** 2 + self.y ** 2 + self.z ** 2), 0.5) def __str__(self): return "[{} {} {}]".format(self.x, self.y, self.z) # (skeliton_tail) ---------------------------------------------------------------------- if __name__ == '__main__': points = list() for i in range(4): a = list(map(float, input().split())) points.append(a) a, b, c, d = Points(*points[0]), Points(*points[1]), Points(*points[2]), Points(*points[3]) x = (b - a).cross(c - b) y = (c - b).cross(d - c) angle = math.acos(x.dot(y) / (x.absolute() * y.absolute())) print("%.2f" % math.degrees(angle)) if False: import numpy as np a = np.array(points[0]) b = np.array(points[1]) c = np.array(points[2]) d = np.array(points[3]) x = np.cross(b - a, c - b) y = np.cross(c - b, d - c) angle = math.acos(x.dot(y) / (np.linalg.norm(x) * np.linalg.norm(y))) print("%.2f" % math.degrees(angle))
{ "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. #### [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](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](class-2-find-the-torsional-angle.py)|Easy
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Sets > The Captain's Room # Out of a list of room numbers, determine the number of the captain's room. # # https://www.hackerrank.com/challenges/py-the-captains-room/problem # k = int(input()) rooms = list(map(int, input().split())) a = set() room_group = set() for room in rooms: if room in a: room_group.add(room) else: a.add(room) a = a - room_group print(a.pop())
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
""" No Idea! https://www.hackerrank.com/challenges/no-idea/problem """ input() N = map(int, input().split()) A = set(map(int, input().split())) B = set(map(int, input().split())) h = 0 for n in N: if n in A: h += 1 if n in B: h -= 1 print(h)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Sets > Set Mutations # Using various operations, change the content of a set and output the new sum. # # https://www.hackerrank.com/challenges/py-set-mutations/problem # n = int(input()) s = set(map(int, input().split())) for _ in range(int(input())): cmd, n = input().split() x = set(map(int, input().split())) if cmd == "intersection_update": s.intersection_update(x) elif cmd == "update": s.update(x) elif cmd == "symmetric_difference_update": s.symmetric_difference_update(x) elif cmd == "difference_update": s.difference_update(x) print(sum(s))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Sets > Check Strict Superset # Check if A is a strict superset of the other given sets. # # https://www.hackerrank.com/challenges/py-check-strict-superset/problem # a = set(map(int, input().split())) strict_superset = True for _ in range(int(input())): x = set(map(int, input().split())) if not ((len(x - a) == 0 and len(a - x) > 0)): strict_superset = False break print(strict_superset)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Sets > Set .discard(), .remove() & .pop() # Different ways to omit set elements. # # https://www.hackerrank.com/challenges/py-set-discard-remove-pop/problem # n = int(input()) s = set(map(int, input().split())) for _ in range(int(input())): cmd = input().split() if cmd[0] == "pop": s.pop() elif cmd[0] == "remove": s.remove(int(cmd[1])) elif cmd[0] == "discard": s.discard(int(cmd[1])) print(sum(s))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
add_hackerrank_py(no-idea.py) add_hackerrank_py(py-set-add.py) add_hackerrank_py(py-introduction-to-sets.py) add_hackerrank_py(symmetric-difference.py) add_hackerrank_py(py-set-discard-remove-pop.py) add_hackerrank_py(py-set-union.py) add_hackerrank_py(py-set-intersection-operation.py) add_hackerrank_py(py-set-difference-operation.py) add_hackerrank_py(py-set-symmetric-difference-operation.py) add_hackerrank_py(py-set-mutations.py) add_hackerrank_py(py-the-captains-room.py) add_hackerrank_py(py-check-subset.py) add_hackerrank_py(py-check-strict-superset.py)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Sets > Set .difference() Operation # Use the .difference() operator to check the differences between sets. # # https://www.hackerrank.com/challenges/py-set-difference-operation/problem # n = int(input()) english = set(map(int, input().split())) n = int(input()) french = set(map(int, input().split())) print(len(english - french))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Sets > Introduction to Sets # Use the set tool to compute the average. # # https://www.hackerrank.com/challenges/py-introduction-to-sets/problem # def average(array): # your code goes here a = set(array) return sum(a) / len(a) # (skeliton_tail) ---------------------------------------------------------------------- if __name__ == '__main__': n = int(input()) arr = list(map(int, input().split())) result = average(arr) print(result)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Sets > Set .intersection() Operation # Use the .intersection() operator to determine the number of same students in both sets. # # https://www.hackerrank.com/challenges/py-set-intersection-operation/problem # n = int(input()) english = set(map(int, input().split())) n = int(input()) french = set(map(int, input().split())) print(len(english & french))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Sets > Set .symmetric_difference() Operation # Making symmetric difference of sets. # # https://www.hackerrank.com/challenges/py-set-symmetric-difference-operation/problem # n = int(input()) english = set(map(int, input().split())) n = int(input()) french = set(map(int, input().split())) print(len(english ^ french))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Sets > Symmetric Difference # Learn about sets as a data type. # # https://www.hackerrank.com/challenges/symmetric-difference/problem # m = int(input()) M = set(map(int, input().split())) n = int(input()) N = set(map(int, input().split())) a = (M - N).union(N - M) for i in sorted(a): print(i)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Sets > Set .add() # Add elements to set. # # https://www.hackerrank.com/challenges/py-set-add/problem # s = set() for _ in range(int(input())): s.add(input()) print(len(s))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Sets > Set .union() Operation # Use the .union() operator to determine the number of students. # # https://www.hackerrank.com/challenges/py-set-union/problem # n = int(input()) english = set(map(int, input().split())) n = int(input()) french = set(map(int, input().split())) print(len(english | french))
{ "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. #### [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-introduction-to-sets.py)|Easy [Symmetric Difference](https://www.hackerrank.com/challenges/symmetric-difference)|Learn about sets as a data type.|[Python](symmetric-difference.py)|Easy [No Idea!](https://www.hackerrank.com/challenges/no-idea)|Compute your happiness.|[Python](no-idea.py)|Medium [Set .add() ](https://www.hackerrank.com/challenges/py-set-add)|Add elements to set.|[Python](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-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-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-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-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-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-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-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-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-check-strict-superset.py)|Easy
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Sets > Check Subset # Verify if set A is a subset of set B. # # https://www.hackerrank.com/challenges/py-check-subset/problem # for _ in range(int(input())): _, a = input(), set(map(int, input().split())) _, b = input(), set(map(int, input().split())) print(b.intersection(a) == a)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Iterables and Iterators # Find the probability using itertools. # # https://www.hackerrank.com/challenges/iterables-and-iterators/problem # # Enter your code here. Read input from STDIN. Print output to STDOUT import itertools n = int(input()) letters = input().split() k = int(input()) nb, tot = 0, 0 for t in itertools.combinations([i for i in range(n)], k): tot += 1 for i in t: if letters[i] == 'a': nb += 1 break print(round(nb / tot, 12))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
""" Maximize It! https://www.hackerrank.com/challenges/maximize-it/problem """ import itertools N = [] K, M = map(int, input().split()) for _ in range(K): N.append(list(map(lambda x: int(x) ** 2, input().split()))[1:]) Smax = max([sum(i) % M for i in itertools.product(*N)]) print(Smax)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
add_hackerrank_py(compress-the-string.py) add_hackerrank_py(maximize-it.py) add_hackerrank_py(iterables-and-iterators.py) add_hackerrank_py(itertools-product.py) add_hackerrank_py(itertools-permutations.py) add_hackerrank_py(itertools-combinations.py) add_hackerrank_py(itertools-combinations-with-replacement.py)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Itertools > itertools.permutations() # Find all permutations of a given size in a given string. # # https://www.hackerrank.com/challenges/itertools-permutations/problem # from itertools import permutations s, n = input().split() for i in permutations(sorted(s), int(n)): print("".join(i))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Itertools > itertools.product() # Find the cartesian product of 2 sets. # # https://www.hackerrank.com/challenges/itertools-product/problem # from itertools import product A = list(map(int, input().split())) B = list(map(int, input().split())) P = list(product(A, B)) print(" ".join(str(x) for x in P))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Itertools > itertools.combinations() # Print all the combinations of a string using itertools. # # https://www.hackerrank.com/challenges/itertools-combinations/problem # from itertools import combinations s, n = input().split() for k in range(1, int(n) + 1): for i in combinations(sorted(s), k): print("".join(i))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Itertools > itertools.combinations_with_replacement() # Find all the combinations of a string with replacements. # # https://www.hackerrank.com/challenges/itertools-combinations-with-replacement/problem # from itertools import combinations_with_replacement s, n = input().split() for i in combinations_with_replacement(sorted(s), int(n)): print("".join(i))
{ "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. #### [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](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](itertools-permutations.py)|Easy [itertools.combinations()](https://www.hackerrank.com/challenges/itertools-combinations)|Print all the combinations of a string using itertools.|[Python](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](itertools-combinations-with-replacement.py)|Easy [Compress the String! ](https://www.hackerrank.com/challenges/compress-the-string)|groupby()|[Python](compress-the-string.py)|Medium [Iterables and Iterators](https://www.hackerrank.com/challenges/iterables-and-iterators)|Find the probability using itertools.|[Python](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](maximize-it.py)|Hard
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Compress the String! # groupby() # # https://www.hackerrank.com/challenges/compress-the-string/problem # import itertools s = input() print(' '.join(str((len(list(g)), int(c))) for c, g in itertools.groupby(s)))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
""" Time Delta https://www.hackerrank.com/challenges/python-time-delta/problem """ import sys import datetime def to_date(t): # Sun 10 May 2015 13:54:36 -0700 t = datetime.datetime.strptime(t, "%a %d %b %Y %H:%M:%S %z") return t def time_delta(t1, t2): # Complete this function delta = to_date(t1) - to_date(t2) return abs(int(delta.total_seconds())) if __name__ == "__main__": t = int(input().strip()) for a0 in range(t): t1 = input().strip() t2 = input().strip() delta = time_delta(t1, t2) print(delta)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
add_hackerrank_py(python-time-delta.py) add_hackerrank_py(calendar-module.py)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Date and Time > Calendar Module # Print the day of a given date. # # https://www.hackerrank.com/challenges/calendar-module/problem # import calendar m, d, y = map(int, input().split()) i = calendar.weekday(y, m, d) print(calendar.day_name[i].upper())
{ "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. #### [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](calendar-module.py)|Easy [Time Delta](https://www.hackerrank.com/challenges/python-time-delta)|Find the absolute time difference.|[Python](python-time-delta.py)|Medium
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
""" Reduce Function https://www.hackerrank.com/challenges/reduce-function/problem """ from fractions import Fraction from functools import reduce def product(fracs): t = reduce(lambda x, y: x * y, fracs) # complete this line with a reduce statement return t.numerator, t.denominator if __name__ == '__main__': fracs = [] for _ in range(int(input())): fracs.append(Fraction(*map(int, input().split()))) result = product(fracs) print(*result)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
add_hackerrank_py(reduce-function.py) add_hackerrank_py(validate-list-of-email-address-with-filter.py) add_hackerrank_py(map-and-lambda-expression.py)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Python Functionals > Map and Lambda Function # This challenge covers the basic concept of maps and lambda expressions. # # https://www.hackerrank.com/challenges/map-and-lambda-expression/problem # cube = lambda x: x ** 3 def fibonacci(n): """ return a list of fibonacci numbers """ fibo = [0, 1] while len(fibo) < n: c = fibo[-2] + fibo[-1] fibo.append(c) return fibo[0:n] # (skeliton_tail) ---------------------------------------------------------------------- if __name__ == '__main__': n = int(input()) print(list(map(cube, fibonacci(n))))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
""" Validating Email Addresses With a Filter https://www.hackerrank.com/challenges/validate-list-of-email-address-with-filter/problem """ import re def fun(s): # return True if s is a valid email, else return False return bool(re.match(r"^[A-Za-z0-9_\-]+@[a-z0-9]+\.[a-z]{1,3}$", s)) def filter_mail(emails): return list(filter(fun, emails)) if __name__ == '__main__': n = int(input()) emails = [] for _ in range(n): emails.append(input()) filtered_emails = filter_mail(emails) filtered_emails.sort() print(filtered_emails)
{ "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. #### [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](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](validate-list-of-email-address-with-filter.py)|Medium [Reduce Function](https://www.hackerrank.com/challenges/reduce-function)|Python Practice|[Python](reduce-function.py)|Medium
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
""" Word Order https://www.hackerrank.com/challenges/word-order/problem """ from collections import OrderedDict dico = OrderedDict() for _ in range(int(input())): word = input() dico[word] = dico.get(word, 0) + 1 print(len(dico)) print(' '.join(map(str, dico.values())))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Collections > Collections.OrderedDict() # Print a dictionary of items that retains its order. # # https://www.hackerrank.com/challenges/py-collections-ordereddict/problem # from collections import OrderedDict prices = OrderedDict() for _ in range(int(input())): item, price = input().rsplit(maxsplit=1) prices[item] = prices.get(item, 0) + int(price) for item, price in prices.items(): print(item, price)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Collections > DefaultDict Tutorial # Create dictionary value fields with predefined data types. # # https://www.hackerrank.com/challenges/defaultdict-tutorial/problem # from collections import defaultdict n, m = map(int, input().split()) A = defaultdict(list) for i in range(1, n + 1): A[input()].append(i) for _ in range(m): r = A[input()] if len(r) == 0: print(-1) else: print(" ".join(map(str, r)))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Collections > Collections.namedtuple() # You need to turn tuples into convenient containers using collections.namedtuple(). # # https://www.hackerrank.com/challenges/py-collections-namedtuple/problem # from collections import namedtuple n = int(input()) Student = namedtuple('Student', input()) print(sum(int(Student(*(input().split())).MARKS) for _ in range(n)) / n)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# https://www.hackerrank.com/domains/python?filters%5Bsubdomains%5D%5B%5D=py-collections add_hackerrank_py(piling-up.py) add_hackerrank_py(word-order.py) add_hackerrank_py(collections-counter.py) add_hackerrank_py(defaultdict-tutorial.py) add_hackerrank_py(py-collections-ordereddict.py) add_hackerrank_py(py-collections-namedtuple.py) add_hackerrank_py(py-collections-deque.py) add_hackerrank_py(most-commons.py)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Collections > Collections.deque() # Perform multiple operations on a double-ended queue or deque. # # https://www.hackerrank.com/challenges/py-collections-deque/problem # from collections import deque d = deque() for _ in range(int(input())): cmd, _, opt = input().strip().partition(' ') if cmd == "append": d.append(opt) elif cmd == "appendleft": d.appendleft(opt) elif cmd == "pop": d.pop() elif cmd == "popleft": d.popleft() print(" ".join(d))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Collections > collections.Counter() # Use a counter to sum the amount of money earned by the shoe shop owner. # # https://www.hackerrank.com/challenges/collections-counter/problem # from collections import Counter input() shoes = Counter(input().split()) earned = 0 for _ in range(int(input())): shoe, price = input().split() if shoes[shoe]: shoes[shoe] -= 1 earned += int(price) print(earned)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Collections > Company Logo # Print the number of character occurrences in descending order. # # https://www.hackerrank.com/challenges/most-commons/problem # from collections import Counter from itertools import groupby name = input() nb = 0 for c, g in groupby(Counter(name).most_common(), key=lambda x: x[1]): for l in sorted(map(lambda x: x[0], g)): print(l, c) nb += 1 if nb == 3: break if nb == 3: break
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
""" Piling Up! https://www.hackerrank.com/challenges/piling-up/problem """ for _ in range(int(input())): input() lengths = list(map(int, input().split())) while len(lengths) >= 2: m = max(lengths[0], lengths[-1]) if lengths[0] == m and lengths[0] >= lengths[1]: del lengths[0] elif lengths[-1] == m and lengths[-1] >= lengths[-2]: del lengths[-1] else: m = 0 break if len(lengths) == 1 and lengths[0] <= m: print("Yes") else: print("No")
{ "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. #### [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](collections-counter.py)|Easy [DefaultDict Tutorial](https://www.hackerrank.com/challenges/defaultdict-tutorial)|Create dictionary value fields with predefined data types.|[Python](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-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-ordereddict.py)|Easy [Word Order](https://www.hackerrank.com/challenges/word-order)|List the number of occurrences of the words in order.|[Python](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-deque.py)|Easy [Piling Up!](https://www.hackerrank.com/challenges/piling-up)|Create a vertical pile of cubes.|[Python](piling-up.py)|Medium [Company Logo](https://www.hackerrank.com/challenges/most-commons)|Print the number of character occurrences in descending order.|[Python](most-commons.py)|Medium
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
add_hackerrank_py(exceptions.py) add_hackerrank_py(incorrect-regex.py)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Exceptions # Handle errors detected during execution. # # https://www.hackerrank.com/challenges/exceptions/problem # n = int(input()) for _ in range(n): a, b = input().split() try: a = int(a) except ValueError: print("Error Code: invalid literal for int() with base 10: '{}'".format(a)) continue try: b = int(b) except ValueError: print("Error Code: invalid literal for int() with base 10: '{}'".format(b)) continue try: print(a // b) except ZeroDivisionError: print("Error Code: integer division or modulo by zero") continue
{ "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. #### [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](exceptions.py)|Easy [Incorrect Regex](https://www.hackerrank.com/challenges/incorrect-regex)|Check whether the regex is valid or not.|[Python](incorrect-regex.py)|Easy
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Errors and Exceptions > Incorrect Regex # Check whether the regex is valid or not. # # https://www.hackerrank.com/challenges/incorrect-regex/problem # import re for _ in range(int(input())): try: re.compile(input()) print(True) except re.error: print(False)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Regex and Parsing > Group(), Groups() & Groupdict() # Using group(), groups(), and groupdict(), find the subgroup(s) of the match. # # https://www.hackerrank.com/challenges/re-group-groups/problem # import re s = input() # \1 (dans la regex) est la référence au premier groupe m = re.search(r"([0-9a-zA-Z])\1+", s) if m: print(m.group(1)) else: print(-1)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Regex and Parsing > Hex Color Code # Validate Hex color codes in CSS. # # https://www.hackerrank.com/challenges/hex-color-code/problem # import re for _ in range(int(input())): s = input() if re.match(r'^(.*\:|\s)', s, re.I): for m in re.finditer(r'(\#(?:[0-9a-f]{3}){1,2})', s, re.I): print(m.group(1))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Regex and Parsing > Validating phone numbers # Check whether the given phone number is valid or not. # # https://www.hackerrank.com/challenges/validating-the-phone-number/problem # import re for _ in range(int(input())): s = input() print("YES" if re.match(r'^[789]\d{9}$', s) else "NO")
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Regex and Parsing > HTML Parser - Part 1 # Parse HTML tags, attributes and attribute values using HTML Parser. # # https://www.hackerrank.com/challenges/html-parser-part-1/problem # from html.parser import HTMLParser class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): print('Start :',tag) for e in attrs: print('->', e[0],'>', e[1]) def handle_endtag(self, tag): print('End :', tag) def handle_startendtag(self, tag, attrs): print('Empty :', tag) for e in attrs: print ('->', e[0], '>', e[1]) parser = MyHTMLParser() parser.feed(''.join([input() for _ in range(int(input()))])) parser.close()
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Regex and Parsing > HTML Parser - Part 2 # Parse HTML comments and data using HTML Parser. # # https://www.hackerrank.com/challenges/html-parser-part-2/problem # from html.parser import HTMLParser class MyHTMLParser(HTMLParser): def handle_comment(self, data): if data.find('\n') >= 0: print('>>> Multi-line Comment') else: print('>>> Single-line Comment') print(data) def handle_data(self, data): if data.strip() != "": print(">>> Data") print(data) html = "" for i in range(int(input())): html += input() html += '\n' parser = MyHTMLParser() parser.feed(html) parser.close()
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Regex and Parsing > Regex Substitution # Substitute a string using regex tools. # # https://www.hackerrank.com/challenges/re-sub-regex-substitution/problem # import re for _ in range(int(input())): s = input() s = re.sub(r'(?<= )(&&)(?= )', 'and', s) # (?<= ) et (?= ) pour ne pas consommer les espaces s = re.sub(r'(?<= )(\|\|)(?= )', 'or', s) print(s)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Regex and Parsing > Validating and Parsing Email Addresses # Print valid email addresses according to the constraints. # # https://www.hackerrank.com/challenges/validating-named-email-addresses/problem # import re for _ in range(int(input())): s = input().strip() if re.match(r'^.*<[a-z][\w\.\-]*@[a-z]+\.[a-z]{1,3}>$', s, re.I): print(s)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Regex and Parsing > Validating UID # Validate all the randomly generated user identification numbers according to the constraints. # # https://www.hackerrank.com/challenges/validating-uid/problem # import re for _ in range(int(input())): s = input() ok1 = bool(re.match(r"^[a-zA-Z0-9]{10}$", s)) ok2 = len(set(s)) == 10 ok3 = bool(re.match(r"(?=(?:.*[A-Z]){2,})", s)) ok4 = bool(re.match(r"(?=(?:.*\d){3,})", s)) if ok1 and ok2 and ok3 and ok4: print("Valid") else: print("Invalid")
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
""" Validating Postal Codes https://www.hackerrank.com/challenges/validating-postalcode/problem """ import re def validate(code): ok = bool(re.match(r"^[1-9][0-9]{5}$", code)) alternative = sum(int(code[i - 1] == code[i + 1]) for i in range(1, len(code) - 1)) return ok and alternative < 2 print(validate(input()))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
add_hackerrank_py(matrix-script.py) add_hackerrank_py(validating-credit-card-number.py) add_hackerrank_py(validating-postalcode.py) add_hackerrank_py(introduction-to-regex.py) add_hackerrank_py(re-split.py) add_hackerrank_py(re-findall-re-finditer.py) add_hackerrank_py(re-group-groups.py) add_hackerrank_py(re-start-re-end.py) add_hackerrank_py(re-sub-regex-substitution.py) add_hackerrank_py(validate-a-roman-number.py) add_hackerrank_py(validating-the-phone-number.py) add_hackerrank_py(validating-named-email-addresses.py) add_hackerrank_py(hex-color-code.py) add_hackerrank_py(html-parser-part-1.py) add_hackerrank_py(html-parser-part-2.py) add_hackerrank_py(detect-html-tags-attributes-and-attribute-values.py) add_hackerrank_py(validating-uid.py)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
""" Validating Credit Card Numbers https://www.hackerrank.com/challenges/validating-credit-card-number/problem """ import re for _ in range(int(input())): num = input() ok1 = bool(re.match(r"^[456]\d{15}$", num)) ok2 = bool(re.match(r"^[456]\d{3}\-\d{4}\-\d{4}\-\d{4}$", num)) num = num.replace("-", "") ok3 = bool(re.match(r"(?!.*(\d)(-?\1){3})", num)) if (ok1 or ok2) and ok3: print("Valid") else: print("Invalid")
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
""" Matrix Script https://www.hackerrank.com/challenges/matrix-script/problem """ import itertools import re n, m = input().strip().split(' ') n, m = [int(n), int(m)] matrix = [] matrix_i = 0 for matrix_i in range(n): matrix_t = str(input()) matrix.append(matrix_t) message = ''.join(itertools.chain.from_iterable(itertools.zip_longest(*matrix, fillvalue=' '))) message = re.sub(r"([a-zA-Z0-9])\W+([a-zA-Z0-9])", r"\1 \2", message) print(message)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Regex and Parsing > Re.split() # Split the string by the pattern occurrence using the re.split() expression. # # https://www.hackerrank.com/challenges/re-split/problem # regex_pattern = r"[,.]" # Do not delete 'r'. # (skeliton_tail) ---------------------------------------------------------------------- import re print("\n".join(re.split(regex_pattern, input())))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Regex and Parsing > Detect HTML Tags, Attributes and Attribute Values # Parse HTML tags, attributes and attribute values in this challenge. # # https://www.hackerrank.com/challenges/detect-html-tags-attributes-and-attribute-values/problem # from html.parser import HTMLParser class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): print(tag) for attr in attrs: print('-> {} > {}'.format(*attr)) html = '\n'.join([input() for _ in range(int(input()))]) parser = MyHTMLParser() parser.feed(html) parser.close()
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Regex and Parsing > Validating Roman Numerals # Use regex to validate Roman numerals. # # https://www.hackerrank.com/challenges/validate-a-roman-number/problem # regex_pattern = r"^" regex_pattern += r"M{0,3}" # 0 à 3000 regex_pattern += r"(C[DM]|D?C{0,3})" # 400,900 ou 0..300,500.. 800 regex_pattern += r"(X[LC]|L?X{0,3})" # idem pour les dizaines regex_pattern += r"(I[VX]|V?I{0,3})" # idem pour les unités regex_pattern += r"$" # (skeliton_tail) ---------------------------------------------------------------------- import re print(str(bool(re.match(regex_pattern, input()))))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Regex and Parsing > Detect Floating Point Number # Validate a floating point number using the regular expression module for Python. # # https://www.hackerrank.com/challenges/introduction-to-regex/problem # import re p = re.compile(r'^[+-]?\d*\.\d+$') for _ in range(int(input())): print(bool(p.match(input())))
{ "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. #### [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](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](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](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](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](re-start-re-end.py)|Easy [Regex Substitution](https://www.hackerrank.com/challenges/re-sub-regex-substitution)|Substitute a string using regex tools.|[Python](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](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](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](validating-named-email-addresses.py)|Easy [Hex Color Code](https://www.hackerrank.com/challenges/hex-color-code)|Validate Hex color codes in CSS.|[Python](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](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](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](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](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](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](validating-postalcode.py)|Hard [Matrix Script](https://www.hackerrank.com/challenges/matrix-script)|Decode the Matrix.|[Python](matrix-script.py)|Hard
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Regex and Parsing > Re.findall() & Re.finditer() # Find all the pattern matches using the expressions re.findall() and re.finditer(). # # https://www.hackerrank.com/challenges/re-findall-re-finditer/problem # import re found = False s = input() for i in re.findall("(?<=[^aeiou])([aeiou]{2,})[^aeiou]", s, flags=re.I): print(i) found = True if not found: print(-1)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Regex and Parsing > Re.start() & Re.end() # Find the indices of the start and end of the substring matched by the group. # # https://www.hackerrank.com/challenges/re-start-re-end/problem # import re s = input() k = input() if False: p = s.find(k) if p == -1: print((-1, -1)) else: while p != -1: print((p, p + len(k) - 1)) p = s.find(k, p + 1) else: found = False for m in re.finditer(r'(?=(' + re.escape(k) + '))', s): print((m.start(1), m.end(1) - 1)) found = True if not found: print((-1, -1))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# XML 1 - Find the Score # Learn about XML parsing in Python. # # https://www.hackerrank.com/challenges/xml-1-find-the-score/problem # import sys import xml.etree.ElementTree as etree # (skeliton_head) ---------------------------------------------------------------------- # version récursive def get_attr_number(node): nb = len(node.attrib) for i in node: nb += get_attr_number(i) return nb # version non récursive: traverse tout l'arbre XML séquentiellement def get_attr_number(node): return sum(len(i.attrib) for i in node.iter()) # (skeliton_tail) ---------------------------------------------------------------------- if __name__ == '__main__': sys.stdin.readline() xml = sys.stdin.read() tree = etree.ElementTree(etree.fromstring(xml)) root = tree.getroot() print(get_attr_number(root))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
add_hackerrank_py(xml-1-find-the-score.py) add_hackerrank_py(xml2-find-the-maximum-depth.py)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# XML2 - Find the Maximum Depth # Find the maximum depth in an XML document. # # https://www.hackerrank.com/challenges/xml2-find-the-maximum-depth/problem # import xml.etree.ElementTree as etree # (skeliton_head) ---------------------------------------------------------------------- maxdepth = 0 def depth(elem, level): global maxdepth # your code goes here maxdepth = max(maxdepth, level + 1) for node in elem: depth(node, level + 1) # (skeliton_tail) ---------------------------------------------------------------------- if __name__ == '__main__': n = int(input()) xml = "" for i in range(n): xml = xml + input() + "\n" tree = etree.ElementTree(etree.fromstring(xml)) depth(tree.getroot(), -1) print(maxdepth)
{ "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. #### [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-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](xml2-find-the-maximum-depth.py)|Easy
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Strings > Designer Door Mat # Print a designer door mat. # # https://www.hackerrank.com/challenges/designer-door-mat/problem # """ ---------.|.--------- ------.|..|..|.------ ---.|..|..|..|..|.--- -------WELCOME------- ---.|..|..|..|..|.--- ------.|..|..|.------ ---------.|.--------- """ N, M = map(int, input().split()) s = list((".|." * i).center(M, "-") for i in range(1, N, 2)) print("\n".join(s + ["WELCOME".center(M, "-")] + list(reversed(s)))) #print("\n".join((".|." * i).center(M, "-") for i in range(1, N, 2))) #print("WELCOME".center(M, "-")) #print("\n".join((".|." * i).center(M, "-") for i in range(N - 2, -1, -2)))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Strings > Find a string # Find the number of occurrences of a substring in a string. # # https://www.hackerrank.com/challenges/find-a-string/problem # def count_substring(string, sub_string): count = 0 pos = 0 while True: pos = string.find(sub_string, pos) if pos == -1: break pos += 1 count += 1 return count # (skeliton_tail) ---------------------------------------------------------------------- if __name__ == '__main__': string = input().strip() sub_string = input().strip() count = count_substring(string, sub_string) print(count)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Strings > Mutations # Understand immutable vs mutable by making changes to a given string. # # https://www.hackerrank.com/challenges/python-mutations/problem # def mutate_string(string, position, character): return string[:position] + character + string[position + 1:] # (skeliton_tail) ---------------------------------------------------------------------- if __name__ == '__main__': s = input() i, c = input().split() s_new = mutate_string(s, int(i), c) print(s_new)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# sWAP cASE # Swap the letter cases of a given string. # # https://www.hackerrank.com/challenges/swap-case/problem # def swap(c): if c.islower(): return c.upper() else: return c.lower() def swap_case(s): return ''.join([swap(c) for c in s]) # (skeliton_tail) ---------------------------------------------------------------------- if __name__ == '__main__': s = input() result = swap_case(s) print(result)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
""" Capitalize! https://www.hackerrank.com/challenges/capitalize/problem """ def capitalize(string): s = "" for i in range(len(string)): if i == 0 or string[i-1] == ' ': s += string[i].upper() else: s += string[i] return s if __name__ == '__main__': string = input() capitalized_string = capitalize(string) print(capitalized_string)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
""" Merge the Tools! https://www.hackerrank.com/challenges/merge-the-tools/problem """ def uniq(tableau): deja_present = set() for element in tableau: if element not in deja_present: deja_present.add(element) yield element def merge_the_tools(string, k): # your code goes here for i in range(0, len(string), k): tableau = string[i:i + k] print(''.join(uniq(tableau))) """ équivalent: resultat = [] deja_present = set() for element in tableau: if element not in deja_present: deja_present.add(element) resultat.append(element) """ if __name__ == '__main__': string, k = input(), int(input()) merge_the_tools(string, k)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# What's Your Name? # Python string practice: Print your name in the console. # # https://www.hackerrank.com/challenges/whats-your-name/problem # def print_full_name(a, b): print("Hello {} {}! You just delved into python.".format(a, b)) # (skeliton_tail) ---------------------------------------------------------------------- if __name__ == '__main__': first_name = input() last_name = input() print_full_name(first_name, last_name)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
add_hackerrank_py(whats-your-name.py) add_hackerrank_py(alphabet-rangoli.py) add_hackerrank_py(python-string-split-and-join.py) add_hackerrank_py(merge-the-tools.py) add_hackerrank_py(swap-case.py) add_hackerrank_py(python-string-formatting.py) add_hackerrank_py(the-minion-game.py) add_hackerrank_py(capitalize.py) add_hackerrank_py(python-mutations.py) add_hackerrank_py(find-a-string.py) add_hackerrank_py(string-validators.py) add_hackerrank_py(text-alignment.py) add_hackerrank_py(text-wrap.py) add_hackerrank_py(designer-door-mat.py)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
""" The Minion Game https://www.hackerrank.com/challenges/the-minion-game/problem """ def minion_game(string): # your code goes here stuart, kevin = 0, 0 length = len(string) for i in range(length): if string[i] in 'AEIOU': kevin += length - i else: stuart += length - i if False: # non optimisé, trop long si length grand substr = [] for i in range(length): for j in range(i, length): substr.append(string[i:j + 1]) scores = dict() for i in set(substr): pos = 0 score = 0 while True: pos = string.find(i, pos) if pos == -1: break pos += 1 score += 1 scores[i] = score for i, score in scores.items(): if i[0] in "AEIOU": kevin += score else: stuart += score if stuart > kevin: print("Stuart", stuart) elif stuart < kevin: print("Kevin", kevin) else: print("Draw") if __name__ == '__main__': s = input() minion_game(s)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Python > Strings > Text Alignment # Generate the Hackerrank logo with alignments in Python. # # https://www.hackerrank.com/challenges/text-alignment/problem # #Replace all ______ with rjust, ljust or center. thickness = int(input()) #This must be an odd number c = 'H' #Top Cone for i in range(thickness): print((c*i).rjust(thickness-1)+c+(c*i).ljust(thickness-1)) #Top Pillars for i in range(thickness+1): print((c*thickness).center(thickness*2)+(c*thickness).center(thickness*6)) #Middle Belt for i in range((thickness+1)//2): print((c*thickness*5).center(thickness*6)) #Bottom Pillars for i in range(thickness+1): print((c*thickness).center(thickness*2)+(c*thickness).center(thickness*6)) #Bottom Cone for i in range(thickness): print(((c*(thickness-i-1)).rjust(thickness)+c+(c*(thickness-i-1)).ljust(thickness)).rjust(thickness*6))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# String Split and Join # Use Python's split and join methods on the input string. # # https://www.hackerrank.com/challenges/python-string-split-and-join/problem # def split_and_join(line): # write your code here return '-'.join(line.split()) # (skeliton_tail) ---------------------------------------------------------------------- if __name__ == '__main__': line = input() result = split_and_join(line) print(result)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# String Formatting # Print the formatted decimal, octal, hexadecimal, and binary values for $n$ integers. # # https://www.hackerrank.com/challenges/python-string-formatting/problem # def print_formatted(number): # your code goes here w = len(bin(number)) - 2 # ne compte pas le préfixe 0b for n in range(1, number + 1): print("{0:{1}d} {0:{1}o} {0:{1}X} {0:{1}b}".format(n, w)) # (skeliton_tail) ---------------------------------------------------------------------- if __name__ == '__main__': n = int(input()) print_formatted(n)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }