problem_id int64 2.36k 5k | question stringlengths 52 14k | solutions stringlengths 79 675k | input_output stringlengths 37 505k | difficulty stringclasses 1
value | url stringlengths 36 94 | starter_code stringlengths 0 952 |
|---|---|---|---|---|---|---|
2,561 | =====Function Descriptions=====
collections.Counter()
A counter is a container that stores elements as dictionary keys, and their counts are stored as dictionary values.
Sample Code
>>> from collections import Counter
>>>
>>> myList = [1,1,2,3,4,5,3,2,3,4,2,1,2,3]
>>> print Counter(myList)
Counter({2: 4, 3: 4, 1: 3, ... | ["x = int(input())\nshoe_size = list(map(int,input().split()))\nn = int(input())\nsell = 0\nfor i in range(n):\n s, p = list(map(int,input().split()))\n if s in shoe_size:\n sell = sell + p\n shoe_size.remove(s)\nprint(sell)\n", "from collections import Counter\n\ndef __starting_point():\n X = in... | {"inputs": ["10\n2 3 4 5 6 8 7 6 5 18\n6\n6 55\n6 45\n6 55\n4 40\n18 60\n10 50"], "outputs": ["200"]} | introductory | https://www.hackerrank.com/challenges/collections-counter/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,562 | =====Problem Statement=====
In this task, we would like for you to appreciate the usefulness of the groupby() function of itertools.
You are given a string S. Suppose a character 'c' occurs consecutively X times in the string. Replace these consecutive occurrences of the character 'c' with (X, c) in the string.
=====I... | ["import itertools\ns = input().strip()\ns_unique_element = list(set(s))\ngroup = []\nkey = []\nfor k,g in itertools.groupby(s):\n group.append(list(g))\n key.append(k)\nfor i in range(len(group)):\n group_length = len(group[i])\n k = int(key[i])\n print(tuple((group_length,k)),end=' ')\n", "from itertoo... | {"inputs": ["1222311"], "outputs": ["(1, 1) (3, 2) (1, 3) (2, 1)"]} | introductory | https://www.hackerrank.com/challenges/compress-the-string/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,563 | =====Function Descriptions=====
inner
The inner tool returns the inner product of two arrays.
import numpy
A = numpy.array([0, 1])
B = numpy.array([3, 4])
print numpy.inner(A, B) #Output : 4
outer
The outer tool returns the outer product of two arrays.
import numpy
A = numpy.array([0, 1])
B = numpy.array([3... | ["import numpy\nnp_ar1 = numpy.array(list(map(int,input().split())))\nnp_ar2 = numpy.array(list(map(int,input().split())))\nprint((numpy.inner(np_ar1,np_ar2)))\nprint((numpy.outer(np_ar1,np_ar2)))\n", "import numpy as np\n\narr1 = np.array(list(map(int, input().strip().split())))\narr2 = np.array(list(map(int, input().... | {"inputs": ["0 1\n2 3"], "outputs": ["3\n[[0 0]\n [2 3]]"]} | introductory | https://www.hackerrank.com/challenges/np-inner-and-outer/problem |
import numpy |
2,564 | =====Problem Statement=====
A valid email address meets the following criteria:
It's composed of a username, domain name, and extension assembled in this format: username@domain.extension
The username starts with an English alphabetical character, and any subsequent characters consist of one or more of the following: ... | ["import re, email.utils\nn = int(input())\nfor t in range(n):\n s = input()\n parsed_email = email.utils.parseaddr(s)[1].strip()\n match_result = bool(re.match(r'(^[A-Za-z][A-Za-z0-9\\._-]+)@([A-Za-z]+)\\.([A-Za-z]{1,3})$',parsed_email))\n if match_result == True:\n print(s)\n", "import re\n\nt = in... | {"inputs": ["2\nDEXTER <dexter@hotmail.com>\nVIRUS <virus!@variable.:p>"], "outputs": ["DEXTER <dexter@hotmail.com>"]} | introductory | https://www.hackerrank.com/challenges/validating-named-email-addresses/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,565 | =====Function Descriptions=====
In Python, a string of text can be aligned left, right and center.
.ljust(width)
This method returns a left aligned string of length width.
>>> width = 20
>>> print 'HackerRank'.ljust(width,'-')
HackerRank----------
.center(width)
This method returns a centered string of length wi... | ["#Replace all ______ with rjust, ljust or center. \n\nthickness = int(input()) #This must be an odd number\nc = 'H'\n\n#Top Cone\nfor i in range(thickness):\n print(((c*i).rjust(thickness-1)+c+(c*i).ljust(thickness-1)))\n\n#Top Pillars\nfor i in range(thickness+1):\n print(((c*thickness).center(thickness*2)+(c*t... | {"inputs": ["5"], "outputs": [" H \n HHH \n HHHHH \n HHHHHHH \nHHHHHHHHH\n HHHHH HHHHH \n HHHHH HHHHH \n HHHHH HHHHH \n HHHHH HHHHH \n HHHHH HHHHH \n HHHHH HH... | introductory | 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).______(thickness-1)+c+(c*i).______(thickness-1))
#Top Pillars
for i in range(thickness+1):
print((c*thickness).______(thickness*2)+(c*thickness).___... |
2,566 | =====Function Descriptions=====
Calendar Module
The calendar module allows you to output calendars and provides additional useful functions for them.
class calendar.TextCalendar([firstweekday])
This class can be used to generate plain text calendars.
Sample Code
>>> import calendar
>>>
>>> print calendar.TextCalend... | ["import datetime\nimport calendar\nm,d,y=list(map(int,input().split()))\ninput_date = datetime.date(y,m,d)\nprint((calendar.day_name[input_date.weekday()].upper()))\n", "import calendar\n\ndef __starting_point():\n date = list(map(int, input().strip().split(' ')))\n print(calendar.day_name[calendar.weekday(date[... | {"inputs": ["08 05 2015"], "outputs": ["WEDNESDAY"]} | introductory | https://www.hackerrank.com/challenges/calendar-module/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,567 | =====Function Descriptions=====
any()
This expression returns True if any element of the iterable is true. If the iterable is empty, it will return False.
Code
>>> any([1>0,1==0,1<0])
True
>>> any([1<0,2<1,3<2])
False
all()
This expression returns True if all of the elements of the iterable are true. If the iterable ... | ["n = int(input())\nar = list(map(int,input().split()))\nar = sorted(ar)\nif(ar[0]<=0):\n print(False)\nelse:\n chk = False\n for i in ar:\n s = str(i)\n if (s==s[::-1]):\n chk = True\n break\n print(chk)\n", "def __starting_point():\n num_cnt = int(input().strip())\n ... | {"inputs": ["5\n12 9 61 5 14"], "outputs": ["True"]} | introductory | https://www.hackerrank.com/challenges/any-or-all/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,568 | =====Function Descriptions=====
If we want to add a single element to an existing set, we can use the .add() operation.
It adds the element to the set and returns 'None'.
=====Example=====
>>> s = set('HackerRank')
>>> s.add('H')
>>> print s
set(['a', 'c', 'e', 'H', 'k', 'n', 'r', 'R'])
>>> print s.add('HackerRank')
N... | ["n = int(input())\ncountry_set = set()\nfor i in range(n):\n country_name = input()\n country_set.add(country_name)\nprint((len(country_set)))\n", "#!/usr/bin/env python3\n\ndef __starting_point():\n N = int(input().strip())\n stamps = set()\n \n for _ in range(N):\n stamp = input().strip()\n ... | {"inputs": ["7\nUK\nChina\nUSA\nFrance\nNew Zealand\nUK\nFrance"], "outputs": ["5"]} | introductory | https://www.hackerrank.com/challenges/py-set-add/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,569 | =====Problem Statement=====
You are asked to ensure that the first and last names of people begin with a capital letter in their passports. For example, alison heck should be capitalised correctly as Alison Heck.
alison heck => Alison Heck
Given a full name, your task is to capitalize the name appropriately.
=====I... | ["s = input()\ns_ar = s.split(' ')\nfinal_ar = []\nspace = ' '\nfor w in s_ar:\n final_ar.append(w.capitalize())\nprint((space.join(final_ar)))\n"] | {"inputs": ["hello world"], "outputs": ["Hello World"]} | introductory | https://www.hackerrank.com/challenges/capitalize/problem |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the solve function below.
def solve(s):
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
result = solve(s)
fptr.write(result + '\n')
fptr.close()
|
2,570 | =====Problem Statement=====
The included code stub will read an integer, n, from STDIN.
Without using any string methods, try to print the following:
123...n
Note that "" represents the consecutive values in between.
=====Example=====
n = 5
Print the string 12345.
=====Input Format=====
The first line contains an int... | ["n=int(input())\nar=range(1,n+1)\nfor i in ar:\n print(i,end=\"\")\n", "def __starting_point():\n n = int(input())\n \n num = 1\n while num <= n:\n print(num, end='')\n num += 1\n\n__starting_point()"] | {"inputs": ["3"], "outputs": ["123"]} | introductory | https://www.hackerrank.com/challenges/python-print/problem |
if __name__ == '__main__':
n = int(input()) |
2,571 | =====Problem Statement=====
We have seen that lists are mutable (they can be changed), and tuples are immutable (they cannot be changed).
Let's try to understand this with an example.
You are given an immutable string, and you want to make changes to it.
Task
Read a given string, change the character at a given index... | ["def mutate_string(string, position, character):\n return string[:position]+character+string[position+1:]\n\n", "def mutate_string(string, position, character):\n out = list(string)\n out[position] = character\n return \"\".join(out)"] | {"fn_name": "mutate_string", "inputs": [["abracadabra", 5, "k"]], "outputs": ["abrackdabra"]} | introductory | https://www.hackerrank.com/challenges/python-mutations/problem |
def mutate_string(string, position, character):
return
if __name__ == '__main__':
s = input()
i, c = input().split()
s_new = mutate_string(s, int(i), c)
print(s_new) |
2,572 | =====Function Descriptions=====
So far, we have only heard of Python's powers. Now, we will witness them!
Powers or exponents in Python can be calculated using the built-in power function. Call the power function a^b as shown below:
>>> pow(a,b)
or
>>> a**b
It's also possible to calculate a^b mod m.
>>> pow(a,b,m)... | ["# Enter your code here. Read input from STDIN. Print output to STDOUT\na=int(input())\nb=int(input())\nc=int(input())\nprint((pow(a,b)))\nprint((pow(a,b,c)))\n", "#!/usr/bin/env python3\n\ndef __starting_point():\n a = int(input().strip())\n b = int(input().strip())\n m = int(input().strip())\n \n prin... | {"inputs": ["3\n4\n5"], "outputs": ["81\n1"]} | introductory | https://www.hackerrank.com/challenges/python-power-mod-power/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,573 | =====Function Descriptions=====
dot
The dot tool returns the dot product of two arrays.
import numpy
A = numpy.array([ 1, 2 ])
B = numpy.array([ 3, 4 ])
print numpy.dot(A, B) #Output : 11
cross
The cross tool returns the cross product of two arrays.
import numpy
A = numpy.array([ 1, 2 ])
B = numpy.array([... | ["import numpy\nn = int(input())\nar1 = []\nar2 = []\nfor i in range(n):\n tmp = list(map(int,input().split()))\n ar1.append(tmp)\nnp_ar1 = numpy.array(ar1)\nfor i in range(n):\n tmp = list(map(int,input().split()))\n ar2.append(tmp)\nnp_ar2 = numpy.array(ar2)\nprint((numpy.dot(np_ar1,np_ar2)))\n", "import ... | {"inputs": ["2\n1 2\n3 4\n1 2\n3 4"], "outputs": ["[[ 7 10]\n [15 22]]"]} | introductory | https://www.hackerrank.com/challenges/np-dot-and-cross/problem |
import numpy |
2,574 | =====Problem Statement=====
The re.sub() tool (sub stands for substitution) evaluates a pattern and, for each valid match, it calls a method (or lambda).
The method is called for all matches and can be used to modify strings in different ways.
The re.sub() method returns the modified string as an output.
Learn more ab... | ["import re, sys\nn = int(input())\nfor line in sys.stdin:\n remove_and = re.sub(r'(?<= )(&&)(?= )',\"and\",line)\n remove_or = re.sub(r'(?<= )(\\|\\|)(?= )',\"or\",remove_and)\n print(remove_or,end='')\n", "import re\n\ndef change(match):\n symb = match.group(0)\n \n if symb == \"&&\":\n retur... | {"inputs": ["11\na = 1;\nb = input();\n\nif a + b > 0 && a - b < 0:\n start()\nelif a*b > 10 || a/b < 1:\n stop()\nprint set(list(a)) | set(list(b)) \n#Note do not change &&& or ||| or & or |\n#Only change those '&&' which have space on both sides.\n#Only change those '|| which have space on both sides."], "outpu... | introductory | https://www.hackerrank.com/challenges/re-sub-regex-substitution/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,575 | =====Problem Statement=====
You are given an HTML code snippet of N lines.
Your task is to detect and print all the HTML tags, attributes and attribute values.
Print the detected items in the following format:
Tag1
Tag2
-> Attribute2[0] > Attribute_value2[0]
-> Attribute2[1] > Attribute_value2[1]
-> Attribute2[2] > A... | ["from html.parser import HTMLParser\n\nclass MyHTMLParser(HTMLParser):\n def handle_starttag(self, tag, attrs):\n print(tag)\n for at in attrs:\n print((\"-> {} > {}\".format(at[0], at[1])))\n def handle_startendtag(self, tag, attrs):\n print(tag)\n for at in attrs:\n ... | {"inputs": ["9\n<head>\n<title>HTML</title>\n</head>\n<object type=\"application/x-flash\"\n data=\"your-file.swf\"\n width=\"0\" height=\"0\">\n <!-- <param name=\"movie\" value=\"your-file.swf\" /> -->\n <param name=\"quality\" value=\"high\"/>\n</object>"], "outputs": ["head\ntitle\nobject\n-> type > application... | introductory | https://www.hackerrank.com/challenges/detect-html-tags-attributes-and-attribute-values/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,576 | =====Problem Statement=====
You are given a string S and width w.
Your task is to wrap the string into a paragraph of width w.
=====Input Format=====
The first line contains a string, S.
The second line contains the width, w.
=====Constraints=====
0 < len(S) < 1000
0 < w < len(S)
=====Output Format=====
Print the te... | ["import textwrap\ns = input()\nw = int(input().strip())\nprint((textwrap.fill(s,w)))\n"] | {"inputs": ["ABCDEFGHIJKLIMNOQRSTUVWXYZ\n4"], "outputs": ["ABCD\nEFGH\nIJKL\nIMNO\nQRST\nUVWX\nYZ"]} | introductory | https://www.hackerrank.com/challenges/text-wrap/problem | |
2,577 | =====Problem Statement=====
You and Fredrick are good friends. Yesterday, Fredrick received
credit cards from ABCD Bank. He wants to verify whether his credit card numbers are valid or not. You happen to be great at regex so he is asking for your help!
A valid credit card from ABCD Bank has the following characterist... | ["import re\nn = int(input())\nfor t in range(n):\n credit = input().strip()\n credit_removed_hiphen = credit.replace('-','')\n valid = True\n length_16 = bool(re.match(r'^[4-6]\\d{15}$',credit))\n length_19 = bool(re.match(r'^[4-6]\\d{3}-\\d{4}-\\d{4}-\\d{4}$',credit)) \n consecutive = bool(re.fin... | {"inputs": ["6\n4123456789123456\n5123-4567-8912-3456\n61234-567-8912-3456\n4123356789123456\n5133-3367-8912-3456\n5123 - 3567 - 8912 - 3456"], "outputs": ["Valid\nValid\nInvalid\nValid\nInvalid\nInvalid"]} | introductory | https://www.hackerrank.com/challenges/validating-credit-card-number/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,578 | =====Problem Statement=====
Given the names and grades for each student in a class of N students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade.
NOTE: If there are multiple students with the second lowest grade, order their names alphabetically and print each name on... | ["# Enter your code here. Read input from STDIN. Print output to STDOUT\nfrom collections import OrderedDict\n\nn=int(input())\nar={}\nval_ar=[]\nfor i in range(0,n):\n tmp_name=input()\n tmp_marks=float(input())\n ar[tmp_name]=tmp_marks\n val_ar.append(tmp_marks)\n \nset_val=set(val_ar)\nval_ar=list(set_v... | {"inputs": ["5\nHarry\n37.21\nBerry\n37.21\nTina\n37.2\nAkriti\n41\nHarsh\n39"], "outputs": ["Berry\nHarry"]} | introductory | https://www.hackerrank.com/challenges/nested-list/problem |
if __name__ == '__main__':
for _ in range(int(input())):
name = input()
score = float(input()) |
2,579 | =====Function Descriptions=====
The NumPy (Numeric Python) package helps us manipulate large arrays and matrices of numeric data.
To use the NumPy module, we need to import it using:
import numpy
Arrays
A NumPy array is a grid of values. They are similar to lists, except that every element of an array must be the s... | ["import numpy\nar = list(map(float,input().split()))\nnp_ar = numpy.array(ar,float)\nprint((np_ar[::-1]))\n"] | {"inputs": ["1 2 3 4 -8 -10"], "outputs": ["[-10. -8. 4. 3. 2. 1.]"]} | introductory | https://www.hackerrank.com/challenges/np-arrays/problem |
import numpy
def arrays(arr):
# complete this function
# use numpy.array
arr = input().strip().split(' ')
result = arrays(arr)
print(result) |
2,580 | =====Problem Statement=====
You are given a string S. S contains alphanumeric characters only. Your task is to sort the string S in the following manner:
All sorted lowercase letters are ahead of uppercase letters.
All sorted uppercase letters are ahead of digits.
All sorted odd digits are ahead of sorted even digits.
... | ["s = input()\ns = sorted(s,key = lambda x:(x.isdigit() and int(x)%2==0, x.isdigit(),x.isupper(),x.islower(),x))\nprint(*(s),sep = '')\n", "#!/usr/bin/env python3\n\ndef __starting_point():\n string = input().strip()\n \n print(*sorted(string, key = lambda x: (-x.islower(), x.isdigit() - x.isupper(), x in '024... | {"inputs": ["Sorting1234"], "outputs": ["ginortS1324"]} | introductory | https://www.hackerrank.com/challenges/ginorts/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,581 | =====Function Descriptions=====
Basic mathematical functions operate element-wise on arrays. They are available both as operator overloads and as functions in the NumPy module.
import numpy
a = numpy.array([1,2,3,4], float)
b = numpy.array([5,6,7,8], float)
print a + b #[ 6. 8. 10. 12.]
prin... | ["import numpy\nn,m = list(map(int,input().split()))\nar1 = []\nar2 = []\nfor i in range(n):\n tmp = list(map(int,input().split()))\n ar1.append(tmp)\nfor i in range(n):\n tmp = list(map(int,input().split()))\n ar2.append(tmp)\nnp_ar1 = numpy.array(ar1)\nnp_ar2 = numpy.array(ar2)\nprint((np_ar1 + np_ar2))\n... | {"inputs": ["1 4\n1 2 3 4\n5 6 7 8"], "outputs": ["[[ 6 8 10 12]]\n[[-4 -4 -4 -4]]\n[[ 5 12 21 32]]\n[[0 0 0 0]]\n[[1 2 3 4]]\n[[ 1 64 2187 65536]]"]} | introductory | https://www.hackerrank.com/challenges/np-array-mathematics/problem |
import numpy |
2,582 | =====Function Descriptions=====
Concatenate
Two or more arrays can be concatenated together using the concatenate function with a tuple of the arrays to be joined:
import numpy
array_1 = numpy.array([1,2,3])
array_2 = numpy.array([4,5,6])
array_3 = numpy.array([7,8,9])
print numpy.concatenate((array_1, array_2, arr... | ["import numpy\nn,m,p=list(map(int,input().split()))\n\nar1 = []\nar2 = []\nfor i in range(n):\n tmp = list(map(int,input().split()))\n ar1.append(tmp)\nfor i in range(m):\n tmp = list(map(int,input().split()))\n ar2.append(tmp) \nnp_ar1 = numpy.array(ar1)\nnp_ar2 = numpy.array(ar2)\nprint((numpy.concate... | {"inputs": ["4 3 2\n1 2\n1 2 \n1 2\n1 2\n3 4\n3 4\n3 4 "], "outputs": ["[[1 2]\n [1 2]\n [1 2]\n [1 2]\n [3 4]\n [3 4]\n [3 4]]"]} | introductory | https://www.hackerrank.com/challenges/np-concatenate/problem |
import numpy
|
2,583 | =====Function Descriptions=====
itertools.combinations(iterable, r)
This tool returns the r length subsequences of elements from the input iterable.
Combinations are emitted in lexicographic sorted order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.
Sample Code
>>> fr... | ["from itertools import *\ns,n = input().split()\nn = int(n) + 1\ns = sorted(s)\nfor i in range(1,n):\n for j in combinations(s,i):\n print((''.join(j)))\n", "#!/usr/bin/env python3\n\nfrom itertools import combinations\n\ndef __starting_point():\n in_data = list(input().strip().split(' '))\n \n for ... | {"inputs": ["HACK 2"], "outputs": ["A\nC\nH\nK\nAC\nAH\nAK\nCH\nCK\nHK"]} | introductory | https://www.hackerrank.com/challenges/itertools-combinations/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,584 | =====Function Descriptions=====
identity
The identity tool returns an identity array. An identity array is a square matrix with all the main diagonal elements as 1 and the rest as 0. The default type of elements is float.
import numpy
print numpy.identity(3) #3 is for dimension 3 X 3
#Output
[[ 1. 0. 0.]
[ 0. 1... | ["import numpy\nn,m = list(map(int,input().split()))\nprint((numpy.eye(n,m,k=0)))\n", "import numpy\n\nn, m = [int(x) for x in input().strip().split()]\n\nprint(numpy.eye(n, m))"] | {"inputs": ["3 3"], "outputs": ["[[1. 0. 0.]\n [0. 1. 0.]\n [0. 0. 1.]]"]} | introductory | https://www.hackerrank.com/challenges/np-eye-and-identity/problem |
import numpy |
2,585 | =====Problem Statement=====
An extra day is added to the calendar almost every four years as February 29, and the day is called a leap day. It corrects the calendar for the fact that our planet takes approximately 365.25 days to orbit the sun. A leap year contains a leap day.
In the Gregorian calendar, three condition... | ["def is_leap(year):\n leap = False\n if (year % 400 == 0):\n leap = True\n elif year % 4 == 0 and year % 100 !=0:\n leap = True \n return leap\n", "def is_leap(year):\n return (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0))"] | {"fn_name": "is_leap", "inputs": [[1990]], "outputs": [false]} | introductory | https://www.hackerrank.com/challenges/write-a-function/problem |
def is_leap(year):
leap = False
# Write your logic here
return leap
year = int(input())
print(is_leap(year)) |
2,586 | =====Function Descriptions=====
start() & end()
These expressions return the indices of the start and end of the substring matched by the group.
Code
>>> import re
>>> m = re.search(r'\d+','1234')
>>> m.end()
4
>>> m.start()
0
=====Problem Statement=====
You are given a string S.
Your task is to find the indices of... | ["import re\ns = input().strip()\nk = input().strip()\ns_len = len(s)\nfound_flag = False\nfor i in range(s_len):\n match_result = re.match(k,s[i:])\n if match_result:\n start_index = i+match_result.start()\n end_index = i+match_result.end()-1\n print((start_index,end_index))\n found_f... | {"inputs": ["aaadaa\naa"], "outputs": ["(0, 1) \n(1, 2)\n(4, 5)"]} | introductory | https://www.hackerrank.com/challenges/re-start-re-end/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,587 | =====Function Descriptions=====
*This section assumes that you understand the basics discussed in HTML Parser - Part 1
.handle_comment(data)
This method is called when a comment is encountered (e.g. <!--comment-->).
The data argument is the content inside the comment tag:
from HTMLParser import HTMLParser
class MyHT... | ["from html.parser import HTMLParser\nclass CustomHTMLParser(HTMLParser):\n def handle_comment(self, data):\n number_of_line = len(data.split('\\n'))\n if number_of_line>1:\n print('>>> Multi-line Comment')\n else:\n print('>>> Single-line Comment')\n if data.strip()... | {"inputs": ["4\n<!--[if IE 9]>IE9-specific content\n<![endif]-->\n<div> Welcome to HackerRank</div>\n<!--[if IE 9]>IE9-specific content<![endif]-->"], "outputs": [">>> Multi-line Comment\n[if IE 9]>IE9-specific content\n<![endif]\n>>> Data\n Welcome to HackerRank\n>>> Single-line Comment\n[if IE 9]>IE9-specific content... | introductory | https://www.hackerrank.com/challenges/html-parser-part-2/problem |
from html.parser import HTMLParser
class MyHTMLParser(HTMLParser):
html = ""
for i in range(int(input())):
html += input().rstrip()
html += '\n'
parser = MyHTMLParser()
parser.feed(html)
parser.close() |
2,588 | =====Problem Statement=====
You are given the firstname and lastname of a person on two different lines. Your task is to read them and print the following:
Hello firstname lastname! You just delved into python.
=====Input Format=====
The first line contains the first name, and the second line contains the last na... | ["# Enter your code here. Read input from STDIN. Print output to STDOUT\nfname=input()\nlname=input()\nprint((\"Hello \"+fname+\" \"+lname+\"! You just delved into python.\"))\n"] | {"inputs": ["Ross\nTaylor"], "outputs": ["Hello Ross Taylor! You just delved into python."]} | introductory | https://www.hackerrank.com/challenges/whats-your-name/problem |
def print_full_name(a, b):
print("")
if __name__ == '__main__':
first_name = input()
last_name = input()
print_full_name(first_name, last_name) |
2,589 | =====Function Descriptions=====
Exceptions
Errors detected during execution are called exceptions.
Examples:
ZeroDivisionError
This error is raised when the second argument of a division or modulo operation is zero.
>>> a = '1'
>>> b = '0'
>>> print int(a) / int(b)
>>> ZeroDivisionError: integer division or modulo by ... | ["n = int(input())\nfor i in range(n):\n a,b=input().split()\n try:\n print((int(a)//int(b)))\n except Exception as e:\n print((\"Error Code: \"+str(e)))\n", "#!/usr/bin/env python3\n\ndef __starting_point():\n t = int(input().strip())\n \n for _ in range(t):\n a, b = input().stri... | {"inputs": ["3\n1 0\n2 $\n3 1"], "outputs": ["Error Code: integer division or modulo by zero\nError Code: invalid literal for int() with base 10: '$'\n3"]} | introductory | https://www.hackerrank.com/challenges/exceptions/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,590 | =====Function Descriptions=====
min
The tool min returns the minimum value along a given axis.
import numpy
my_array = numpy.array([[2, 5],
[3, 7],
[1, 3],
[4, 0]])
print numpy.min(my_array, axis = 0) #Output : [1 0]
print numpy.min(m... | ["import numpy\nn,m = list(map(int,input().split()))\nar = []\nfor i in range(n):\n tmp = list(map(int,input().split()))\n ar.append(tmp)\nnp_ar = numpy.array(ar)\nprint((numpy.max(numpy.min(np_ar,axis=1))))\n", "import numpy as np\n\nn, m = [int(x) for x in input().strip().split()]\narray = np.array([[int(x) for... | {"inputs": ["4 2\n2 5\n3 7\n1 3\n4 0"], "outputs": ["3"]} | introductory | https://www.hackerrank.com/challenges/np-min-and-max/problem |
import numpy |
2,591 | =====Function Descriptions=====
shape
The shape tool gives a tuple of array dimensions and can be used to change the dimensions of an array.
(a). Using shape to get array dimensions
import numpy
my__1D_array = numpy.array([1, 2, 3, 4, 5])
print my_1D_array.shape #(5,) -> 5 rows and 0 columns
my__2D_array = num... | ["import numpy\nar = list(map(int,input().split()))\nnp_ar = numpy.array(ar)\nprint((numpy.reshape(np_ar,(3,3))))\n", "import numpy\narr = numpy.array([int(x) for x in input().strip().split()])\narr.shape = (3, 3)\nprint(arr)"] | {"inputs": ["1 2 3 4 5 6 7 8 9"], "outputs": ["[[1 2 3]\n [4 5 6]\n [7 8 9]]"]} | introductory | https://www.hackerrank.com/challenges/np-shape-reshape/problem |
import numpy |
2,592 | =====Function Descriptions=====
floor
The tool floor returns the floor of the input element-wise.
The floor of x is the largest integer i where i≤x.
import numpy
my_array = numpy.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9])
print numpy.floor(my_array) #[ 1. 2. 3. 4. 5. 6. 7. 8. 9.]
ceil
The t... | ["import numpy\nnp_ar = numpy.array(list(map(float,input().split())),float)\nprint((numpy.floor(np_ar)))\nprint((numpy.ceil(np_ar)))\nprint((numpy.rint(np_ar)))\n", "import numpy as np\n\narray = np.array(list(input().strip().split()), dtype = float)\n \nprint(np.floor(array))\nprint(np.ceil(array))\npr... | {"inputs": ["1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9"], "outputs": ["[1. 2. 3. 4. 5. 6. 7. 8. 9.]\n[ 2. 3. 4. 5. 6. 7. 8. 9. 10.]\n[ 1. 2. 3. 4. 6. 7. 8. 9. 10.]"]} | introductory | https://www.hackerrank.com/challenges/floor-ceil-and-rint/problem |
import numpy |
2,593 | =====Problem Statement=====
Kevin and Stuart want to play the 'The Minion Game'.
Game Rules
Both players are given the same string, S.
Both players have to make substrings using the letters of the string S.
Stuart has to make words starting with consonants.
Kevin has to make words starting with vowels.
The game ends ... | ["def minion_game(string):\n n=len(string)\n player1,player2=0,0\n for i in range(0,n):\n if(string[i] in 'AEIOU'):\n player1+=n-i\n else:\n player2+=n-i\n if(player1>player2):\n return 'Kevin '+ str(player1)\n elif(player1==player2):\n return 'Draw'\n ... | {"fn_name": "minion_game", "inputs": [["BANANA"]], "outputs": ["Stuart 12"]} | introductory | https://www.hackerrank.com/challenges/the-minion-game/problem |
def minion_game(string):
# your code goes here
if __name__ == '__main__':
s = input()
minion_game(s) |
2,594 | =====Problem Statement=====
You are given n words. Some words may repeat. For each word, output its number of occurrences. The output order should correspond with the input order of appearance of the word. See the sample input/output for clarification.
Note: Each input line ends with a "\n" character.
=====Constraint... | ["from collections import Counter, OrderedDict\nclass OrderedCounter(Counter,OrderedDict):\n pass\n\nword_ar = []\nn = int(input())\nfor i in range(n):\n word_ar.append(input().strip())\nword_counter = OrderedCounter(word_ar)\nprint(len(word_counter))\nfor word in word_counter:\n print(word_counter[word],end='... | {"inputs": ["4\nbcdef\nabcdefg\nbcde\nbcdef\n"], "outputs": ["3\n2 1 1"]} | introductory | https://www.hackerrank.com/challenges/word-order/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,595 | =====Function Descriptions=====
Polar coordinates are an alternative way of representing Cartesian coordinates or Complex Numbers.
A complex number z
z = x + yj
is completely determined by its real part y. Here, j is the imaginary unit.
A polar coordinate (r, φ) is completely determined by modulus r and phase angle φ.... | ["import cmath\nz = complex(input())\np = cmath.polar(z)\nprint((p[0]))\nprint((p[1]))\n", "#!/usr/bin/env python3\n\nimport cmath\n\ndef __starting_point():\n cnum = complex(input().strip())\n \n print(abs(cnum))\n print(cmath.phase(cnum))\n__starting_point()"] | {"inputs": ["1+2j"], "outputs": ["2.23606797749979 \n1.1071487177940904"]} | introductory | https://www.hackerrank.com/challenges/polar-coordinates/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,596 | =====Function Descriptions=====
A set is an unordered collection of elements without duplicate entries.
When printed, iterated or converted into a sequence, its elements will appear in an arbitrary order.
=====Example=====
>>> print set()
set([])
>>> print set('HackerRank')
set(['a', 'c', 'e', 'H', 'k', 'n', 'r', 'R'... | ["n = input()\nar = list(map(int,input().split(' ')))\nar=set(ar)\nprint((sum(ar) / len(ar)))\n", "def average(array):\n uniq = set(array)\n \n return sum(uniq)/len(uniq)\n"] | {"inputs": ["10\n161 182 161 154 176 170 167 171 170 174"], "outputs": ["169.375"]} | introductory | https://www.hackerrank.com/challenges/py-introduction-to-sets/problem |
def average(array):
# your code goes here
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().split()))
result = average(arr)
print(result) |
2,597 | =====Problem Statement=====
Given an integer, n, print the following values for each integer i from 1 to n:
1. Decimal
2. Octal
3. Hexadecimal (capitalized)
4. Binary
The four values must be printed on a single line in the order specified above for each i from 1 to n. Each value should be space-padded to match the wid... | ["n = int(input().strip())\nw = len(str(bin(n))[2:])\nfor i in range(1,n+1,1):\n o = str(oct(i))[2:]\n h = str(hex(i))[2:]\n h = h.upper()\n b = str(bin(i))[2:]\n d = str(i)\n print(('{:>{width}} {:>{width}} {:>{width}} {:>{width}}'.format(d,o,h,b,width=w)))\n"] | {"inputs": ["2"], "outputs": [" 1 1 1 1\n 2 2 2 10"]} | introductory | https://www.hackerrank.com/challenges/python-string-formatting/problem |
def print_formatted(number):
# your code goes here
if __name__ == '__main__':
n = int(input())
print_formatted(n) |
2,598 | =====Problem Statement=====
You are given a set A and n other sets.
Your job is to find whether set A is a strict superset of each of the N sets.
Print True, if A is a strict superset of each of the N sets. Otherwise, print False.
A strict superset has at least one element that does not exist in its subset.
=====Examp... | ["A = set(input().split())\nn = int(input())\ncheck = True\nfor i in range(n):\n s = set(input().split())\n if (s&A != s) or (s == A):\n check = False\n break\nprint(check)\n", "#!/usr/bin/env python3\n\ndef __starting_point():\n A = set(map(int, input().strip().split(' ')))\n t = int(input()... | {"inputs": ["1 2 3 4 5 6 7 8 9 10 11 12 23 45 84 78\n2\n1 2 3 4 5\n100 11 12"], "outputs": ["False"]} | introductory | https://www.hackerrank.com/challenges/py-check-strict-superset/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,599 | =====Problem Statement=====
You are given a positive integer N. Print a numerical triangle of height N - 1 like the one below:
1
22
333
4444
55555
......
Can you do it using only arithmetic operations, a single for loop and print statement?
Use no more than two lines. The first line (the for statement) is already wri... | ["for i in range(1,int(input())): #More than 2 lines will result in 0 score. Do not leave a blank line also\n print((10**i//9 * i))\n"] | {"inputs": ["5"], "outputs": ["1\n22\n333\n4444"]} | introductory | 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 |
2,600 | =====Function Descriptions=====
sum
The sum tool returns the sum of array elements over a given axis.
import numpy
my_array = numpy.array([ [1, 2], [3, 4] ])
print numpy.sum(my_array, axis = 0) #Output : [4 6]
print numpy.sum(my_array, axis = 1) #Output : [3 7]
print numpy.sum(my_array, axis = None)... | ["import numpy\nn,m=list(map(int,input().split()))\nar = []\nfor i in range(n):\n tmp = list(map(int,input().split()))\n ar.append(tmp)\nnp_ar = numpy.array(ar)\ns = numpy.sum(np_ar,axis=0)\nprint((numpy.prod(s)))\n", "import numpy as np\n\nn, m = [int(x) for x in input().strip().split()]\narray = np.array([[int(... | {"inputs": ["2 2\n1 2\n3 4"], "outputs": ["24"]} | introductory | https://www.hackerrank.com/challenges/np-sum-and-prod/problem |
import numpy |
2,601 | =====Function Descriptions=====
One of the built-in functions of Python is divmod, which takes two arguments a and b and returns a tuple containing the quotient of first and then the remainder.
=====Problem Statement=====
For example:
>>> print divmod(177,10)
(17, 7)
Here, the integer division is 177/10 => 17 and the... | ["# Enter your code here. Read input from STDIN. Print output to STDOUT\na=int(input())\nb=int(input())\nd=divmod(a,b)\nprint((d[0]))\nprint((d[1]))\nprint(d)\n", "output = divmod(int(input().strip()), int(input().strip()))\nprint(output[0])\nprint(output[1])\nprint(output)"] | {"inputs": ["177\n10"], "outputs": ["17\n7\n(17, 7)"]} | introductory | https://www.hackerrank.com/challenges/python-mod-divmod/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,602 | =====Function Descriptions=====
Transpose
We can generate the transposition of an array using the tool numpy.transpose.
It will not affect the original array, but it will create a new array.
import numpy
my_array = numpy.array([[1,2,3],
[4,5,6]])
print numpy.transpose(my_array)
#Output
[[1 4... | ["import numpy\nn,m = list(map(int,input().split()))\nar = []\nfor i in range(n):\n row = list(map(int,input().split()))\n ar.append(row)\n\nnp_ar = numpy.array(ar)\nprint((numpy.transpose(np_ar)))\nprint((np_ar.flatten()))\n", "import numpy\nn, m = [int(x) for x in input().strip().split()]\narr = []\nfor _ in ra... | {"inputs": ["2 2\n1 2\n3 4"], "outputs": ["[[1 3]\n [2 4]]\n[1 2 3 4]"]} | introductory | https://www.hackerrank.com/challenges/np-transpose-and-flatten/problem |
import numpy |
2,603 | =====Function Descriptions=====
mean
The mean tool computes the arithmetic mean along the specified axis.
import numpy
my_array = numpy.array([ [1, 2], [3, 4] ])
print numpy.mean(my_array, axis = 0) #Output : [ 2. 3.]
print numpy.mean(my_array, axis = 1) #Output : [ 1.5 3.5]
print numpy.mean(my_arra... | ["import numpy\nn,m = list(map(int,input().split()))\nar = []\nfor i in range(n):\n tmp = list(map(int,input().split()))\n ar.append(tmp)\nnp_ar = numpy.array(ar)\nprint((numpy.mean(np_ar,axis=1)))\nprint((numpy.var(np_ar,axis=0)))\nprint((numpy.std(np_ar,axis=None)))\n", "import numpy as np\n\nn, m = [int(x) for... | {"inputs": ["2 2\n1 2\n3 4"], "outputs": ["[1.5 3.5]\n[1. 1.]\n1.118033988749895"]} | introductory | https://www.hackerrank.com/challenges/np-mean-var-and-std/problem |
import numpy |
2,604 | =====Function Descriptions=====
itertools.permutations(iterable[, r])
This tool returns successive rlength permutations of elements in an iterable.
If r is not specified or is None, then r defaults to the length of the iterable, and all possible full length permutations are generated.
Permutations are printed in a lex... | ["import itertools\ns,n = list(map(str,input().split(' ')))\ns = sorted(s)\nfor p in list(itertools.permutations(s,int(n))):\n print((''.join(p)))\n", "#!/usr/bin/env python3\n\nfrom itertools import permutations\n\ndef __starting_point():\n in_data = list(input().strip().split(' '))\n \n for el in permutat... | {"inputs": ["HACK 2"], "outputs": ["AC\nAH\nAK\nCA\nCH\nCK\nHA\nHC\nHK\nKA\nKC\nKH"]} | introductory | https://www.hackerrank.com/challenges/itertools-permutations/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,605 | =====Problem Statement=====
Given the participants' score sheet for your University Sports Day, you are required to find the runner-up score. You are given n scores. Store them in a list and find the score of the runner-up.
=====Input Format=====
The first line contains n. The second line contains an array A[] of n in... | ["# Enter your code here. Read input from STDIN. Print output to STDOUT\nn=int(input())\nnum_str_ar=input().strip().split()\n\nnum_ar=list(map(int,num_str_ar))\nset_tmp=set(num_ar)\nfinal_ar=list(set_tmp)\nfinal_ar.sort()\nprint((final_ar[-2]))\n", "def __starting_point():\n n = int(input())\n arr = list(map(int,... | {"inputs": ["5\n2 3 6 6 5"], "outputs": ["5"]} | introductory | https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list/problem |
if __name__ == '__main__':
n = int(input())
arr = map(int, input().split()) |
2,606 | =====Function Descriptions=====
poly
The poly tool returns the coefficients of a polynomial with the given sequence of roots.
print numpy.poly([-1, 1, 1, 10]) #Output : [ 1 -11 9 11 -10]
roots
The roots tool returns the roots of a polynomial with the given coefficients.
print numpy.roots([1, 0, -1]) ... | ["import numpy\np = numpy.array(list(map(float,input().split())),float)\nx = float(input())\nprint((numpy.polyval(p,x)))\n", "import numpy as np\n\narray = np.array(list(map(float, input().strip().split())))\nx = float(input().strip())\n\nprint((np.polyval(array, x)))\n"] | {"inputs": ["1.1 2 3\n0"], "outputs": ["3.0"]} | introductory | https://www.hackerrank.com/challenges/np-polynomials/problem |
import numpy |
2,607 | =====Problem Statement=====
A newly opened multinational brand has decided to base their company logo on the three most common characters in the company name. They are now trying out various combinations of company names and logos based on this condition. Given a string s, which is the company name in lowercase letters... | ["#!/bin/python3\n\nimport sys\nfrom collections import Counter\n\ndef __starting_point():\n s = input().strip()\n best = Counter(s)\n sortit = sorted(list(best.items()), key = lambda x: (-x[1], x[0]))[:3]\n \n print((\"\\n\".join(x[0]+\" \"+str(x[1]) for x in sortit)))\n\n__starting_point()"] | {"inputs": ["aabbbccde"], "outputs": ["b 3\na 2\nc 2"]} | introductory | https://www.hackerrank.com/challenges/most-commons/problem |
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
s = input()
|
2,608 | =====Problem Statement=====
You are given a string s consisting only of digits 0-9, commas ,, and dots .
Your task is to complete the regex_pattern defined below, which will be used to re.split() all of the , and . symbols in s.
It’s guaranteed that every comma and every dot in s is preceeded and followed by a digit. | ["#!/usr/bin/env python3\n\nimport re\n\ndef __starting_point():\n out = list(re.split('[.,]', input()))\n print(\"\\n\".join(filter(lambda x: re.match('[0-9]+',x), out)))\n__starting_point()"] | {"inputs": ["100,000,000.000\n"], "outputs": ["100\n000\n000\n000\n"]} | introductory | https://www.hackerrank.com/challenges/re-split/problem |
regex_pattern = r"" # Do not delete 'r'.
import re
print("\n".join(re.split(regex_pattern, input()))) |
2,609 | =====Example=====
In Python, a string can be split on a delimiter.
Example:
>>> a = "this is a string"
>>> a = a.split(" ") # a is converted to a list of strings.
>>> print a
['this', 'is', 'a', 'string']
Joining a string is simple:
>>> a = "-".join(a)
>>> print a
this-is-a-string
=====Problem Statement=====
You ... | ["# Enter your code here. Read input from STDIN. Print output to STDOUT\nprint((\"-\").join(input().strip().split()))\n"] | {"inputs": ["this is a string"], "outputs": ["this-is-a-string"]} | introductory | https://www.hackerrank.com/challenges/python-string-split-and-join/problem |
def split_and_join(line):
# write your code here
if __name__ == '__main__':
line = input()
result = split_and_join(line)
print(result) |
2,610 | =====Function Descriptions=====
.intersection()
The .intersection() operator returns the intersection of a set and the set of elements in an iterable.
Sometimes, the & operator is used in place of the .intersection() operator, but it only operates on the set of elements in set.
The set is immutable to the .intersectio... | ["e = int(input())\neng = set(map(int,input().split()))\nf = int(input())\nfre = set(map(int,input().split()))\nprint((len(eng & fre)))\n", "#!/usr/bin/env python3\n\ndef __starting_point():\n n = int(input().strip())\n english = set(map(int, input().strip().split(' ')))\n m = int(input().strip())\n french ... | {"inputs": ["9\n1 2 3 4 5 6 7 8 9\n9\n10 1 2 3 11 21 55 6 8"], "outputs": ["5"]} | introductory | https://www.hackerrank.com/challenges/py-set-intersection-operation/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,611 | =====Function Descriptions=====
zeros
The zeros tool returns a new array with a given shape and type filled with 0's.
import numpy
print numpy.zeros((1,2)) #Default type is float
#Output : [[ 0. 0.]]
print numpy.zeros((1,2), dtype = numpy.int) #Type changes to int
#Output : [[0 0]]
ones
The o... | ["import numpy\nn_ar = list(map(int,input().split()))\nn = tuple(n_ar)\nprint((numpy.zeros(n,dtype=numpy.int)))\nprint((numpy.ones(n,dtype=numpy.int)))\n", "import numpy\ndims = [int(x) for x in input().strip().split()]\n\nprint(numpy.zeros(tuple(dims), dtype = numpy.int))\nprint(numpy.ones(tuple(dims), dtype = numpy.i... | {"inputs": ["3 3 3"], "outputs": ["[[[0 0 0]\n [0 0 0]\n [0 0 0]]\n\n [[0 0 0]\n [0 0 0]\n [0 0 0]]\n\n [[0 0 0]\n [0 0 0]\n [0 0 0]]]\n[[[1 1 1]\n [1 1 1]\n [1 1 1]]\n\n [[1 1 1]\n [1 1 1]\n [1 1 1]]\n\n [[1 1 1]\n [1 1 1]\n [1 1 1]]]"]} | introductory | https://www.hackerrank.com/challenges/np-zeros-and-ones/problem | |
2,612 | =====Problem Statement=====
The provided code stub reads and integer, n, from STDIN. For all non-negative integers i < n, print i^2.
=====Example=====
The list of non-negative integers that are less than n = 3 is [0,1,2]. Print the square of each number on a separate line.
0
1
4
=====Input Format=====
The first and o... | ["# Enter your code here. Read input from STDIN. Print output to STDOUT\na=int(input())\nfor i in range(0,a):\n print((i*i))\n", "def __starting_point():\n n = int(input())\n\n num = 0\n while num < n:\n print(pow(num, 2))\n num += 1\n__starting_point()"] | {"inputs": ["5"], "outputs": ["0\n1\n4\n9\n16"]} | introductory | https://www.hackerrank.com/challenges/python-loops/problem |
if __name__ == '__main__':
n = int(input()) |
2,613 | =====Function Descriptions=====
.union()
The .union() operator returns the union of a set and the set of elements in an iterable.
Sometimes, the | operator is used in place of .union() operator, but it operates only on the set of elements in set.
Set is immutable to the .union() operation (or | operation).
Example
>... | ["n = input()\neng = set(map(int,input().split()))\nb = input()\nfre = set(map(int,input().split()))\nprint((len(eng.union(fre))))\n", "#!/usr/bin/env python3\n\ndef __starting_point():\n n = int(input().strip())\n english = set(map(int, input().strip().split(' ')))\n m = int(input().strip())\n french = set... | {"inputs": ["9\n1 2 3 4 5 6 7 8 9\n9\n10 1 2 3 11 21 55 6 8"], "outputs": ["13"]} | introductory | https://www.hackerrank.com/challenges/py-set-union/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,614 | =====Problem Statement=====
Integers in Python can be as big as the bytes in your machine's memory. There is no limit in size as there is: 2^31 - 1 (c++ int) or 2^63 - 1 (C++ long long int).
As we know, a^b the result of grows really fast with increasing b.
Let's do some calculations on very large integers.
Task
Read f... | ["# Enter your code here. Read input from STDIN. Print output to STDOUT\na=int(input())\nb=int(input())\nc=int(input())\nd=int(input())\nprint((pow(a,b)+pow(c,d)))\n", "#!/usr/bin/env python3\n\ndef __starting_point():\n a = int(input().strip())\n b = int(input().strip())\n c = int(input().strip())\n d = in... | {"inputs": ["9\n29\n7\n27"], "outputs": ["4710194409608608369201743232"]} | introductory | https://www.hackerrank.com/challenges/python-integers-come-in-all-sizes/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,615 | =====Problem Statement=====
You are given a string N.
Your task is to verify that N is a floating point number.
In this task, a valid float number must satisfy all of the following requirements:
> Number can start with +, - or . symbol.
For example:
✔+4.50
✔-1.0
✔.5
✔-.7
✔+.4
✖ -+4.5
> Number must contain at least 1... | ["import re\nn = int(input())\nfor i in range(n):\n s = input() \n search_result = re.search(r'^[+-]?\\d*\\.\\d+$',s)\n print((bool(search_result)))\n", "#!/usr/bin/env python3\n\nimport re\n\ndef __starting_point():\n t = int(input().strip())\n pattern = '^[+-]?[0-9]*\\.[0-9]+$'\n \n for _ in r... | {"inputs": ["4\n4.0O0\n-1.00\n+4.54\nSomeRandomStuff"], "outputs": ["False\nTrue\nTrue\nFalse"]} | introductory | https://www.hackerrank.com/challenges/introduction-to-regex/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,616 | =====Function Descriptions=====
input()
In Python 2, the expression input() is equivalent to eval(raw _input(prompt)).
Code
>>> input()
1+2
3
>>> company = 'HackerRank'
>>> website = 'www.hackerrank.com'
>>> input()
'The company name: '+company+' and website: '+website
'The company name: HackerRank and website: www.... | ["#!/usr/bin/env python3\n\ndef __starting_point():\n x, k = map(int, input().strip().split())\n string = input().strip()\n \n if eval(string) == k:\n print(True)\n else:\n print(False)\n__starting_point()"] | {"inputs": ["1 4\nx**3 + x**2 + x + 1"], "outputs": ["True"]} | introductory | https://www.hackerrank.com/challenges/input/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,617 | =====Problem Statement=====
Consider a list (list = []). You can perform the following commands:
1. insert i e: Insert integer e at position i.
2. print: Print the list.
3. remove e: Delete the first occurrence of integer e.
4. append e: Insert integer e at the end of the list.
5. sort: Sort the list.
6. pop: Pop the l... | ["# Enter your code here. Read input from STDIN. Print output to STDOUT\nar=[]\nn=int(input())\nfor i in range(0,n):\n tmp_str=input()\n tmp_str_ar=tmp_str.strip().split(\" \")\n cmd=tmp_str_ar[0]\n if(cmd==\"print\"):\n print(ar)\n elif(cmd==\"sort\"):\n ar.sort()\n elif(cmd==\"reverse\... | {"inputs": ["12\ninsert 0 5\ninsert 1 10\ninsert 0 6\nprint\nremove 6\nappend 9\nappend 1\nsort\nprint\npop\nreverse\nprint"], "outputs": ["[6, 5, 10]\n[1, 5, 9, 10]\n[9, 5, 1]"]} | introductory | https://www.hackerrank.com/challenges/python-lists/problem |
if __name__ == '__main__':
N = int(input()) |
2,618 | =====Problem Statement=====
ABCXYZ company has up to 100 employees.
The company decides to create a unique identification number (UID) for each of its employees.
The company has assigned you the task of validating all the randomly generated UIDs.
A valid UID must follow the rules below:
It must contain at least 2 upp... | ["import re\nn = int(input())\nupper_check = r'.*([A-Z].*){2,}'\ndigit_check = r'.*([0-9].*){3,}'\nalphanumeric_and_length_check = r'([A-Za-z0-9]){10}$'\nrepeat_check = r'.*(.).*\\1'\nfor i in range(n):\n uid_string = input().strip()\n upper_check_result = bool(re.match(upper_check,uid_string))\n digit_check_r... | {"inputs": ["2\nB1CD102354\nB1CDEF2354"], "outputs": ["Invalid\nValid"]} | introductory | https://www.hackerrank.com/challenges/validating-uid/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,619 | =====Problem Statement=====
The provided code stub reads two integers, a and b, from STDIN.
Add logic to print two lines. The first line should contain the result of integer division,
a // b. The second line should contain the result of float division, a / b.
No rounding or formatting is necessary.
=====Example=====
a... | ["def __starting_point():\n a = int(input())\n b = int(input())\n \n print((a//b))\n print((a/b))\n\n__starting_point()"] | {"inputs": ["4\n3"], "outputs": ["1\n1.33333333333"]} | introductory | https://www.hackerrank.com/challenges/python-division/problem |
if __name__ == '__main__':
a = int(input())
b = int(input()) |
2,620 | =====Function Descriptions=====
collections.deque()
A deque is a double-ended queue. It can be used to add or remove elements from both ends.
Deques support thread safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction.
Example
Code
>>> f... | ["import collections\nn = int(input())\nd = collections.deque()\nfor i in range(n):\n cmd = list(input().strip().split())\n opt = cmd[0]\n if opt == 'pop':\n d.pop()\n elif opt == 'popleft':\n d.popleft()\n elif opt == 'append':\n d.append(int(cmd[1]))\n elif opt == 'appendleft':\... | {"inputs": ["6\nappend 1\nappend 2\nappend 3\nappendleft 4\npop\npopleft"], "outputs": ["1 2"]} | introductory | https://www.hackerrank.com/challenges/py-collections-deque/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,621 | =====Problem Statement=====
Mr. Anant Asankhya is the manager at the INFINITE hotel. The hotel has an infinite amount of rooms.
One fine day, a finite number of tourists come to stay at the hotel.
The tourists consist of:
→ A Captain.
→ An unknown group of families consisting of K members per group where K ≠ 1.
The C... | ["k = int(input())\nroom_number_list = list(map(int,input().split()))\nroom_number_set = set(room_number_list)\nroom_number_list_sum = sum(room_number_list)\nroom_number_set_sum = sum(room_number_set) * k\ndiff = room_number_set_sum - room_number_list_sum\nfor i in room_number_set:\n if diff == ((k-1)*i):\n p... | {"inputs": ["5\n1 2 3 6 5 4 4 2 5 3 6 1 6 5 3 2 4 1 2 5 1 4 3 6 8 4 3 1 5 6 2"], "outputs": ["8"]} | introductory | https://www.hackerrank.com/challenges/py-the-captains-room/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,622 | =====Problem Statement=====
There is an array of n integers. There are also 2 disjoint sets, A and B, each containing m integers. You like all the integers in set A and dislike all the integers in set B. Your initial happiness is 0. For each integer i in the array, if i ∈ A, you add 1 to your happiness. If i ∈ B, you a... | ["from collections import Counter\nn, m = list(map(int,input().split()))\nar = list(map(int,input().split()))\nar_set = set(ar)\nar_counter = Counter(ar)\nset_a = set(map(int,input().split()))\nset_b = set(map(int,input().split()))\nintersect_ar_a = list(ar_set&set_a)\nintersect_ar_b = list(ar_set&set_b)\nresult = 0\nf... | {"inputs": ["3 2\n1 5 3\n3 1\n5 7"], "outputs": ["1"]} | introductory | https://www.hackerrank.com/challenges/no-idea/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,623 | =====Problem Statement=====
The provided code stub reads two integers from STDIN, a and b. Add code to print three lines where:
The first line contains the sum of the two numbers.
The second line contains the difference of the two numbers (first - second).
The third line contains the product of the two numbers.
=====E... | ["# Enter your code here. Read input from STDIN. Print output to STDOUT\na=int(input())\nb=int(input())\nprint((a+b))\nprint((a-b))\nprint((a*b))\n", "def __starting_point():\n a = int(input())\n b = int(input())\n \n print((a + b))\n print((a - b))\n print((a * b))\n\n__starting_point()"] | {"inputs": ["3\n2"], "outputs": ["5\n1\n6"]} | introductory | https://www.hackerrank.com/challenges/python-arithmetic-operators/problem |
if __name__ == '__main__':
a = int(input())
b = int(input()) |
2,624 | =====Problem Statement=====
Mr. Vincent works in a door mat manufacturing company. One day, he designed a new door mat with the following specifications:
Mat size must be NXM. (N is an odd natural number, M and is 3 times N.)
The design should have 'WELCOME' written in the center.
The design pattern should only use |, ... | ["N, M = list(map(int,input().split())) # More than 6 lines of code will result in 0 score. Blank lines are not counted.\nfor i in range(1,N,2): \n print((int((M-3*i)/2)*'-'+(i*'.|.')+int((M-3*i)/2)*'-'))\nprint((int((M-7)/2)*'-'+'WELCOME'+int((M-7)/2)*'-'))\nfor i in range(N-2,-1,-2): \n print((int((M-3*i)/2)*'-... | {"inputs": ["7 21"], "outputs": ["---------.|.---------\n------.|..|..|.------\n---.|..|..|..|..|.---\n-------WELCOME-------\n---.|..|..|..|..|.---\n------.|..|..|.------\n---------.|.---------"]} | introductory | https://www.hackerrank.com/challenges/designer-door-mat/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,625 | =====Problem Statement=====
A valid postal code P have to fullfil both below requirements:
1. P must be a number in the range from 100000 to 999999 inclusive.
2. P must not contain more than one alternating repetitive digit pair.
Alternating repetitive digits are digits which repeat immediately after the next digit. ... | ["import re\np = input().strip()\nrange_check = bool(re.match(r'^[1-9][0-9]{5}$',p))\nrepeat_check = len(re.findall(r'(?=([0-9])[0-9]\\1)',p))\nprint((range_check == True and repeat_check<2))\n", "import re\n\nnum = input()\nprint(bool(re.match(r'^[1-9][\\d]{5}$', num) and len(re.findall(r'(\\d)(?=\\d\\1)', num))<2 ))"... | {"inputs": ["110000"], "outputs": ["False"]} | introductory | https://www.hackerrank.com/challenges/validating-postalcode/problem |
regex_integer_in_range = r"_________" # Do not delete 'r'.
regex_alternating_repetitive_digit_pair = r"_________" # Do not delete 'r'.
import re
P = input()
print (bool(re.match(regex_integer_in_range, P))
and len(re.findall(regex_alternating_repetitive_digit_pair, P)) < 2) |
2,626 | =====Function Descriptions=====
We have seen the applications of union, intersection, difference and symmetric difference operations, but these operations do not make any changes or mutations to the set.
We can use the following operations to create mutations to a set:
.update() or |=
Update the set by adding element... | ["n = int(input())\na = set(map(int,input().split()))\nN = int(input())\nfor i in range(N):\n cmd = input().split()\n opt = cmd[0]\n s = set(map(int,input().split()))\n if (opt == 'update'):\n a |= s\n elif (opt == 'intersection_update'):\n a &= s\n elif (opt == 'difference_update'):\n ... | {"inputs": ["16\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 24 52\n4\nintersection_update 10\n2 3 5 6 8 9 1 4 7 11\nupdate 2\n55 66\nsymmetric_difference_update 5\n22 7 35 62 58\ndifference_update 7\n11 22 35 55 58 62 66"], "outputs": ["38"]} | introductory | https://www.hackerrank.com/challenges/py-set-mutations/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,627 | =====Problem Statement=====
The itertools module standardizes a core set of fast, memory efficient tools that are useful by themselves or in combination. Together, they form an iterator algebra making it possible to construct specialized tools succinctly and efficiently in pure Python.
You are given a list of N lowerc... | ["from itertools import combinations\nn = int(input())\nar = input().split()\nk = int(input())\ncomb_list = list(combinations(ar,k))\na_list = [e for e in comb_list if 'a' in e]\nprint((len(a_list) / len(comb_list)))\n", "#!/usr/bin/env python3\n\nimport string\nsymbols = string.ascii_lowercase\n\nfrom itertools import... | {"inputs": ["4\na a c d\n2"], "outputs": ["0.833333333333"]} | introductory | https://www.hackerrank.com/challenges/iterables-and-iterators/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,628 | =====Problem Statement=====
The defaultdict tool is a container in the collections class of Python. It's similar to the usual dictionary (dict) container, but the only difference is that a defaultdict will have a default value if that key has not been set yet. If you didn't use a defaultdict you'd have to check to see ... | ["from collections import defaultdict\nd = defaultdict(list)\nn,m=list(map(int,input().split()))\nfor i in range(n):\n w = input()\n d[w].append(str(i+1))\nfor j in range(m):\n w = input()\n print((' '.join(d[w]) or -1))\n", "#!/usr/bin/env python3\n\nfrom collections import defaultdict\n\ndef __starting_po... | {"inputs": ["5 2\na\na\nb\na\nb\na\nb"], "outputs": ["1 2 4\n3 5"]} | introductory | https://www.hackerrank.com/challenges/defaultdict-tutorial/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,629 | =====Function Descriptions=====
HTML
Hypertext Markup Language is a standard markup language used for creating World Wide Web pages.
Parsing
Parsing is the process of syntactic analysis of a string of symbols. It involves resolving a string into its component parts and describing their syntactic roles.
HTMLParser
An ... | ["import re\nfrom html.parser import HTMLParser\n\nclass MyHTMLParser(HTMLParser):\n def handle_starttag(self, tag, attrs):\n print(\"Start\".ljust(6) + \":\", tag)\n for at in attrs:\n print(\"-> {} > {}\".format(at[0], at[1]))\n def handle_endtag(self, tag):\n print(\"End\".ljust... | {"inputs": ["2\n<html><head><title>HTML Parser - I</title></head>\n<body data-modal-target class='1'><h1>HackerRank</h1><br /></body></html>"], "outputs": ["Start : html\nStart : head\nStart : title\nEnd : title\nEnd : head\nStart : body\n-> data-modal-target > None\n-> class > 1\nStart : h1\nEnd : h1\nEmpty : br... | introductory | https://www.hackerrank.com/challenges/html-parser-part-1/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,630 | =====Problem Statement=====
You are given a positive integer N.
Your task is to print a palindromic triangle of size N.
For example, a palindromic triangle of size 5 is:
1
121
12321
1234321
123454321
You can't take more than two lines. The first line (a for-statement) is already written for you.
You have to complete ... | ["for i in range(1,int(input())+1): #More than 2 lines will result in 0 score. Do not leave a blank line also\n print(((10**i//9)**2))\n"] | {"inputs": ["5"], "outputs": ["1\n121\n12321\n1234321\n123454321"]} | introductory | https://www.hackerrank.com/challenges/triangle-quest-2/problem |
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 |
2,631 | =====Problem Statement=====
You are given a function f(X) = X^2. You are also given K lists. The ith list consists of N_i elements.
You have to pick one element from each list so that the value from the equation below is maximized:
S = (f(X_1) + f(X_2) + ... + f(X_k))%M
X_i denotes the element picked from the ith list... | ["import itertools\n\nk, m = list(map(int,input().split()))\n\nmain_ar = []\nfor i in range(k):\n ar = list(map(int,input().split()))\n main_ar.append(ar[1:])\n\nall_combination = itertools.product(*main_ar)\nresult = 0\nfor single_combination in all_combination: \n result = max(sum([x*x for x in single_comb... | {"inputs": ["3 1000\n2 5 4\n3 7 8 9\n5 5 7 8 9 10"], "outputs": ["206"]} | introductory | https://www.hackerrank.com/challenges/maximize-it/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,632 | =====Function Descriptions=====
collections.OrderedDict
An OrderedDict is a dictionary that remembers the order of the keys that were inserted first. If a new entry overwrites an existing entry, the original insertion position is left unchanged.
Example
Code
>>> from collections import OrderedDict
>>>
>>> ordinary_d... | ["import collections, re\nn = int(input())\nitem_od = collections.OrderedDict()\nfor i in range(n):\n record_list = re.split(r'(\\d+)$',input().strip())\n item_name = record_list[0]\n item_price = int(record_list[1])\n if item_name not in item_od:\n item_od[item_name]=item_price\n else:\n i... | {"inputs": ["9\nBANANA FRIES 12\nPOTATO CHIPS 30\nAPPLE JUICE 10\nCANDY 5\nAPPLE JUICE 10\nCANDY 5\nCANDY 5\nCANDY 5\nPOTATO CHIPS 30"], "outputs": ["BANANA FRIES 12\nPOTATO CHIPS 60\nAPPLE JUICE 20\nCANDY 20"]} | introductory | https://www.hackerrank.com/challenges/py-collections-ordereddict/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,633 | =====Problem Statement=====
You are given a spreadsheet that contains a list of N athletes and their details (such as age, height, weight and so on). You are required to sort the data based on the Kth attribute and print the final resulting table. Follow the example given below for better understanding.
image
Note th... | ["n, m = map(int,input().split())\nar = []\nfor i in range(n):\n ar.append(list(map(int,input().split())))\nk = int(input())\nar = sorted(ar,key = lambda x:x[k])\nfor i in ar:\n [print(x,end=' ') for x in i]\n print('')\n", "#!/bin/python3\n\nimport sys\n\ndef __starting_point():\n n, m = input().strip().sp... | {"inputs": ["5 3\n10 2 5\n7 1 0\n9 9 9\n1 23 12\n6 5 9\n1"], "outputs": ["7 1 0\n10 2 5\n6 5 9\n9 9 9\n1 23 12"]} | introductory | https://www.hackerrank.com/challenges/python-sort-sort/problem |
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
nm = input().split()
n = int(nm[0])
m = int(nm[1])
arr = []
for _ in range(n):
arr.append(list(map(int, input().rstrip().split())))
k = int(input())
|
2,634 | =====Function Descriptions=====
The NumPy module also comes with a number of built-in routines for linear algebra calculations. These can be found in the sub-module linalg.
linalg.det
The linalg.det tool computes the determinant of an array.
print numpy.linalg.det([[1 , 2], [2, 1]]) #Output : -3.0
linalg.eig
... | ["import numpy\nn = int(input())\nar = []\nfor i in range(n):\n tmp = list(map(float,input().split()))\n ar.append(tmp)\nnp_ar = numpy.array(ar,float)\nprint((numpy.linalg.det(np_ar)))\n", "import numpy as np\n\nn = int(input().strip())\narray = np.array([[float(x) for x in input().strip().split()] for _ in range... | {"inputs": ["2\n1.1 1.1\n1.1 1.1"], "outputs": ["0.0"]} | introductory | https://www.hackerrank.com/challenges/np-linear-algebra/problem |
import numpy |
2,635 | =====Problem Statement=====
In this challenge, the user enters a string and a substring. You have to print the number of times that the substring occurs in the given string. String traversal will take place from left to right, not from right to left.
NOTE: String letters are case-sensitive.
=====Input Format=====
The... | ["# Enter your code here. Read input from STDIN. Print output to STDOUT\ns=input()\nss=input()\ncnt=0\nlen_s=len(s)\nlen_ss=len(ss)\nfor i in range(0,len_s):\n tmp=s[i:i+len_ss]\n if(tmp==ss):\n cnt=cnt+1\nprint(cnt)\n", "def count_substring(string, sub_string):\n res = 0\n len_sub = len(sub_string)\... | {"inputs": ["ABCDCDC\nCDC"], "outputs": ["2"]} | introductory | https://www.hackerrank.com/challenges/find-a-string/problem |
def count_substring(string, sub_string):
return
if __name__ == '__main__':
string = input().strip()
sub_string = input().strip()
count = count_substring(string, sub_string)
print(count) |
2,636 | =====Function Descriptions=====
zip([iterable, ...])
This function returns a list of tuples. The ith tuple contains the ith element from each of the argument sequences or iterables. If the argument sequences are of unequal lengths, then the returned list is truncated to the length of the shortest argument sequence.
S... | ["n, x = list(map(int,input().split()))\nar = [0 for i in range(n)]\nfor i in range(x):\n temp_ar=list(map(float,input().split()))\n for j in range(n):\n ar[j] += temp_ar[j]\nfor i in range(n):\n print((ar[i]/x))\n", "#!/usr/bin/env python3\n\ndef __starting_point():\n st_num, sb_num = list(map(int, ... | {"inputs": ["5 3\n89 90 78 93 80\n90 91 85 88 86\n91 92 83 89 90.5"], "outputs": ["90.0 \n91.0 \n82.0 \n90.0 \n85.5"]} | introductory | https://www.hackerrank.com/challenges/zipped/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,637 | =====Problem Statement=====
ABC is a right triangle, 90°, at B. Therefore, ANGLE{ABC} = 90°.
Point M is the midpoint of hypotenuse AC.
You are given the lengths AB and BC.
Your task is to find ANGLE{MBC} (angle θ°, as shown in the figure) in degrees.
=====Input Format=====
The first contains the length of side AB.
The... | ["import math\nab = float(input())\nbc = float(input())\nac = math.sqrt((ab*ab)+(bc*bc))\nbm = ac / 2.0\nmc = bm\n#let, \nb = mc\nc = bm\na = bc\n#where b=c\nangel_b_radian = math.acos(a / (2*b))\nangel_b_degree = int(round((180 * angel_b_radian) / math.pi))\noutput_str = str(angel_b_degree)+'\u00b0'\nprint(output_str)... | {"inputs": ["10\n10"], "outputs": ["45\u00b0"]} | introductory | https://www.hackerrank.com/challenges/find-angle/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,638 | =====Problem Statement=====
Neo has a complex matrix script. The matrix script is a NXM grid of strings. It consists of alphanumeric characters, spaces and symbols (!,@,#,$,%,&).
To decode the script, Neo needs to read each column and select only the alphanumeric characters and connect them. Neo reads the column from t... | ["import re\nn, m = list(map(int,input().split()))\ncharacter_ar = [''] * (n*m)\nfor i in range(n):\n line = input()\n for j in range(m):\n character_ar[i+(j*n)]=line[j]\ndecoded_str = ''.join(character_ar)\nfinal_decoded_str = re.sub(r'(?<=[A-Za-z0-9])([ !@#$%&]+)(?=[A-Za-z0-9])',' ',decoded_str)\nprint(f... | {"inputs": ["7 3\nTsi\nh%x\ni #\nsM \n$a \n#t%\nir!"], "outputs": ["This is Matrix# %!"]} | introductory | https://www.hackerrank.com/challenges/matrix-script/problem |
#!/bin/python3
import math
import os
import random
import re
import sys
first_multiple_input = input().rstrip().split()
n = int(first_multiple_input[0])
m = int(first_multiple_input[1])
matrix = []
for _ in range(n):
matrix_item = input()
matrix.append(matrix_item)
|
2,639 | =====Function Descriptions=====
The eval() expression is a very powerful built-in function of Python. It helps in evaluating an expression. The expression can be a Python statement, or a code object.
For example:
>>> eval("9 + 5")
14
>>> x = 2
>>> eval("x + 3")
5
Here, eval() can also be used to work with Python keyw... | ["input()\n", "#!/usr/bin/env python3\n\ndef __starting_point():\n input().strip()\n__starting_point()"] | {"inputs": ["print(2 + 3)"], "outputs": ["5"]} | introductory | https://www.hackerrank.com/challenges/python-eval/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,640 | =====Problem Statement=====
There is a horizontal row of n cubes. The length of each cube is given. You need to create a new vertical pile of cubes. The new pile should follow these directions: if cube_i is on top of cube_j then sideLength_j ≥ sideLength_i.
When stacking the cubes, you can only pick up either the leftm... | ["from collections import deque\ncas = int(input())\nfor t in range(cas):\n n = int(input())\n dq = deque(list(map(int,input().split())))\n possible = True\n element = (2**31)+1\n while dq:\n left_element = dq[0]\n right_element = dq[-1]\n if left_element>=right_element and element>=... | {"inputs": ["2\n6\n4 3 2 1 3 4\n3\n1 3 2\n"], "outputs": ["Yes\nNo\n"]} | introductory | https://www.hackerrank.com/challenges/piling-up/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,641 | =====Problem Statement=====
When users post an update on social media,such as a URL, image, status update etc., other users in their network are able to view this new post on their news feed. Users can also see exactly when the post was published, i.e, how many hours, minutes or seconds ago.
Since sometimes posts are p... | ["import datetime\ncas = int(input())\nfor t in range(cas):\n timestamp1 = input().strip()\n timestamp2 = input().strip()\n time_format = \"%a %d %b %Y %H:%M:%S %z\"\n time_second1 = datetime.datetime.strptime(timestamp1,time_format)\n time_second2 = datetime.datetime.strptime(timestamp2,time_format)\n ... | {"inputs": ["2\nSun 10 May 2015 13:54:36 -0700\nSun 10 May 2015 13:54:36 -0000\nSat 02 May 2015 19:54:36 +0530\nFri 01 May 2015 13:54:36 -0000"], "outputs": ["25200\n88200"]} | introductory | https://www.hackerrank.com/challenges/python-time-delta/problem |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the time_delta function below.
def time_delta(t1, t2):
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input())
for t_itr in range(t):
t1 = input()
t2 = input()
d... |
2,642 | =====Problem Statement=====
You are given a string and your task is to swap cases. In other words, convert all lowercase letters to uppercase letters and vice versa.
=====Example=====
Www.HackerRank.com → wWW.hACKERrANK.COM
Pythonist 2 → pYTHONIST 2
=====Input Format=====
A single line containing a string S.
=====O... | ["def swap_case(s):\n newstring = \"\"\n \n for item in s:\n if item.isupper():\n newstring += item.lower()\n else:\n newstring += item.upper()\n \n return newstring\n", "def swap_case(s):\n out = ''\n for ind, let in enumerate(s):\n if let.isalpha... | {"fn_name": "swap_case", "inputs": [["HackerRank.com presents \"Pythonist 2\"."]], "outputs": ["hACKERrANK.COM PRESENTS \"pYTHONIST 2\"."]} | introductory | https://www.hackerrank.com/challenges/swap-case/problem |
def swap_case(s):
return
if __name__ == '__main__':
s = input()
result = swap_case(s)
print(result) |
2,643 | =====Function Descriptions=====
.symmetric_difference()
The .symmetric_difference() operator returns a set with all the elements that are in the set and the iterable but not both.
Sometimes, a ^ operator is used in place of the .symmetric_difference() tool, but it only operates on the set of elements in set.
The set i... | ["e = int(input())\neng = set(map(int,input().split())) \nf = int(input())\nfre = set(map(int,input().split()))\nprint((len(eng ^ fre)))\n", "#!/usr/bin/env python3\n\ndef __starting_point():\n n = int(input().strip())\n english = set(map(int, input().strip().split(' ')))\n m = int(input().strip())\n french... | {"inputs": ["9\n1 2 3 4 5 6 7 8 9\n9\n10 1 2 3 11 21 55 6 8"], "outputs": ["8"]} | introductory | https://www.hackerrank.com/challenges/py-set-symmetric-difference-operation/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,644 | =====Function Descriptions=====
Python has built-in string validation methods for basic data. It can check if a string is composed of alphabetical characters, alphanumeric characters, digits, etc.
str.isalnum()
This method checks if all the characters of a string are alphanumeric (a-z, A-Z and 0-9).
>>> print 'ab123'... | ["# Enter your code here. Read input from STDIN. Print output to STDOUT\ninputStr=input()\nresalnum = False\nresalpha = False\nresdigit = False\nreslower = False\nresupper = False\nfor i in inputStr:\n if(i.isalnum()):\n resalnum=True\n if(i.isalpha()):\n resalpha=True\n if(i.isdigit()):\n ... | {"inputs": ["qA2"], "outputs": ["True\nTrue\nTrue\nTrue\nTrue"]} | introductory | https://www.hackerrank.com/challenges/string-validators/problem |
if __name__ == '__main__':
s = input() |
2,645 | =====Function Descriptions=====
itertools.combinations_with_replacement(iterable, r)
This tool returns
length subsequences of elements from the input iterable allowing individual elements to be repeated more than once.
Combinations are emitted in lexicographic sorted order. So, if the input iterable is sorted, the co... | ["from itertools import *\ns,n = input().split()\nn = int(n)\ns = sorted(s)\nfor j in combinations_with_replacement(s,n):\n print((''.join(j)))\n", "#!/usr/bin/env python3\n\nfrom itertools import combinations_with_replacement\n\ndef __starting_point():\n in_data = list(input().strip().split(' '))\n \n for ... | {"inputs": ["HACK 2"], "outputs": ["AA\nAC\nAH\nAK\nCC\nCH\nCK\nHH\nHK\nKK"]} | introductory | https://www.hackerrank.com/challenges/itertools-combinations-with-replacement/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,646 | =====Problem Statement=====
CSS colors are defined using a hexadecimal (HEX) notation for the combination of Red, Green, and Blue color values (RGB).
Specifications of HEX Color Code
It must start with a '#' symbol.
It can have 3 or 6 digits.
Each digit is in the range of 0 to F. (1, 2, 3, 4, 5, 6, 7, 8, 9, 0, A, B, ... | ["import re\nn = int(input())\nfor t in range(n):\n s = input()\n match_result = re.findall(r'(#[0-9A-Fa-f]{3}|#[0-9A-Fa-f]{6})(?:[;,.)]{1})',s)\n for i in match_result:\n if i != '':\n print(i)\n", "import re\n\nn = int(input().strip())\ninside = False\nfor _ in range(n):\n line = input()... | {"inputs": ["11\n#BED\n{\n color: #FfFdF8; background-color:#aef;\n font-size: 123px;\n\n}\n#Cab\n{\n background-color: #ABC;\n border: 2px dashed #fff;\n}"], "outputs": ["#FfFdF8\n#aef\n#ABC\n#fff"]} | introductory | https://www.hackerrank.com/challenges/hex-color-code/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,647 | =====Problem Statement=====
You are given a string S.
Your task is to find out whether is a valid regex or not.
=====Input Format=====
The first line contains integer T, the number of test cases.
The next T lines contains the string S.
=====Constraints=====
0<T<100
=====Output Format=====
Print "True" or "False" for... | ["import re\nn = int(input())\nfor i in range(n):\n s = input()\n try:\n re.compile(s)\n print(True)\n except Exception as e:\n print(False)\n", "#!/usr/bin/env python3\n\nimport re\n\ndef __starting_point():\n t = int(input().strip())\n \n for _ in range(t):\n try:\n ... | {"inputs": ["2\n.*\\+\n.*+"], "outputs": ["True\nFalse"]} | introductory | https://www.hackerrank.com/challenges/incorrect-regex/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,648 | =====Function Descriptions=====
.difference()
The tool .difference() returns a set with all the elements from the set that are not in an iterable.
Sometimes the - operator is used in place of the .difference() tool, but it only operates on the set of elements in set.
Set is immutable to the .difference() operation (or... | ["e = int(input())\neng = set(map(int,input().split())) \nf = int(input())\nfre = set(map(int,input().split()))\nprint((len(eng - fre)))\n", "#!/usr/bin/env python3\n\ndef __starting_point():\n n = int(input().strip())\n english = set(map(int, input().strip().split(' ')))\n m = int(input().strip())\n french... | {"inputs": ["9\n1 2 3 4 5 6 7 8 9\n9\n10 1 2 3 11 21 55 6 8"], "outputs": ["4"]} | introductory | https://www.hackerrank.com/challenges/py-set-difference-operation/problem |
# Enter your code here. Read input from STDIN. Print output to STDOUT |
2,649 | =====Problem Statement=====
Here is a sample line of code that can be executed in Python:
print("Hello, World!")
You can just as easily store a string as a variable and then print it to stdout:
my_string = "Hello, World!"
print(my_string)
The above code will print Hello, World! on your screen. Try it yourself in the ... | ["def __starting_point():\n print(\"Hello, World!\")\n\n__starting_point()"] | {"inputs": [""], "outputs": ["Hello, World!"]} | introductory | https://www.hackerrank.com/challenges/py-hello-world/problem |
print("") |
2,650 | Iroha has a sequence of N strings S_1, S_2, ..., S_N. The length of each string is L.
She will concatenate all of the strings in some order, to produce a long string.
Among all strings that she can produce in this way, find the lexicographically smallest one.
Here, a string s=s_1s_2s_3...s_n is lexicographically smalle... | ["n,l = map(int,input().split())\na = []\nfor i in range(n):\n a.append(input())\n \na.sort()\nprint(\"\".join(str(i) for i in a))", "n,l = [int(x) for x in input().split()]\ns = []\nfor i in range(n):\n s.append(input())\ns.sort()\n\nprint(\"\".join(s))", "n, l = map(int, input().split( ))\nt = list()\nfor i in ran... | {"inputs": ["3 3\ndxx\naxx\ncxx\n"], "outputs": ["axxcxxdxx\n"]} | introductory | https://atcoder.jp/contests/abc042/tasks/abc042_b | |
2,651 | We are still with squared integers.
Given 4 integers `a, b, c, d` we form the sum of the squares of `a` and `b`
and then the sum of the squares of `c` and `d`. We multiply the two sums hence a number `n` and we try to
decompose `n` in a sum of two squares `e` and `f` (e and f integers >= 0) so that `n = e² + f²`.
Mo... | ["def prod2sum(a, b, c, d):\n e = sorted([abs(a*d-b*c), abs(a*c+b*d)])\n f = sorted([abs(a*c-b*d), abs(a*d+b*c)])\n if e == f:\n return [e]\n else:\n return sorted([e, f])\n\n", "def prod2sum(a, b, c, d):\n r1 = sorted([abs(a*c-b*d),abs(a*d+b*c)])\n r2 = sorted([abs(a*c+b*d),abs(a*d-b*c)... | {"fn_name": "prod2sum", "inputs": [[1, 2, 1, 3], [2, 3, 4, 5], [1, 2, 2, 3], [1, 1, 3, 5], [10, 11, 12, 13], [1, 20, -4, -5], [100, 100, 100, 100], [0, 0, 0, 0], [-14, 12, -10, 8], [7, 96, -1, 81], [112, 0, 0, 1]], "outputs": [[[[1, 7], [5, 5]]], [[[2, 23], [7, 22]]], [[[1, 8], [4, 7]]], [[[2, 8]]], [[[2, 263], [23, 26... | introductory | https://www.codewars.com/kata/55e86e212fce2aae75000060 |
def prod2sum(a, b, c, d):
|
2,652 | Your task is to write a function which counts the number of squares contained in an ASCII art picture.
The input pictures contain rectangles---some of them squares---drawn with the characters `-`, `|`, and `+`, where `-` and `|` are used to represent horizontal and vertical sides, and `+` is used to represent corners ... | ["def count_squares(lines):\n def s(i, j, z):\n try:\n return (\n '+' == lines[i+z][j] == lines[i][j+z] == lines[i+z][j+z]\n and all(lines[i][c] in '-+' for c in range(j+1, j+z))\n and all(lines[i+z][c] in '-+' for c in range(j+1, j+z))\n ... | {"fn_name": "count_squares", "inputs": [[["+--+ +----+", "| | | | +-+", "| | +----+ | |", "+--+ +-+"]], [["+-----+", "| |", "+-----+"]], [["+---+", "| |", "| +-+-+", "| | | |", "+-+-+ |", " | |", " +---+"]], [["+-+-+", "| | |", "+-+-+", "| | |", "+-+-+"]], [["+---+", "| |", "| |",... | introductory | https://www.codewars.com/kata/5bf71b94e50d1b00590000fe |
def count_squares(lines):
|
2,653 | For this game of `BINGO`, you will receive a single array of 10 numbers from 1 to 26 as an input. Duplicate numbers within the array are possible.
Each number corresponds to their alphabetical order letter (e.g. 1 = A. 2 = B, etc). Write a function where you will win the game if your numbers can spell `"BINGO"`. They ... | ["BINGO = {ord(c)-64 for c in \"BINGO\"}\n\ndef bingo(lst): \n return \"WIN\" if set(lst) >= BINGO else \"LOSE\"", "def bingo(array): \n return \"WIN\" if all(i in array for i in [2,9,14,7,15]) else \"LOSE\"", "def bingo(array):\n ctr = 0\n for i in [2, 9, 14, 7, 15]:\n if i in list(set(array)):\n ... | {"fn_name": "bingo", "inputs": [[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]], [[20, 12, 23, 14, 6, 22, 12, 17, 2, 26]], [[1, 2, 3, 7, 5, 14, 7, 15, 9, 10]], [[5, 2, 13, 7, 5, 14, 17, 15, 9, 10]]], "outputs": [["LOSE"], ["LOSE"], ["WIN"], ["WIN"]]} | introductory | https://www.codewars.com/kata/5a1ee4dfffe75f0fcb000145 |
def bingo(array):
|
2,654 | Kate and Michael want to buy a pizza and share it. Depending on the price of the pizza, they are going to divide the costs:
* If the pizza is less than €5,- Michael invites Kate, so Michael pays the full price.
* Otherwise Kate will contribute 1/3 of the price, but no more than €10 (she's broke :-) and Michael pays th... | ["def michael_pays(cost):\n return round(cost if cost < 5 else max(cost*2/3, cost-10), 2)", "def michael_pays(c):\n return round(c if c < 5 else c * 2 / 3 if c <= 30 else c - 10, 2)", "def michael_pays(costs):\n if costs < 5:\n michael = costs\n else:\n kate = min(costs / 3, 10)\n micha... | {"fn_name": "michael_pays", "inputs": [[15], [4], [4.99], [5], [30], [80], [22], [5.9181], [28.789], [4.325]], "outputs": [[10], [4], [4.99], [3.33], [20], [70], [14.67], [3.95], [19.19], [4.33]]} | introductory | https://www.codewars.com/kata/5b043e3886d0752685000009 |
def michael_pays(costs):
|
2,655 | You've arrived at a carnival and head straight for the duck shooting tent. Why wouldn't you?
You will be given a set amount of ammo, and an aim rating of between 1 and 0. No your aim is not always perfect - hey maybe someone fiddled with the sights on the gun...
Anyway your task is to calculate how many successful sh... | ["def duck_shoot(ammo, aim, ducks):\n return ducks.replace('2', 'X', int(ammo * aim))", "duck_shoot = lambda am, aim, d: d.replace('2','X', int(am*aim))", "def duck_shoot(ammo, aim, ducks):\n b = 0\n b += int(aim * ammo)\n return ducks.replace('2','X', b)\n", "duck_shoot=lambda a,b,c:c.replace('2','X',int(a... | {"fn_name": "duck_shoot", "inputs": [[4, 0.64, "|~~2~~~22~2~~22~2~~~~2~~~|"], [9, 0.22, "|~~~~~~~2~2~~~|"], [6, 0.41, "|~~~~~22~2~~~~~|"], [8, 0.05, "|2~~~~|"], [8, 0.92, "|~~~~2~2~~~~~22~~2~~~~2~~~2|"]], "outputs": [["|~~X~~~X2~2~~22~2~~~~2~~~|"], ["|~~~~~~~X~2~~~|"], ["|~~~~~XX~2~~~~~|"], ["|2~~~~|"], ["|~~~~X~X~~~~~... | introductory | https://www.codewars.com/kata/57d27a0a26427672b900046f |
def duck_shoot(ammo, aim, ducks):
|
2,656 | In the world of birding there are four-letter codes for the common names of birds. These codes are created by some simple rules:
* If the bird's name has only one word, the code takes the first four letters of that word.
* If the name is made up of two words, the code takes the first two letters of each word.
* If th... | ["import re\n\nSPLITTER = re.compile(r\"[\\s-]\")\n\ndef birdify(lst):\n return ''.join(x[:4//len(lst)] for x in lst) + ('' if len(lst)!=3 else lst[-1][1])\n\ndef bird_code(arr):\n return [birdify(SPLITTER.split(name)).upper() for name in arr]", "def bird_code(arr):\n codes = []\n \n for name in arr:\n ... | {"fn_name": "bird_code", "inputs": [[["American Redstart", "Northern Cardinal", "Pine Grosbeak", "Barred Owl", "Starling", "Cooper's Hawk", "Pigeon"]], [["Great Crested Flycatcher", "Bobolink", "American White Pelican", "Red-Tailed Hawk", "Eastern Screech Owl", "Blue Jay"]], [["Black-Crowned Night Heron", "Northern Moc... | introductory | https://www.codewars.com/kata/5a580064e6be38fd34000147 |
def bird_code(arr):
|
2,657 | In this exercise, a string is passed to a method and a new string has to be returned with the first character of each word in the string.
For example:
```
"This Is A Test" ==> "TIAT"
``` | ["def make_string(s):\n return ''.join(a[0] for a in s.split())\n", "def make_string(s):\n return \"\".join(word[0] for word in s.split())\n", "def make_string(s):\n return ''.join(w[0] for w in s.split())", "def make_string(s):\n return \"\".join(i[0] for i in s.split()) # first split the sentence by space... | {"fn_name": "make_string", "inputs": [["sees eyes xray yoat"], ["brown eyes are nice"], ["cars are very nice"], ["kaks de gan has a big head"]], "outputs": [["sexy"], ["bean"], ["cavn"], ["kdghabh"]]} | introductory | https://www.codewars.com/kata/5639bdcef2f9b06ce800005b |
def make_string(s):
|
2,658 | Complete the function to determine the number of bits required to convert integer `A` to integer `B` (where `A` and `B` >= 0)
The upper limit for `A` and `B` is 2^(16), `int.MaxValue` or similar.
For example, you can change 31 to 14 by flipping the 4th and 0th bit:
```
31 0 0 0 1 1 1 1 1
14 0 0 0 0 1 1 1 0
--- -... | ["def convert_bits(a,b):\n return bin(a^b).count(\"1\")", "def convert_bits(a, b):\n return f'{a^b:b}'.count('1')", "def convert_bits(a, b):\n return str(bin(a ^ b)).count('1')", "def convert_bits(a, b):\n return format(a ^ b, 'b').count('1')", "def convert_bits(a, b):\n difference=bin(a^b)[2:]\n retu... | {"fn_name": "convert_bits", "inputs": [[31, 14], [7, 17], [31, 0], [0, 0], [127681, 127681], [312312312, 5645657], [43, 2009989843]], "outputs": [[2], [3], [5], [0], [0], [13], [17]]} | introductory | https://www.codewars.com/kata/538948d4daea7dc4d200023f |
def convert_bits(a, b):
|
2,659 | There's a waiting room with N chairs set in single row. Chairs are consecutively numbered from 1 to N. First is closest to the entrance (which is exit as well).
For some reason people choose a chair in the following way
1. Find a place as far from other people as possible
2. Find a place as close to exit as possible... | ["def last_chair(n):\n return n - 1", "def last_chair(n):\n # Propn:\n # Given there are n seats, n >= 2. The (n-1)th seat is always the\n # last to be taken (taken in iteration n).\n # Proof:\n # Suppose that, for some n >= 2, the (n-1)th seat is taken on\n # iteration i > 2. The nth seat ... | {"fn_name": "last_chair", "inputs": [[10]], "outputs": [[9]]} | introductory | https://www.codewars.com/kata/542f0c36d002f8cd8a0005e5 |
def last_chair(n):
|
2,660 | Given an array of arguments, representing system call arguments keys and values, join it into a single, space-delimited string. You don't need to care about the application name -- your task is only about parameters.
Each element of the given array can be:
* a single string,
* a single string array,
* an array of two ... | ["def args_to_string(args):\n L = []\n for arg in args:\n if isinstance(arg, str):\n L.append(arg)\n elif len(arg) == 1:\n L.append(arg[0])\n elif len(arg[0]) == 1:\n L.append('-' + ' '.join(arg))\n else:\n L.append('--' + ' '.join(arg))\n ... | {"fn_name": "args_to_string", "inputs": [[["foo"]], [["f"]], [[["f"]]], [[["foo", "bar"]]], [[["f", "bar"]]], [[["foo", "bar"], ["baz", "qux"]]], [[["foo"], "bar", ["baz", "qux"], ["xyzzy", "a"], "a", ["a"], ["a", "plugh"]]], [[]], [[["---"], "---", ["---", "---"], ["-----", "-"], "-", ["-"], ["-", "-----"]]]], "output... | introductory | https://www.codewars.com/kata/53689951c8a5ca91ac000566 |
def args_to_string(args):
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.