problem_id
stringlengths
32
32
name
stringclasses
1 value
problem
stringlengths
200
14k
solutions
stringlengths
12
1.12M
test_cases
stringlengths
37
74M
difficulty
stringclasses
3 values
language
stringclasses
1 value
source
stringclasses
7 values
num_solutions
int64
12
1.12M
starter_code
stringlengths
0
956
202ead04fcf149c02d99cb2e22dacb9e
UNKNOWN
Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements. Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums. Example 1: Input: [1, 2, 2, 3, 1] Output: 2 Explanatio...
["class Solution:\n def findShortestSubArray(self, nums):\n \n diction = {}\n \n for i in nums:\n if i not in diction:\n diction[i] = 1\n else:\n diction[i] += 1\n \n degree = max(list(diction.values()))\n ...
{"fn_name": "findShortestSubArray", "inputs": [[[1, 2, 2, 3, 1]]], "outputs": [2]}
INTRODUCTORY
PYTHON3
LEETCODE
7,691
class Solution: def findShortestSubArray(self, nums: List[int]) -> int:
dd92d0d97349a2372cbd1d962e764eda
UNKNOWN
Given an unsorted array of integers, find the length of longest continuous increasing subsequence (subarray). Example 1: Input: [1,3,5,4,7] Output: 3 Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3. Even though [1,3,5,7] is also an increasing subsequence, it's not a continuous...
["class Solution:\n def findLengthOfLCIS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if len(nums) < 1:\n return 0\n cur_len = 1\n max_len = 1\n for i in range(1,len(nums)):\n if nums[i] > nums[i-1]:\n ...
{"fn_name": "findLengthOfLCIS", "inputs": [[[1, 3, 5, 4, 7]]], "outputs": [3]}
INTRODUCTORY
PYTHON3
LEETCODE
7,618
class Solution: def findLengthOfLCIS(self, nums: List[int]) -> int:
a6d83bc0ca65d5a98781c484dd11dd12
UNKNOWN
The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, calculate the Hamming distance. Note: 0 ≤ x, y < 231. Example: Input: x = 1, y = 4 Output: 2 Explanation: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ The above arrows poin...
["class Solution:\n def hammingDistance(self, x, y):\n \"\"\"\n :type x: int\n :type y: int\n :rtype: int\n \"\"\"\n x = x ^ y\n y = 0\n while (x):\n y += 1\n x &= x-1\n return y\n", "class Solution:\n def hammingDis...
{"fn_name": "hammingDistance", "inputs": [[1, 4]], "outputs": [2]}
INTRODUCTORY
PYTHON3
LEETCODE
4,953
class Solution: def hammingDistance(self, x: int, y: int) -> int:
6033e367453977a6b2cbef32652c2701
UNKNOWN
Given an integer n, return the number of trailing zeroes in n!. Example 1: Input: 3 Output: 0 Explanation: 3! = 6, no trailing zero. Example 2: Input: 5 Output: 1 Explanation: 5! = 120, one trailing zero. Note: Your solution should be in logarithmic time complexity.
["class Solution:\n def trailingZeroes(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n n_fives = 0\n while n > 0:\n n = n // 5\n n_fives += n\n return n_fives", "class Solution:\n def trailingZeroes(self, n):\n \"...
{"fn_name": "trailingZeroes", "inputs": [[3]], "outputs": [0]}
INTRODUCTORY
PYTHON3
LEETCODE
4,534
class Solution: def trailingZeroes(self, n: int) -> int:
62857384315a59510e32c52208435ac1
UNKNOWN
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Example: Given a = 1 and b = 2, return 3. Credits:Special thanks to @fujiaozhu for adding this problem and creating all test cases.
["class Solution:\n def getSum(self, a, b):\n max = 0x7FFFFFFF\n mask = 0xFFFFFFFF\n while b != 0:\n a, b = (a ^ b) & mask, ((a & b) << 1) & mask\n return a if a <= max else ~(a ^ mask)", "class Solution:\n def getSum(self, a, b):\n \"\"\"\n :type a: i...
{"fn_name": "getSum", "inputs": [[1, 2]], "outputs": [3]}
INTRODUCTORY
PYTHON3
LEETCODE
4,535
class Solution: def getSum(self, a: int, b: int) -> int:
9225f9084219f4fde146d98cab1803b9
UNKNOWN
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". Example 1: Input: ["flower","flow","flight"] Output: "fl" Example 2: Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input st...
["class Solution:\n def longestCommonPrefix(self, strs):\n \"\"\"\n :type strs: List[str]\n :rtype: str\n \"\"\" \n strs = strs\n import os \n return os.path.commonprefix(strs)\n \n \n # for x in strs:\n # if prefix in x:\n # ...
{"fn_name": "longestCommonPrefix", "inputs": [[["\"flower\"", "\"flow\"", "\"flight\""]]], "outputs": ["\"fl"]}
INTRODUCTORY
PYTHON3
LEETCODE
10,108
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str:
dd86329b05d110b979df62e82bf327b7
UNKNOWN
Given a rows x cols matrix mat, where mat[i][j] is either 0 or 1, return the number of special positions in mat. A position (i,j) is called special if mat[i][j] == 1 and all other elements in row i and column j are 0 (rows and columns are 0-indexed).   Example 1: Input: mat = [[1,0,0],   [0,0,1],   ...
["import itertools\n\nclass Solution:\n def numSpecial(self, mat: List[List[int]]) -> int:\n rr = [i for i, r in enumerate(mat) if sum(r) == 1]\n cc = [i for i, c in enumerate(zip(*mat)) if sum(c) == 1]\n return sum(1 for i, j in itertools.product(rr, cc) if mat[i][j] == 1)", "import numpy as np\n\nclass Solu...
{"fn_name": "numSpecial", "inputs": [[[[1, 0, 0], [0, 0, 1], [1, 0, 0], [], []]]], "outputs": [0]}
INTRODUCTORY
PYTHON3
LEETCODE
2,417
class Solution: def numSpecial(self, mat: List[List[int]]) -> int:
dbb4444fd262c03517cf741d6f08c9ec
UNKNOWN
In a list of songs, the i-th song has a duration of time[i] seconds.  Return the number of pairs of songs for which their total duration in seconds is divisible by 60.  Formally, we want the number of indices i, j such that i < j with (time[i] + time[j]) % 60 == 0.   Example 1: Input: [30,20,150,100,40] Output: 3 Expla...
["class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n \n arr = [0] * 60\n \n for t in time:\n arr[t % 60] += 1\n \n \n res = 0\n for i in range(31):\n if i == 0 or i == 30:\n res += (arr[i] * (arr[i]...
{"fn_name": "numPairsDivisibleBy60", "inputs": [[[30, 20, 150, 100, 40]]], "outputs": [3]}
INTRODUCTORY
PYTHON3
LEETCODE
30,920
class Solution: def numPairsDivisibleBy60(self, time: List[int]) -> int:
94646e2989045657d34157cab0992fed
UNKNOWN
Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too. You need to find the shortest such subarray and output its length. Example 1: Input: [2, 6, 4, 8, 10, 9, 15] Output: 5 Explanation: Y...
["class Solution:\n def findUnsortedSubarray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n left = 1\n size = len(nums)\n if size == 0:\n return 0\n while left < size and nums[left - 1] <= nums[left]:\n l...
{"fn_name": "findUnsortedSubarray", "inputs": [[[2, 6, 4, 8, 10, 9, 15]]], "outputs": [5]}
INTRODUCTORY
PYTHON3
LEETCODE
6,998
class Solution: def findUnsortedSubarray(self, nums: List[int]) -> int:
6ac563fe53fdd8bd2b6d998c297b292f
UNKNOWN
Given an integer n, add a dot (".") as the thousands separator and return it in string format.   Example 1: Input: n = 987 Output: "987" Example 2: Input: n = 1234 Output: "1.234" Example 3: Input: n = 123456789 Output: "123.456.789" Example 4: Input: n = 0 Output: "0"   Constraints: 0 <= n < 2^31
["class Solution:\n def thousandSeparator(self, n: int) -> str:\n arr = []\n i, count = 0, 0\n num = str(n)\n while i < len(num):\n if count != 3:\n arr.append(num[~i])\n i += 1\n count += 1\n else:\n arr.ap...
{"fn_name": "thousandSeparator", "inputs": [[987]], "outputs": ["987"]}
INTRODUCTORY
PYTHON3
LEETCODE
1,657
class Solution: def thousandSeparator(self, n: int) -> str:
4cdf60cf7e6c72daa29e1df93b97d484
UNKNOWN
You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins. Given n, find the total number of full staircase rows that can be formed. n is a non-negative integer and fits within the range of a 32-bit signed integer. Example 1: n = 5 The coins can form th...
["class Solution:\n def arrangeCoins(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n #brute force:\n #m = i (i+1) / 2 \n #i = 0\n #while True:\n # row = i * (i+1) / 2\n # if n - row < 0:\n # return i - 1\...
{"fn_name": "arrangeCoins", "inputs": [[5]], "outputs": [2]}
INTRODUCTORY
PYTHON3
LEETCODE
2,855
class Solution: def arrangeCoins(self, n: int) -> int:
64b79e9e7b1d02b1eb9b39386c2d8161
UNKNOWN
Given a string s of zeros and ones, return the maximum score after splitting the string into two non-empty substrings (i.e. left substring and right substring). The score after splitting a string is the number of zeros in the left substring plus the number of ones in the right substring.   Example 1: Input: s = "011101...
["class Solution:\n def maxScore(self, s: str) -> int:\n maxi=0\n for i in range(1,len(s)):\n a=s[:i]\n b=s[i:]\n maxi=max(a.count('0')+b.count('1'),maxi)\n return maxi", "class Solution:\n def maxScore(self, s: str) -> int:\n maxi = 0\n for i in...
{"fn_name": "maxScore", "inputs": [["\"011101\""]], "outputs": [5]}
INTRODUCTORY
PYTHON3
LEETCODE
6,958
class Solution: def maxScore(self, s: str) -> int:
598af9f423a24c3e09aa12285026f184
UNKNOWN
Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome. Example 1: Input: "aba" Output: True Example 2: Input: "abca" Output: True Explanation: You could delete the character 'c'. Note: The string will only contain lowercase characters a-z. The maximum l...
["class Solution:\n def validPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n if s == s[::-1]:\n return True\n r = s[::-1]\n for i in range(0, len(s)):\n if r[i] == s[i]:\n continue\n el...
{"fn_name": "validPalindrome", "inputs": [["\"aba\""]], "outputs": [true]}
INTRODUCTORY
PYTHON3
LEETCODE
2,542
class Solution: def validPalindrome(self, s: str) -> bool:
862cdf0495f90ab14bd7f380f793c5e5
UNKNOWN
Given an array of integers arr, a lucky integer is an integer which has a frequency in the array equal to its value. Return a lucky integer in the array. If there are multiple lucky integers return the largest of them. If there is no lucky integer return -1.   Example 1: Input: arr = [2,2,3,4] Output: 2 Explanation: Th...
["class Solution:\n def findLucky(self, arr: List[int]) -> int:\n c=collections.Counter(arr)\n maxi=-1\n for i in c:\n if i==c[i]:\n maxi=max(maxi,i)\n return maxi", "from collections import Counter\nclass Solution:\n def findLucky(self, arr: List[int]) -> int...
{"fn_name": "findLucky", "inputs": [[[2, 2, 3, 4]]], "outputs": [2]}
INTRODUCTORY
PYTHON3
LEETCODE
12,195
class Solution: def findLucky(self, arr: List[int]) -> int:
529253f864c69391ac3ac98be8e83050
UNKNOWN
A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between all pairs of neighboring stops where distance[i] is the distance between the stops number i and (i + 1) % n. The bus goes along both directions i.e. clockwise and counterclockwise. Return the shortest distance between the given ...
["class Solution:\n def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:\n \n if start > destination: \n start, destination = destination, start \n \n sum1 = sum(distance[start:destination])\n sum2 = sum(distance) - sum1 \n ...
{"fn_name": "distanceBetweenBusStops", "inputs": [[[1, 2, 3, 4], 0, 1]], "outputs": [1]}
INTRODUCTORY
PYTHON3
LEETCODE
7,381
class Solution: def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:
18665fd9749cdd276f6874ed599514e4
UNKNOWN
Given an integer n. Each number from 1 to n is grouped according to the sum of its digits.  Return how many groups have the largest size.   Example 1: Input: n = 13 Output: 4 Explanation: There are 9 groups in total, they are grouped according sum of its digits of numbers from 1 to 13: [1,10], [2,11], [3,12], [4,13], [...
["class Solution:\n memory = {}\n largest = [0]\n trackerForLargest = {}\n largestSize = [0]\n numGroups = [0]\n \n def countLargestGroup(self, n: int) -> int:\n if n > self.largest[0]:\n for num in range(self.largest[0] + 1, n + 1):\n curr = num\n cu...
{"fn_name": "countLargestGroup", "inputs": [[13]], "outputs": [4]}
INTRODUCTORY
PYTHON3
LEETCODE
23,385
class Solution: def countLargestGroup(self, n: int) -> int:
9b5c7baf5d38441f445c7f032ad9d280
UNKNOWN
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. Example 1: Input: [3,0,1] Output: 2 Example 2: Input: [9,6,4,2,3,5,7,0,1] Output: 8 Note: Your algorithm should run in linear runtime complexity. Could you implement it using only constant extr...
["class Solution:\n def missingNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if 0 not in nums:\n return 0\n array=sorted(nums)\n for i in range(len(array)):\n try:\n dif=array[i+1]-array[i...
{"fn_name": "missingNumber", "inputs": [[[3, 0, 1]]], "outputs": [2]}
INTRODUCTORY
PYTHON3
LEETCODE
4,451
class Solution: def missingNumber(self, nums: List[int]) -> int:
24237b10a13362883761e92e186fc2a9
UNKNOWN
Given an array A of positive lengths, return the largest perimeter of a triangle with non-zero area, formed from 3 of these lengths. If it is impossible to form any triangle of non-zero area, return 0.   Example 1: Input: [2,1,2] Output: 5 Example 2: Input: [1,2,1] Output: 0 Example 3: Input: [3,2,3,4] Output: 1...
["class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n \n A.sort(reverse=True)\n la=len(A)\n for i in range(la-2):\n if A[i]<A[i+1]+A[i+2]:\n return A[i]+A[i+1]+A[i+2]\n return 0", "class Solution:\n def largestPerimeter(self, A: List[in...
{"fn_name": "largestPerimeter", "inputs": [[[1, 2, 2]]], "outputs": [5]}
INTRODUCTORY
PYTHON3
LEETCODE
18,786
class Solution: def largestPerimeter(self, A: List[int]) -> int:
f325a31cd8bf9fd496ce63e166947a9b
UNKNOWN
Given an integer (signed 32 bits), write a function to check whether it is a power of 4. Example: Given num = 16, return true. Given num = 5, return false. Follow up: Could you solve it without loops/recursion? Credits:Special thanks to @yukuairoy for adding this problem and creating all test cases.
["class Solution:\n def isPowerOfFour(self, num):\n \"\"\"\n :type num: int\n :rtype: bool\n \"\"\"\n return num != 0 and num & (num -1) == 0 and num & 0x55555555 == num", "class Solution:\n def isPowerOfFour(self, num):\n \"\"\"\n :type num: int\n ...
{"fn_name": "isPowerOfFour", "inputs": [[16]], "outputs": [true]}
INTRODUCTORY
PYTHON3
LEETCODE
2,616
class Solution: def isPowerOfFour(self, num: int) -> bool:
f60d06188fb44ebafef84dbc502bdf90
UNKNOWN
An array is monotonic if it is either monotone increasing or monotone decreasing. An array A is monotone increasing if for all i <= j, A[i] <= A[j].  An array A is monotone decreasing if for all i <= j, A[i] >= A[j]. Return true if and only if the given array A is monotonic.   Example 1: Input: [1,2,2,3] Output: tru...
["class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n if not A: return True\n increasing = True\n index = 0\n while index<len(A)-1 and A[index] == A[index+1]:\n index+=1\n if index == len(A)-1:\n return True\n if A[index] > A[index+1]:\n ...
{"fn_name": "isMonotonic", "inputs": [[[1, 2, 2, 3]]], "outputs": [true]}
INTRODUCTORY
PYTHON3
LEETCODE
48,926
class Solution: def isMonotonic(self, A: List[int]) -> bool:
6ef0cb63da1ace14a9ff0edc28a5555c
UNKNOWN
Given a string S, return the "reversed" string where all characters that are not a letter stay in the same place, and all letters reverse their positions.   Example 1: Input: "ab-cd" Output: "dc-ba" Example 2: Input: "a-bC-dEf-ghIj" Output: "j-Ih-gfE-dCba" Example 3: Input: "Test1ng-Leet=code-Q!" Output: "...
["class Solution:\n def reverseOnlyLetters(self, S: str) -> str:\n stack = [char for char in S if char.isalpha()]\n result = ''\n for char in S:\n if char.isalpha():\n temp = stack.pop()\n result += temp\n else:\n result += char\...
{"fn_name": "reverseOnlyLetters", "inputs": [["\"ab-cd\""]], "outputs": ["\"dc-ba\""]}
INTRODUCTORY
PYTHON3
LEETCODE
4,224
class Solution: def reverseOnlyLetters(self, S: str) -> str:
111f5ed95b8c2569f3c1cff034e57719
UNKNOWN
On a N * N grid, we place some 1 * 1 * 1 cubes that are axis-aligned with the x, y, and z axes. Each value v = grid[i][j] represents a tower of v cubes placed on top of grid cell (i, j). Now we view the projection of these cubes onto the xy, yz, and zx planes. A projection is like a shadow, that maps our 3 dimensional ...
["class Solution:\n def projectionArea(self, grid: List[List[int]]) -> int:\n ans=0\n for i in range(len(grid)):\n row=0\n col=0\n for j in range(len(grid[i])):\n if(grid[i][j]):\n ans+=1\n row=max(row,grid[i][j])\n ...
{"fn_name": "projectionArea", "inputs": [[[[2], [], []]]], "outputs": [5]}
INTRODUCTORY
PYTHON3
LEETCODE
1,209
class Solution: def projectionArea(self, grid: List[List[int]]) -> int:
d72a511942b9f8753ea6b33f999e094b
UNKNOWN
On an 8 x 8 chessboard, there is one white rook.  There also may be empty squares, white bishops, and black pawns.  These are given as characters 'R', '.', 'B', and 'p' respectively. Uppercase characters represent white pieces, and lowercase characters represent black pieces. The rook moves as in the rules of Chess: it...
["class Solution:\n def numRookCaptures(self, board: List[List[str]]) -> int:\n count=0;\n for i in range(len(board)):\n for j in range(len(board[i])):\n if board[i][j]=='R':\n d=1;\n #\uc704\n while 0<=i-d:\n ...
{"fn_name": "numRookCaptures", "inputs": [[[["\".\"", "\".\"", "\".\"", "\".\"", "\".\"", "\".\"", "\".\"", "\".\""], ["\".\"", "\".\"", "\".\"", "\"p\"", "\".\"", "\".\"", "\".\"", "\".\""], ["\".\"", "\".\"", "\".\"", "\"R\"", "\".\"\n", "\".\"", "\".\"", "\"p\""], ["\".\"", "\".\"", "\".\"", "\".\"", "\".\"", "\".\"...
INTRODUCTORY
PYTHON3
LEETCODE
1,753
class Solution: def numRookCaptures(self, board: List[List[str]]) -> int:
207eaf8372775d3532aa790c19915409
UNKNOWN
Given an array of integers nums. A pair (i,j) is called good if nums[i] == nums[j] and i < j. Return the number of good pairs.   Example 1: Input: nums = [1,2,3,1,1,3] Output: 4 Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed. Example 2: Input: nums = [1,1,1,1] Output: 6 Explanation: Each pair...
["class Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n my_count = 0\n my_dict = {}\n for n in nums:\n my_count += my_dict.get(n,0)\n my_dict[n] = my_dict.get(n,0) +1\n return my_count\n \n\n", "class Solution:\n def numIdenticalPairs(...
{"fn_name": "numIdenticalPairs", "inputs": [[[1, 2, 3, 1, 1, 3]]], "outputs": [4]}
INTRODUCTORY
PYTHON3
LEETCODE
4,073
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int:
9682cf6068257a4b6c4626e93191ecf0
UNKNOWN
Given a m * n matrix grid which is sorted in non-increasing order both row-wise and column-wise.  Return the number of negative numbers in grid.   Example 1: Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]] Output: 8 Explanation: There are 8 negatives number in the matrix. Example 2: Input: grid = [[3,2...
["class Solution:\n def countNegatives(self, grid: List[List[int]]) -> int:\n count = 0\n for arr in grid:\n for num in arr:\n if num < 0:\n count +=1\n return count", "class Solution:\n def countNegatives(self, grid: List[List[int]]) -> int:\n ...
{"fn_name": "countNegatives", "inputs": [[[[4, 3, 2, -1], [3, 2, 1, -1], [1, 1, -1, -2], [-1, -1, -2, -3], [], []]]], "outputs": [8]}
INTRODUCTORY
PYTHON3
LEETCODE
6,579
class Solution: def countNegatives(self, grid: List[List[int]]) -> int:
ac55805920ae1289ed8c3712e9e3d749
UNKNOWN
Write a program to check whether a given number is an ugly number. Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. Example 1: Input: 6 Output: true Explanation: 6 = 2 × 3 Example 2: Input: 8 Output: true Explanation: 8 = 2 × 2 × 2 Example 3: Input: 14 Output: false Explanation: 1...
["class Solution:\n def isUgly(self, num):\n \"\"\"\n :type num: int\n :rtype: bool\n \"\"\"\n if num < 1:\n return False\n while num % 2 == 0:\n num = num / 2\n while num % 3 == 0:\n num = num / 3\n while num % 5 ==...
{"fn_name": "isUgly", "inputs": [[6]], "outputs": [true]}
INTRODUCTORY
PYTHON3
LEETCODE
6,808
class Solution: def isUgly(self, num: int) -> bool:
048d4393c5845c94a532286405eec335
UNKNOWN
You are given a string text of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that text contains at least one word. Rearrange the spaces so that there is an equal number of spaces between every pair ...
["class Solution:\n def reorderSpaces(self, text: str) -> str:\n s = text.split()\n if len(s) == 1: \n text = ''.join(s) + ' '*text.count(' ')\n return text\n count = text.count(' ')//(len(s)-1)\n extra = text.count(' ')%(len(s)-1)\n result = ''\n num =...
{"fn_name": "reorderSpaces", "inputs": [["\" this is a sentence \""]], "outputs": ["\" this is a sentence \" "]}
INTRODUCTORY
PYTHON3
LEETCODE
3,347
class Solution: def reorderSpaces(self, text: str) -> str:
c622090470ecd6a29019352ef4c23113
UNKNOWN
At a lemonade stand, each lemonade costs $5.  Customers are standing in a queue to buy from you, and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill.  You must provide the correct change to each customer, so that the net transact...
["class Solution:\n \n def lemonadeChange(self, bills: List[int]) -> bool: \n n5=0\n n10=0 \n for i in bills:\n if i == 5:\n n5 +=1\n elif i == 10:\n if n5<=0:\n return False\n ...
{"fn_name": "lemonadeChange", "inputs": [[[5, 5, 5, 10, 20]]], "outputs": [true]}
INTRODUCTORY
PYTHON3
LEETCODE
38,478
class Solution: def lemonadeChange(self, bills: List[int]) -> bool:
bbba6518f91a85c562d07041579a03a7
UNKNOWN
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considere...
["class Solution:\n def isValid(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n stack = []\n dict = {\"]\":\"[\", \"}\":\"{\", \")\":\"(\"}\n \n for i in s:\n if i in dict.values():\n stack.append(i)\n ...
{"fn_name": "isValid", "inputs": [["\"()\""]], "outputs": [false]}
INTRODUCTORY
PYTHON3
LEETCODE
8,547
class Solution: def isValid(self, s: str) -> bool:
b53b16a9922ce07ca4adbec7e502d4cb
UNKNOWN
Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time. Return that integer.   Example 1: Input: arr = [1,2,2,6,6,6,6,7,10] Output: 6   Constraints: 1 <= arr.length <= 10^4 0 <= arr[i] <= 10^5
["class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n count = 0\n num = arr[0]\n for x in arr:\n if x == num:\n count = count+ 1\n elif x != num and ((count / len(arr))>0.25):\n return num\n else:\n ...
{"fn_name": "findSpecialInteger", "inputs": [[[1, 2, 2, 6, 6, 6, 6, 7, 10]]], "outputs": [6]}
INTRODUCTORY
PYTHON3
LEETCODE
31,260
class Solution: def findSpecialInteger(self, arr: List[int]) -> int:
192fc74a257c5c0963e3d45e1f988c77
UNKNOWN
Return the number of permutations of 1 to n so that prime numbers are at prime indices (1-indexed.) (Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smaller than it.) Since the answer may be large, return the answer modulo 10^9 + 7.  ...
["class Solution:\n def numPrimeArrangements(self, n: int) -> int:\n primes = [True] * (n + 1)\n for prime in range(2, int(math.sqrt(n)) + 1):\n if primes[prime]:\n for composite in range(prime * prime, n + 1, prime):\n primes[composite] = False\n cnt...
{"fn_name": "numPrimeArrangements", "inputs": [[5]], "outputs": [12]}
INTRODUCTORY
PYTHON3
LEETCODE
5,164
class Solution: def numPrimeArrangements(self, n: int) -> int:
bd1a558c334c61853841b81f0eb15a14
UNKNOWN
Given a list of strings words representing an English Dictionary, find the longest word in words that can be built one character at a time by other words in words. If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty string...
["class Solution:\n def longestWord(self, words):\n \"\"\"\n :type words: List[str]\n :rtype: str\n \"\"\"\n \n result = \"\";\n wordSet = set(words);\n for word in words:\n if (len(word) > len(result) or len(word) == len(result) and word <...
{"fn_name": "longestWord", "inputs": [[["\"w\"", "\"wo\"", "\"wor\"", "\"worl\"", "\"world\""]]], "outputs": [""]}
INTRODUCTORY
PYTHON3
LEETCODE
4,505
class Solution: def longestWord(self, words: List[str]) -> str:
1a1517c8f50cee7013a5929cf2b6bdae
UNKNOWN
=====Function Descriptions===== .remove(x) This operation removes element x from the set. If element x does not exist, it raises a KeyError. The .remove(x) operation returns None. Example >>> s = set([1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> s.remove(5) >>> print s set([1, 2, 3, 4, 6, 7, 8, 9]) >>> print s.remove(4) None >>>...
["n = int(input())\ns = set(map(int, input().split())) \nn = int(input())\nfor i in range(n):\n cmd = list(input().split(' '))\n if (len(cmd) == 1):\n s.pop()\n else:\n value = int(cmd[1])\n s.discard(value)\nprint((sum(s)))\n", "#!/usr/bin/env python3\n\ndef __starting_point():\n n = i...
{"inputs": ["9\n1 2 3 4 5 6 7 8 9\n10\npop\nremove 9\ndiscard 9\ndiscard 8\nremove 7\npop\ndiscard 6\nremove 5\npop\ndiscard 5"], "outputs": ["4"]}
INTRODUCTORY
PYTHON3
HACKERRANK
729
n = int(input()) s = set(map(int, input().split()))
5abe33e6dbbeb6e360eb776dbe80073b
UNKNOWN
=====Function Descriptions===== group() A group() expression returns one or more subgroups of the match. Code >>> import re >>> m = re.match(r'(\w+)@(\w+)\.(\w+)','username@hackerrank.com') >>> m.group(0) # The entire match 'username@hackerrank.com' >>> m.group(1) # The first parenthesized subgroup. 'use...
["import re\ns = input()\nres = re.search(r'([A-Za-z0-9])\\1',s)\nif res == None:\n print((-1))\nelse:\n print((res.group(1)))\n", "#!/usr/bin/env python3\n\nimport re\n\ndef __starting_point():\n string = input()\n \n match = re.search(r'([a-zA-Z0-9])\\1+', string)\n \n print((match.group(1) if ma...
{"inputs": ["12345678910111213141516171820212223"], "outputs": ["1"]}
INTRODUCTORY
PYTHON3
HACKERRANK
357
# Enter your code here. Read input from STDIN. Print output to STDOUT
470726cda87c34b9039dc45b117025d6
UNKNOWN
=====Function Descriptions===== itertools.product() This tool computes the cartesian product of input iterables. It is equivalent to nested for-loops. For example, product(A, B) returns the same as ((x,y) for x in A for y in B). Sample Code >>> from itertools import product >>> >>> print list(product([1,2,3],repeat ...
["import itertools\nar1 = list(map(int,input().split()))\nar2 = list(map(int,input().split()))\ncross = list(itertools.product(ar1,ar2))\nfor i in cross:\n print(i,end=' ')\n", "#!/usr/bin/env python3\n\nfrom itertools import product\n\ndef __starting_point():\n arr1 = list(map(int, input().strip().split(' ')))\n...
{"inputs": ["1 2\n3 4"], "outputs": ["(1, 3) (1, 4) (2, 3) (2, 4)"]}
INTRODUCTORY
PYTHON3
HACKERRANK
486
# Enter your code here. Read input from STDIN. Print output to STDOUT
c6331eac51315d911e16b3b6fa23ad05
UNKNOWN
=====Problem Statement===== You are given an integer, N. Your task is to print an alphabet rangoli of size N. (Rangoli is a form of Indian folk art based on creation of patterns.) Different sizes of alphabet rangoli are shown below: #size 3 ----c---- --c-b-c-- c-b-a-b-c --c-b-c-- ----c---- #size 5 --------e-------...
["n = int(input().strip())\nw = (n-1) * 2 + ((n * 2) - 1)\n#upper half\nfor i in range(1,n,1):\n number_of_letter = (i*2) - 1\n s = ''\n letter_value = 97 + n - 1\n for i in range(0,number_of_letter):\n if(i != 0):\n s += '-' \n s += chr(letter_value) \n if(i<(number_of_lette...
{"inputs": ["5"], "outputs": ["--------e--------\n------e-d-e------\n----e-d-c-d-e----\n--e-d-c-b-c-d-e--\ne-d-c-b-a-b-c-d-e\n--e-d-c-b-c-d-e--\n----e-d-c-d-e----\n------e-d-e------\n--------e--------"]}
INTRODUCTORY
PYTHON3
HACKERRANK
915
def print_rangoli(size): # your code goes here if __name__ == '__main__': n = int(input()) print_rangoli(n)
3b8b55f6b0d327cefce84b053dce3db2
UNKNOWN
=====Problem Statement===== You are given two sets, A and B. Your job is to find whether set A is a subset of set B. If set A is subset of set B, print True. If set A is not a subset of set B, print False. =====Input Format===== The first line will contain the number of test cases, T. The first line of each test case...
["for i in range(int(input())): #More than 4 lines will result in 0 score. Blank lines won't be counted. \n a = int(input()); A = set(input().split()) \n b = int(input()); B = set(input().split())\n print(((A & B) == A))\n", "for i in range(int(input())): #More than 4 lines will result in 0 score. Blank lines ...
{"inputs": ["3\n5\n1 2 3 5 6\n9\n9 8 5 6 3 2 1 4 7\n1\n2\n5\n3 6 5 4 1\n7\n1 2 3 5 6 8 9\n3\n9 8 2"], "outputs": ["True\nFalse\nFalse"]}
INTRODUCTORY
PYTHON3
HACKERRANK
471
# Enter your code here. Read input from STDIN. Print output to STDOUT
3297db0479a19bcf76364f6c07983671
UNKNOWN
=====Problem Statement===== Given a list of rational numbers,find their product. Concept The reduce() function applies a function of two arguments cumulatively on a list of objects in succession from left to right to reduce it to one value. Say you have a list, say [1,2,3] and you have to find its sum. >>> reduce(lam...
["from fractions import Fraction\nfrom functools import reduce\ndef product(fracs):\n t = Fraction(reduce(lambda x,y : x*y,fracs))\n return t.numerator, t.denominator\ndef __starting_point():\n fracs = []\n for _ in range(int(input())):\n fracs.append(Fraction(*list(map(int, input().split()))))\n ...
{"inputs": ["3\n1 2\n3 4\n10 6"], "outputs": ["5 8"]}
INTRODUCTORY
PYTHON3
HACKERRANK
420
from fractions import Fraction from functools import reduce def product(fracs): t = # 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 ...
8d2f49f31545ad5f0db1f1c9bc19048c
UNKNOWN
=====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
PYTHON3
HACKERRANK
704
# Enter your code here. Read input from STDIN. Print output to STDOUT
d7a396ead675db715cf8820cf4bba603
UNKNOWN
=====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
PYTHON3
HACKERRANK
538
# Enter your code here. Read input from STDIN. Print output to STDOUT
72ac3639490787ef9ec3fc8821031ff4
UNKNOWN
=====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
PYTHON3
HACKERRANK
406
import numpy
4d58a3bf612cc307d1793c6e53bfe2e9
UNKNOWN
=====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
PYTHON3
HACKERRANK
535
# Enter your code here. Read input from STDIN. Print output to STDOUT
f09e227fbafdff81cf53ab71ff507a3b
UNKNOWN
=====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
PYTHON3
HACKERRANK
1,502
#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).___...
3c682af7c1fe59e7827178a7070a49dc
UNKNOWN
=====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
PYTHON3
HACKERRANK
373
# Enter your code here. Read input from STDIN. Print output to STDOUT
6531598f70f7c10200c6d327055eb475
UNKNOWN
=====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
PYTHON3
HACKERRANK
464
# Enter your code here. Read input from STDIN. Print output to STDOUT
730ce47fcac42d5ffde59aa618be5d73
UNKNOWN
=====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
PYTHON3
HACKERRANK
400
# Enter your code here. Read input from STDIN. Print output to STDOUT
ed0f326ad06cf60f681939201ac07120
UNKNOWN
=====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
PYTHON3
HACKERRANK
150
#!/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()
7e58ef777769badcf1fcbad862230d84
UNKNOWN
=====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
PYTHON3
HACKERRANK
231
if __name__ == '__main__': n = int(input())
5adcf4e55089313bb07c1ef78b1f1656
UNKNOWN
=====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
PYTHON3
HACKERRANK
248
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)
11a9d527938b0be3396a20d17fcb1c8b
UNKNOWN
=====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
PYTHON3
HACKERRANK
379
# Enter your code here. Read input from STDIN. Print output to STDOUT
e6de70cfb77c7dd05f6c1a1a8890964f
UNKNOWN
=====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
PYTHON3
HACKERRANK
550
import numpy
b6493fe44dcba10d383452be009efb98
UNKNOWN
=====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
PYTHON3
HACKERRANK
495
# Enter your code here. Read input from STDIN. Print output to STDOUT
76db7984a5342b5008ac62e9929f8fbe
UNKNOWN
=====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
PYTHON3
HACKERRANK
535
# Enter your code here. Read input from STDIN. Print output to STDOUT
ebfa2fa1c1b99e6dba3b411ddfc295e2
UNKNOWN
=====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
PYTHON3
HACKERRANK
89
7513b553124ca99dc7ef8480edb12c08
UNKNOWN
=====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
PYTHON3
HACKERRANK
1,058
# Enter your code here. Read input from STDIN. Print output to STDOUT
230fc98aaa15927a28a89cff11293f10
UNKNOWN
=====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
PYTHON3
HACKERRANK
985
if __name__ == '__main__': for _ in range(int(input())): name = input() score = float(input())
618c302da0c7c16c1ac37217e66733d4
UNKNOWN
=====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
PYTHON3
HACKERRANK
110
import numpy def arrays(arr): # complete this function # use numpy.array arr = input().strip().split(' ') result = arrays(arr) print(result)
abc5ae43dd89c238ade18c37f4a0c1c7
UNKNOWN
=====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
PYTHON3
HACKERRANK
359
# Enter your code here. Read input from STDIN. Print output to STDOUT
60e89b3d457fb22ac51493cc93d7b869
UNKNOWN
=====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
PYTHON3
HACKERRANK
784
import numpy
1845260351c4c42307fc6e00d92fea6d
UNKNOWN
=====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
PYTHON3
HACKERRANK
718
import numpy
27440efe4f8b9eb32d9fdad27e9fa286
UNKNOWN
=====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
PYTHON3
HACKERRANK
469
# Enter your code here. Read input from STDIN. Print output to STDOUT
ddc4d505aa6f3b53677f35142163703b
UNKNOWN
=====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
PYTHON3
HACKERRANK
179
import numpy
e5017229567e92e679bf9f2789818c60
UNKNOWN
=====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
PYTHON3
HACKERRANK
271
def is_leap(year): leap = False # Write your logic here return leap year = int(input()) print(is_leap(year))
b83580d315d704c1fd19df793eb90a92
UNKNOWN
=====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
PYTHON3
HACKERRANK
733
# Enter your code here. Read input from STDIN. Print output to STDOUT
2834a4d9622c990227bb425886a1ca2f
UNKNOWN
=====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
PYTHON3
HACKERRANK
1,217
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()
cbef6cfef0833c97a189180305ee793b
UNKNOWN
=====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
PYTHON3
HACKERRANK
179
def print_full_name(a, b): print("") if __name__ == '__main__': first_name = input() last_name = input() print_full_name(first_name, last_name)
e9e9f0a1bd50845ff8b2b545ed721ccc
UNKNOWN
=====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
PYTHON3
HACKERRANK
594
# Enter your code here. Read input from STDIN. Print output to STDOUT
9164608164ca1bfb8530d44e0fd48053
UNKNOWN
=====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
PYTHON3
HACKERRANK
412
import numpy
b2f4b48e177db7cb80e15493dd03bb07
UNKNOWN
=====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
PYTHON3
HACKERRANK
227
import numpy
a00c2b6103ab9060fd26445b96c0c5d2
UNKNOWN
=====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
PYTHON3
HACKERRANK
341
import numpy
bf5c61c9a2634d263e614190cc234e22
UNKNOWN
=====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
PYTHON3
HACKERRANK
865
def minion_game(string): # your code goes here if __name__ == '__main__': s = input() minion_game(s)
de2bb6a47bb9356d2d9629e9ed6b73cd
UNKNOWN
=====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
PYTHON3
HACKERRANK
816
# Enter your code here. Read input from STDIN. Print output to STDOUT
80eca6b1683f2caa01eaf5b704c19544
UNKNOWN
=====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
PYTHON3
HACKERRANK
274
# Enter your code here. Read input from STDIN. Print output to STDOUT
ff8c945981c4cd728143cd5cbfeac8e5
UNKNOWN
=====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
PYTHON3
HACKERRANK
183
def average(array): # your code goes here if __name__ == '__main__': n = int(input()) arr = list(map(int, input().split())) result = average(arr) print(result)
4405bdd362e8eda19544bd1cbbba35c3
UNKNOWN
=====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
PYTHON3
HACKERRANK
280
def print_formatted(number): # your code goes here if __name__ == '__main__': n = int(input()) print_formatted(n)
b64d1a78b9993974eabb8c2fdbf08ec3
UNKNOWN
=====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
PYTHON3
HACKERRANK
596
# Enter your code here. Read input from STDIN. Print output to STDOUT
fc0b2c5f5d4809887433e18f6b95eafa
UNKNOWN
=====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
PYTHON3
HACKERRANK
138
for i in range(1,int(input())): #More than 2 lines will result in 0 score. Do not leave a blank line also print
2574f95cbd2c3bf8fb0cf736975dc3ab
UNKNOWN
=====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
PYTHON3
HACKERRANK
419
import numpy
456d202757b3d4f0b04ee79b239d722b
UNKNOWN
=====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
PYTHON3
HACKERRANK
276
# Enter your code here. Read input from STDIN. Print output to STDOUT
8ffa3b375da5bf49d192d68ffc317088
UNKNOWN
=====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
PYTHON3
HACKERRANK
460
import numpy
f5e48eda9f5a93a6ca386ea07cf81a29
UNKNOWN
=====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
PYTHON3
HACKERRANK
535
import numpy
f61cf5ef6086b1405bc77eabe11ac82e
UNKNOWN
=====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
PYTHON3
HACKERRANK
414
# Enter your code here. Read input from STDIN. Print output to STDOUT
d22a5f4d49a355d9daf2593a3627674a
UNKNOWN
=====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
PYTHON3
HACKERRANK
446
if __name__ == '__main__': n = int(input()) arr = map(int, input().split())
7b0520217f2ca7eb0df1e55475fb23a8
UNKNOWN
=====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
PYTHON3
HACKERRANK
272
import numpy
3b6d19940799a6e2e59273919840c363
UNKNOWN
=====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
PYTHON3
HACKERRANK
313
#!/bin/python3 import math import os import random import re import sys if __name__ == '__main__': s = input()
693e4ec0095e2f4e242b60aa269ab6e7
UNKNOWN
=====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
PYTHON3
HACKERRANK
199
regex_pattern = r"" # Do not delete 'r'. import re print("\n".join(re.split(regex_pattern, input())))
4c2c49e5276f8a7c7b025afd050fb65d
UNKNOWN
=====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
PYTHON3
HACKERRANK
121
def split_and_join(line): # write your code here if __name__ == '__main__': line = input() result = split_and_join(line) print(result)
e3042796358e1ba3acf44fc77b92a939
UNKNOWN
=====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
PYTHON3
HACKERRANK
437
# Enter your code here. Read input from STDIN. Print output to STDOUT
c3e9e75091127ce3cc48a76e83015dc5
UNKNOWN
=====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
PYTHON3
HACKERRANK
326
70e141083a5fc95f03b72dcbe09c7404
UNKNOWN
=====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
PYTHON3
HACKERRANK
281
if __name__ == '__main__': n = int(input())
af9240d43eebbd2154bacf2d64de46be
UNKNOWN
=====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
PYTHON3
HACKERRANK
435
# Enter your code here. Read input from STDIN. Print output to STDOUT
465daaceb78407a218c1cd9908f309d9
UNKNOWN
=====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
PYTHON3
HACKERRANK
400
# Enter your code here. Read input from STDIN. Print output to STDOUT
0c34d3403d6e07b0fac6f04e58e718f6
UNKNOWN
=====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
PYTHON3
HACKERRANK
399
# Enter your code here. Read input from STDIN. Print output to STDOUT
a1de173a6d5dd20100b205d866a25470
UNKNOWN
=====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
PYTHON3
HACKERRANK
236
# Enter your code here. Read input from STDIN. Print output to STDOUT
bad69ec5d835285f2c894eb21f9fd7e2
UNKNOWN
=====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
PYTHON3
HACKERRANK
1,533
if __name__ == '__main__': N = int(input())
92aee6a6dcf3748cd9fb3d12629131fb
UNKNOWN
=====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
PYTHON3
HACKERRANK
1,222
# Enter your code here. Read input from STDIN. Print output to STDOUT
c6f7ae70491fcb748ea55f9f3d94e052
UNKNOWN
=====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
PYTHON3
HACKERRANK
136
if __name__ == '__main__': a = int(input()) b = int(input())
39dbb685ff1ef4125c9e3d58988abf26
UNKNOWN
=====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
PYTHON3
HACKERRANK
1,028
# Enter your code here. Read input from STDIN. Print output to STDOUT
6c18053ff26d4aa3766f1df037b69a2e
UNKNOWN
=====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
PYTHON3
HACKERRANK
569
# Enter your code here. Read input from STDIN. Print output to STDOUT
6da8f49530e9cb6aed6ccbb870d271e5
UNKNOWN
=====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
PYTHON3
HACKERRANK
943
# Enter your code here. Read input from STDIN. Print output to STDOUT