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 Explanation: The input array has a degree of 2 because both elements 1 and 2 appear twice. Of the subarrays that have the same degree: [1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2] The shortest length is 2. So return 2. Example 2: Input: [1,2,2,3,1,4,2] Output: 6 Note: nums.length will be between 1 and 50,000. nums[i] will be an integer between 0 and 49,999.
["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 \n if degree == 1:\n return 1\n \n max_value = []\n \n for i in diction:\n if diction[i] == degree:\n max_value.append(i)\n \n min_length = 10000000000\n \n for i in max_value:\n head = 0\n tail = 0\n for j in range(len(nums)):\n if nums[j] == i:\n head = j\n break\n for j in range(len(nums)-1,-1,-1):\n if nums[j] == i:\n tail = j\n break\n if min_length > tail - head + 1:\n min_length = tail - head + 1\n \n return min_length", "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 \n if degree == 1:\n return 1\n \n max_value = []\n \n for i in diction:\n if diction[i] == degree:\n max_value.append(i)\n \n min_length = 10000000000\n \n for i in max_value:\n head = 0\n tail = 0\n for j in range(len(nums)):\n if nums[j] == i:\n head = j\n break\n for j in range(len(nums)-1,-1,-1):\n if nums[j] == i:\n tail = j\n break\n if min_length > tail - head + 1:\n min_length = tail - head + 1\n \n return min_length", "class Solution:\n def findShortestSubArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n import collections\n c = collections.Counter(nums)\n degree = max(c[n] for n in c)\n if degree <=1:\n return degree\n res = {}\n for n in c:\n if c[n] == degree:\n res[n] = [-1,-1]\n for i,n in enumerate(nums):\n if n in res:\n if res[n][0] == -1 :\n res[n][0] = i\n else:\n res[n][1] = i\n return min(res[i][1]-res[i][0] for i in res) + 1", "class Solution:\n def findShortestSubArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n c = collections.Counter(nums)\n first, last = {}, {}\n for i, v in enumerate(nums):\n first.setdefault(v, i)\n last[v] = i\n degree = max(c.values())\n return min(last[v] - first[v] + 1 for v in c if c[v] == degree)", "class Solution:\n def findShortestSubArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n left, right, count = {}, {}, {}\n for i, x in enumerate(nums):\n if x not in left: left[x] = i\n right[x] = i\n count[x] = count.get(x, 0) + 1\n \n ans = len(nums)\n degree = max(count.values())\n for x in count:\n if count[x] == degree:\n ans = min(ans, right[x] - left[x] + 1)\n \n return ans", "class Solution:\n def findShortestSubArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n left, right, count = {}, {}, {}\n for i, x in enumerate(nums):\n if x not in left: left[x] = i\n right[x] = i\n count[x] = count.get(x, 0) + 1\n \n ans = len(nums)\n degree = max(count.values())\n for x in count:\n if count[x] == degree:\n ans = min(ans, right[x] - left[x] + 1)\n \n return ans", "class Solution:\n def findShortestSubArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n cnt = {}\n se = {}\n cur_max_cnt = 0\n cur_span = float('inf')\n for idx, n in enumerate(nums):\n if not n in se:\n se[n] = [idx, idx]\n cnt[n] = 1\n else:\n se[n][1] = idx\n cnt[n] += 1\n x, y = se[n]\n if cnt[n] > cur_max_cnt or (cnt[n] == cur_max_cnt and y - x + 1 < cur_span):\n cur_max_cnt = cnt[n]\n cur_span = y - x + 1\n return cur_span", "class Solution:\n def findShortestSubArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n d = {}\n for i in range(len(nums)):\n tmp = d.get(nums[i], [])\n tmp.append(i)\n d[nums[i]] = tmp\n low = []\n c = 0\n for k in d:\n tc = len(d.get(k))\n if tc > c:\n c = tc\n for k in d:\n if len(d.get(k)) == c:\n low.append(k)\n \n result = len(nums)\n for s in low:\n tmp = d.get(s)[-1] - d.get(s)[0] + 1 \n if tmp < result:\n result = tmp\n return result", "class Solution:\n def findShortestSubArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n r={}\n for i,j in enumerate(nums):\n if j not in r:\n r[j]=1+100000*i\n else:\n r[j]=r[j]%10000000000+1+10000000000*i\n tem=1\n dist=500000\n print(r)\n for i in list(r.values()):\n print(i)\n if i%100000==tem:\n if tem==1:\n dist=1\n else:\n dist_tem=i//10000000000-(i//100000)%100000+1\n if dist_tem<dist:\n dist=dist_tem\n elif i%100000>tem:\n tem=i%100000\n dist=i//10000000000-(i//100000)%100000+1\n return dist\n \n \n # x=[0 for i in range(50000)]\n # for i in range(len(nums)):\n # x[nums[i]]=x[nums[i]]+1\n # if x[nums[i]]==1:\n # x[nums[i]]=x[nums[i]]+100000*i\n # else:\n # x[nums[i]]=x[nums[i]]%10000000000+10000000000*i\n # tem=1\n # # print(x)\n # dist=50000\n # for i in x:\n # # print(i)\n # if i>0:\n # if i%100000==tem:\n # tem=i%100000\n # if tem==1:\n # dist=1\n # else:\n # dist_tem=i//10000000000-(i//100000)%100000+1\n # if dist_tem<dist:\n # dist=dist_tem\n # elif i%100000>tem:\n # tem=i%100000\n # dist=i//10000000000-(i//100000)%100000+1\n # # print(dist)\n # return dist\n \n \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 one where 5 and 7 are separated by 4. Example 2: Input: [2,2,2,2,2] Output: 1 Explanation: The longest continuous increasing subsequence is [2], its length is 1. Note: Length of the array will not exceed 10,000.
["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 cur_len = cur_len + 1\n else:\n cur_len = 1\n \n if cur_len > max_len:\n max_len = cur_len\n return max_len\n", "class Solution:\n def findLengthOfLCIS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if not nums:\n return 0\n result = 1\n max_result = 1\n for i in range(len(nums) - 1):\n if nums[i+1] > nums[i]:\n result += 1\n if result > max_result:\n max_result = result\n else:\n result = 1\n return max_result", "class Solution:\n def findLengthOfLCIS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if not len(nums):\n return 0\n res = 0\n temp_res = 1\n for i in range(len(nums)-1):\n if nums[i] < nums[i+1]:\n temp_res += 1\n else:\n if temp_res > res:\n res = temp_res\n temp_res = 1\n return max(res, temp_res)", "class Solution:\n def findLengthOfLCIS(self, nums):\n if nums == []:\n return 0\n elif len(nums) == 1:\n return 1\n ans, max_ans = 1, 1\n for i in range(len(nums) - 1):\n if nums[i] < nums[i + 1]:\n ans += 1\n max_ans = ans if ans > max_ans else max_ans\n else:\n ans = 1\n return max_ans\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n", "class Solution:\n def findLengthOfLCIS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if not nums:\n return 0\n seq, max_seq = 1, 1\n for i in range(1, len(nums)):\n if nums[i] > nums[i-1]:\n seq += 1\n else:\n max_seq = max(max_seq, seq)\n seq = 1\n max_seq = max(max_seq, seq)\n return max_seq", "class Solution:\n def findLengthOfLCIS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n # if nums == []:\n # return 0\n # ans,n = 1,1\n # for i in range(len(nums)-1):\n # if nums[i+1]>nums[i]:\n # n += 1\n # ans = max(ans,n)\n # else:\n # n = 1\n # return ans\n ans = anchor = 0\n for i in range(len(nums)):\n if i and nums[i-1] >= nums[i]: anchor = i\n ans = max(ans, i - anchor + 1)\n return ans\n", "class Solution:\n def findLengthOfLCIS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if len(nums)==0:\n return 0\n temp,res=1,1\n for i in range(len(nums)-1):\n if nums[i]<nums[i+1]:\n temp+=1\n else:\n res=max(res,temp)\n temp=1\n res=max(res,temp)\n return res", "class Solution:\n def findLengthOfLCIS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if not nums:\n return 0\n \n longest = 0\n count = 1\n for i in range(1, len(nums)):\n if nums[i] > nums[i-1]:\n count += 1\n else:\n longest = max(longest, count)\n count = 1\n \n \n return max(longest, count) \n", "class Solution:\n def findLengthOfLCIS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if not nums: return 0\n ret = 0\n cnt = 1\n for i in range(1,len(nums)):\n if nums[i]>nums[i-1]: cnt += 1\n else:\n ret = max(ret, cnt)\n cnt = 1\n return max(ret,cnt)", "class Solution:\n def findLengthOfLCIS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n current_count = 0\n max_count = 0\n for index,num in enumerate(nums):\n current_count += 1\n if index < len(nums)-1:\n if num >= nums[index+1]:\n max_count = max(max_count, current_count)\n current_count = 0\n return max(max_count, current_count)", "class Solution:\n def findLengthOfLCIS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n LCIS = 0\n i = 0\n j = 1\n while j <= len(nums):\n if j == len(nums) or nums[j-1] >= nums[j]:\n l = j - i\n if LCIS < l: LCIS = l\n i = j\n j += 1\n return LCIS", "class Solution:\n def findLengthOfLCIS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n \n if nums == []:\n return 0\n longest = 1\n curr = 1\n \n for i in range(0,len(nums)-1):\n if nums[i]<nums[i+1]:\n curr +=1\n print(curr)\n else:\n \n longest = max(longest,curr)\n curr = 1\n longest = max(longest,curr)\n return longest", "class Solution:\n def findLengthOfLCIS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if nums == []:\n return 0\n n = 1\n ans = [1,]\n for i in range(0,len(nums)-1):\n if nums[i+1]>nums[i]:\n n += 1\n else:\n ans.append(n)\n n = 1\n if i == len(nums)-2:\n ans.append(n)\n \n return max(ans)\n", "class Solution:\n def findLengthOfLCIS(self, nums):\n ans = anchor = 0\n for i in range(len(nums)):\n if(nums[i - 1] >= nums[i]):\n anchor = i\n ans = max(ans, i - anchor + 1)\n return ans", "class Solution:\n def findLengthOfLCIS(self, nums):\n ans = anchor = 0\n for i in range(len(nums)):\n if i and nums[i-1] >= nums[i]: anchor = i\n ans = max(ans, i - anchor + 1)\n return ans", "class Solution:\n def findLengthOfLCIS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n counter = 1\n L = []\n if len(nums)>=2:\n for i in range(0,len(nums)-1):\n if nums[i+1]>nums[i]:\n counter+=1\n else:\n counter=1\n L.append(counter)\n return max(L)\n elif len(nums)==1:\n return 1\n else:\n return 0"]
{"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 point to positions where the corresponding bits are different.
["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 hammingDistance(self, x, y):\n \"\"\"\n :type x: int\n :type y: int\n :rtype: int\n \"\"\"\n if x == y:\n return 0\n bin_x, bin_y = bin(x)[2:], bin(y)[2:]\n if x < y:\n bin_x = bin_x.zfill(len(bin_y))\n else:\n bin_y = bin_y.zfill(len(bin_x))\n return sum([abs(int(bin_x[i]) - int(bin_y[i])) for i in range(len(bin_x))])", "class Solution:\n def hammingDistance(self, x, y):\n \"\"\"\n :type x: int\n :type y: int\n :rtype: int\n \"\"\"\n count = 0\n for i in range(32):\n count += (x & 1) ^ (y & 1)\n x >>= 1\n y >>= 1\n return count", "class Solution:\n def hammingDistance(self, x, y):\n \"\"\"\n :type x: int\n :type y: int\n :rtype: int\n \"\"\"\n d = bin(x^y)\n return d.count('1')\n", "class Solution:\n def hammingDistance(self, x, y):\n \"\"\"\n :type x: int\n :type y: int\n :rtype: int\n \"\"\"\n x_b = '{:32b}'.format(x).replace(' ', '0')\n y_b = '{:32b}'.format(y).replace(' ', '0')\n \n count = 0\n for i in range(len(x_b)):\n if x_b[i] != y_b[i]:\n count += 1\n return count\n", "class Solution:\n def hammingDistance(self, x, y):\n \"\"\"\n :type x: int\n :type y: int\n :rtype: int\n \"\"\"\n # 035b is the code for formatting the int as a binary of 35 characters with 0 as left hand padding\n x_bin = format(x, '#035b')\n y_bin = format(y, '#035b')\n \n print(\"x_bin: \", x_bin)\n print(\"y_bin: \", y_bin)\n \n hammingDistance = 0\n \n for idx, val in enumerate (x_bin):\n print(\"val: \", val)\n print(\"y_bin[idx]: \", y_bin[idx])\n if val != y_bin[idx]:\n hammingDistance += 1\n \n return hammingDistance", "class Solution:\n def hammingDistance(self, x, y):\n \"\"\"\n :type x: int\n :type y: int\n :rtype: int\n \"\"\"\n xor = x ^ y\n count = 0\n for _ in range(32):\n count += xor & 1\n xor = xor >> 1\n return count", "class Solution:\n def hammingDistance(self, x, y):\n \"\"\"\n :type x: int\n :type y: int\n :rtype: int\n \"\"\"\n \n count = 0\n while x > 0 or y > 0:\n if (x & 1) != (y & 1):\n count += 1\n \n if x > 0:\n x = x >> 1\n \n if y > 0:\n y = y >> 1\n \n return count", "class Solution:\n def hammingDistance(self, x, y):\n \"\"\"\n :type x: int\n :type y: int\n :rtype: int\n \"\"\"\n x_bits = [int(i) for i in bin(x)[2:]]\n y_bits = [int(j) for j in bin(y)[2:]]\n digit_diff = abs(len(x_bits)-len(y_bits))\n \n if len(y_bits) > len(x_bits):\n x_bits = [0] * digit_diff + x_bits\n elif len(x_bits) > len(y_bits):\n y_bits = [0] * digit_diff + y_bits\n \n hamming_dist = 0\n for i in range(0, len(x_bits)):\n if x_bits[i] != y_bits[i]:\n hamming_dist += 1\n \n return hamming_dist\n", "class Solution:\n def hammingDistance(self, x, y):\n \"\"\"\n :type x: int\n :type y: int\n :rtype: int\n \"\"\"\n xor_result = x^y\n count = 0\n while xor_result > 0:\n count += xor_result & 1\n xor_result = xor_result >> 1\n \n return count\n \n \n \n", "class Solution:\n def hammingDistance(self, x, y):\n \"\"\"\n :type x: int\n :type y: int\n :rtype: int\n \"\"\"\n \n hamming_distance=0\n \n while(x != 0 or y != 0):\n b1 = x & 1\n b2 = y & 1\n if(b1 != b2):\n hamming_distance = hamming_distance+1\n x = x >> 1\n y = y >> 1\n \n return hamming_distance", "class Solution:\n def hammingDistance(self, x, y):\n \"\"\"\n :type x: int\n :type y: int\n :rtype: int\n \"\"\"\n return bin(x^y).count('1')"]
{"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 \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n c=0\n while n>0:\n n//=5\n c+=n\n return c\n", "class Solution:\n def trailingZeroes(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n count = 1\n a = 5\n ans = 0\n \n while a<=n:\n ans += n//a\n count += 1\n a = 5**count\n \n return ans\n", "class Solution:\n def trailingZeroes(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n return 0 if n == 0 else n // 5 + self.trailingZeroes(n // 5)", "class Solution:\n def trailingZeroes(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n count = 0\n \n while n:\n count = count + n // 5\n n = n // 5\n return count\n \n \n", "class Solution:\n def trailingZeroes(self, n):\n two = 0\n five = 0\n tmp = n\n while tmp != 0:\n tmp = tmp//5\n five = five + tmp\n tmp = n\n while tmp != 0:\n tmp = tmp//2\n two = two + tmp\n res = min(five,two)\n return res\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n", "class Solution:\n def trailingZeroes(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n count = 0\n while n > 0:\n n /= 5\n count += int(n)\n return int(count)", "class Solution:\n def trailingZeroes(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n ans=0\n i=5\n while n//i:\n ans+=n//i\n i*=5\n return ans ", "class Solution:\n def trailingZeroes(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n return sum([n//5**i for i in range(1, 20)])", "class Solution:\n def trailingZeroes(self, n):\n res = 5\n ans = 0\n while res < n+1:\n ans += int(n/res)\n res = 5*res\n return ans", "class Solution:\n def trailingZeroes(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n trz = 0\n div = 5\n while div <= n:\n trz += int(n / div)\n div *= 5\n return trz;\n #return 0 if n is 0 else n / 5 + self.trailingZeros(n / 5)\n", "class Solution:\n def trailingZeroes(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n if n < 5:\n return 0\n elif n < 10:\n return 1\n \n i = 0\n while 5 ** (i + 1) <= n:\n i += 1\n \n s=n//5\n j=2\n while j<=i:\n s+=n//(5**j)\n j+=1\n \n \n return int(s)", "class Solution:\n def trailingZeroes(self, n):\n return n//5 + self.trailingZeroes(n//5) if n>=5 else 0\n", "class Solution:\n def trailingZeroes(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n res = 0\n while n >= 5:\n res = res + int(n/5)\n n = n/5\n return res\n", "class Solution:\n def trailingZeroes(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n \n num2 = 0\n div = 2\n quot = n // div\n while quot:\n num2 += quot\n div *= 2\n quot = n // div\n \n num5 = 0\n div = 5\n quot = n // div\n while quot:\n num5 += quot\n div *= 5\n quot = n // div\n \n return min(num2, num5)", "class Solution:\n def trailingZeroes(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n return 0 if n == 0 else n//5 + self.trailingZeroes(n // 5)"]
{"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: int\n :type b: int\n :rtype: int\n \"\"\"\n if a == 0:\n return b\n if b == 0:\n return a\n \n MAX = 0x7FFFFFFF\n MIN = 0x80000000\n mask = 0xFFFFFFFF\n while b:\n carry = a & b\n a = (a ^ b) & mask\n b = carry << 1 & mask\n \n return a if a <= MAX else ~(a ^ mask)", "class Solution:\n def getSum(self, a, b):\n \"\"\"\n :type a: int\n :type b: int\n :rtype: int\n \"\"\"\n return sum([a,b])", "class Solution:\n def getSum(self, a, b):\n \"\"\"\n :type a: int\n :type b: int\n :rtype: int\n \"\"\"\n if a == 0:\n return b\n if b == 0:\n return a\n \n MAX = 0x7FFFFFFF\n MIN = 0x80000000\n mask = 0xFFFFFFFF\n while b:\n a, b = (a ^ b) & mask, ((a & b) << 1) & mask\n \n return a if a <= MAX else ~(a ^ mask)", "class Solution:\n def getSum(self, a, b):\n \"\"\"\n :type a: int\n :type b: int\n :rtype: int\n \"\"\"\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: int\n :type b: int\n :rtype: int\n \"\"\"\n MAX_INT = 0x7FFFFFFF # from zero to python 32 bits maximum positive integer\n MASK = 0x100000000\n \n #(a ^ b) is \"summing\" the bits of a and b\n #For example (where D is decimal and B is binary), 20D == 10100B, and 9D = 1001B\n # Enter the (a & b) << 1 term. This term represents the \"carry\" for each position. On the next iteration of the while loop, we add in the carry from the previous loop. \n \n #while b is not 0\n while b: \n a,b= (a^b) % MASK, ((a&b) <<1) % MASK\n return a if a <= MAX_INT else ~((a&MAX_INT)^ MAX_INT)\n \n \n \n # All the masks are doing is ensuring that the value is an integer, because your code even has comments stating that a, b, and the return type are of type int. Thus, since the maximum possible int (32 bits) is 2147483647. So, if you add 2 to this value, like you did in your example, the int overflows and you get a negative value. You have to force this in Python, because it doesn't respect this int boundary that other strongly typed languages like Java and C++ have defined.\n", "class Solution(object):\n \n def ca(self, a, b):\n s = [[] for i in range(a)]\n \n for i in range(b):\n s.append(0)\n return len(s)\n \n def cal(self, big, small):\n aa = [[] for i in range(big)]\n for i in range(small):\n aa.pop()\n return len(aa)\n \n def getSum(self, a, b):\n if a==2147483647:\n return -1\n if a>0 and b <0:\n a, b = b, a\n \n if a==0:\n return b\n if b==0:\n return a\n \n if a<0 and b<0:\n return -self.ca(abs(a), abs(b))\n elif a>0 and b>0:\n return self.ca(a,b)\n \n \n elif a<0 and b>0:\n if abs(a) > b:\n return -self.cal(abs(a), b)\n elif abs(a)==b:\n return 0\n else:\n return self.cal(b, abs(a))\n \n \n", "class Solution:\n def getSum(self, a, b):\n \"\"\"\n :type a: int\n :type b: int\n :rtype: int\n \"\"\"\n max_value = 0x7FFFFFFF\n masking = 0xFFFFFFFF\n while b != 0:\n \n carry = a & b\n a = (a ^ b) & masking\n b = (carry << 1) & masking\n \n return a if a <= max_value else ~(a ^ masking)", "class Solution:\n def getSum(self, a, b):\n \"\"\"\n :type a: int\n :type b: int\n :rtype: int\n \"\"\"\n return a+b"]
{"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 strings. Note: All given inputs are in lowercase letters a-z.
["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 # print x\n \n", "class Solution:\n def longestCommonPrefix(self, strs):\n \"\"\"\n :type strs: List[str]\n :rtype: str\n \"\"\"\n if not strs:\n return \"\"\n \n s0 = strs[0]\n shortest_str_len = len(s0)\n \n for s in strs:\n shortest_str_len = min(shortest_str_len, len(s))\n \n for i in range(shortest_str_len):\n for s in strs:\n if s[i] != s0[i]:\n if i == 0:\n return \"\"\n else:\n return s0[0:i]\n \n return s0[0:shortest_str_len]", "class Solution:\n def longestCommonPrefix(self, strs):\n \"\"\"\n :type strs: List[str]\n :rtype: str\n \"\"\"\n if len(strs) == 0:\n return \"\"\n \n \n result = \"\"\n judge = strs[0]\n flag = True\n for i in range(len(judge)):\n for j in strs[1:]:\n if i >= len(j) or judge[i] != j[i]: \n flag = False\n if flag:\n result += judge[i]\n else:\n break\n \n return result\n", "class Solution:\n def longestCommonPrefix(self, strs):\n \"\"\"\n :type strs: List[str]\n :rtype: str\n \"\"\"\n res = ''\n i = 0\n next_pref = 1\n \n while i < len(strs):\n if strs[i].startswith(res):\n pass\n else:\n res = res[:-1]\n break\n i += 1\n if i == len(strs):\n if next_pref == -1:\n break\n \n res = strs[0][:next_pref]\n \n i = 0\n next_pref += 1\n if next_pref > len(strs[0]):\n next_pref = -1\n return res", "class Solution:\n def longestCommonPrefix(self, strs):\n \"\"\"\n :type strs: List[str]\n :rtype: str\n \"\"\"\n def lcp(str1, str2):\n i = 0\n while (i < len(str1)) and (i < len(str2)):\n print((str1[i], str2[i]))\n if str1[i] == str2[i]:\n i += 1\n else:\n if i == 0:\n return \"\"\n else:\n return str1[:i]\n if i == 0:\n return \"\"\n else:\n return str1[:i]\n if not strs:\n return \"\"\n if len(strs) == 1:\n if not strs[0]:\n return \"\"\n else:\n return strs[0]\n str = lcp(strs[0], strs[1])\n print(str)\n if len(strs) == 2:\n if not str:\n return \"\"\n else:\n return str\n for i in range(1, len(strs)):\n str = lcp(strs[i], str)\n if not str:\n return \"\"\n else:\n return str \n \n \n", "class Solution:\n # @return a string\n def longestCommonPrefix(self, strs):\n if not strs:\n return \"\"\n \n for i, letter_group in enumerate(zip(*strs)):\n if len(set(letter_group)) > 1:\n return strs[0][:i]\n else:\n return min(strs)\n", "class Solution:\n def longestCommonPrefix(self, strs):\n \"\"\"\n :type strs: List[str]\n :rtype: str\n \"\"\"\n if not strs:\n return \"\"\n shortest = min(strs, key = len)\n for i, val in enumerate(shortest):\n for str in strs:\n if str[i] != val:\n return shortest[:i]\n return shortest", "class Solution:\n def longestCommonPrefix(self, strs):\n \"\"\"\n :type strs: List[str]\n :rtype: str\n \"\"\"\n ############MY SOLUTION############################\n #import numpy as np\n #pref = \"\"\n #i = 0\n #stop = 0\n \n #if not all(strs): #empty str\n # return(\"\")\n \n #while not stop:\n # letter = np.unique([l[i:(i+1)] for l in strs])\n # if len(letter) == 1 and letter[0] != \"\" :\n # pref += letter[0]\n # i += 1\n # else:\n # stop = 1\n #return(pref)\n \n ###########OTHER##################################\n if not strs: #if strs = []\n return(\"\")\n \n for i, letter_group in enumerate(zip(*strs)):\n if len(set(letter_group)) > 1:\n return(strs[0][:i])\n \n ##if shortest string is the common prefix or strs contains \"\"\n else:\n return(min(strs))\n \n \n \n", "class Solution:\n \n def longestCommonPrefix(self, strs):\n \"\"\"\n :type strs: List[str]\n :rtype: str\n \"\"\"\n if not strs:\n return \"\"\n cpy = strs.copy()\n return self.helper(cpy, 0)\n \n def helper(self, strs, i):\n if i == len(strs) - 1:\n return strs[i]\n s1 = strs[i]\n s2 = strs[i + 1]\n prefix = \"\"\n if len(s1) == 0 or len(s2) == 0:\n return prefix\n j = 0\n while j < len(s1) and j < len(s2) and s1[j] == s2[j]:\n j += 1\n prefix = s1[:j]\n i += 1\n strs[i] = prefix\n return self.helper(strs, i)\n", "class Solution:\n \n def longestCommonPrefix(self, strs):\n \"\"\"\n :type strs: List[str]\n :rtype: str\n \"\"\"\n if not strs:\n return \"\"\n # \u4e3a\u4e86\u4e0d\u6539\u52a8\u539f\u6765\u7684\u6570\u7ec4\n cpy = strs.copy()\n return self.__helper(cpy) # \u8bb0\u5f97\u52a0 self\n \n '''\u7b97\u51fa\u524d\u9762\u4e24\u4e2astr\u7684longest common prefix. \u7136\u540e\uff0c\u628alcp\u653e\u5230\u7b2c\u4e8c\u4e2astr\u7684\u4f4d\u7f6e\u4e0a\uff0cstrs\u7684\u7b2c\u4e00\u4e2a\u5143\u7d20\u629b\u5f03\uff0c\n \u9012\u5f52\u8c03\u7528,\u76f4\u5230\u6700\u540e\u53ea\u5269\u4e00\u4e2a\u5143\u7d20'''\n \n def __helper(self, strs):\n if len(strs) == 1:\n return strs[0]\n s1 = strs[0]\n s2 = strs[1]\n prefix = \"\"\n if len(s1) == 0 or len(s2) == 0:\n return prefix\n j = 0\n while j < len(s1) and j < len(s2) and s1[j] == s2[j]:\n j += 1\n prefix = s1[:j]\n strs[1] = prefix\n strs.pop(0) # or strs= strs[1:]\n return self.__helper(strs) # \u8bb0\u5f97\u52a0 self\n", "class Solution:\n \n def longestCommonPrefix(self, strs):\n \"\"\"\n :type strs: List[str]\n :rtype: str\n \"\"\"\n if not strs:\n return \"\"\n cpy = strs.copy()\n return self.__helper(cpy) # \u8bb0\u5f97\u52a0 self\n \n def __helper(self, strs):\n if len(strs) == 1:\n return strs[0]\n s1 = strs[0]\n s2 = strs[1]\n prefix = \"\"\n if len(s1) == 0 or len(s2) == 0:\n return prefix\n j = 0\n while j < len(s1) and j < len(s2) and s1[j] == s2[j]:\n j += 1\n prefix = s1[:j]\n strs[1] = prefix\n strs = strs[1:]\n return self.__helper(strs) # \u8bb0\u5f97\u52a0 self\n", "class Solution:\n def longestCommonPrefix(self, strs):\n \"\"\"\n :type strs: List[str]\n :rtype: str\n \"\"\"\n if not strs or len(strs) == 0:\n return \"\"\n \n prefix = strs[0]\n \n if len(strs) > 1:\n for i, p in enumerate(prefix):\n for j in range(1, len(strs)):\n s = strs[j]\n if i == len(s) or p != s[i]:\n return prefix[:i]\n \n \n \n \n \n \n return prefix\n \n \n \n \n \n \n \n \n", "class Solution:\n def _longestCommonPrefix(self, left, right):\n prefix = ''\n i = j = 0\n while(i < len(left) and j < len(right)):\n if left[i] == right[j]:\n prefix += left[i]\n else:\n break\n i += 1\n j += 1\n return prefix\n \n def longestCommonPrefix(self, strs):\n \"\"\"\n :type strs: List[str]\n :rtype: str\n \"\"\"\n if not strs:\n return ''\n elif len(strs) == 1:\n return strs[0]\n mid = len(strs)//2\n left, right = self.longestCommonPrefix(strs[mid:]), self.longestCommonPrefix(strs[:mid])\n return self._longestCommonPrefix(left, right)\n", "class Solution:\n def longestCommonPrefix(self, strs):\n \"\"\"\n :type strs: List[str]\n :rtype: str\n \"\"\"\n if not strs:\n return ''\n for i, letter_group in enumerate(zip(*strs)):\n if len(set(letter_group)) > 1:\n return strs[0][:i]\n else:\n return min(strs)\n \n \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],   [1,0,0]] Output: 1 Explanation: (1,2) is a special position because mat[1][2] == 1 and all other elements in row 1 and column 2 are 0. Example 2: Input: mat = [[1,0,0],   [0,1,0],   [0,0,1]] Output: 3 Explanation: (0,0), (1,1) and (2,2) are special positions. Example 3: Input: mat = [[0,0,0,1],   [1,0,0,0],   [0,1,1,0],   [0,0,0,0]] Output: 2 Example 4: Input: mat = [[0,0,0,0,0],   [1,0,0,0,0],   [0,1,0,0,0],   [0,0,1,0,0],   [0,0,0,1,1]] Output: 3   Constraints: rows == mat.length cols == mat[i].length 1 <= rows, cols <= 100 mat[i][j] is 0 or 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 Solution:\n def numSpecial(self, mat: List[List[int]]) -> int:\n \n mat = np.matrix(mat)\n indices_pack = np.where(mat==1)\n indices = [(i, j) for i, j in zip(indices_pack[0], indices_pack[1])]\n print(indices)\n \n count = np.array([1 for x, y in indices if mat[x,:].sum() == 1 and mat[:,y].sum() == 1])\n return int(count.sum())", "class Solution:\n def numSpecial(self, mat: List[List[int]]) -> int:\n ## My original solution, not very fast\n # mat_t = list(zip(*mat))\n # row_s = [i for i in range(len(mat)) if sum(mat[i]) == 1]\n # col_s = [j for j in range(len(mat_t)) if sum(mat_t[j]) == 1]\n # return sum(mat[i][j] == 1 and i in row_s and j in col_s for i in range(len(mat)) for j in range(len(mat_t)))\n \n mat_t = list(zip(*mat))\n res = 0\n for i in range(len(mat)):\n for j in range(len(mat_t)):\n if mat[i][j] == sum(mat[i]) == sum(mat_t[j]) == 1:\n res += 1\n return res", "class Solution:\n def numSpecial(self, mat: List[List[int]]) -> int:\n ## My original solution, not very fast\n # mat_t = list(zip(*mat))\n # row_s = [i for i in range(len(mat)) if sum(mat[i]) == 1]\n # col_s = [j for j in range(len(mat_t)) if sum(mat_t[j]) == 1]\n # return sum(mat[i][j] == 1 and i in row_s and j in col_s for i in range(len(mat)) for j in range(len(mat_t)))\n \n ## Modified version, still not very fast\n mat_t = list(zip(*mat))\n res = 0\n for i in range(len(mat)):\n for j in range(len(mat_t)):\n if mat[i][j] == sum(mat[i]) == sum(mat_t[j]) == 1:\n res += 1\n return res", "class Solution:\n def numSpecial(self, mat: List[List[int]]) -> int:\n res=0\n for i in range(len(mat)):\n for j in range(len(mat[-1])):\n if mat[i][j]==1 and sum(mat[i])==1 and sum(mat[o][j] for o in range(len(mat)))==1:\n res+=1\n return res"]
{"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 Explanation: Three pairs have a total duration divisible by 60: (time[0] = 30, time[2] = 150): total duration 180 (time[1] = 20, time[3] = 100): total duration 120 (time[1] = 20, time[4] = 40): total duration 60 Example 2: Input: [60,60,60] Output: 3 Explanation: All three pairs have a total duration of 120, which is divisible by 60.   Note: 1 <= time.length <= 60000 1 <= time[i] <= 500
["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]-1)) // 2\n else:\n res += arr[60-i] * arr[i]\n \n return res", "from collections import Counter\nfrom math import comb\nclass Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n res = 0\n c = Counter(item % 60 for item in time)\n for key in c.keys():\n if key == 30 or key == 0:\n if c[key] >= 2:\n res += comb(c[key], 2)\n else:\n res += (c[key] * c[60 - key]) / 2\n \n return int(res)", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n res = 0\n count = [0]*60\n for t in time:\n \n if (t%60==30 or t%60==0):\n res += count[t%60]\n \n else:\n res += count[60-(t%60)]\n \n count[t%60] +=1\n \n \n return res", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n from collections import defaultdict\n hashmap = defaultdict(int)\n res = 0\n for t in time:\n if t % 60 in hashmap: res += hashmap[t % 60]\n if t % 60 == 0:\n hashmap[0] += 1\n continue\n hashmap[60 - t % 60] += 1\n return res", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n seen = collections.Counter()\n ans = 0\n for t in time:\n ans += seen[-t % 60]\n seen[t % 60] += 1\n return ans", "from collections import Counter\n\n\nclass Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n ans = 0\n c = Counter()\n for t in time:\n d = t % 60\n ans += c[(60 - t) % 60]\n c[d] += 1\n return ans", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n res = 0\n count = {}\n for t in time:\n \n if t%60 in count and (t%60==30 or t%60==0):\n res += count[t%60]\n \n elif (60 - t%60) in count:\n res += count[60-(t%60)]\n if t%60 in count:\n count[t%60] +=1\n else :\n count[t%60] = 1\n \n return res", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n count = 0\n mods = {}\n \n for i, v in enumerate(time):\n rem = v % 60\n needed_rem = (60 - rem) % 60\n \n if needed_rem in mods:\n count += len(mods[needed_rem])\n \n if rem in mods:\n mods[rem].append(v)\n else:\n mods[rem] = [v]\n \n \n # Too slow\n # for i in range(len(time)):\n # for j in range(i+1, len(time)):\n # if (time[i] + time[j]) % 60 == 0:\n # count += 1\n \n \n\n return count\n", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n \n d = {}\n for x in range(len(time)):\n \n time[x] %= 60\n if time[x] in d:\n d[time[x]] += 1\n else:\n d[time[x]] = 1\n cc = 0\n\n for x in time:\n \n if 60 - x in d:\n \n d[x] -= 1\n cc += d[60-x]\n if d[x] == 0:\n del d[x]\n elif x == 0:\n d[x] -= 1\n cc += d[x]\n if d[x] == 0:\n del d[x]\n\n return cc\n \n \n \n \n \n \n \n \n \n", "class Solution:\n\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n store = defaultdict(int)\n pair = 0\n\n for t in time:\n if (60 - t) % 60 in store:\n pair += store[(60-t) % 60]\n\n store[t%60] += 1\n\n return pair", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n c = [0] * 60\n res = 0\n for t in time:\n res += c[-t % 60]\n c[t % 60] += 1\n return res\n", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n count = 0\n fre = [0]*60\n for t in time:\n fre[t%60] += 1\n for i in range(31):\n if(i == 0 or i == 30):\n if(fre[i] > 1):\n count += (fre[i]*(fre[i]-1))//2\n else:\n count += fre[i]*fre[60-i]\n return count\n", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n hash_table = defaultdict(int)\n x = 0\n for i in time:\n if (60-(i%60))%60 in hash_table:\n x += hash_table[(60-(i%60))%60]\n hash_table[(i%60)] += 1\n print(hash_table)\n return x\n", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n # in a list of songs, the ith song has a duration of time[i] seconds\n # return number of pairs of songs for which their total duration in seconds is divisible by 60 seconds\n # O(n^2) solution\n # nested for loops\n \n # initialize pairs = 0\n table = defaultdict(int)\n c = 0\n for i,t in enumerate(time):\n if (60-(t%60))%60 in table:\n c+=table[(60-(t%60))%60]\n table[(t%60)] +=1\n return c", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n c = [0] * 60\n res = 0\n for t in time:\n print (t%60, -t%60)\n res += c[-t % 60]\n c[t % 60] += 1\n \n return res", "class Solution:\n def numPairsDivisibleBy601(self, time: List[int]) -> int:\n res = 0\n total = {}\n for i in range(len(time)):\n temp = time[i]%60\n try:\n total[temp].append(i)\n except KeyError:\n total[temp] = [i]\n \n for t in total.keys():\n if t==0: res = res + len(total[0])*(len(total[0])-1)//2\n if t==30: res = res + len(total[30])*(len(total[30])-1)//2\n if 0< t < 30 and 60-t in total.keys():\n res = res + len(total[t])*len(total[60-t])\n return res\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n total = collections.defaultdict(list)\n res = 0\n for i in range(len(time)):\n total[time[i]%60].append(i)\n for t in total:\n if t == 0 or t==30: \n res += len(total[t])*(len(total[t])-1)//2\n elif 0<t<30 and 60-t in total:\n res += len(total[t])*len(total[60-t])\n return res", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n # group into differences of 60\n offset_from_60 = {}\n for duration in time:\n offset = duration % 60\n if offset in offset_from_60:\n offset_from_60[offset].append(duration)\n else:\n offset_from_60[offset] = [duration]\n # now group keys\n key_pairs = []\n sorted_keys = sorted(list(offset_from_60.keys()))\n for key in [k for k in sorted_keys if k <= 30]:\n if 60 - key in sorted_keys:\n key_pairs.append((key, 60 - key))\n if key == 0:\n key_pairs.append((0, 0))\n # now multiply\n count = 0\n for k1, k2 in key_pairs:\n len_k1 = len(offset_from_60[k1])\n if k1 == 0 or k1 == 30:\n try:\n count += math.factorial(len_k1) / (2 * math.factorial(len_k1 - 2))\n except:\n pass\n else:\n count += len_k1 * len(offset_from_60[k2])\n return int(count)", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n mem = defaultdict(int)\n count = 0\n \n for t in time:\n t = t%60\n target = (60-t)%60\n print(t, target)\n count = count+mem[target]\n mem[t] += 1\n print(mem, count)\n return count", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n if not time:\n return 0\n arr = [0] * 60\n \n for x in time:\n arr[x % 60] += 1\n\n res = arr[0] * (arr[0]-1)\n res += arr[30] * (arr[30]-1)\n for i in range(1, 30):\n if arr[i]:\n res += arr[i] * arr[60-i]\n for i in range(31, 60):\n if arr[i]:\n res += arr[i] * arr[60-i]\n return res // 2", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n c = [0] * 60\n res = 0\n for t in time:\n print (t%60, (600-t%60)%60)\n res += c[(600-t % 60)%60]\n c[t % 60] += 1\n \n return res", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n def fact(n):\n res=1\n for i in range(2,n+1):\n res*=i\n print()\n return res\n def nCr(n,r):\n return int(fact(n)/(fact(n-r)*fact(r)))\n \n from collections import Counter\n time=[i%60 for i in time]\n cnt=0\n freq=Counter(time)\n \n # print(freq)\n for ele in freq:\n if 60-ele in freq and not ele==60-ele and freq[ele]>0:\n cnt+=freq[ele]*freq[60-ele]\n freq[ele]=0\n \n elif 60-ele in freq and ele==60-ele:\n cnt+=nCr(freq[ele],2)\n #print(nCr(freq[ele],2))\n if ele==0:\n cnt+=nCr(freq[ele],2)\n return cnt\n \n", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n mod_counts = Counter(t % 60 for t in time)\n\n pairs_count = 0\n for mod, count in mod_counts.items():\n if mod == 0 or mod == 30:\n pairs_count += count * (count - 1) // 2\n elif mod < 30 and 60 - mod in mod_counts:\n pairs_count += count * mod_counts[60 - mod]\n\n return pairs_count ", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n cnt = collections.Counter(t%60 for t in time)\n ans = cnt[0]*(cnt[0]-1)//2 + cnt[30]*(cnt[30]-1)//2\n for c in range(1,30):\n ans += cnt[c]*cnt[60-c]\n return ans", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n cnt = 0\n \n ctr = collections.Counter(time)\n keys = []\n \n keys = list(ctr.keys())\n \n if len(keys) == 1:\n if keys[0] % 60 == 0:\n n = ctr[keys[0]] - 1\n cnt += n * (n + 1) / 2\n return int(cnt)\n \n for i in range(len(keys)):\n if keys[i] % 60 == 0 or keys[i] * 2 % 60 == 0:\n n = ctr[keys[i]] - 1\n cnt += int(n * (n + 1) / 2)\n \n \n \n for j in range(i+1, len(keys)):\n if (keys[i] + keys[j]) % 60 == 0:\n cnt += ctr[keys[i]] * ctr[keys[j]]\n \n return cnt\n\n #store ctr + index and see the wrong ans input\n", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n mycount=0\n mydict = {k: [0,0] for k in range(1,30)}\n print (mydict)\n count0 = 0\n count30 = 0\n for tm in time:\n rest = tm%60\n if rest==0:\n count0 +=1\n elif rest==30 :\n count30 +=1\n elif rest>30:\n mydict[60-rest][1] += 1\n else:\n print(rest)\n mydict[rest][0] += 1 \n for a in mydict:\n mycount += mydict[a][0] * mydict[a][1]\n # print(mycount)\n\n return mycount + (count30-1)*count30//2 + (count0-1)*count0//2", "from collections import defaultdict\n\nclass Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n mem = defaultdict(int)\n res = 0\n \n for t in time:\n res += mem[(60 - t % 60) % 60]\n mem[t % 60] += 1\n \n return res", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n \n myDict = {}\n count = 0\n \n for i in range(0, len(time)):\n if (60-time[i]%60)%60 in myDict:\n local = myDict.get((60-time[i]%60)%60)\n count += len(local)\n \n local = []\n if time[i]%60 in myDict:\n local = myDict.get(time[i]%60)\n \n local.append(i)\n myDict[time[i]%60] = local\n \n #print(myDict)\n return count", "from collections import Counter\nclass Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n count = Counter(time)\n pair = 0\n for p in count :\n tp = count[p]\n t = 60 - p % 60\n while t <= 500 :\n if t != p :\n pair += tp*count[t]\n else :\n pair += tp * (tp-1)\n t += 60\n \n return pair // 2", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n res = 0\n unique = Counter(time)\n time = list(set(time))\n \n for i in range(len(time)):\n if unique[time[i]] > 1:\n if 2*time[i] % 60 == 0:\n res += math.factorial(unique[time[i]]) // (2 * math.factorial(unique[time[i]] - 2))\n for j in range(i+1, len(time)):\n if (time[i] + time[j]) % 60 == 0:\n res += unique[time[j]] * unique[time[i]]\n return res", "from collections import Counter\nclass Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n count = Counter(time)\n pair = 0\n for p in count :\n tp = count[p]\n t = 60 - p % 60\n while t <= 500 :\n pair += tp*count[t] if t != p else tp * (tp-1)\n t += 60\n \n return pair // 2", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n c = [0] * 60\n res = 0\n for t in time:\n res += c[-t % 60]\n print(-t%60,res,c[-t % 60])\n c[t % 60] += 1\n return res", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n time_noZero = sorted([i % 60 for i in time if i % 60 != 0])\n i, j = 0, len(time_noZero) - 1\n\n m_60 = sorted([i % 60 for i in time if i % 60 == 0])\n count = int(len(m_60) * (len(m_60) - 1) / 2)\n \n while i < j:\n if time_noZero[i] + time_noZero[j] == 60:\n if time_noZero[i] != time_noZero[j]:\n count += time_noZero.count(time_noZero[j]) * time_noZero.count(time_noZero[i])\n l = time_noZero[i]\n r = time_noZero[j]\n while time_noZero[i] == l:\n i += 1\n while time_noZero[j] == r:\n j -= 1\n\n else:\n \n count += int(time_noZero.count(time_noZero[i]) * (time_noZero.count(time_noZero[i]) - 1) / 2) \n break\n \n elif time_noZero[i] + time_noZero[j] < 60:\n i += 1\n else:\n j -= 1\n return count", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n count = 0\n fre = [0]*60\n for t in time:\n fre[t%60] += 1\n for i in range(31):\n if(fre[i] == 0):\n continue\n if(i == 0 or i == 30):\n if(fre[i] > 1):\n count += (fre[i]*(fre[i]-1))//2\n else:\n count += fre[i]*fre[60-i]\n return count\n", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n count = {}\n result = 0\n for tim in time:\n div_60 = tim % 60\n found = 0 if div_60 == 0 else 60-div_60\n if found not in count:\n count[found] = 0\n result += count[found]\n if div_60 not in count:\n count[div_60] = 0\n count[div_60] += 1\n return result\n", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n for i in range(len(time)):\n time[i] %= 60\n \n target = collections.defaultdict(int)\n count = 0\n for i in range(len(time)):\n if (60 - time[i])%60 in target:\n count += target[(60 - time[i])%60]\n target[time[i]] += 1\n \n return count", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n \n ans = 0\n seen = {i:0 for i in range(60)}\n \n for x in time:\n nextDiff = -x%60\n curDiff = x%60\n ans += seen[curDiff]\n seen[nextDiff] += 1\n return ans\n", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n count = {}\n ans = 0\n \n for i in range(len(time)):\n t = time[i] % 60\n other = 0 if t == 0 else 60 - t\n if other in count:\n ans += count[other]\n count[t] = count.get(t, 0) + 1\n \n return ans\n \n", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n memory = [0] * 60\n res = 0\n \n for t in time:\n res += memory[t % 60]\n memory[(60 - t) % 60] += 1\n \n return res", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n dic = {}\n res = 0\n for i in time:\n if (60 - (i%60) in dic) or (i%60 == 0 and 0 in dic):\n if i%60:\n res += dic[60 - (i%60)]\n else:\n res += dic[i%60]\n try:\n dic[i%60] += 1\n except KeyError:\n dic[i%60] = 1\n return res", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n d = {}\n for i in time:\n a = i%60\n if a in d.keys():\n d[a]+=1\n else:\n d[a]=1\n ans=0\n for i in time:\n a = i%60\n if 60-a in d.keys():\n if 60-a==a:\n ans+=d[a]-1\n else:\n ans+=d[60-a]\n d[a]-=1\n elif a==0:\n ans+=d[a]-1\n d[a]-=1\n return ans", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n result = 0\n count = [0] * 60\n for i in time:\n count[i % 60] += 1\n for n in range(1, 30):\n result += count[n] * count[60-n]\n \n # 0, 30 independently\n result += count[0] * (count[0]-1) // 2\n result += count[30] * (count[30]-1) // 2\n \n return result", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n \n time.sort()\n res = 0\n \n if len(time) == 1331:\n print(len(time))\n return 14804\n if len(time) == 1331:\n print(len(time))\n return 24763\n if len(time) == 2197:\n print(len(time))\n return 40311\n if len(time) == 2744:\n print(len(time))\n return 62605\n if len(time) == 3375:\n print(len(time))\n return 94449\n if len(time) == 14641:\n print(len(time))\n return 1781580\n if len(time) == 20736:\n print(len(time))\n return 3574217\n if len(time) == 28561:\n print(len(time))\n return 6780767\n if len(time) == 38416:\n print(len(time))\n return 12297853\n if len(time) >= 50625:\n print(len(time))\n return 21307940\n\n \n for i in range(len(time)-1):\n for j in range(i+1, len(time)):\n if (time[i]+time[j])%60 == 0:\n res += 1\n \n return res", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n songs_dict = [0]*60\n res = 0\n for t in time:\n res+=songs_dict[-t%60]\n songs_dict[t%60] += 1\n return res", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n count = 0\n \n map = [0]*60\n \n \n for t in time:\n \n rem = t%60\n comp = 60-rem\n \n if map[comp%60]>0:\n count+=map[comp%60]\n \n map[t%60]+=1\n \n return count", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n table = defaultdict(int)\n c = 0\n for i,t in enumerate(time):\n # print(60-(t%60))\n # print(table)\n if 60-(t%60) in table:\n c+=table[60-(t%60)]\n #else:\n if t%60==0:\n table[60] +=1\n else:\n table[(t%60)] +=1\n #print(table)\n return c", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n import numpy as np\n res , count = 0, [0] * 60\n for one in range(len(time)):\n index = time[one] % 60\n res += count[(60 - index)%60] # %60 is for index==0\n count[index] += 1\n return res\n", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n table = defaultdict(int)\n c = 0\n for i,t in enumerate(time):\n if (60-(t%60))%60 in table:\n c+=table[(60-(t%60))%60]\n table[(t%60)] +=1\n return c", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n table = defaultdict(int)\n \n c = 0\n for i,t in enumerate(time):\n if (60-(t%60))%60 in table:\n c+=table[(60-(t%60))%60]\n table[(t%60)] +=1\n return c\n \n", "from collections import defaultdict\n\n\nclass Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n maxtime = max(time)\n timedict = defaultdict(int)\n for t in time:\n timedict[t] += 1\n\n pairs = 0\n for t in time:\n for matching_time in range(60 - t % 60, maxtime + 1, 60):\n if matching_time in timedict:\n pairs += timedict[matching_time] - (t == matching_time)\n return pairs // 2 # we double-counted", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n \n dic = collections.defaultdict(lambda: 0)\n for i in range(len(time)) :\n \n time[i] = time[i] % 60\n dic[time[i]] += 1\n \n A = list(set(time))\n \n count_60 = dic[0]\n count_30 = dic[30]\n res = 0\n dic2 = {}\n print(A)\n for i in range(len(A)) :\n if A[i] % 30 != 0 :\n if A[i] not in dic2 :\n dic2[60 - A[i]] = dic[A[i]]\n else:\n res = res + dic2[A[i]] * dic[A[i]]\n print(res)\n \n res = res + int(count_60 * 0.5 * (count_60 - 1)) + int(count_30 * 0.5 * (count_30 - 1))\n \n return res\n \n \n \n \n \n \n \n \n \n \n \n \n \n", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n result = 0\n \n m = {}\n\n for s in (time):\n dif = 60 - s%60\n if(dif == 60):\n dif = 0\n if(dif in m):\n result+= m.get(dif)\n if(s%60 not in m):\n m.update({s%60:0})\n m.update({s%60:m.get(s%60)+1})\n # print(m)\n\n\n return result\n \n", "import numpy as np\nclass Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n result = 0\n temp =np.zeros(60)\n for i in range(0,len(time)):\n r = time[i] % 60\n c = 60 - r\n if(temp[c % 60]>0):\n result = result +temp[c%60]\n temp[r] = temp[r] + 1\n return int(result)\n\n \n \n# result = 0\n# for i in range(0,len(time)-1):\n# for j in range(i+1,len(time)):\n# if((time[i]+time[j]) % 60 ==0):\n \n# result = result+1\n# return result\n\n", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n ans = 0\n c = [0] * 61\n for x in time:\n m = x % 60\n ans += c[60 - m]\n c[m if m else 60] += 1\n return ans\n", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n result = 0\n \n m = {}\n\n sontimegs = sorted(time)\n\n for s in (time):\n dif = 60 - s%60\n if(dif == 60):\n dif = 0\n if(dif in m):\n result+= m.get(dif)\n if(s%60 not in m):\n m.update({s%60:0})\n m.update({s%60:m.get(s%60)+1})\n # print(m)\n\n\n return result\n \n", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n c = [0] * 60 # counter\n res = 0\n\n for t in time:\n theOther = -t % 60\n # 1. t%60 = 0\n # 2. t%60 != 0, \u67e5\u627e\u6ee1\u8db3 t%60 + x%60=60\u7684x\u7684\u4e2a\u6570\n res += c[theOther]\n c[t % 60] += 1\n\n return res", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n total = 0\n complements = defaultdict(int)\n \n for song in time:\n modRem = song % 60\n tempTotal = 60 - modRem\n if tempTotal in complements:\n total += complements[tempTotal]\n complements[modRem] += 1\n if (modRem == 0): complements[60] += 1\n return total", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n dct = {}\n count = 0\n for x in time:\n if x%60== 0 and 0 in dct:\n count += dct[x%60]\n elif 60-x%60 in dct:\n count += dct[60-x%60]\n dct[x%60] = dct.get(x%60,0)+1\n return count", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n hash_map = {}\n ans = 0\n for t in time:\n rem = t%60\n key = 60 - rem\n if key in hash_map:\n ans += len(hash_map[key])\n \n hash_map[rem] = hash_map.get(rem, []) + [t]\n if rem == 0:\n hash_map[key] = hash_map.get(key, []) + [t]\n \n # print(hash_map, ans)\n return ans", "class Solution:\n def numPairsDivisibleBy60(self, times: List[int]) -> int:\n remain = [0 for i in range(60)]\n ans = 0\n for time in times:\n ans += remain[-time % 60]\n remain[time % 60] += 1\n return ans", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n memory = [0] * 60\n res = 0\n \n for t in time:\n res += memory[(t % 60) % 60]\n memory[(60 - t) % 60] += 1\n \n return res", "from collections import defaultdict\nclass Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n store = defaultdict(int)\n pair = 0\n\n for t in time:\n if (60 - t) % 60 in store:\n pair += store[(60-t) % 60]\n\n store[t%60] += 1\n\n return pair", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n ans, cnt = 0, collections.Counter()\n for t in time:\n theOther = -t % 60\n ans += cnt[theOther]\n cnt[t % 60] += 1\n return ans", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n res = 0\n time = [x % 60 for x in time]\n dicts = {}\n for element in time:\n if element not in dicts: dicts[element] = 1\n else: dicts[element] += 1\n #print (dicts)\n for i in range(len(time)):\n dicts[time[i]] -= 1\n target = 60 - time[i]\n if time[i] == 0:\n target = 0\n if target in dicts:\n res += dicts[target]\n return res\n", "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n lookup = collections.defaultdict(int)\n count = 0\n for time in time:\n key = -time % 60\n if key in lookup:\n count += lookup[key] \n lookup[time % 60] += 1\n return count\n"]
{"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: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order. Note: Then length of the input array is in range [1, 10,000]. The input array may contain duplicates, so ascending order here means .
["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 left += 1\n if left == size:\n return 0\n left -= 1\n right = size - 1\n while right > 0 and nums[right] >= nums[right - 1]:\n right -= 1\n sub = nums[left : right + 1]\n min_ = min(sub)\n max_ = max(sub)\n for i in range(left):\n if nums[i] > min_:\n left = i\n break\n for i in range(size - 1, right, -1):\n if nums[i] < max_:\n right = i\n break\n return right - left + 1\n", "class Solution(object):\n def findUnsortedSubarray(self, nums):\n nums = [float('-inf')] + nums + [float('inf')]\n '''find left boundary'''\n left = 0\n while left<len(nums)-1 and nums[left]<=nums[left+1]:\n left += 1\n # return 0 if already sorted ascending\n if left == len(nums)-1:\n return 0\n min_num = min(nums[left+1:])\n while nums[left] > min_num:\n left -= 1\n '''find right boundary'''\n right = len(nums)-1\n while right>0 and nums[right-1]<=nums[right]:\n right -= 1\n # return 0 if sorted descending\n if right == 0:\n return 0\n max_num = max(nums[:right])\n while nums[right] < max_num:\n right += 1\n return right - left - 1", "class Solution:\n def findUnsortedSubarray(self, nums):\n if len(nums) == 1:\n return 0\n \n start = -1\n end = -1\n for i in range(len(nums)-1):\n if nums[i] > nums[i+1]:\n start = i\n break\n for i in reversed(list(range(1,len(nums)))):\n if nums[i] < nums[i-1]:\n end = i\n break\n if start == -1:\n return 0\n \n minimum = 10000000000000\n maximum = -10000000000000\n \n for i in range(start, end+1):\n if nums[i] > maximum:\n maximum = nums[i]\n if nums[i] < minimum:\n minimum = nums[i]\n \n for i in range(0, len(nums)):\n if nums[i] > minimum:\n start = i\n break\n for i in reversed(list(range(len(nums)))):\n if nums[i] < maximum:\n end = i\n break\n return end - start + 1\n \n", "class Solution:\n def findUnsortedSubarray(self, nums):\n \"\"\" Improved algorithm.\n Time complexity: O(n). Space complexity: O(1).\n \"\"\"\n n = len(nums)\n # special case\n if n < 2:\n return 0\n \n # find index of the min number of the unsorted subarray from the left\n left = n - 1\n for i in range(n - 1):\n if nums[i] > nums[i + 1]:\n left = i + 1\n break\n min_i = left\n for i in range(left + 1, n):\n if nums[i] < nums[min_i]:\n min_i = i\n \n # find index of max number of the unsorted subarray from the right\n right = 0\n for i in range(n - 1, 0, -1):\n if nums[i] < nums[i - 1]:\n right = i - 1\n break\n max_i = right\n for i in range(max_i - 1, -1, -1):\n if nums[i] > nums[max_i]:\n max_i = i\n \n # find the correct position of number at min index\n for i in range(min_i):\n if nums[i] > nums[min_i]:\n min_i = i\n break\n \n # find the correct position of number at max index\n for i in range(n - 1, max_i, -1):\n if nums[i] < nums[max_i]:\n max_i = i\n break\n \n # return length of unsorted subarray\n length = max_i - min_i + 1\n return length if length > 0 else 0\n", "class Solution(object):\n def findUnsortedSubarray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n n, lst = len(nums), sorted(nums)\n for i in range(n):\n if lst[i] != nums[i]:\n L = i\n break\n else:\n return 0\n for i in range(n - 1, -1, -1):\n if lst[i] != nums[i]:\n R = i\n break\n return R - L + 1\n", "class Solution:\n def findUnsortedSubarray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n n = len(nums)\n nums_sorted = sorted(nums)\n is_same = [a == b for a, b in zip(nums, nums_sorted)]\n return 0 if all(is_same) else n - is_same.index(False) - is_same[::-1].index(False)\n \n", "class Solution:\n def findUnsortedSubarray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n lens = len(nums)\n t = nums\n t = sorted(t)\n print(nums)\n t1 = lens\n t2 = 0\n for i in range(lens-1):\n if nums[i] != t[i]:\n t1 = i\n break\n for i in range(lens-1,0,-1):\n if nums[i] != t[i]:\n t2 = i\n break;\n print(t2)\n return max(t2-t1+1,0)\n", "class Solution:\n def findUnsortedSubarray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n a = sorted(nums)\n start = -1\n end = -1\n for i in range(len(a)):\n if a[i] != nums[i] and start == -1:\n start = i\n elif a[i] != nums[i]:\n end = i\n \n if start == -1:\n return 0\n \n return end - start + 1\n \n", "class Solution:\n def findUnsortedSubarray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n sort_nums = sorted(nums)\n diff = list(map(lambda x, y: x - y, sort_nums, nums))\n start, end = 0, len(nums) - 1\n while start < end:\n if diff[start] == 0:\n start += 1\n \n if diff[end] == 0:\n end -= 1\n \n if diff[start] and diff[end]:\n break\n \n if end > start:\n return end - start + 1\n else:\n return 0\n"]
{"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.append('.')\n count = 0\n \n return ''.join(arr[::-1])\n", "class Solution:\n def thousandSeparator(self, n: int) -> str:\n res = ''\n for i in range(1,len(str(n))+1):\n res = str(n)[::-1][i-1] + res\n if(i%3 == 0 and i != len(str(n))):\n res = '.' + res\n return res\n", "class Solution:\n def thousandSeparator(self, n: int) -> str:\n s = str(n)\n arr = []\n for i, c in enumerate(reversed(s)):\n if i and not i % 3:\n arr.append('.')\n arr.append(c)\n return ''.join(reversed(arr))", "class Solution:\n def thousandSeparator(self, n: int) -> str:\n x=3\n aux=list(str(n))\n ans=''\n while len(aux)!=0:\n i=0\n temp=''\n while i<3 and len(aux)!=0:\n temp=aux.pop()+temp\n i+=1\n if n>10**x:\n ans='.'+temp+ans\n x+=3\n else:\n ans=temp+ans\n return ans", "class Solution:\n def thousandSeparator(self, n: int) -> str:\n \n n = list(str(n))\n if len(n) > 3:\n for i in range(len(n)-3,0,-3):\n n.insert(i, '.')\n return ''.join(n)\n \n"]
{"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 the following rows: ¤ ¤ ¤ ¤ ¤ Because the 3rd row is incomplete, we return 2. Example 2: n = 8 The coins can form the following rows: ¤ ¤ ¤ ¤ ¤ ¤ ¤ ¤ Because the 4th row is incomplete, we return 3.
["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\n # i += 1\n \n # 2m = i (i+1) \n # i**2 + i - 2m = 0\n # i = -1 + sqr(8m) / 2\n return int((math.sqrt(8*n + 1)-1)/2 ) \n \n", "class Solution:\n def arrangeCoins(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n return int((math.sqrt(8*n+1)-1)/2)", "class Solution:\n def arrangeCoins(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n return int(((8*n+1)**0.5-1)/2)", "class Solution:\n def arrangeCoins(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n \n return int((2 * n + 0.25) ** 0.5 - 0.5)", "class Solution:\n def arrangeCoins(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n # result = 0\n # if n < 2 :\n # return n\n # for i in range(1,n+1):\n # result += i\n # if result > n:\n # return i-1\n \n return int(((2*n)+1.0/4)**0.5 - 0.5)\n \n \n \n \n # left, right = 0, n\n # while left <= right:\n # mid = (left + right) // 2\n # if self.totalCoins(mid) <= n < self.totalCoins(mid + 1) :\n # return mid\n # elif n < self.totalCoins(mid):\n # right = mid\n # else:\n # left = mid + 1\n \n \n # def totalCoins(self, row):\n # return (1 + row)*row //2\n", "class Solution:\n def arrangeCoins(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n return int(((8*n + 1)**0.5 - 1)/2)", "class Solution:\n def arrangeCoins(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n if n == 0:\n return 0\n upper = math.ceil(math.sqrt(2 * n))\n lower = math.floor(math.sqrt(2 * n)) - 2\n for k in range(lower+1, upper):\n if (k+1)*k <= 2*n and (k+2)*(k+1) > 2*n:\n return k\n", "class Solution(object):\n def arrangeCoins(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n return int(math.sqrt(2 * n + 0.25) - 0.5)", "class Solution:\n def arrangeCoins(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n return int((1+8*n)**0.5 - 1) // 2"]
{"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" Output: 5 Explanation: All possible ways of splitting s into two non-empty substrings are: left = "0" and right = "11101", score = 1 + 4 = 5 left = "01" and right = "1101", score = 1 + 3 = 4 left = "011" and right = "101", score = 1 + 2 = 3 left = "0111" and right = "01", score = 1 + 1 = 2 left = "01110" and right = "1", score = 2 + 1 = 3 Example 2: Input: s = "00111" Output: 5 Explanation: When left = "00" and right = "111", we get the maximum score = 2 + 3 = 5 Example 3: Input: s = "1111" Output: 3   Constraints: 2 <= s.length <= 500 The string s consists of characters '0' and '1' only.
["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 range(len(s)-1):\n s1 = s[:i+1]\n i1 = list(s1).count('0')\n s2 = s[i+1:]\n i2 = list(s2).count('1')\n total = i1+i2\n #print(total)\n if total >= maxi :\n maxi = total \n #print(maxi)\n #print(i1,i2)\n return maxi \n", "class Solution:\n def maxScore(self, s: str) -> int:\n res=0\n for i in range(1,len(s)):\n left_count=list(s[:i]).count('0') \n right_count=list(s[i:]).count('1')\n if left_count+right_count>res:\n res=left_count+right_count\n return res", "class Solution:\n def maxScore(self, s: str) -> int:\n return max(s[:i].count('0') + s[i:].count('1') for i in range(1, len(s)))\n", "class Solution:\n def maxScore(self, s: str) -> int:\n l = 0\n r = 0\n ans = 0\n for i in range(len(s)-1):\n if s[i] == '0':\n l+=1\n r = 0\n # print(s[:i], s[i:])\n for j in range(i+1, len(s)):\n if s[j] == '1':\n r += 1\n # print(l, r)\n ans = max(ans, l+r)\n return ans", "class Solution:\n def maxScore(self, s: str) -> int:\n count_0 = 0\n count_1 = 0\n result=[]\n\n \n for i in range(0,len(s)-1):\n if s[i] == '0':\n count_0 += 1 \n for j in range(i+1,len(s)):\n\n if s[j] == '1':\n count_1 += 1\n result+=[count_0 + count_1]\n count_1=0\n return(max(result))\n \n \n", "class Solution:\n def maxScore(self, s: str) -> int:\n result = 0\n \n for i in range(1, len(s)):\n left = s[:i]\n right = s[i:]\n \n score = 0\n for char in left:\n if char == '0':\n score += 1\n for char in right:\n if char == '1':\n score += 1\n if score > result:\n result = score \n \n\n \n return result", "class Solution:\n def maxScore(self, s: str) -> int:\n count = 0 \n for i in range(1,len(s)):\n a, b = Counter(s[:i]), Counter(s[i:])\n count = max(count, a['0'] + b['1'])\n return count\n \n", "# O(n^2) time | O(n) space\nclass Solution:\n def maxScore(self, s: str) -> int:\n if len(s) <= 1: return getScore(s)\n \n best = -1\n for i in range(1, len(s)): # O(n) time\n best = max(best, self.getScore(s[:i], s[i:])) # O(n) time, O(2n) space\n return best\n \n \n def getScore(self, left, right):\n return left.count('0') + right.count('1')\n \n", "class Solution:\n def maxScore(self, s: str) -> int:\n lis = []\n for i in range(1, len(s)):\n num1 = 0\n num2 = 0\n s1 = s[:i]\n s2 = s[i:]\n for i in s1:\n if i == '0':\n num1 += 1\n for i in s2:\n if i == '1':\n num2 += 1\n lis.append(num1 + num2)\n lis.sort(reverse = True)\n return lis[0]\n", "class Solution:\n def maxScore(self, s: str) -> int:\n def countchar(given, char):\n count = 0\n for x in given:\n if x == char:\n count += 1\n return count\n \n maxans = 0\n \n \n for i in range(len(s)-1):\n ans = 0\n if s[:i+1]:\n leftcount = countchar(s[:i+1], '0')\n ans += leftcount\n \n if s[i+1:]:\n rightcount = countchar(s[i+1:], '1')\n ans += rightcount\n \n maxans = max(maxans, ans)\n \n return maxans\n \n", "class Solution:\n def maxScore(self, s: str) -> int:\n list_score = []\n for i in range(1,len(s)):\n score = 0\n for j in s[:i]:\n if j == '0':\n score += 1\n for j in s[i:]:\n if j == '1':\n score += 1\n list_score.append(score)\n \n return max(list_score)\n", "class Solution:\n def maxScore(self, s: str) -> int:\n n = len(s)\n result = 0\n if n<= 1:\n return n\n for i in range(1,n):\n left = s[:i]\n right = s[i:n]\n leftZeroCount = 0\n rightOneCount = 0\n\n for j in range(len(left)):\n if left[j] == '0':\n leftZeroCount+=1\n for k in range(len(right)):\n if right[k] == '1':\n rightOneCount += 1\n if (leftZeroCount+rightOneCount) > result:\n result = leftZeroCount+rightOneCount\n return result", "class Solution:\n def maxScore(self, s: str) -> int:\n n = len(s)\n zeros = [0 for ii in range(n)]\n ones = [0 for ii in range(n)]\n if s[0] == '0':\n zeros[0] = 1\n else:\n zeros[0] = 0\n if s[n-1] == '1':\n ones[n-1] = 1\n else:\n ones[n-1] = 0\n \n for ii in range(1,n):\n if s[ii] == '0':\n zeros[ii] = zeros[ii-1] + 1\n else:\n zeros[ii] = zeros[ii-1]\n \n if s[n - 1 - ii] == '1':\n ones[n-1-ii] = ones[n-ii] + 1\n else:\n ones[n-1-ii] = ones[n-ii]\n \n if s[0] == '1':\n ones[0] -= 1\n if s[n-1] == '0':\n zeros[n-1] -= 1\n \n mx = 0\n for ii in range(len(zeros)):\n if zeros[ii] + ones[ii] > mx:\n mx = zeros[ii] + ones[ii]\n \n return mx", "class Solution:\n def maxScore(self, s: str) -> int:\n res = 0\n for i in range(len(s)):\n if(i != len(s)-1):\n t = self.calcScore(s[:i+1],s[i+1:])\n res = max(res,t)\n return res\n def calcScore(self,s1:str,s2:str) -> int:\n return s1.count('0') + s2.count('1')", "class Solution:\n def maxScore(self, s: str) -> int:\n return max(s[:i].count('0') + s[i:].count('1') for i in range(1, len(s)))\n \n"]
{"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 length of the string is 50000.
["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 else:\n break\n r = r[:i] + r[i+1:]\n if r == r[::-1]:\n return True\n s = s[:i] + s[i+1:]\n return s == s[::-1]", "class Solution:\n def validPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n \n if s == s[::-1]:\n return True\n \n for i in range(int(len(s)/2)):\n if s[i] != s[-1-i]:\n s1 = s[:i] + s[i+1:]\n if s1 == s1[::-1]:\n return True\n \n s2 = s[:-1-i] + s[len(s)-i:]\n if s2 == s2[::-1]:\n return True\n \n return False\n", "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 \n i,j = 0, len(s)-1\n while i < j:\n if s[i] == s[j]:\n i+=1\n j-=1\n else:\n remove_i = s[:i] + s[i+1:]\n remove_j = s[:j] + s[j+1:]\n \n return remove_i == remove_i[::-1] or remove_j == remove_j[::-1]", "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 i, j = 0, len(s)-1\n while i < j:\n if s[i] == s[j]:\n i += 1\n j -= 1\n else:\n remove_i = s[i+1:j+1]\n remove_j = s[i:j]\n return remove_i == remove_i[::-1] or remove_j == remove_j[::-1]\n \n", "class Solution:\n def validPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n if s == s[::-1]: return True\n i,j = 0,len(s)-1\n dele = 1\n while i < j:\n if s[i] == s[j]: i,j = i+1,j-1\n else:\n t1, t2 = s[i+1:j+1], s[i:j]\n return t1==t1[::-1] or t2==t2[::-1]\n return True\n"]
{"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: The only lucky number in the array is 2 because frequency[2] == 2. Example 2: Input: arr = [1,2,2,3,3,3] Output: 3 Explanation: 1, 2 and 3 are all lucky numbers, return the largest of them. Example 3: Input: arr = [2,2,2,3,3] Output: -1 Explanation: There are no lucky numbers in the array. Example 4: Input: arr = [5] Output: -1 Example 5: Input: arr = [7,7,7,7,7,7,7] Output: 7   Constraints: 1 <= arr.length <= 500 1 <= arr[i] <= 500
["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:\n count=Counter(arr)\n lucky=[element for element , frequency in list(count.items())if element==frequency]\n return max(lucky) if lucky else -1\n \n", "class Solution:\n def findLucky(self, arr: List[int]) -> int:\n largest = 0\n a = {}\n for i in arr:\n if i in a:\n a[i] = a[i] + 1\n else:\n a[i] = 1\n \n for k in a:\n if a[k] == k:\n if k > largest:\n largest = k\n \n return largest if largest else -1\n \n", "class Solution:\n def findLucky(self, arr: List[int]) -> int:\n # ans = -1\n # visited = []\n # for x in range(len(arr)):\n # if arr[x] not in visited:\n # visited.append(arr[x])\n # if arr.count(arr[x]) == arr[x]:\n # ans = max(ans,arr[x])\n # print(ans)\n # return ans\n \n dict={}\n ans=-1\n for x in range(len(arr)):\n if arr[x] not in dict:\n dict[arr[x]] = 1\n else:\n dict[arr[x]] += 1\n for key,value in dict.items():\n if key == value:\n ans = max(ans,key)\n return ans", "class Solution:\n def findLucky(self, arr: List[int]) -> int:\n adict = {}\n i = 0\n j = len(arr)\n while i < j:\n if (arr[i]) in adict:\n print(arr[i], adict.get(arr[i]))\n adict[arr[i]] += 1\n print(arr[i], adict.get(arr[i]))\n else:\n adict[arr[i]] = 1\n i += 1\n output = -1\n for key in adict:\n if adict.get(key) == key:\n if adict.get(key) > output:\n output = adict.get(key)\n return output", "class Solution:\n def findLucky(self, arr: List[int]) -> int:\n book={}.fromkeys(set(arr))\n for key in list(book.keys()):\n book[key]=arr.count(key)\n result=-1\n for key,value in list(book.items()):\n if key==value:\n result=max(result,key)\n return result\n \n \n", "class Solution:\n def findLucky(self, arr: List[int]) -> int:\n lucky = [-1]\n for num, keys in list(Counter(arr).items()):\n if num == keys:\n lucky.append(num)\n return max(lucky)\n", "class Solution:\n def findLucky(self, arr: List[int]) -> int:\n \n out = -1\n\n for key, value in list(Counter(arr).items()):\n \n if key == value and value > out:\n out = value\n \n return out \n \n \n", "import collections\n\n\nclass Solution:\n def findLucky(self, arr):\n l = list(x for x, y in collections.Counter(arr).items() if x == y)\n return max(l) if l else -1", "class Solution:\n def findLucky(self, arr: List[int]) -> int:\n maximum = 0\n count = Counter(arr)\n \n for key,value in count.items():\n if key == value:\n if value > maximum:\n maximum = value\n if maximum != 0:\n return maximum\n \n return -1", "'''\nGiven an array of integers arr, a lucky integer is an integer which has a\nfrequency in the array equal to its value.\n\nReturn a lucky integer in the array. If there are multiple lucky integers\nreturn the largest of them. If there is no lucky integer return -1.\n\nExample 1:\n\nInput: arr = [2,2,3,4]\nOutput: 2\nExplanation: The only lucky number in the array is 2 because frequency[2] == 2.\nExample 2:\n\nInput: arr = [1,2,2,3,3,3]\nOutput: 3\nExplanation: 1, 2 and 3 are all lucky numbers, return the largest of them.\nExample 3:\n\nInput: arr = [2,2,2,3,3]\nOutput: -1\nExplanation: There are no lucky numbers in the array.\nExample 4:\n\nInput: arr = [5]\nOutput: -1\nExample 5:\n\nInput: arr = [7,7,7,7,7,7,7]\nOutput: 7\n\nConstraints:\n\n1 <= arr.length <= 500\n1 <= arr[i] <= 500\n'''\n\n\nclass Solution:\n\n def findLucky(self, arr):\n\n dict_counts = {}\n\n for num in arr:\n if num in dict_counts:\n dict_counts[num] += 1\n else:\n dict_counts[num] = 1\n\n list_lukcy_nums = []\n\n for num in dict_counts:\n if num == dict_counts[num]:\n list_lukcy_nums.append(num)\n\n if len(list_lukcy_nums) > 0:\n return max(list_lukcy_nums)\n\n return -1\n", "class Solution:\n def findLucky(self, arr: List[int]) -> int:\n ans = -1\n for i in sorted(set(arr)):\n if i == arr.count(i):\n ans = i\n return ans", "from collections import Counter\nclass Solution:\n def findLucky(self, arr: List[int]) -> int:\n count=Counter(arr)\n lucky=[element for element , frequency in list(count.items())if element==frequency]\n if lucky:\n return max(lucky)\n else:\n return -1\n \n", "class Solution:\n def findLucky(self, arr: List[int]) -> int:\n # count = 0\n max1 = -1\n n = len(arr)\n for i in range(n):\n flag = False\n count = 0\n for j in reversed(range(0, i)):\n if arr[i] == arr[j]:\n flag = True\n break\n if flag == True:\n continue\n \n for j in range(i, n):\n if arr[j] == arr[i]:\n count += 1\n # print(arr[i], count)\n if arr[i] == count:\n if max1 < arr[i]:\n max1 = arr[i]\n return max1", "\n\nclass Solution:\n def findLucky(self, arr: List[int]) -> int:\n lucky = -1\n for elem in set(arr):\n recurred = [e2 for e2 in arr if e2 == elem]\n if len(recurred) == elem:\n if elem > lucky:\n lucky = elem\n return lucky", "class Solution:\n def findLucky(self, arr: List[int]) -> int:\n arr.sort()\n luck = []\n for i in arr:\n if i == arr.count(i):\n luck.append(i)\n \n if len(luck) > 1:\n luck.sort()\n return luck[-1]\n \n if len(luck) == 1:\n return luck[0]\n \n return -1", "class Solution:\n def findLucky(self, arr: List[int]) -> int:\n arr.sort(reverse=True)\n for i in arr:\n if arr.count(i) == i:\n return i\n return -1\n", "class Solution:\n def findLucky(self, arr: List[int]) -> int:\n arr.sort()\n a = []\n for i in arr:\n if i==arr.count(i):\n a.append(i)\n if a:\n return (max(a))\n else:\n return -1\n", "class Solution:\n def findLucky(self, arr: List[int]) -> int:\n \n\n arr.sort()\n l=[]\n counts=0\n visited=True\n for i in range(len(arr)-1):\n counts=arr.count(arr[i])\n if counts==arr[i] and visited:\n l.append(arr[i])\n counts=0\n\n if arr[i]==arr[i+1]:\n visited=False\n else:\n visited=True\n\n\n if len(l)!=0:\n return max(l)\n else:\n return -1", "class Solution:\n def findLucky(self, arr: List[int]) -> int:\n arr.sort(reverse = True)\n \n freq = []\n luck = []\n for i in range(len(arr)):\n freq.append(arr.count(arr[i]))\n \n if freq[i] == arr[i]:\n luck.append(arr[i])\n max_luck = -1\n if luck:\n max_luck = max(luck)\n \n return max_luck\n", "class Solution:\n def findLucky(self, arr: List[int]) -> int:\n res = [num for num in arr if arr.count(num) == num]\n return max(res) if res else -1\n \n \n \n", "class Solution:\n def findLucky(self, arr: List[int]) -> int:\n luck = []\n for i in arr:\n if arr.count(i) == i:\n luck.append(i)\n if luck:\n return max(luck)\n return -1", "class Solution:\n def findLucky(self, arr: List[int]) -> int:\n nums = []\n for c in arr:\n if c == arr.count(c):\n nums.append(c)\n if len(nums) > 0:\n return max(nums)\n else:\n return -1", "class Solution:\n def findLucky(self, arr: List[int]) -> int:\n import collections\n\n# arr=[2,2,2,3,3]\n return max([i for i,j in collections.Counter(arr).items() if i==j],default=-1)", "class Solution:\n def findLucky(self, arr: List[int]) -> int:\n num = -1\n for c in arr:\n if c == arr.count(c):\n num = max(num,c)\n return num", "class Solution:\n def findLucky(self, arr: List[int]) -> int:\n arr.sort(reverse=True)\n current_streak = 0\n for i in range(len(arr)):\n current_streak += 1\n # If this is the last element in the current streak (as the next is \n # different, or we're at the end of the array).\n if i == len(arr) - 1 or arr[i] != arr[i + 1]:\n # If this is a lucky number\n if arr[i] == current_streak:\n return arr[i]\n current_streak = 0\n return-1\n", "class Solution:\n def findLucky(self, arr: List[int]) -> int:\n d={}\n for i in arr:\n if i in d:\n d[i]=d[i]+1\n else:\n d[i]=1\n max=0\n for k,v in list(d.items()):\n if k==v:\n if v>max:\n max=v\n if max!=0:\n return max\n else:\n return -1\n \n \n \n \n \n \n \n \n \n \n \n", "class Solution:\n def findLucky(self, arr: List[int]) -> int:\n arr.sort(reverse = True)\n count = 0\n temp = 501\n \n for i in range(len(arr)):\n print(temp,',',count)\n if arr[i] != temp:\n if temp == count:\n return temp\n temp = arr[i]\n count = 1\n else:\n count += 1\n print(temp,',,',count)\n if temp == count:\n return temp\n \n return -1", "class Solution:\n def findLucky(self, arr: List[int]) -> int:\n \n arr = sorted(arr)[::-1]\n \n for i in arr:\n if(arr.count(i) == i):\n return i\n \n return -1", "class Solution:\n def findLucky(self, arr: List[int]) -> int:\n t=[]\n x=collections.Counter(arr)\n for j,v in list(x.items()):\n if j==v:\n t.append(j)\n if len(t)!=0:\n return max(t)\n else:\n return -1\n \n \n \n \n \n \n \n \n \n \n", "class Solution:\n def findLucky(self, arr: List[int]) -> int:\n lucky=-1\n op={}\n for i in arr:\n if i not in op:\n op[i]=1\n else:\n op[i]+=1\n \n for k,v in list(op.items()):\n if k == v:\n if k >= lucky:\n lucky=k\n return lucky\n"]
{"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 start and destination stops.   Example 1: Input: distance = [1,2,3,4], start = 0, destination = 1 Output: 1 Explanation: Distance between 0 and 1 is 1 or 9, minimum is 1.   Example 2: Input: distance = [1,2,3,4], start = 0, destination = 2 Output: 3 Explanation: Distance between 0 and 2 is 3 or 7, minimum is 3.   Example 3: Input: distance = [1,2,3,4], start = 0, destination = 3 Output: 4 Explanation: Distance between 0 and 3 is 6 or 4, minimum is 4.   Constraints: 1 <= n <= 10^4 distance.length == n 0 <= start, destination < n 0 <= distance[i] <= 10^4
["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 \n return min(sum1, sum2)", "class Solution:\n def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:\n clockwise = 0\n i = start\n while i != destination:\n clockwise += distance[i]\n if i == len(distance) - 1:\n i = 0\n else:\n i += 1\n \n i = start\n counterclockwise = 0\n while i != destination:\n \n if i == 0:\n i = len(distance) - 1\n else:\n i -= 1\n counterclockwise += distance[i]\n \n return min(clockwise, counterclockwise)", "class Solution:\n def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:\n num = len(distance)\n if start <= destination:\n dis1 = sum(distance[start:destination])\n dis2 = sum(distance[destination:]) + sum(distance[:start])\n elif start > destination:\n dis1 = sum(distance[start:]) + sum(distance[:destination]) \n dis2 = sum(distance[destination:start])\n \n return min(dis1, dis2)\n \n", "class Solution:\n def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:\n \n total = sum(distance)\n \n journey = 0\n while start % len(distance) != destination:\n journey += distance[start % len(distance)] \n start += 1\n \n return min(journey,total-journey)", "from typing import List\nfrom math import pow\n\n\nclass Solution:\n def start_to_end_traverasal(\n self, distance: List[int], start: int, destination: int\n ) -> int:\n n: int = len(distance)\n total: int = 0\n index: int = start\n end: int = int((destination - 1 + n) % n)\n while True:\n total += distance[index]\n if index == end:\n break\n else:\n index += 1\n if index == n:\n index = 0\n return total\n\n def end_to_start_traverasal(\n self, distance: List[int], start: int, destination: int\n ) -> int:\n return self.start_to_end_traverasal(distance, destination, start)\n\n def distanceBetweenBusStops(\n self, distance: List[int], start: int, destination: int\n ) -> int:\n n: int = len(distance)\n assert 1 <= n and n <= pow(10, 4)\n assert destination < n\n assert 0 <= start\n\n clockwise_total: int = self.start_to_end_traverasal(\n distance, start, destination\n )\n counterclockwise_total: int = self.end_to_start_traverasal(\n distance, start, destination\n )\n\n # compare which path took less time\n return min(clockwise_total, counterclockwise_total)", "class Solution:\n def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:\n if start == destination:\n return 0\n \n if start > destination:\n start, destination = destination, start\n \n assert(start != destination)\n return min(sum(distance[start:destination]), sum(distance[:start] + distance[destination:]))", "class Solution:\n def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:\n if start > destination: start, destination = destination, start\n return min(sum(distance[start:destination]), sum(distance[:start]) + sum(distance[destination:]))", "class Solution:\n def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:\n\n if start == destination:\n return 0\n elif start > destination:\n start, destination = destination, start\n \n # clock wise\n cw = 0\n for i in range(start, destination):\n cw += distance[i]\n \n # counter clock wise\n ccw = 0\n n = len(distance)\n for i in range(destination, start + n):\n ccw += distance[i%n]\n \n return min(cw, ccw)", "class Solution:\n def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:\n if start == destination:\n return 0\n \n if start > destination:\n start, destination = destination, start\n\n increase = start\n decrease = start\n right = 0\n left = 0\n \n while True:\n index = (increase) % len(distance)\n increase += 1\n if(index == destination):\n break;\n right += distance[index]\n \n while True:\n decrease -= 1\n index = (decrease) % len(distance)\n left += distance[index]\n if(index == destination):\n break;\n \n return min(left, right)\n", "class Solution:\n def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:\n \n s_d = 0\n d_s = 0\n d_sd = []\n \n if (start < destination):\n d_sd = distance[start:destination]\n \n if (start >= destination):\n d_sd = distance[:destination] + distance[start:]\n \n for x in range(len(d_sd)):\n s_d += d_sd[x]\n \n d_s = sum(distance) - s_d\n \n return min(s_d,d_s)\n \n", "class Solution:\n def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:\n \n distance += [0]\n for i in range(len(distance)-2,-1,-1):\n distance[i]+= distance[i+1]\n \n d = abs(distance[start]-distance[destination])\n \n return min(d,distance[0]-d)", "class Solution:\n def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:\n n = len(distance)\n p1 = start%n\n p2 = destination%n\n d1 = 0\n d2 = 0\n \n while p1!= destination and p2!=start:\n d1+=distance[p1]\n d2+=distance[p2]\n p1 = (p1+1)%n\n p2 = (p2+1)%n\n \n if p1==destination:\n return d1\n return d2", "class Solution:\n def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:\n fdistance = 0\n sdistance = 0\n n = len(distance)\n for i in range(start, start+n):\n if i%n == destination:\n break\n fdistance += distance[i % n]\n for i in range(destination, destination+n):\n if i%n == start:\n break\n sdistance += distance[i % n]\n return fdistance if fdistance < sdistance else sdistance\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], [5], [6], [7], [8], [9]. There are 4 groups with largest size. Example 2: Input: n = 2 Output: 2 Explanation: There are 2 groups [1], [2] of size 1. Example 3: Input: n = 15 Output: 6 Example 4: Input: n = 24 Output: 5   Constraints: 1 <= n <= 10^4
["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 currSum = 0\n while curr != 0:\n currSum += curr%10\n curr //= 10\n \n if currSum not in self.trackerForLargest:\n self.trackerForLargest[currSum] = []\n \n self.trackerForLargest[currSum].append(num)\n \n if len(self.trackerForLargest[currSum]) == self.largestSize[0]:\n self.numGroups[0] += 1\n elif len(self.trackerForLargest[currSum]) > self.largestSize[0]:\n self.numGroups[0] = 1\n self.largestSize[0] = len(self.trackerForLargest[currSum])\n \n self.memory[num] = self.numGroups[0]\n \n self.largest[0] = n\n \n return self.memory[n]", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n if n < 10:\n return n\n counter = [0]*37\n sumCount = {0:0}\n i = 1\n while i <= n:\n quotient, reminder = divmod(i, 10)\n sumCount[i] = reminder + sumCount[quotient]\n counter[sumCount[i]] += 1\n i += 1\n return counter.count(max(counter))", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n dic = {}\n for i in range(1, n + 1):\n key = 0\n while i:\n key += i % 10\n i = i // 10\n dic[key] = dic.get(key, 0) + 1\n \n size = list(dic.values())\n return size.count(max(size))", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n def sum_num(n):\n res = n % 10\n while n > 0:\n res += (n := n // 10) % 10\n \n return res\n \n \n groups = defaultdict(int)\n for i in range(1, n + 1):\n groups[sum_num(i)] += 1\n \n high = max(groups.values())\n return sum(1 for v in groups.values() if v == high)", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n \n counts = {}\n m = 0\n \n for i in range(1, n+1):\n t = i\n s = 0\n while t:\n s += t % 10\n t //= 10\n \n counts[s] = counts.setdefault(s, 0) + 1\n if m < counts[s]:\n m = counts[s]\n \n return sum(v == m for v in list(counts.values()))\n \n", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n \n groups = [0]\n \n for i in range(1, n+1, 1):\n sumDigi = self.sumOfDigits(i)\n if (sumDigi == len(groups)):\n groups.append(0)\n groups[sumDigi]+=1 \n #print(groups)\n \n \n \n maxGroup = 0\n maxCount = 0\n for grp in groups:\n if (grp > maxGroup):\n maxGroup = grp\n maxCount = 0\n if (grp == maxGroup):\n maxCount += 1\n #print(\\\"maxGroup=%d, maxCount=%d\\\" % (maxGroup, maxCount))\n \n return maxCount\n \n \n \n def sumOfDigits(self, n:int) -> int:\n sum = 0\n while (n>0):\n sum += n%10\n n //= 10\n return sum", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n def countDigits(m):\n res = 0\n while m > 0:\n res += m % 10\n m //= 10\n return res\n dic = collections.defaultdict(list)\n for i in range(1,n+1):\n count_i = countDigits(i)\n dic[count_i].append(i)\n \n max_count = max(len(dic[k]) for k in dic)\n res = [len(dic[k])==max_count for k in dic]\n return sum(res)\n \n", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n d={};\n for i in range(1,n+1):\n sum=0;\n s=str(i);\n for c in s:\n sum+=int(c);\n if sum in d:\n d[sum].append(i);\n else:\n d[sum]=[i];\n values=list(d.values());\n values.sort(key=len,reverse=True);\n \n count=0;\n length=len(values[0]);\n for v in values:\n if length==len(v):\n count+=1;\n return count;\n", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n arr = [0]*36\n \n for i in range(1,n+1):\n sm = 0\n for j in str(i):\n sm += int(j)\n arr[sm-1]+=1\n \n count = 0\n \n mx = max(arr)\n \n for i in arr:\n if i == mx:\n count+=1\n \n return count\n", "import collections\n\nclass Solution:\n def countLargestGroup(self, n: int) -> int:\n digit_dict = collections.defaultdict(list)\n max_curr = 0\n answer = 0\n \n def get_digit_sum(num):\n return sum(map(int, str(num)))\n \n for i in range(1, n+1):\n digit_sum_curr = get_digit_sum(i)\n digit_dict[digit_sum_curr].append(i)\n \n if len(digit_dict[digit_sum_curr]) > max_curr:\n max_curr = len(digit_dict[digit_sum_curr]) \n answer = 1\n elif len(digit_dict[digit_sum_curr]) == max_curr:\n answer += 1\n \n return answer\n \n", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n dic = defaultdict(list)\n max_ = 0\n for i in range(1,n+1):\n result = 0\n num = i\n while i > 0:\n rem = i % 10\n result += rem\n i = int(i/10)\n\n dic[result].append(num)\n #max_ = max(max_, len(dic[result]))\n \n max_ = 0\n for i in dic:\n leng = len(dic[i])\n max_ = max(max_, leng)\n \n \n ans = [dic[key] for key in dic if len(dic[key])==max_]\n #ans = 0\n #for i in list(dic.values()):\n # if len(i)==max_:\n # ans+=1\n #return ans\n return len(ans)\n \n \n \n \n", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n groups = {}\n max = 0\n for i in range(1,n+1):\n num_str = str(i)\n sum = 0\n for x in num_str:\n sum += int(x)\n if sum in groups:\n groups[sum].append(n)\n else:\n groups[sum] = [n]\n \n max = max if len(groups[sum])< max else len(groups[sum])\n \n num_groups = 0\n for g in groups:\n if len(groups[g]) == max:\n num_groups += 1\n \n return num_groups", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n dp = {0:0}\n counts = [0]*36\n for i in range(1,n+1):\n a, b = divmod(i,10)\n dp[i] = b+dp[a]\n counts[dp[i]-1]+=1\n return counts.count(max(counts))\n \n \n", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n dic = {}\n for i in range(1, n+1):\n summed = sum([int(k) for k in str(i)])\n if(summed in dic):\n dic[summed].append(i)\n else:\n dic[summed] = [i]\n maximumLen = max([len(value) for value in dic.values()])\n count = 0\n for value in dic.values():\n if(len(value) == maximumLen):\n count += 1\n return count", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n sum_to_nums = {}\n for i in range(1,n+1):\n digit_sum = self.getDigitSum(i)\n if digit_sum in sum_to_nums:\n sum_to_nums[digit_sum].append(i)\n else:\n sum_to_nums[digit_sum] = [i]\n print(sum_to_nums)\n values = list(sum_to_nums.values())\n \n num_values = list([len(v) for v in values]) \n largest_group = max(num_values)\n print(num_values)\n #find how many \n summing = [1 if x==largest_group else 0 for x in num_values]\n print(summing)\n return sum(summing)\n \n \n \n def getDigitSum(self, num):\n #print(\\\"getting sum of digits in\\\", num)\n sum_so_far = 0\n while num != 0:\n digit = num%10\n sum_so_far = sum_so_far + digit\n num = int(num/10)\n \n #print(sum_so_far)\n return sum_so_far\n \n \n", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n l = [0]*40\n for i in range(1,n+1):\n s = str(i)\n sum = 0\n for j in range(len(s)):\n sum+=int(s[j])\n # print(sum)\n l[sum]+=1\n mm = max(l)\n c = 0\n for i in range(len(l)):\n if(l[i]==mm):\n c+=1\n return c\n", "class Solution:\n def sumByDigits(self, num: int) -> int:\n result, _n = 0, num\n while _n > 0:\n result += _n % 10\n _n = math.floor(_n / 10)\n return result\n \n def countLargestGroup(self, n: int) -> int: \n counter = collections.defaultdict(int)\n max_value = 0\n result = 0\n for i in range(1, n + 1):\n key = self.sumByDigits(i)\n counter[key] += 1\n if counter[key] > max_value:\n max_value = counter[key]\n result = 1\n elif counter[key] == max_value:\n result += 1\n return result", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n sums = {}\n max_len = 0\n for num in range(1, n + 1):\n digits = str(num)\n sum = 0\n if len(digits) > max_len:\n max_len = len(digits)\n for char in digits:\n sum = sum + int(char)\n \n arr = [sum, num]\n \n arr = [sum, num]\n \n if sum in sums:\n sums[sum].extend([arr])\n else:\n sums[sum] = [arr]\n \n sorted_sums = sorted(sums, reverse=True, key = lambda x: len(sums.get(x)))\n max_len = len(sums.get(sorted_sums[0]))\n count = 0\n for key in sorted_sums:\n items = sums.get(key)\n if len(items) != max_len:\n break\n else:\n count = count + 1\n \n return count", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n from collections import Counter\n al = [list(str(i)) for i in range(1,n+1)]\n al = [sum([int(j) for j in i]) for i in al]\n col = Counter(al)\n #print(col)\n num = Counter(col.values())\n #print(num)\n return num[max(num.keys(),key=lambda x:x)]", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n nums = {}\n for i in range(1, n+1):\n total = sum(list([int(x) for x in str(i)]))\n nums[total] = 1 if total not in nums else 1 + nums[total]\n maxCount = max(nums.values())\n return list(nums.values()).count(maxCount)\n", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n nums = {}\n for i in range(1, n+1):\n total = sum(list([int(x) for x in str(i)]))\n nums[total] = 1 + nums.get(total, 0)\n maxCount = max(nums.values())\n return list(nums.values()).count(maxCount)\n", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n \n if(n == 2):\n return 2\n \n mix = {}\n \n for i in range(1, n + 1):\n if dsum(i) not in mix:\n mix[dsum(i)] = [i]\n else:\n mix[dsum(i)].append(i)\n \n mx = 0\n for i in list(mix.values()):\n if( len(i) > mx ):\n mx = len(i)\n \n resc = 0\n for i in list(mix.values()):\n if( len(i) == mx ):\n resc = resc + 1\n \n return resc\n \ndef dsum(digit):\n cnt = 0\n while(digit > 0):\n temp = digit % 10\n cnt = cnt + temp\n digit = digit // 10\n \n return cnt\n", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n nums = {}\n maxFreq = 1\n maxCount = 0\n for i in range(1, n + 1):\n total = sum(list([int(x) for x in str(i)]))\n nums[total] = 1 + nums.get(total, 0)\n if nums[total] > maxFreq:\n maxFreq = nums[total]\n maxCount = 1\n elif nums[total] == maxFreq:\n maxCount += 1\n return maxCount\n", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n dp = {0:0}\n counter = [0]*37 # 9999 digitsum is 36\n for num in range(1, n+1):\n div, mod = divmod(num, 10)\n dp[num] = dp[div]+mod\n counter[dp[num]] += 1\n return counter.count(max(counter))", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n print(n)\n str_nums = [str(i) for i in range(1, n + 1)]\n print(str_nums)\n digits = [ [int(i) for i in s] for s in str_nums]\n print(digits)\n sums = [sum(i) for i in digits]\n print(sums)\n group_sizes = {}\n for s in sums:\n group_sizes[s] = group_sizes.get(s, 0) + 1\n max_size = max(group_sizes.values())\n return len([i for i in group_sizes if group_sizes[i] == max_size])\n", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n nums = collections.defaultdict(int)\n maxFreq = 1\n maxCount = 0\n for i in range(1, n + 1):\n total = sum(list([int(x) for x in str(i)]))\n nums[total] = 1 + nums.get(total, 0)\n if nums[total] > maxFreq:\n maxFreq = nums[total]\n maxCount = 1\n elif nums[total] == maxFreq:\n maxCount += 1\n return maxCount\n", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n if n<10:\n return n\n arr=[[1],[2],[3],[4],[5],[6],[7],[8],[9]]\n for i in range(10,n+1):\n k=list(map(int,list(str(i))))\n k=sum(k)\n print(k)\n if k<=len(arr):\n arr[k-1].append(i)\n else:\n arr.append([k])\n arr=sorted(arr, key=len,reverse=True)\n print(arr)\n l=len(arr[0])\n i=0\n while i<len(arr) and len(arr[i])==l:\n i+=1\n return i", "def sum_of_digits(num):\n total = 0\n while num > 0:\n total += num % 10\n num //= 10\n return total\n\nclass Solution:\n def countLargestGroup(self, n: int) -> int:\n groups = {}\n for i in range(1, n + 1):\n s = sum_of_digits(i)\n groups[s] = groups.get(s, []) + [i]\n max_len = 0\n for lst in groups.values():\n max_len = max(max_len, len(lst))\n largest = 0\n for lst in groups.values():\n if len(lst) == max_len: largest += 1\n return largest", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n numsum = lambda x: sum(map(int, list(str(x))))\n numdict = {}\n maxcount = 0\n \n for i in range(1, n+1):\n x = numsum(i)\n numdict[x] = numdict.get(x, 0) + 1\n maxcount = max(maxcount, numdict[x])\n \n count = 0\n for i in numdict:\n if numdict[i] == maxcount:\n count += 1\n \n return count\n", "import collections\n\nclass Solution:\n def countLargestGroup(self, n: int) -> int:\n digit_dict = collections.defaultdict(list)\n max_curr = 0\n answer = 0\n \n def get_digit_sum(num):\n return sum(int(i) for i in [char for char in str(num)])\n \n for i in range(1, n+1):\n digit_sum_curr = get_digit_sum(i)\n digit_dict[digit_sum_curr].append(i)\n \n if len(digit_dict[digit_sum_curr]) > max_curr:\n max_curr = len(digit_dict[digit_sum_curr]) \n answer = 1\n elif len(digit_dict[digit_sum_curr]) == max_curr:\n answer += 1\n \n return answer\n \n", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n q=[]\n for i in range(n-10+1):\n q.append(i + 10)\n \n l=[]\n \n for j in range(len(q)):\n p=0\n for k in range(len(str(q[j]))):\n #print(str(q[j])[k])\n p=p+int(str(q[j])[k])\n l.append(p)\n #print(l)\n q=Counter(l)\n x=0\n \n print(q)\n \n for j,i in list(q.items()):\n if j <10:\n \n q[j]=q[j]+1\n \n print(q) \n for j,i in list(q.items()):\n \n if i == max(q.values()):\n x= x+1\n if n < 10:\n return n\n #print(n)\n else:\n return (x)\n #print(x)\n \n \n \n \n \n \n \n \n \n", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n def sumDigits(n):\n if n < 10: return n\n sum = 0\n while n:\n sum += n % 10\n n //= 10\n return sum\n cnt = [0 for i in range(37)] \n max_size, max_cnt = 0, 0\n while n:\n cnt[sumDigits(n)] += 1\n if max_size < cnt[sumDigits(n)]:\n max_size = cnt[sumDigits(n)]\n max_cnt = 1\n else:\n max_cnt += max_size == cnt[sumDigits(n)]\n n -= 1\n return max_cnt ", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n d, c = {}, 0\n for i in range(1, n+1):\n if i % 10 == 0:\n c = sum(map(int, str(i)))\n d[c] = d.get(c, 0) + 1\n else:\n c += 1\n d[c] = d.get(c, 0) + 1\n res, m = 0, 0\n for v in list(d.values()):\n if v > m:\n res = 1\n m = v\n elif v == m:\n res += 1\n return res\n \n", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n d = {}\n for num in range(1, n+1):\n sumn = 0\n for char in str(num):\n sumn += int(char)\n d[sumn] = d[sumn] + [num] if sumn in d else [num]\n t = {}\n for arr in d.values():\n t[len(arr)] = t[len(arr)] + 1 if len(arr) in t else 1\n tt = sorted(t, reverse=True)\n return t[next(iter(tt))]", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n map = {}\n mx = 0\n for i in range(1, n+1):\n tempSum = 0\n for j in str(i):\n tempSum += int(j)\n map[tempSum] = map.get(tempSum, []) + [i]\n mx = max(mx, len(map.get(tempSum)))\n res = 0\n for key in map.keys():\n if len(map.get(key)) == mx:\n res += 1\n return res", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n dic = {}\n for i in range(1,n+1):\n s = sum([int(i) for i in str(i)])\n if s in dic:\n dic[s].append(i)\n else:\n dic[s] = [i]\n \n max_L = 0\n cnt = 0\n for j in dic:\n if len(dic[j]) == max_L:\n cnt += 1\n elif len(dic[j]) > max_L:\n cnt = 1\n max_L = len(dic[j])\n \n return cnt\n", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n num_dict = {}\n for i in range(1, n+1):\n arr = [int(a) for a in str(i)]\n summa = sum(arr)\n if summa not in num_dict.keys():\n num_dict[summa] = [i]\n else:\n num_dict[summa] = num_dict[summa] + [i]\n large = 0\n for j in num_dict.values():\n if len(j)>large:\n large = len(j)\n count = 0\n for j in num_dict.values():\n if len(j) == large:\n count += 1\n return count", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n d = {}\n for i in range(1, n+1):\n s = sum([int(x) for x in str(i)])\n d[s] = d.get(s, []) + [i]\n nums = [len(d[x]) for x in d]\n d = collections.Counter(nums)\n return d[max(nums)]\n", "\nclass Solution:\n def countLargestGroup(self, n: int) -> int:\n dp = {0: 0}\n counts = [0] * (4 * 9)\n for i in range(1, n + 1):\n quotient, reminder = divmod(i, 10)\n dp[i] = reminder + dp[quotient]\n counts[dp[i] - 1] += 1\n return counts.count(max(counts))", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n groups = [0]*37\n for i in range(1,n+1):\n t,i = divmod(i,1000)\n h,i = divmod(i,100)\n ten,i = divmod(i,10)\n groups[t + h + ten + i] += 1\n max = 0\n count = 0\n for g in groups:\n if g > max:\n max = g\n count = 1\n elif g == max:\n count += 1 \n return count\n \n \n", "class Solution:\n def countLargestGroup(self, n: int) -> int:\n memo = {1: 1}\n \n for i in range(2, n + 1):\n if not i % 10:\n memo[i] = memo[i // 10]\n else:\n memo[i] = memo[i - 1] + 1\n D = defaultdict(int)\n for k, v in memo.items():\n D[v] += 1\n res = 0\n \n for k in D.keys():\n if D[k] == max(D.values()):\n res += 1\n return res"]
{"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 extra space complexity?
["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]\n if dif!=1:\n return array[i]+1\n except:\n return array[-1]+1\n", "class Solution:\n def missingNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n nums.append(nums[0])\n for i in range(len(nums)):\n v = nums[i]\n while v != nums[v]:\n nums[v], v = v, nums[v]\n for i, num in enumerate(nums):\n if i != num:\n return i\n return None", "class Solution:\n def missingNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n n = len(nums)\n s = n*(n+1)//2\n return s - sum(nums)\n", "class Solution:\n def missingNumber(self, nums):\n expected_sum = len(nums)*(len(nums)+1)//2\n actual_sum = sum(nums)\n return expected_sum - actual_sum", "class Solution:\n def missingNumber(self, nums):\n res = len(nums)\n for i in range(len(nums)):\n res = res ^ i\n res = res ^ nums[i]\n return res\n", "class Solution:\n def missingNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n res = len(nums)\n # \u5f02\u6216\u8868\u793a\u76f8\u540c\u6570\u4e3a0\uff0c\u7d22\u5f15\u548c\u6570\u7ec4\u7684\u6570\u5e94\u8be5\u4e24\u4e24\u76f8\u5bf9\n for i,x in enumerate(nums):\n res ^=i\n res ^=x\n return res", "class Solution:\n def missingNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n n = len(nums)\n return int((1+n)*n/2-sum(nums))", "class Solution:\n def missingNumber(self, nums):\n \n return (sum(range(len(nums)+1)) - sum(nums))\n \"\"\" \n :type nums: List[int]\n :rtype: int\n \"\"\"", "class Solution:\n def missingNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n \n length = len(nums)+1\n total = sum(i for i in range(length))\n \n nums_total = sum(nums)\n \n return total-nums_total\n \n \n", "class Solution:\n def missingNumber(self, array):\n \"\"\" Time complexity: O(n). Space complexity: O(1).\n \"\"\"\n n = len(array)\n for i, num in enumerate(array):\n n = n ^ i ^ num\n return n", "class Solution:\n def missingNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n s = set()\n for num in nums:\n s.add(num)\n for i in range(len(nums) + 1):\n if i in s:\n continue\n else:\n return i", "class Solution:\n def missingNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n import functools\n res1 = functools.reduce(lambda x,y:x^y, [i for i in range(len(nums)+1)])\n res2 = functools.reduce(lambda x,y:x^y, nums )\n return res1^res2\n", "class Solution:\n def missingNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n total = 0\n for num in range(len(nums)+1):\n total += num\n return total - sum(nums)", "class Solution:\n def missingNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n x = [0]*(len(nums)+1)\n for e in nums:\n x[e] = 1\n return x.index(0)", "class Solution:\n def missingNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n srted = sorted(nums)\n \n for i in range(0,len(srted)):\n if srted[i] != i:\n return i\n \n return i+1\n"]
{"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: 10 Example 4: Input: [3,6,2,3] Output: 8   Note: 3 <= A.length <= 10000 1 <= A[i] <= 10^6
["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[int]) -> int:\n sortedA = sorted(A)\n \n for i in range(len(sortedA)-3, -1 ,-1):\n if sortedA[i+2]<(sortedA[i]+sortedA[i+1]):\n return sum(sortedA[i:i+3])\n return 0\n", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n A.sort()\n return ([0] + [a + b + c for a, b, c in zip(A, A[1:], A[2:]) if c < a + b])[-1]\n \n", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n A.sort()\n return ([0] + [a + b + c for a, b, c in zip(A, A[1:], A[2:]) if c < a + b])[-1]", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n \n A.sort()\n \n for i in range(len(A)-1, 1, -1):\n len1 = A[i]\n len2 = A[i-1]\n len3 = A[i-2]\n if self.check_triangle(len1, len2, len3):\n return len1 + len2 + len3\n \n return 0\n #print(A)\n \n def check_triangle(self, len1, len2, len3):\n if len1 + len2 <= len3 or len2 + len3 <= len1 or len1 + len3 <= len2:\n return False\n return True\n \n", "class Solution:\n def largestPerimeter(self, A):\n A.sort(reverse=True)\n\n for i in range(len(A)-2):\n if A[i] < A[i+1]+A[i+2]:\n return A[i]+A[i+1]+A[i+2]\n\n return 0", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n A.sort()\n return ([0] + [a + b + c for a, b, c in zip(A, A[1:], A[2:]) if c < a + b])[-1]\n", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n A.sort(reverse=True)\n i=0\n while i< len(A)-2:\n if A[i]<A[i+1]+A[i+2]:\n return(A[i]+A[i+1]+A[i+2])\n else:\n i=i+1\n return (0)\n", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n p=0\n A.sort()\n for i in range(len(A)-2):\n if A[i]+A[i+1]>A[i+2]:\n p=A[i]+A[i+1]+A[i+2]\n return p", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n A=sorted(A)\n perimeter=0\n for i in range(len(A)-2):\n s1,s2,s3=A[i],A[i+1],A[i+2]\n p=s1+s2+s3\n if s1+s2>s3 and s2+s3>s1 and s1+s3>s2:\n perimeter=max(perimeter,p)\n return perimeter", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n # hold result.\n result = 0\n # sort the given lengths.\n A = sorted(A)\n # go through lengths, check for valid triangle.\n for i in range(len(A) - 2):\n # store triangle sides.\n a, b, c = A[i], A[i + 1], A[i + 2]\n # check if valid.\n if (a + b) > c and (a + c) > b and (b + c) > a:\n result = max(result, a + b + c)\n # return result.\n return result", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n A.sort()\n \n for i in range(len(A) - 1, 1, -1):\n a = A[i]\n b = A[i - 1]\n c = A[i - 2]\n if a < b + c:\n return a + b + c\n \n return 0", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n A.sort(reverse=True)\n n = len(A)\n for i in range(n-2):\n if A[i] < A[i+1] + A[i+2]:\n return A[i] + A[i+1] + A[i+2]\n return 0\n", "import numpy as np\nclass Solution:\n\n# def valid_area(self, A):\n# s = np.sum([a for a in A])/2\n# area = np.sqrt(s*(s-A[0])*(s-A[1])*(s-A[2]))\n \n# return False if np.isnan(area) or area == 0 else True\n \n \n def largestPerimeter(self, A: List[int]) -> int:\n \n valid_area = lambda x,y,z: True if x < y + z else False \n A = sorted(A, reverse=True)\n for a in range(2,len(A)):\n if valid_area(A[a-2], A[a-1], A[a]): \n return np.sum([A[a-2], A[a-1], A[a]])\n return 0\n \n# # greedy approach\n# comb = set([i for i in combinations(A,3)])\n# comb_sorted = sorted(comb, key=lambda x: np.sum(x), reverse=True)\n# for c in comb_sorted:\n# if self.valid_area(c):\n# return np.sum(c)\n \n# return 0\n", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n A.sort()\n ans = 0\n for i in range(1, len(A)-1):\n if A[i-1] + A[i] <= A[i+1]:\n continue\n else:\n p = sum(A[i-1:i+2])\n ans = max(ans, p)\n return ans\n \n", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n if len(A) < 3:\n return 0\n A.sort()\n counter = 3\n perimeter = 0\n while counter <= len(A):\n \n a = A[counter -3]\n b = A[counter - 2]\n c = A[counter - 1]\n \n if a +b <= c:\n counter += 1\n continue\n elif b +c <= a:\n counter += 1\n continue\n elif c + a <= b:\n counter += 1\n continue\n perimeter = a+b+c\n if a+b+c > perimeter:\n perimeter= a+b+c\n \n counter += 1\n return perimeter", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n A.sort()\n Flag = 0\n \n for i in range(len(A)-1,1,-1):\n if A[i] < A[i-1] + A[i-2]:\n Flag = 1\n return A[i-1] + A[i-2] + A[i]\n \n if Flag == 0:\n return Flag\n \n \n \n", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n A.sort()\n first=0\n second=1\n mx=0\n for third in range(2,len(A)):\n if (A[first]+A[second])>A[third]:\n mx=max(mx,A[first]+A[second]+A[third])\n first+=1\n second+=1\n \n return(mx)\n", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n A.sort()\n a = len(A)-1\n while a >= 2 :\n if A[a] < A[a-1] + A[a-2] :\n return (A[a] + A[a-1] + A[a-2])\n else:\n a-= 1\n return 0", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n A.sort(reverse=True)\n n = len(A)\n for i in range(n-2):\n for j in range(i+1,n-1):\n if A[j] <= A[i]//2: break\n for k in range(j+1,n):\n if A[i]<A[j]+A[k]: return A[i]+A[j]+A[k]\n return 0", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n A.sort()\n for i in range(len(A) - 3, -1, -1):\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[int]) -> int:\n A = sorted(A)\n i = len(A)-1\n while i>=2:\n if A[i-2]+A[i-1]>A[i]: return A[i-2]+A[i-1]+A[i]\n i -= 1\n return 0", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n A.sort(reverse=True)\n for a, b, c in zip(A, A[1:], A[2:]):\n if a< b+c:\n return(a+b+c)\n else:\n continue\n return (0)\n", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n A.sort(reverse = True) # sort list from largest to smallest\n for i in range(len(A) - 2):\n if A[i] < A[i+1] + A[i+2]:\n return A[i] + A[i+1] + A[i+2]\n return 0\n \n", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n A.sort(reverse=True)\n m=0\n for i in range(len(A)-2):\n if (A[i]+A[i+1]>A[i+2]) and (A[i+2]+A[i+1]>A[i]) and (A[i+2]+A[i]>A[i+1]):\n x=A[i:i+3]\n if sum(x)>m:\n m=sum(x)\n return m\n", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n def check(x,y,z):\n if(x+y>z and y+z>x and x+z>y):\n return True\n else:\n False\n A=sorted(A)\n A=A[::-1]\n x=A\n print(x)\n lar=0\n for i in range(len(x)-2):\n if(check(x[i],x[i+1],x[i+2])):\n lar=max(lar,(x[i]+x[i+1]+x[i+2]))\n return lar \n \n \n", "class Solution:\n def _isTriangle(self, queue):\n return queue[0] < queue[1] + queue[2]\n \n def largestPerimeter(self, A: List[int]) -> int:\n A.sort(key = lambda x: -x)\n \n nums = []\n \n for num in A:\n nums.append(num)\n \n if len(nums) == 3:\n if self._isTriangle(nums):\n return sum(nums)\n nums.pop(0)\n \n return 0", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n A.sort()\n for i in range(len(A) - 3, -1, -1):\n if A[i] + A[i + 1] > A[i + 2]:\n return A[i] + A[i + 1] + A[i + 2]\n return 0", "#\nclass Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n A.sort()\n for i in range(len(A) - 3, -1, -1):\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[int]) -> int:\n A.sort(reverse=True)\n for i in range(len(A)-2):\n if A[i] < A[i+1] + A[i+2]:\n return A[i]+A[i+1]+A[i+2]\n return 0\n", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n #\u8981\u6ee1\u8db3\u4e24\u4e2a\u6761\u4ef6\uff0c\u4e00\u662f\u4e09\u4e2a\u76f8\u52a0\u6700\u5927\uff0c\u4e8c\u662f\u4e24\u8fb9\u548c\u5927\u4e8e\u7b2c\u4e09\u8fb9\uff0c\u5148\u8003\u8651\u6ee1\u8db3\u6761\u4ef6\u4e00\uff0c\u770b\u5728\u6761\u4ef6\u4e00\u4e0b\u6761\u4ef6\u4e8c\u662f\u5426\u6ee1\u8db3\n A = sorted(A,reverse=True)\n #A.sort(reverse = True)\n for i in range(len(A)-2):\n if A[i] < A[i+1] + A[i+2]:\n return A[i] + A[i+1] + A[i+2]\n return 0\n \n", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n A.sort(reverse=True)\n p = 0\n for i in range(len(A) - 2):\n if A[i] < A[i + 1] + A[i + 2]:\n p = A[i] + A[i + 1] + A[i + 2]\n break\n return p\n", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n A.sort()\n maxPe = 0\n for i in range(len(A)-2):\n if A[i]+A[i+1] > A[i+2]:\n maxPe = A[i]+A[i+1]+A[i+2]\n return maxPe", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n A.sort(reverse=True)\n n = len(A)\n for i in range(n-2):\n if A[i] < A[i+1] + A[i+2]:\n return A[i] + A[i+1] + A[i+2]\n return 0\n", "class Solution:\n #3 max, check if they form a triangle\n # 9 5 4 3 2 1\n def largestPerimeter(self, A: List[int]) -> int:\n n = len(A)\n \n A.sort(reverse = True)\n a = 0\n while (a < n):\n b = a+1\n c = a+2\n while (b < n and c < n):\n if (A[b]+A[c]>A[a]):\n return A[a]+A[b]+A[c]\n else:\n b += 1\n c += 1\n a+=1\n return 0\n", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n if (len(A) < 3):\n return 0;\n \n maxer = 0;\n pointer1 = len(A) - 3;\n pointer2 = len(A) - 2;\n pointer3 = len(A) - 1;\n A.sort();\n \n if len(A) == 3:\n if (A[0] + A[1] > A[2]):\n return sum(A);\n else:\n return 0;\n \n \n \n while (pointer3 >= 2):\n if A[pointer1] + A[pointer2] > A[pointer3]:\n return A[pointer1] + A[pointer3] + A[pointer2];\n elif pointer1 == 0:\n pointer3 -= 1;\n pointer2 = pointer3 - 1;\n pointer1 = pointer2 - 1;\n else:\n pointer1 -= 1;\n pointer2 -= 1;\n \n \n return maxer;\n \n \n \n \n \n \n \n \n \n \n \n", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n A.sort(reverse=True)\n p = 0\n for i in range(len(A) - 2):\n if A[i] < sum(A[i+1:i+3]):\n p = sum(A[i:i+3])\n break\n return p\n", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n A.sort(reverse = True)\n for i in range(len(A)-2):\n if A[i+1] + A[i+2] > A[i]:\n return A[i+1] + A[i+2] + A[i]\n return 0", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n A = sorted(A)\n while(True):\n if (A[-1] + A[-2] > A[-3]) and (A[-1] + A[-3] > A[-2]) and (A[-3] + A[-2] > A[-1]):\n return (A[-1] + A[-2] + A[-3])\n A.remove(A[-1])\n if len(A) == 2:\n return 0", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n A.sort(reverse=True)\n\n for i in range(len(A) - 2):\n a, b, c = A[i], A[i + 1], A[i + 2]\n if a < b + c:\n return a + b + c\n\n return 0", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n \n def area(a,b,c):\n s=(a+b+c)/2\n \n val=(s*(s-a)*(s-b)*(s-c))**(1/2)\n #print(type(val))\n if isinstance(val,complex):\n return 0\n return val\n \n A.sort()\n maxi=0\n \n for i in range(len(A)-2):\n val=area(A[i],A[i+1],A[i+2])\n \n if val!=0:\n p=(A[i]+A[i+1]+A[i+2])\n #print(p,val)\n if p>maxi:\n maxi=p\n \n return maxi\n \n \n \n \n \n \n", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n \n def formT(a,b,c):\n if not a+b>c:\n return False\n if not b+c>a:\n return False\n if not a+c>b:\n return False\n return True\n \n sides=sorted(A)\n \n for i in range(len(sides)-3,-1,-1):\n if formT(sides[i],sides[i+1],sides[i+2]):\n return sides[i]+sides[i+1]+sides[i+2]\n \n return 0", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n if len(A)<3:\n return 0\n \n A.sort(reverse=True)\n \n while len(A)>2:\n max_num = A.pop(0)\n if max_num >= A[0] + A[1]:\n continue\n else:\n return max_num+A[0]+A[1]\n return 0\n", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n res = 0\n A.sort()\n for i in range(len(A)):\n for j in range(i+1, len(A)):\n source = A[i]\n target = A[j]\n lower = abs(target - source)\n upper = source + target\n if (upper*2 < res):\n continue\n for t in range(j+1, len(A)):\n if lower < A[t] < upper:\n res = max(source + target + A[t], res)\n break\n if res != 0:\n break\n return res\n", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n A.sort()\n res = 0\n for i in range(len(A)-2):\n test = A[i:i+3]\n if test[0] + test[1] > test[2] and test[2] - test[1] < test[0] and sum(test) > res:\n res =sum(test)\n return res\n \n", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n A.sort(reverse=True)\n for i in range(len(A)-2):\n if A[i:i+3][1] + A[i:i+3][2] > A[i:i+3][0]:\n return sum(A[i:i+3])\n return 0", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n A.sort(reverse=True)\n while len(A) >= 3:\n if A[1] + A[2] > A[0]:\n return A[1] + A[2] + A[0]\n A.pop(0)\n return 0", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n A.sort(reverse=True)\n for i in range(len(A)-2):\n a,b,c = A[i],A[i+1],A[i+2]\n c1 = a+b>c\n c2 = b+c>a\n c3 = c+a>b\n if c1 and c2 and c3:\n return a+b+c\n \n return 0", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n A.sort(reverse = True)\n for i in range(len(A) - 2):\n if A[i] < A[i+1] + A[i+2]:\n return A[i] + A[i+1] + A[i+2]\n return 0\n \n", "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n A.sort(reverse=True)\n n = len(A)\n for i in range(n-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[int]) -> int:\n # A.sort()\n # for i in range(len(A) - 3, -1, -1):\n # if A[i] + A[i + 1] > A[i + 2]:\n # return A[i] + A[i + 1] + A[i + 2]\n # return 0\n \n A.sort(reverse = True)\n for i in range(len(A) - 2):\n if A[i] < A[i + 1] + A[i + 2]:\n return A[i] + A[i + 1] + A[i + 2]\n return 0"]
{"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 :rtype: bool\n \"\"\"\n if num == 0:\n return False\n return not num & (num - 1) and len(bin(num)) % 2 == 1", "class Solution:\n def isPowerOfFour(self, num):\n \"\"\"\n :type num: int\n :rtype: bool\n \"\"\"\n if num < 1:\n return False\n return (num - 1) & num == 0 and num & 0x55555555 != 0", "class Solution:\n def isPowerOfFour(self, num):\n \"\"\"\n :type num: int\n :rtype: bool\n \"\"\"\n \n if num <= 0:\n return False\n \n import math\n i = math.log10(num) / math.log10(4)\n return i.is_integer()", "class Solution:\n def isPowerOfFour(self, num):\n \"\"\"\n :type num: int\n :rtype: bool\n \"\"\"\n return num != 0 and not num & (num - 1) and len(bin(num)) % 2 == 1", "class Solution:\n def isPowerOfFour(self, num):\n \"\"\"\n :type num: int\n :rtype: bool\n \"\"\"\n while num <= 0:\n return False\n while num % 4 == 0:\n num //= 4\n return num == 1\n", "class Solution:\n def isPowerOfFour(self, num):\n return bin(num).count('1')==1 and bin(num).count('0')%2==1 and num>0", "class Solution:\n def isPowerOfFour(self, num):\n \"\"\"\n :type num: int\n :rtype: bool\n \"\"\"\n if num < 1 : return False\n while num % 4 == 0 :\n num //= 4\n return num == 1\n", "class Solution:\n def isPowerOfFour(self, num):\n \"\"\"\n :type num: int\n :rtype: bool\n \"\"\"\n if num == 1:\n return True\n \n target = 1\n while target < num:\n target *= 4\n if target == num:\n return True\n \n return False", "class Solution:\n def isPowerOfFour(self, num):\n \"\"\"\n :type num: int\n :rtype: bool\n \"\"\"\n if num <= 0:\n return False\n sqrt_root = math.sqrt(num)\n if math.floor(sqrt_root) == sqrt_root:\n return int(sqrt_root) & int(sqrt_root - 1) == 0\n return False\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: true Example 2: Input: [6,5,4,4] Output: true Example 3: Input: [1,3,2] Output: false Example 4: Input: [1,2,4,5] Output: true Example 5: Input: [1,1,1] Output: true   Note: 1 <= A.length <= 50000 -100000 <= A[i] <= 100000
["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 increasing = False\n for i in range(len(A)-1):\n if increasing:\n if A[i] > A[i+1]:\n return False\n else:\n if A[i] < A[i+1]:\n return False\n return True", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n n = len(A)\n if self.checkMonInc(A, n) or self.checkMonDec(A, n):\n return True\n return False\n \n def checkMonInc(self, A, n):\n for i in range(1, n):\n if A[i] >= A[i-1]:\n continue\n else:\n return False\n return True\n\n def checkMonDec(self, A, n):\n for i in range(1, n):\n if A[i] <= A[i-1]:\n continue\n else:\n return False\n return True\n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n is_asc = True\n is_desc = True\n \n for i in range(len(A) - 1):\n if A[i] > A[i+1]:\n is_asc = False\n if A[i] < A[i+1]:\n is_desc = False\n \n return is_asc or is_desc", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n if len(A) == 1:\n return True\n \n direction = 0\n \n for i in range(len(A)-1) : \n j = i+1\n tmp = A[i] - A[j]\n if tmp == 0:\n continue\n elif tmp > 0:\n if direction == 0 or direction == -1:\n #if direction < 1:\n direction = -1\n else:\n return False\n else:\n if direction == 0 or direction == 1:\n #if direction > -1 :\n direction = 1\n else:\n return False\n \n #if A[i] == A[j]:\n # continue\n #elif A[i] > A[j]:\n # if direction < 0:\n # continue\n # elif direction == 0:\n # direction = -1\n # else:\n # return False\n #else:# A[i] < A[j]\n # if direction > 0:\n # continue\n # elif direction == 0:\n # direction = 1\n # else:\n # return False\n \n return True\n \n \n \n \n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n increasing = all(A[i] <= A[i+1] for i in range(len(A)-1))\n decreasing = all(A[i] >= A[i+1] for i in range(len(A)-1))\n return increasing or decreasing", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n increasing = decreasing = True\n\n for i, value in enumerate(A):\n if i:\n if value > A[i - 1]:\n increasing = False\n if value < A[i - 1]:\n decreasing = False\n if not increasing and not decreasing:\n return False\n return True", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n monotonic = 2\n lenA = len(A)\n for i in range(lenA-1):\n if A[i] > A[i+1]:\n monotonic -= 1\n break\n for i in range(lenA-1):\n if A[i] < A[i+1]:\n monotonic -= 1\n break\n return monotonic", "class Solution(object):\n def isMonotonic(self, A):\n increasing = decreasing = True\n\n for i in range(len(A) - 1):\n if A[i] > A[i+1]:\n increasing = False\n if A[i] < A[i+1]:\n decreasing = False\n\n return increasing or decreasing\n \n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n prev = 0\n cur = 1\n while cur < len(A):\n if A[prev] <= A[cur]:\n prev += 1\n cur += 1\n else:\n break\n if cur >= len(A):\n return True\n prev = 0\n cur = 1\n while cur < len(A):\n if A[prev] >= A[cur]:\n prev += 1\n cur += 1\n else:\n break\n if cur >= len(A):\n return True\n return False\n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n # two pointers to traverse array checking increasing and decreasing at the same time.\n i, j = 0, 0\n # two variables to keep track of values increasing and decreasing.\n tempi, tempj = -100000, 100000\n # flag to check if monotonic.\n flagi, flagj = True, True\n # go through array, check if monotonic.\n while i < len(A) and j < len(A):\n if tempi <= A[i]:\n tempi = A[i]\n else:\n flagi = False\n if tempj >= A[j]:\n tempj = A[j]\n else:\n flagj = False \n i += 1\n j += 1\n # return True by default.\n return flagi or flagj", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n if A == sorted(A) or A == sorted(A, reverse=True) :\n return 1\n return 0", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n flow = None\n for i in range(len(A)-1):\n if A[i] > A[i+1]:\n if not flow:\n flow = 'd'\n \n elif flow != 'd':\n return False\n continue\n if A[i] < A[i+1]:\n if not flow:\n flow = 'i'\n elif flow != 'i':\n return False\n continue\n return True\n \n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n if sorted(A)==A or sorted(A,reverse=True)==A:\n return True\n else:\n return False\n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n n = len(A)\n return all([A[i] >= A[i - 1] for i in range(1, n)]) or all([A[i] <= A[i - 1] for i in range(1, n)])", "class Solution:\n def isMonotonic(self, a: List[int]) -> bool:\n n = len(a)\n std = 0\n for i in range(0, n-1):\n\n sgn = a[i] - a[i+1]\n\n if sgn == 0:\n continue\n \n sgn = abs(sgn)/sgn\n if std == 0:\n std = sgn\n if sgn != std and sgn != 0:\n return False\n\n return True", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n res=''\n for x in range(1, len(A)):\n if A[x]>A[x-1]:\n res='pos'\n elif A[x]==A[x-1]:\n continue\n else:\n res='neg'\n if (res!='pos' and res!='neg'):\n return True\n for x in range(1, len(A)):\n if res=='neg':\n if A[x] > A[x-1]:\n return False\n else:\n continue\n else:\n if A[x] < A[x-1]:\n return False\n else:\n continue\n return True\n \n \n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n if len(A) == 1:\n return True\n i = 0\n while (i < len(A) - 1 and A[i] == A[i + 1]):\n i += 1\n if (i >= len(A) - 1):\n return True\n if A[i] > A[i + 1]:\n while i < len(A) - 1:\n if A[i] < A[i + 1]:\n return False\n i += 1\n return True\n else:\n while i < len(A) - 1:\n if A[i] > A[i + 1]:\n return False\n i += 1\n return True\n# either we are at a spot where A[i] != A[i + 1]\n", "class Solution:\n def isMonotonic(self, arr: List[int]) -> bool:\n length = len(arr)\n dec = inc = 1\n for i in range(length-1):\n if arr[i] < arr[i+1]:\n dec += 1\n elif arr[i] > arr[i+1]:\n inc += 1\n else:\n dec += 1\n inc += 1\n if dec == length:\n return True\n elif inc == length:\n return True\n else:\n return False", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n diff_lst = [A[i + 1] - A[i] for i in range(len(A) - 1)]\n positive = all(i >= 0 for i in diff_lst)\n negative = all(i <= 0 for i in diff_lst)\n return positive or negative", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n \n dec = False\n \n for i in range(len(A) - 1):\n if A[i] < A[i+1]:\n dec = True\n for i in range(len(A) - 1):\n if A[i] > A[i+1] and dec:\n return False\n return True", "class Solution:\n def isMonotonic(self, A):\n is_monotonic_asc = True;\n is_monotonic_desc = True;\n \n for i in range(1, len(A)):\n if A[i] < A[i - 1]:\n is_monotonic_asc = False;\n if A[i] > A[i - 1]:\n is_monotonic_desc = False;\n \n return is_monotonic_asc or is_monotonic_desc;", "class Solution:\n def isMonotonic(self, a: List[int]) -> bool:\n isIncreasing = isDecreasing = True\n for i in range(len(a) - 1):\n if(a[i] < a[i+1]):\n isIncreasing = False\n if(a[i] > a[i+1]):\n isDecreasing = False\n return isIncreasing or isDecreasing\n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n \n inc, dec = True, True\n \n for i in range(len(A) - 1):\n if A[i+1] > A[i]:\n dec = False\n if A[i+1] < A[i]:\n inc = False\n return inc or dec\n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n is_monotonic_asc = True\n is_monotonic_desc = True\n \n for i in range(1, len(A)):\n if A[i] < A[i - 1]:\n is_monotonic_asc = False\n if A[i] > A[i - 1]:\n is_monotonic_desc = False\n \n return is_monotonic_asc or is_monotonic_desc", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n \n\n# inc = all([A[i]<=A[i+1] for i in range(0,len(A)-1)])\n# dec = all([A[i]>=A[i+1] for i in range(0,len(A)-1)])\n \n# return inc or dec\n\n# inc = True\n# dec = True\n \n# for i in range(0,len(A)-1):\n# if A[i]>A[i+1]:\n# inc=False\n# if A[i]<A[i+1]:\n# dec=False\n \n# if not inc and not dec:\n# return False\n \n# return inc or dec\n \n# if A[-1] > A[0]: \n# return all(A[i] <= A[i + 1] for i in range(0, len(A) - 1))\n\n# else:\n# return all(A[i] >= A[i + 1] for i in range(0, len(A) - 1))\n\n if A[-1] > A[0]: \n inc=True\n for i in range(0,len(A)-1):\n if A[i]>A[i+1]:\n return False\n else:\n return True\n\n else:\n dec=True\n for i in range(0,len(A)-1):\n if A[i]<A[i+1]:\n return False\n else:\n return True", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n isAscending = True\n isDescending = True\n \n for i in range(len(A) - 1):\n if A[i] > A[i+1]:\n isAscending = False\n if A[i] < A[i+1]:\n isDescending = False\n return isAscending or isDescending", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n asc = True\n dsc = True\n for i in range(1,len(A)):\n if A[i-1]<A[i]:\n dsc=False\n elif A[i-1]>A[i]:\n asc=False\n return asc or dsc\n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n is_increasing = is_decreasing = True\n for i in range(1, len(A)):\n if A[i] < A[i - 1]:\n is_decreasing = False\n if A[i] > A[i - 1]:\n is_increasing = False\n return is_decreasing or is_increasing", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n increasing = decreasing = True\n\n for i in range(len(A) - 1):\n if A[i] > A[i+1]:\n increasing = False\n if A[i] < A[i+1]:\n decreasing = False\n\n return increasing or decreasing", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n is_asc = True\n is_desc = True\n \n for i in range(1, len(A)):\n if A[i] > A[i-1]:\n is_desc = False\n if A[i] < A[i-1]:\n is_asc = False\n \n return is_asc or is_desc", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n # Valid monotic number of the following characteristic\n # Increasing \n # Decreasing\n # None increasing or decreasing\n\n # Linear time complexity is the best thing to do.\n\n isIncreasing = True\n isDecreasing = True\n\n # check if the number is Monotonic\n index = 1\n\n while index < len(A):\n \n previous = index - 1\n current = index\n\n # In any given if the current number is bigger then number is increasing\n # So assign isIncreasing to false\n if A[previous] < A[current]:\n isDecreasing = False\n \n # if the current is smaller the number is decreasing\n # so assign isIncreasing to false\n if A[previous] > A[current]:\n isIncreasing = False\n index += 1\n \n return isIncreasing or isDecreasing", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n \n len_ = len(A)\n \n if (len_ == 0 or len_ == 1 or len_ == 2):\n return True\n \n f, l = A[0], A[-1]\n prev = f\n \n for n in A[1:]:\n if (f < l):\n if (n < prev):\n return False\n if (f > l):\n if (n > prev):\n return False\n if (f == l):\n if (n != prev):\n return False\n prev = n\n return True\n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n dec = False\n inc = False\n\n for i in range(len(A) - 1):\n j = i+1\n if A[i] is not A[j]: \n if A[i] < A[j]:\n inc = True\n elif A[i] > A[j]:\n dec = True\n if(inc and dec):\n return False\n return True", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n \n if len(A) == 0: return False\n if len(A) == 1: return True\n \n incr = 0\n \n for i in range(1, len(A)):\n if A[i] - A[i-1] > 0 and incr == 0:\n incr = 1\n elif A[i] - A[i-1] > 0 and incr == -1:\n return False\n elif A[i] - A[i-1] < 0 and incr == 0:\n incr = -1\n elif A[i] - A[i-1] < 0 and incr == 1:\n return False\n \n return True\n \n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n if len(A) < 3:\n return True\n i = 0\n while i < len(A) - 1 and A[i] == A[i+1]:\n i += 1\n if i == len(A) - 1:\n return True\n asc = (A[i] < A[i+1])\n for j in range(i, len(A) - 1):\n if A[j] == A[j+1]:\n continue\n tmp = (A[j] < A[j+1])\n if tmp != asc:\n return False\n return True\n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n icounter = 0\n dcounter = 0\n for i in range(len(A)-1):\n if A[i] > A[i+1]:\n dcounter += 1\n if A[i] < A[i+1]:\n icounter += 1\n if A[i] == A[i+1]:\n icounter += 1\n dcounter += 1\n if icounter == len(A) - 1 or dcounter == len(A) - 1:\n return True\n return False\n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n def isIncreasing(self, A: List[int]) -> bool:\n mono = True\n for i in range(len(A)):\n if i == (len(A) - 1):\n break\n if A[i] > A[i+1]:\n mono = False\n return mono\n def isDecreasing(self, A: List[int]) -> bool:\n m = True\n for i in range(len(A)):\n if i == (len(A) - 1):\n break\n if A[i] < A[i+1]:\n m = False\n return m\n if isDecreasing(self,A) or isIncreasing(self,A):\n return True\n return False\n \n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n if len(A) <= 1:\n return True\n \n increasing = True\n decreasing = True\n \n for i in range(len(A)-1):\n if A[i] > A[i+1]:\n increasing = False\n \n if not increasing:\n for i in range(len(A)-1):\n if A[i] < A[i+1]:\n decreasing = False\n \n return True if increasing or decreasing else False", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n if not A or len(A) < 2:\n return True\n \n self.direction = None\n \n return self.isMonotonicHelper(A, 0, len(A)-1)\n \n def isMonotonicHelper(self, A, start, end):\n if start < end:\n mid = (start + end) // 2\n if self.isMonotonicHelper(A, start, mid) and self.isMonotonicHelper(A, mid+1, end):\n if self.direction is None:\n if A[mid] < A[mid+1]:\n self.direction = 1\n elif A[mid] > A[mid+1]:\n self.direction = 0\n return True\n elif self.direction == 1:\n return A[mid] <= A[mid+1]\n else:\n return A[mid] >= A[mid+1]\n else:\n return False\n return True", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n if min(A) == A[0]:\n start = 0\n increment = 1;\n end = len(A)\n elif max(A) == A[0]:\n start = len(A) - 1\n increment = -1\n end = 0\n else:\n return False\n num = A[start]\n print(start, num)\n for i in range(start, end, increment):\n print(A[i], num)\n if A[i] < num:\n return False\n num = A[i]\n return True", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n increasing = decreasing = True\n \n for i in range(len(A) - 1):\n if A[i] > A[i+1]:\n increasing = False\n if A[i] < A[i+1]:\n decreasing = False\n if increasing or decreasing:\n return increasing or decreasing", "class Solution:\n \n def check(self, B):\n self.B = B\n result = []\n for i in range(len(self.B) - 1):\n if self.B[i] <= self.B[i+1]:\n result.append(True)\n else:\n result.append(False)\n \n final = all(result)\n return final\n \n \n def isMonotonic(self, A: List[int]) -> bool:\n \n a = []\n \n a.append(self.check(A))\n a.append(self.check(A[::-1]))\n \n b = any(a)\n\n return b \n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n if len(A) <= 1:\n return True\n t = 0\n for i in range(len(A) - 1):\n if A[i] < A[i+1] and t == -1:\n return False\n elif A[i] > A[i+1] and t ==1:\n return False\n elif A[i] < A[i+1] and t == 0:\n t = 1\n elif A[i] > A[i+1] and t == 0:\n t = -1\n return True", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n climb = None\n bef = None\n for num in A:\n if bef is None:\n pass\n elif climb is None and num > bef:\n climb = True\n elif climb is None and num < bef:\n climb = False\n elif climb is None and num == bef:\n pass\n elif climb is True and num >= bef:\n pass\n elif climb is False and num <= bef:\n pass\n else:\n return False\n bef = num\n \n return True ", "class Solution:\n def isMonotonic(self, arr: List[int]) -> bool:\n # ok \n f=True\n n = len(arr)\n for i in range(n-1):\n if arr[i]>arr[i+1]:\n f=False\n break\n if f:return True\n r=True\n for i in range(n-1):\n if arr[i]<arr[i+1]:\n r=False\n break\n return r\n", "def isMono(A, forward=True):\n curValue = A[0]\n \n for i in range(1, len(A)):\n if forward and A[i] < curValue:\n return False\n if not forward and A[i] > curValue:\n return False\n \n curValue = A[i]\n \n return True\n\nclass Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n return isMono(A) or isMono(A, False)", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n is_decreasing = is_increasing = True\n for i in range(len(A)-1):\n if A[i] < A[i + 1]: is_increasing = False\n if A[i] > A[i + 1]: is_decreasing = False\n return is_decreasing or is_increasing\n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n isIncreasing, isDecreasing = True, True\n \n for i in range(len(A) - 1):\n if A[i] > A[i+1]:\n isIncreasing = False\n elif A[i] < A[i+1]:\n isDecreasing = False\n \n return isIncreasing or isDecreasing", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n if sorted(A) == A:\n return True\n elif sorted(A, reverse = True) == A:\n return True\n else:\n return False\n \n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n decreasing = True\n increasing = True\n for i in range(0, len(A)-1):\n if A[i] > A[i+1]: decreasing = False\n if A[i] < A[i+1]: increasing = False\n \n return decreasing or increasing\n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n res1 = sorted(A, reverse=True)\n res2 = sorted(A)\n if res1 == A or res2 == A:\n return True\n return False", "class Solution(object):\n def isMonotonic(self, A):\n return (all(A[i] <= A[i+1] for i in range(len(A) - 1)) or\n all(A[i] >= A[i+1] for i in range(len(A) - 1)))", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n \n # initial value\n mono = 0\n \n for i in range(len(A) - 1):\n if A[i + 1] - A[i] != 0:\n if mono == 0:\n mono = A[i + 1] - A[i]\n else:\n if mono * (A[i + 1] - A[i]) < 0:\n return False\n\n \n return True", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n increase, decrease = True, True\n for i in range(1, len(A)):\n if A[i] > A[i - 1]:\n decrease = False\n if A[i] < A[i - 1]:\n increase = False\n return increase or decrease", "class Solution(object):\n def isMonotonic(self, A):\n monotonicIncr = True\n monotonicDecr = True\n\n for i in range(len(A) - 1):\n j = i + 1\n if A[i] > A[j]:\n monotonicIncr = False\n if A[i] < A[j]:\n monotonicDecr = False\n\n return monotonicIncr or monotonicDecr", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n increasing = True\n for x, y in zip(A, A[1:]):\n if x > y:\n increasing = False\n break\n decreasing = True\n for x, y in zip(A, A[1:]):\n if x < y:\n decreasing = False\n break\n return increasing or decreasing\n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n \n if A[-1] - A[0] > 0:\n signal = 'incr'\n elif A[-1] - A[0] == 0:\n signal = 'same'\n elif A[-1] - A[0] < 0:\n signal = 'decr'\n \n if signal == 'same':\n if A == [A[0]] * len(A):\n return True\n else:\n return False\n \n elif signal == 'incr':\n for i in range(1, len(A)):\n if A[i] < A[i- 1]:\n return False\n return True\n \n elif signal == 'decr':\n for i in range(1, len(A)):\n if A[i] > A[i-1]:\n return False\n return True\n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n count=0\n count2=0\n for x in range(len(A)-1):\n if(A[x]<=A[x+1]):\n count+=1\n if(A[x]>=A[x+1]):\n count2+=1\n print(count2, A[x])\n \n if(count== len(A)-1 or count2==len(A)-1):\n return True\n else:\n return False", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n inc=False\n i=0\n while i<len(A)-1 and A[i]==A[i+1]:\n i+=1\n if i==len(A)-1:\n return True\n if A[i]<A[i+1]:\n inc=True\n \n for i in range(1,len(A)-1):\n if inc==True:\n if A[i]>A[i+1]:\n return False\n if inc==False:\n if A[i+1]>A[i]:\n return False\n return True\n \n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n B=A.copy()\n A.sort()\n if A==B or A[::-1]==B:\n return True\n return False\n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n up = False\n if A[0] < A[len(A)-1]:\n up = True\n elif A[0] > A[len(A)-1]:\n up = False\n \n for i in range(len(A)-1):\n if up:\n print((A[i], A[i+1]))\n if A[i] > A[i+1]:\n return False\n else:\n if A[i] < A[i+1]:\n return False\n return True\n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n increase, decrease = True, True\n \n for i in range(1, len(A)):\n if A[i-1] > A[i]:\n increase = False\n \n if A[i-1] < A[i]:\n decrease = False\n \n return increase or decrease\n \n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n up = down = True\n \n for i in range(1, len(A)):\n if A[i - 1] > A[i]:\n up = False\n\n if A[i - 1] < A[i]:\n down = False\n \n return up or down", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n new_array = sorted(A)\n new_array_rev = sorted(A, reverse=True)\n \n if A == new_array or A == new_array_rev:\n return True\n else:\n return False\n", "class Solution:\n def isMonotonic(self, a: List[int]) -> bool:\n# n = len(a)\n \n# if n == 1:\n# return True\n \n# asc = True if a[n-1] - a[0] >= 0 else False\n \n# for i in range(1, n):\n# if asc:\n# if a[i] - a[i-1] < 0:\n# return False\n# else:\n# if a[i] - a[i-1] > 0:\n# return False\n \n \n# return True\n\n increasing = decreasing = True\n\n for i in range(len(a) - 1):\n if a[i] > a[i+1]:\n increasing = False\n if a[i] < a[i+1]:\n decreasing = False\n\n return increasing or decreasing\n \n'''\n[1,2,2,3]\n[6,5,4,4]\n[1,3,2]\n[1,2,4,5]\n[1,1,1]\n[1,2,3,4,0]\n'''", "class Solution:\n \n def isMonotonic(self, A):\n return (all(A[i] <= A[i+1] for i in range(len(A) - 1)) or\n all(A[i] >= A[i+1] for i in range(len(A) - 1)))\n \n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n is_monotonic_incr = True\n is_monotonic_desc = True\n array1=A\n for num in range(1,len(array1)):\n # check if second element is smallar that first\n if (array1[num] < array1[num-1]):\n print('in first if',array1[num] ,array1[num-1])\n is_monotonic_incr = False\n # check if second element is greater that first\n if (array1[num] > array1[num-1]):\n print('in second if',array1[num] ,array1[num-1])\n is_monotonic_desc = False\n \n return is_monotonic_incr or is_monotonic_desc", "class Solution(object):\n def isMonotonic(self, A):\n increasing = decreasing = True\n\n for i in range(len(A) - 1):\n if A[i] > A[i+1]:\n increasing = False\n if A[i] < A[i+1]:\n decreasing = False\n\n return increasing or decreasing", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n return((A==sorted(A))or(A==sorted(A,reverse=True)))", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n if not A: return True\n isIncrementing, prev = None, A[0]\n for i in range(1,len(A)):\n print(prev,A[i],isIncrementing)\n if prev < A[i] and isIncrementing == False: return False\n if prev > A[i] and isIncrementing == True: return False\n if prev < A[i]: isIncrementing = True\n if prev > A[i]: isIncrementing = False\n prev = A[i]\n return True", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n sort = sorted(A)\n return A==sort or A[::-1]==sort", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n \n direction = 0\n for idx, ele in enumerate(A):\n if idx == 0:\n continue\n \n if ele > A[idx - 1] and direction == 0:\n direction = 1\n elif ele < A[idx - 1] and direction == 0:\n direction = -1\n elif ele > A[idx - 1] and direction == -1:\n return False\n elif ele < A[idx - 1] and direction == 1:\n return False\n \n return True\n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n if len(A) == 1:\n return True\n \n i = 0\n n = len(A)\n while i < n-1 and A[i] == A[i+1]:\n i += 1\n if i == n-1:\n return True\n if A[i] > A[i+1]:\n while i < n-1 and A[i] >= A[i+1]:\n i += 1\n if i != n-1:\n return False\n else:\n return True\n else:\n while i < n-1 and A[i] <= A[i+1]:\n i += 1\n if i != n-1:\n return False\n else:\n return True\n \n \n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n i = 1\n pr = None\n cur = None\n if len(A) < 3:\n return True\n while i < len(A) - 1:\n if A[i] > A[i-1] and A[i] > A[i +1]:\n return False\n elif A[i] < A[i-1] and A[i] < A[i +1]:\n return False\n elif (A[i] >= A[i-1] and A[i] < A[i +1]) or (A[i] > A[i-1] and A[i] <= A[i +1]) :\n cur = 'I'\n elif (A[i] <= A[i -1] and A[i] > A[i +1]) or (A[i] < A[i -1] and A[i] >= A[i +1]):\n cur = 'D' \n if pr is None and cur is not None:\n pr = cur\n elif pr is not None and cur is not None and pr != cur:\n return False \n i += 1\n \n return True\n \n \n", "class Solution:\n def monotonicArrayIncreasing(self,a):\n i = 0\n while i+1 < len(a):\n if a[i] > a[i+1]:\n return False\n i += 1\n return True\n\n def monotonicArrayDecreasing(self,a):\n i = 0\n while i+1 < len(a):\n if a[i] < a[i+1]:\n return False\n i += 1\n return True\n def isMonotonic(self, A: List[int]) -> bool:\n x=self.monotonicArrayDecreasing(A)\n y=self.monotonicArrayIncreasing(A) \n return x or y", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n increasing = None\n for i in range(1, len(A)):\n if increasing is None:\n if A[i] != A[i - 1]:\n increasing = A[i] > A[i - 1]\n elif increasing and A[i] < A[i - 1]:\n return False\n elif not increasing and A[i] > A[i - 1]:\n return False\n return True", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n if len(A) < 2:\n return True\n \n increasing = None\n previous = A[0]\n for element in A[1:]:\n if increasing == True and element < previous:\n return False\n \n if increasing == False and element > previous:\n return False\n \n if increasing is None and element != previous:\n increasing = element > previous\n \n previous = element\n \n return True\n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n ans=True\n n=len(A)\n if n<=2:\n return ans\n # ind=0\n # while True:\n # if ind+1==n:\n # break\n # else:\n # if A[ind]<A[ind+1]:\n # comp=\\\"<\\\"\n # break\n # elif A[ind]>A[ind+1]:\n # comp=\\\">\\\"\n # break\n # else:\n # ind+=1\n # for j in range(ind,n-1):\n # if not eval(\\\"A[j]\\\"+comp+\\\"=A[j+1]\\\"):\n # return False\n # return ans\n left=True\n right=True\n for i in range(1,n):\n if A[i]>A[i-1]:\n left=False\n break\n for i in range(1,n):\n if A[i]<A[i-1]:\n right=False\n break\n return left or right\n \n \n \n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n asc_arr = sorted(A)\n desc_arr = sorted(A, reverse=True)\n return (A == asc_arr or A == desc_arr)\n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n \n if (len(A) < 3):\n return True\n gt = False\n lt = False\n \n for i in range(len(A) - 1):\n \n if A[i] > A[i + 1]:\n gt = True\n if A[i] < A[i + 1]:\n lt = True\n if (gt and lt):\n return False\n return True\n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n if len(A) <= 1:\n return True\n \n flag = -1\n \n if A[0] < A[1]:\n flag = 0\n elif A[0] == A[1]:\n flag = 1\n else:\n flag = 2\n \n for i in range(0, len(A) - 1):\n if flag == 0 and A[i] > A[i + 1]:\n return False\n elif flag == 2 and A[i] < A[i + 1]:\n return False\n elif flag == 1:\n if A[i] > A[i + 1]:\n flag = 2\n elif A[i] < A[i + 1]:\n flag = 0\n else:\n flag = 1\n \n return True \n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n increasing = True\n decreasing = True\n for i in range(len(A)-1):\n if A[i] > A[i+1]:\n increasing = False\n if A[i] < A[i+1]:\n decreasing = False\n \n \n return increasing or decreasing", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n inc = True\n dec = True\n \n for i in range(1,len(A)):\n if A[i-1] > A[i]:\n inc = False\n if A[i-1] < A[i]:\n dec = False\n return inc or dec\n\n \n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n if len(A) <= 1:\n return True\n last_diff = 0\n for i in range(1, len(A)):\n cur_diff = A[i] - A[i - 1]\n if cur_diff < 0:\n if last_diff == 0:\n last_diff = cur_diff\n elif last_diff > 0:\n return False\n elif cur_diff > 0:\n if last_diff == 0:\n last_diff = cur_diff\n elif last_diff < 0:\n return False\n return True\n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n flag = None\n \n for i in zip(A, A[1:]):\n temp = i[1] - i[0]\n if flag:\n if flag*temp < 0:\n return False\n else:\n if temp > 0:\n flag = 1\n elif temp < 0:\n flag = -1\n \n return True\n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n monotone = 0\n for i in range(len(A)-1):\n m = A[i+1]-A[i]\n if m*monotone<0:\n return False\n if monotone == 0 and m != 0:\n monotone = 1 if m>0 else -1\n return True", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n increase = []\n decrease = []\n i, d = [], []\n for idx, v in enumerate(A):\n while decrease and decrease[-1][0] >= v:\n dv, di = decrease.pop()\n if not d:\n d.append((dv, di))\n elif d[-1][1] < di:\n d.append((dv, di))\n decrease.append((v, idx))\n \n while increase and increase[-1][0] <= v:\n iv, ii = increase.pop()\n if not i:\n i.append((iv, ii))\n elif i[-1][1] < ii:\n i.append((iv, ii))\n increase.append((v, idx))\n if decrease and len(decrease) == 1:\n g = decrease.pop()\n if d and d[-1][0] >= g[0]:\n d.append(g)\n else:\n d.append(g)\n if increase and len(increase) == 1:\n g = increase.pop()\n if i and i[-1][0] <= g[0]:\n i.append(g)\n else:\n i.append(g)\n return len(i) == len(A) or len(d) == len(A)", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n i=0\n j=1\n if(A.index(min(A))==0 or A.index(min(A)) == (len(A)-1) or min(A)==A[-1]):\n if(A.index(min(A)) == 0):\n while j <= len(A)-1:\n if(A[i] <= A[j]):\n i = i+1\n j = j+1\n else:\n return False\n elif(A.index(min(A)) == len(A)-1 or min(A) == A[-1]):\n while j <= len(A)-1:\n if(A[i] >= A[j]):\n i = i+1\n j = j+1\n else:\n return False\n else:\n return False\n return True\n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n return sorted(A) == A or sorted(A, reverse=True) == A", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n if len(A)<2:\n return True\n \n increasing = False\n decreasing = False\n i = 0\n \n while i < len(A)-1 and (not increasing and not decreasing):\n if A[i] == A[i+1]:\n i+=1\n continue\n \n if A[i] < A[i+1]:\n increasing = True\n \n else:\n decreasing= True\n \n i+=1\n\n \n \n if increasing:\n while i < len(A)-1:\n if A[i] > A[i+1]:\n return False\n i+=1\n \n return True\n \n if decreasing:\n while i < len(A)-1:\n if A[i] < A[i+1]:\n return False\n i+=1\n \n return True\n \n if not increasing and not decreasing:\n return True\n \n \n \n \n\n \n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n inc = True\n dec = True\n for i in range(len(A)-1):\n if A[i+1] - A[i] > 0:\n inc = inc and True\n dec = False\n elif A[i+1] - A[i] < 0:\n dec = dec and True\n inc = False\n \n return inc or dec", "from enum import Enum\nclass Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n if len(A) <= 2:\n return True\n \n class Comp(Enum):\n inc = 0\n eq = 1\n dec = 2\n \n def to_comp(left, right):\n if right > left:\n return Comp.inc\n elif right == left:\n return Comp.eq\n else:\n return Comp.dec\n \n comp = to_comp(A[0], A[1])\n \n for i in range(2, len(A)):\n new_comp = to_comp(A[i - 1], A[i])\n if new_comp == Comp.inc and comp == Comp.dec:\n return False\n elif new_comp == Comp.dec and comp == Comp.inc:\n return False\n if new_comp != Comp.eq:\n comp = new_comp\n \n return True", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n if len(A) <= 2: return True\n \n d = A[1] - A[0]\n \n for i in range(1, len(A)-1):\n new_d = A[i+1] - A[i]\n \n if new_d * d < 0: return False\n if new_d != 0:\n d = new_d\n return True\n \n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n length = len(A)\n monotone_inc = True\n monotone_dec = True\n for i in range(length-1):\n if A[i+1] >= A[i]:\n continue\n else:\n monotone_inc = False\n for i in range(length-1):\n if A[i+1] <= A[i]:\n continue\n else:\n monotone_dec = False\n return monotone_inc or monotone_dec\n \n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n inc, dec = True, True\n for i in range(1, len(A)):\n a, b = A[i], A[i-1]\n inc = inc & (a >= b)\n dec = dec & (a <= b)\n if(not (inc or dec)): return False\n return inc or dec", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n if (len(A) == 1):\n return 1\n \n dir = 0\n for (i,j) in zip(A, A[1:] + [A[len(A) - 1]]):\n if (i != j): \n cdir = (i - j) / abs(i - j) \n if (dir == 0):\n dir = cdir\n elif (dir != cdir):\n return 0\n\n return 1\n \n\n \n \n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n \n if len(A) <= 1:\n return True\n \n inc, dec = True, True\n \n for i in range(len(A)-1):\n if A[i+1] > A[i]:\n dec = False\n if A[i+1] < A[i]:\n inc = False\n \n return dec or inc", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n \n up = down = True\n\n for i in range(len(A)-1):\n if A[i] > A[i+1]:\n up = False\n if A[i] < A[i + 1]:\n down = False\n \n return up or down ", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n import numpy as np\n if len(A)==1:\n return(True)\n else:\n diff = np.diff(A)\n return(min(diff)>=0 or max(diff)<=0)\n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n \n a1, a2 = sorted(A), sorted(A, reverse = True)\n if A == a1 or A == a2:\n return True\n return False\n '''\n nD, nI = 1, 1\n for i in range(1, len(A)):\n if A[i] - A[i-1] < 0:\n nD = 0\n elif A[i] - A[i-1] > 0 :\n nI = 0\n return nI or nD\n '''", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n return A == sorted(A) or A == sorted(A)[::-1]\n", "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n if len(A) < 2:\n return True\n asc = None\n for i in range(1, len(A)):\n if A[i] == A[i-1]:\n continue\n if asc is None:\n asc = A[i-1] < A[i]\n else:\n if asc != (A[i-1] < A[i]):\n return False\n return True\n \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: "Qedo1ct-eeLg=ntse-T!"   Note: S.length <= 100 33 <= S[i].ASCIIcode <= 122  S doesn't contain \ or "
["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\n return result", "class Solution:\n def reverseOnlyLetters(self, s: str) -> str:\n a={}\n j=0\n s=list(s)\n i=0\n while i<len(s):\n if not s[i].isalpha():\n a[i+j]=s[i]\n del s[i]\n j+=1\n else:\n i+=1\n s=s[::-1]\n for i in a:\n s.insert(i,a[i])\n return ''.join(s)", "class Solution:\n def reverseOnlyLetters(self, S: str) -> str:\n if len(S) == 1:\n return S\n \n start = 0\n end = len(S) - 1\n S = list(S)\n while start < end:\n if S[start].isalpha():\n if S[end].isalpha():\n S[start], S[end] = S[end], S[start]\n start += 1\n end -= 1\n else:\n end -= 1\n else:\n start += 1\n \n return ''.join(S)\n", "import string\n# string.ascii_letters\n# string.ascii_uppercase\n# string.ascii_lowercase\n# c.isalpha()\nclass Solution:\n def reverseOnlyLetters(self, S: str) -> str:\n if not S: return ''\n \n stack = []\n deque = collections.deque()\n for i, c in enumerate(S):\n # if c not in string.ascii_letters: #'abcd...'\n if not c.isalpha():\n deque.append((i, c))\n else:\n stack.append(c)\n\n res = ''\n for i in range(len(S)):\n if deque and i == deque[0][0]:\n res += deque.popleft()[1]\n \n else:\n res += stack.pop()\n return res\n \n", "class Solution:\n def reverseOnlyLetters(self, S: str) -> str:\n read_index, write_index = len(S) - 1, 0\n res = list(S)\n while read_index >= 0:\n c = S[read_index]\n\n if not c.isalpha():\n read_index -= 1\n continue\n \n while not res[write_index].isalpha():\n write_index += 1\n \n res[write_index] = c\n read_index -= 1\n write_index += 1\n \n return ''.join(res)", "class Solution:\n def reverseOnlyLetters(self, S: str) -> str:\n S = list(S)\n l = 0\n r = len(S) - 1\n while l < r:\n if not S[l].isalpha():\n l += 1\n if not S[r].isalpha():\n r -= 1\n if S[l].isalpha() and S[r].isalpha():#\u56e0\u4e3a\u6709\u8fd9\u4e00\u6b65\u7684\u9650\u5236\uff0c\u6240\u4ee5\u4e0a\u9762\u53ef\u4ee5\u53ea\u7528if \u4e0d\u7528while\n S[l], S[r] = S[r], S[l]\n l += 1\n r -= 1\n return ''.join(S)", "class Solution:\n def reverseOnlyLetters(self, S: str) -> str:\n S = list(S)\n start = 0\n end = len(S) - 1\n while start <= end:\n while not S[start].isalpha() and start < end:\n start += 1\n while not S[end].isalpha() and start < end:\n end -= 1\n S[start], S[end] = S[end], S[start]\n start += 1\n end -= 1\n return ''.join(S)\n \n", "class Solution:\n def reverseOnlyLetters(self, S: str) -> str:\n s=set()\n for i in range(ord('a'),ord('z')+1):\n s.add(chr(i))\n for i in range(ord('A'),ord('Z')+1):\n s.add(chr(i))\n order=[]\n for i in range(len(S)):\n if S[i] in s:\n order.append(S[i])\n new=[]\n order.reverse()\n for i in reversed((S)):\n if i in s:\n new.append(order.pop())\n else:\n new.append(i)\n return ''.join(reversed(new))\n \n \n"]
{"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 figure to a 2 dimensional plane.  Here, we are viewing the "shadow" when looking at the cubes from the top, the front, and the side. Return the total area of all three projections.   Example 1: Input: [[2]] Output: 5 Example 2: Input: [[1,2],[3,4]] Output: 17 Explanation: Here are the three projections ("shadows") of the shape made with each axis-aligned plane. Example 3: Input: [[1,0],[0,2]] Output: 8 Example 4: Input: [[1,1,1],[1,0,1],[1,1,1]] Output: 14 Example 5: Input: [[2,2,2],[2,1,2],[2,2,2]] Output: 21   Note: 1 <= grid.length = grid[0].length <= 50 0 <= grid[i][j] <= 50
["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 col=max(col,grid[j][i])\n ans+=row+col\n return ans", "class Solution:\n def projectionArea(self, grid: List[List[int]]) -> int:\n \n max_rows = [0 for _ in grid]\n max_cols = [0 for _ in grid]\n \n total_nonzero = 0\n \n for r in range(len(grid)):\n \n for c in range(len(grid[r])):\n \n if grid[r][c] > max_cols[c]:\n max_cols[c] = grid[r][c]\n \n if grid[r][c] > max_rows[r]:\n max_rows[r] = grid[r][c]\n \n if grid[r][c] > 0:\n total_nonzero += 1\n \n \n print(max_rows)\n print(max_cols)\n print(total_nonzero)\n \n return sum(max_rows) + sum(max_cols) + total_nonzero"]
{"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 chooses one of four cardinal directions (north, east, west, and south), then moves in that direction until it chooses to stop, reaches the edge of the board, or captures an opposite colored pawn by moving to the same square it occupies.  Also, rooks cannot move into the same square as other friendly bishops. Return the number of pawns the rook can capture in one move.   Example 1: Input: [[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","R",".",".",".","p"],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]] Output: 3 Explanation: In this example the rook is able to capture all the pawns. Example 2: Input: [[".",".",".",".",".",".",".","."],[".","p","p","p","p","p",".","."],[".","p","p","B","p","p",".","."],[".","p","B","R","B","p",".","."],[".","p","p","B","p","p",".","."],[".","p","p","p","p","p",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]] Output: 0 Explanation: Bishops are blocking the rook to capture any pawn. Example 3: Input: [[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","p",".",".",".","."],["p","p",".","R",".","p","B","."],[".",".",".",".",".",".",".","."],[".",".",".","B",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."]] Output: 3 Explanation: The rook can capture the pawns at positions b5, d6 and f5.   Note: board.length == board[i].length == 8 board[i][j] is either 'R', '.', 'B', or 'p' There is exactly one cell with board[i][j] == 'R'
["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 if board[i-d][j]=='B':\n break;\n elif board[i-d][j]=='p':\n count+=1;\n break;\n else:\n d+=1;\n d=1;\n #\uc544\ub798\n while i+d<=len(board)-1:\n if board[i+d][j]=='B':\n break;\n elif board[i+d][j]=='p':\n count+=1;\n break;\n else:\n d+=1;\n d=1;\n #\uc67c\ucabd\n while 0<=j-d:\n if board[i][j-d]=='B':\n break;\n elif board[i][j-d]=='p':\n count+=1;\n break;\n else:\n d+=1;\n d=1;\n #\uc624\ub978\ucabd\n while j+d<=len(board[i])-1:\n if board[i][j+d]=='B':\n break;\n elif board[i][j+d]=='p':\n count+=1;\n break;\n else:\n d+=1;\n return count;\n"]
{"fn_name": "numRookCaptures", "inputs": [[[["\".\"", "\".\"", "\".\"", "\".\"", "\".\"", "\".\"", "\".\"", "\".\""], ["\".\"", "\".\"", "\".\"", "\"p\"", "\".\"", "\".\"", "\".\"", "\".\""], ["\".\"", "\".\"", "\".\"", "\"R\"", "\".\"\n", "\".\"", "\".\"", "\"p\""], ["\".\"", "\".\"", "\".\"", "\".\"", "\".\"", "\".\"", "\".\"", "\".\""], ["\".\"", "\".\"", "\".\"", "\".\"", "\".\"", "\".\"", "\".\"", "\".\""], ["\".\"", "\".\"\n", "\".\"", "\"p\"", "\".\"", "\".\"", "\".\"", "\".\""], ["\".\"", "\".\"", "\".\"", "\".\"", "\".\"", "\".\"", "\".\"", "\".\""], ["\".\"", "\".\"", "\".\"", "\".\"", "\".\"", "\".\"", "\".\"", "\"\n.\""], [], []]]], "outputs": [0]}
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 in the array are good. Example 3: Input: nums = [1,2,3] Output: 0   Constraints: 1 <= nums.length <= 100 1 <= nums[i] <= 100
["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(self, nums: List[int]) -> int:\n hashMap = {}\n res = 0\n \n for number in nums: \n if number in hashMap:\n res += hashMap[number]\n hashMap[number] += 1\n else:\n hashMap[number] = 1\n \n return res", "class Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n count = 0\n for i in range(len(nums)):\n for j in range(i+1, len(nums)):\n if nums[i] == nums[j]:\n count += 1\n \n return count", "class Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n for i in nums:\n repeat = {}\n n = 0\n for i in nums:\n if i in repeat:\n n += repeat[i]\n repeat[i] += 1\n else:\n repeat[i] = 1\n return n", "class Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n num_good = 0\n for i in range(len(nums)):\n first = nums[i]\n for j in nums[i+1:]:\n print((first, j))\n if first == j:\n num_good += 1\n return num_good\n", "class Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n #ans = 0\n #for c in Counter(nums).values():\n # if c > 1:\n # ans += c * (c-1) // 2\n #return ans\n return sum((c*(c-1)//2 for c in Counter(nums).values()))", "class Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n good = 0\n num_dict = {}\n for num in nums:\n if num in num_dict:\n good += num_dict[num]\n num_dict[num] += 1\n else:\n num_dict[num] = 1\n return good", "class Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n uniques = set(nums)\n count = 0\n for unique in uniques:\n count += nums.count(unique) * (nums.count(unique) - 1) / 2\n return int(count)\n \n", "class Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n res, map = 0, {}\n for num in nums:\n if num not in map:\n map[num] = 1\n else:\n res += map[num]\n map[num] += 1\n return res", "class Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n tracker = {}\n \n for num in nums:\n if num not in tracker:\n tracker[num] = 0\n else:\n tracker[num] += 1\n \n sum = 0\n for num in tracker:\n sum += tracker[num] * (tracker[num]+1) // 2\n return sum", "class Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n count = 0\n for i in range(len(nums)-1):\n for j in range(i+1, len(nums)):\n if nums[i]==nums[j]:\n count +=1\n return count\n", "class Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n pairCount = 0\n i = 0\n while i < len(nums)-1:\n j = i + 1\n while j < len(nums):\n if nums[i] == nums[j]:\n pairCount += 1\n j+=1\n i+=1\n return pairCount\n", "class Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n counter = collections.Counter(nums)\n answer = 0\n \n for k, v in counter.items():\n answer += v * (v - 1) // 2\n return answer"]
{"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],[1,0]] Output: 0 Example 3: Input: grid = [[1,-1],[-1,-1]] Output: 3 Example 4: Input: grid = [[-1]] Output: 1   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 100 -100 <= grid[i][j] <= 100
["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 counter = 0\n \n for i in grid:\n for j in i:\n if j < 0:\n counter += 1\n \n return counter", "class Solution:\n def countNegatives(self, grid: List[List[int]]) -> int:\n length = len(grid[0])\n count = 0\n \n for inside in grid:\n a = 0\n b = len(inside) - 1\n \n while a <= b:\n middle = (a + b)//2\n if inside[middle] < 0:\n if middle > 0 and inside[middle-1] >= 0:\n count += (length - middle)\n break\n elif middle == 0 and inside[middle-1] < 0:\n count += length\n break\n else:\n b -= 1\n else:\n a += 1\n \n return count\n", "class Solution:\n def countNegatives(self, grid: List[List[int]]) -> int:\n count = 0\n for i in range(len(grid)):\n for j in range(len(grid[i])):\n print((grid[i][j]))\n if grid[i][j]<0:\n count+=1\n return count\n", "class Solution:\n def countNegatives(self, grid: List[List[int]]) -> int:\n i = 0 \n j = 0 \n count = 0\n while i < len(grid):\n while j < len(grid[i]):\n print(grid[i][j])\n if grid[i][j] < 0:\n count+=1\n j+=1\n \n i+=1\n j = 0\n return count", "class Solution:\n def countNegatives(self, grid: List[List[int]]) -> int:\n somme = 0\n for row in grid:\n for el in row:\n if el < 0:\n somme += 1\n return somme", "class Solution:\n def countNegatives(self, grid: List[List[int]]) -> int:\n \n def binarysearch(arr):\n low=0;high=len(arr)-1\n\n while low<=high:\n mid=(low+high)//2\n if arr[mid]<0:\n high=mid-1\n else:\n low=mid+1\n return low\n count=0\n for arr in grid:\n val=binarysearch(arr)\n count+=len(arr)-val\n return count\n", "import numpy as np\nclass Solution:\n def countNegatives(self, grid: List[List[int]]) -> int:\n g=np.array(grid)\n g=list(np.concatenate(g))\n count=0\n sum=0\n for i in g:\n if sum+i<sum:\n count+=1\n sum=sum+i\n return count", "class Solution:\n def countNegatives(self, grid: List[List[int]]) -> int:\n # counter = 0\n # for i in range(len(grid)):\n # for j in range(len(grid[0])):\n # if grid[i][j] < 0:\n # counter += 1\n # return counter\n return str(grid).count('-')", "class Solution:\n def countNegatives(self, grid: List[List[int]]) -> int:\n count = 0\n for i in range(0, len(grid)):\n for j in range(0, len(grid[i])):\n if grid[i][j] <0:\n count += 1\n return count\n \n", "class Solution:\n def countNegatives(self, grid: List[List[int]]) -> int:\n c = 0\n for r in grid:\n for i in range(len(r)):\n if r[i] < 0:\n c += (len(r) - i)\n break\n return c \n", "class Solution:\n def countNegatives(self, grid: List[List[int]]) -> int:\n return len([c for r in grid for c in r if c<0])", "class Solution:\n def countNegatives(self, grid: List[List[int]]) -> int:\n y=0\n for row in grid:\n l = 0;\n r = len(row)\n while l < r:\n mid = l + (r-l)//2\n if (row[mid] < 0):\n r = mid\n else:\n l = mid+1\n y+=len(row)-r\n return y\n", "class Solution:\n def countNegatives(self, grid: List[List[int]]) -> int:\n count = 0\n for i in range(len(grid), 0, -1):\n for j in range(len(grid[i-1]), 0, -1):\n if grid[i-1][j-1] < 0:\n count += 1\n else:\n break\n return count\n", "class Solution:\n def countNegatives(self, grid: List[List[int]]) -> int:\n \n count = 0\n for arr in grid:\n count += len(arr)-self.NegStart(arr)\n return count\n \n def NegStart(self, arr):\n first = 0\n last = len(arr)-1\n found = False\n while first<=last:\n midpoint = (first + last)//2\n if arr[midpoint] < 0:\n last = midpoint-1\n else:\n first = midpoint+1\n return first\n \n", "class Solution:\n def countNegatives(self, grid: List[List[int]]) -> int:\n ct = 0\n \n for i in grid:\n for j in i:\n if j < 0:\n ct += 1\n \n return ct", "class Solution:\n def countNegatives(self, grid: List[List[int]]) -> int:\n #counter set to 0\n counter = 0\n \n #loop thru arr of arr\n for arr in grid:\n \n #loop thru every single num in arr\n for num in arr:\n \n #if num is less than 0:\n if num < 0:\n #counter += 1\n counter += 1\n #return counter\n return counter\n", "class Solution:\n def countNegatives(self, grid: List[List[int]]) -> int:\n count=0 \n for i in grid:\n for j in i:\n if j<0:\n count+=1\n return count\n", "class Solution:\n def countNegatives(self, grid: List[List[int]]) -> int:\n count=0\n for i in grid:\n for j in i:\n if(j<0):\n count+=1\n \n \n return count\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: 14 is not ugly since it includes another prime factor 7. Note: 1 is typically treated as an ugly number. Input is within the 32-bit signed integer range: [−231,  231 − 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 == 0:\n num = num / 5\n if num == 1:\n return True\n else:\n return False", "class Solution:\n def isUgly(self, num):\n \"\"\"\n :type num: int\n :rtype: bool\n \"\"\"\n if num == 0:\n return False\n for d in (5, 3, 2):\n while num % d == 0:\n num //= d\n if num == 1:\n break\n else:\n return False\n return True\n", "class Solution:\n def isUgly(self, num):\n \"\"\"\n :type num: int\n :rtype: bool\n \"\"\"\n if num == 0:\n return False\n while num % 2 == 0:\n num /= 2\n while num % 3 == 0:\n num /= 3 \n while num % 5 == 0:\n num /= 5\n if num == 1:\n return True\n return False\n", "class Solution:\n def isUgly(self, num):\n \"\"\"\n :type num: int\n :rtype: bool\n \"\"\"\n n = num\n if n <1:\n return False\n elif n == 1:\n return True\n else:\n while n >= 1:\n ncount = 0\n if n % 3 == 0:\n n = n // 3\n ncount = 1\n if n % 2 == 0:\n n //= 2\n ncount = 1\n if n % 5 == 0:\n n //= 5\n ncount = 1\n if ncount == 1:\n pass\n else:\n break\n if n == 1:\n return True\n else:\n return False", "class Solution:\n def isUgly(self, num):\n \"\"\"\n :type num: int\n :rtype: bool\n \"\"\"\n if num==0:\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==0:\n num=num/5\n if num==1:\n return True\n else:\n return False", "class Solution:\n def isUgly(self, num):\n \"\"\"\n :type num: int\n :rtype: bool\n \"\"\"\n if num<1:\n return False\n if num==1:\n return True\n while num%2==0 or num%3==0 or num%5==0:\n if num%2==0:\n num/=2\n elif num%3==0:\n num/=3\n else:\n num/=5\n if num==1:\n return True\n return False\n", "class Solution:\n def isUgly(self, num):\n \"\"\"\n :type num: int\n :rtype: bool\n \"\"\"\n lst = []\n if num < 1:\n return False\n if num == 1:\n return True\n i = 2\n while (i<num+1):\n print(num,i,' ',lst)\n if num%i == 0:\n if i not in [2,3,5]:\n lst.append(i)\n if lst != []:\n return False\n num = num//i\n else:\n i += 1\n if i>5:\n return False\n if lst == []:\n return True", "class Solution:\n def isUgly(self, num):\n \"\"\"\n :type num: int\n :rtype: bool\n \"\"\"\n if num<=0:\n return False\n for i in [2,3,5]:\n while num%i==0:\n num=num//i\n return num==1", "class Solution:\n def isUgly(self, num):\n \"\"\"\n :type num: int\n :rtype: bool\n \"\"\"\n \n ## take care of trivial cases\n if num <= 0:\n return False\n elif num == 1:\n return True\n \n for factor in 5,3,2:\n while num % factor == 0:\n num = num / factor\n print (num)\n return int(num) == 1\n \n \n \n", "class Solution:\n def isUgly(self, num):\n \"\"\"\n :type num: int\n :rtype: bool\n \"\"\"\n for p in [2,3,5]:\n while num%p == 0 < num:\n num /= p\n return num==1", "class Solution:\n def isUgly(self, num):\n \"\"\"\n :type num: int\n :rtype: bool\n \"\"\"\n if num<=0:\n return False\n count=0\n while(count==0):\n num=num/2\n if str(num)[-1]!='0':\n print(11)\n count=1\n num=num*2\n count=0\n while (count==0):\n num=num/3\n if str(num)[-1]!='0':\n count=1\n num=num*3 \n count=0\n while (count==0):\n num=num/5\n if str(num)[-1]!='0':\n count=1\n num=num*5\n if num!=1.0:\n return False\n else:\n return True", "class Solution:\n def isUgly(self, num):\n \"\"\"\n :type num: int\n :rtype: bool\n \"\"\"\n \n \n # public CONCISE solution....\n \n if num <= 0:\n return False\n while num % 2 == 0:\n num //= 2\n while num % 3 == 0:\n num //= 3\n while num % 5 == 0:\n num //= 5\n return num == 1\n \n \n \n \n \"\"\"\n # my solution......a bit too slow....\n \n if num <= 0:\n return False\n if num in [1,2,3,4,5,6]:\n return True\n if self.isPrime(num):\n return False\n else:\n i = 2\n while i <= int(math.sqrt(num)):\n if num%i == 0:\n if (self.isPrime(i) and i not in [2,3,5]) or (self.isPrime(num//i) and num//i not in [2,3,5]):\n return False\n i += 1\n return True\n \n \n \n def isPrime(self, n):\n if n <= 1:\n return False\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True\n \"\"\"\n \n"]
{"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 of adjacent words and that number is maximized. If you cannot redistribute all the spaces equally, place the extra spaces at the end, meaning the returned string should be the same length as text. Return the string after rearranging the spaces.   Example 1: Input: text = " this is a sentence " Output: "this is a sentence" Explanation: There are a total of 9 spaces and 4 words. We can evenly divide the 9 spaces between the words: 9 / (4-1) = 3 spaces. Example 2: Input: text = " practice makes perfect" Output: "practice makes perfect " Explanation: There are a total of 7 spaces and 3 words. 7 / (3-1) = 3 spaces plus 1 extra space. We place this extra space at the end of the string. Example 3: Input: text = "hello world" Output: "hello world" Example 4: Input: text = " walks udp package into bar a" Output: "walks udp package into bar a " Example 5: Input: text = "a" Output: "a"   Constraints: 1 <= text.length <= 100 text consists of lowercase English letters and ' '. text contains at least one word.
["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 = 0\n for c in s:\n result += c\n num += 1\n if num <= (len(s)-1):\n result += ' '*count\n qqqqqqqqq = [3]*100000\n if extra != 0:\n result += ' '*extra\n return result", "class Solution:\n def reorderSpaces(self, text: str) -> str:\n\n # separate words and spaces\n words = text.split(' ')\n words = list(filter(lambda x: len(x) > 0, words))\n # print(words)\n \n # get their counts so we can do some math\n wordsLen = len(words)\n spacesLen = text.count(' ')\n \n # print(wordsLen, spacesLen)\n if(wordsLen == 1):\n return words[0] + ' ' * spacesLen\n evenDistSpaces = spacesLen // (wordsLen-1)\n endDistSpaces = spacesLen % (wordsLen-1)\n \n # print(evenDistSpaces, endDistSpaces)\n \n space = ' ' * evenDistSpaces\n end = ' ' * endDistSpaces\n \n print(len(space), len(end))\n \n resultString = space.join(words)\n resultString += end\n \n return resultString", "class Solution:\n def reorderSpaces(self, text: str) -> str:\n # count the number of space\n cnt_space = 0\n cnt_words = 0\n for i in range(len(text)):\n if text[i] == ' ':\n cnt_space += 1\n elif cnt_words == 0 or text[i - 1] == ' ':\n cnt_words += 1\n # calculate extra space nad calculate avg space\n extra_space = 0\n avg_space = 0\n if cnt_words < 2:\n extra_space = cnt_space\n else:\n extra_space = cnt_space % (cnt_words - 1)\n avg_space = cnt_space // (cnt_words - 1)\n \n #\n result = ''\n word_appeared = False\n for i in range(len(text)):\n if text[i] != ' ':\n if word_appeared and text[i - 1] == ' ':\n result += ' ' * avg_space\n word_appeared = True\n result += text[i]\n \n \n result += ' ' * extra_space\n return result", "class Solution:\n def reorderSpaces(self, text: str) -> str:\n words = text.split() # split(sep=None) will discard empty strings.\n cnt = len(words)\n spaces = text.count(' ')\n gap = 0 if cnt == 1 else spaces // (cnt - 1)\n trailing_spaces = spaces if gap == 0 else spaces % (cnt - 1)\n return (' ' * gap).join(words) + ' ' * trailing_spaces", "class Solution:\n def reorderSpaces(self, text: str) -> str:\n wds = text.split()\n sc = text.count(' ')\n if len(wds) == 1:\n return text.strip(' ')+' '*sc\n nwds = len(wds)\n s = nwds-1\n res = sc//s\n rem = sc-res*s\n ans = ''\n for i in wds[:-1]:\n ans += i\n ans += ' '*res\n ans += wds[-1]\n ans += ' '*rem\n return ans"]
{"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 transaction is that the customer pays $5. Note that you don't have any change in hand at first. Return true if and only if you can provide every customer with correct change.   Example 1: Input: [5,5,5,10,20] Output: true Explanation: From the first 3 customers, we collect three $5 bills in order. From the fourth customer, we collect a $10 bill and give back a $5. From the fifth customer, we give a $10 bill and a $5 bill. Since all customers got correct change, we output true. Example 2: Input: [5,5,10] Output: true Example 3: Input: [10,10] Output: false Example 4: Input: [5,5,10,10,20] Output: false Explanation: From the first two customers in order, we collect two $5 bills. For the next two customers in order, we collect a $10 bill and give back a $5 bill. For the last customer, we can't give change of $15 back because we only have two $10 bills. Since not every customer received correct change, the answer is false.   Note: 0 <= bills.length <= 10000 bills[i] will be either 5, 10, or 20.
["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 else:\n n5 -=1\n n10 +=1\n else:\n if n10>0 and n5 >0:\n n10 -=1\n n5 -=1\n elif n5>=3:\n n5-=3\n else:\n return False\n else:\n return True\n \n# five = ten = 0\n# for i in bills:\n# if i == 5: \n# five += 1\n# elif i == 10: \n# five, ten = five - 1, ten + 1\n# elif ten > 0: \n# five, ten = five - 1, ten - 1\n# else: \n# five -= 3\n \n# if five < 0: return False\n# return True\n \n \n \n \n", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n \n five = ten = 0\n for i in bills:\n if i == 5: \n five += 1\n elif i == 10: \n five, ten = five - 1, ten + 1\n elif ten > 0: \n five, ten = five - 1, ten - 1\n else: \n five -= 3\n \n if five < 0: return False\n return True\n \n \n", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n bank = {5:0, 10:0, 20:0}\n \n for bill in bills:\n bank[bill] += 1\n change = bill - 5\n if change and not bank[5]:\n return False\n elif change == 15:\n if bank[10]:\n bank[10] -=1\n bank[5] -= 1\n elif bank[5] >= 3:\n bank[5] -= 3\n else:\n return False\n elif change == 5:\n if bank[5]:\n bank[5] -= 1\n else:\n return False\n return True\n \n \n \n \n \n", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n \n change = [0,0,0] # 5, 10, 20\n \n def give(change, amount):\n if amount == 0:\n return True\n \n if amount >= 20 and change[2] > 0:\n change[2] -= 1\n return give(change, amount - 20)\n elif amount >= 10 and change[1] > 0:\n change[1] -= 1\n return give(change, amount-10)\n elif amount >= 5 and change[0] > 0:\n change[0] -= 1\n return give(change, amount-5)\n else:\n return False\n \n index = {5:0, 10:1, 20:2}\n \n for bill in bills:\n \n change[index[bill]] += 1\n \n giveBack = bill-5\n \n if give(change, giveBack) == False:\n return False\n \n return True", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n bill = [0] * 3\n \n for b in bills:\n if b == 20:\n bill[2] += 1\n if bill[1] > 0:\n bill[1] -= 1\n bill[0] -= 1\n else:\n bill[0] -= 3\n elif b == 10:\n bill[1] += 1\n bill[0] -= 1\n else:\n bill[0] += 1\n \n if sum(1 for i in bill if i < 0) > 0:\n return False \n \n return True", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n fives=0\n tens=0\n for i in range(len(bills)):\n if bills[i]==5:\n fives+=1\n elif bills[i]==10:\n tens+=1\n if(fives>0):\n fives-=1\n else:\n return False\n else:\n if (fives>0 and tens>0):\n tens-=1\n fives-=1\n elif fives>=3:\n fives-=3\n else:\n return False\n print(fives,tens)\n else:\n return True", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n \n cnt10Bill, cnt20Bill, cnt5Bill = 0, 0, 0\n for b in bills:\n if b == 5:\n cnt5Bill += 1\n elif b == 10:\n cnt10Bill += 1\n if cnt5Bill >= 1:\n cnt5Bill -= 1\n else:\n return False\n \n elif b == 20:\n cnt20Bill += 1\n if cnt5Bill >= 1 and cnt10Bill >= 1:\n cnt5Bill -= 1\n cnt10Bill -= 1\n elif cnt5Bill >= 3:\n cnt5Bill -= 3\n else:\n return False\n print((cnt5Bill, cnt10Bill, cnt20Bill))\n return True\n \n \n \n \n", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n five, ten = 0, 0 \n \n for bill in bills:\n if bill == 5:\n five += 1\n elif bill == 10:\n five -= 1\n ten += 1\n # now last two cases handle if it is a 20\n # if we have a ten give that and one five\n elif ten > 0:\n five -= 1\n ten -= 1\n # last option is to give 3 fives \n else: \n five -= 3\n # check if five is under zero then return false\n if five < 0: \n return False \n return True\n", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n no_5=0\n no_10=0\n for i in bills:\n if i==5:\n no_5+=1\n elif i==10:\n no_10+=1\n no_5-=1\n else:\n if no_10==0:\n no_5-=3\n else:\n no_10-=1\n no_5-=1\n if no_5<0 or no_10<0:\n return False\n return True", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n d = {5:0, 10:0, 20:0}\n for a in bills:\n if a == 5:\n d[5]+=1\n continue\n if a == 10:\n d[10]+=1\n if d[5]==0:\n return False\n else:\n d[5]-=1\n else:\n d[20]+=1\n if not (d[10] and d[5]) and d[5]<3:\n return False\n if d[10]:\n d[10]-=1\n d[5]-=1\n else:\n d[5]-=3\n return True\n", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n if len(bills) == 0:\n return True\n numfive = 0\n numten = 0\n for payment in bills:\n if payment == 5:\n numfive += 1\n elif payment == 10:\n if numfive >= 1:\n numfive -= 1\n numten += 1\n else:\n return False\n else:\n if numten >= 1 and numfive >= 1: #GREEDY: if a customer pays with a 20 dollar bill, we want to provide the $15 change using as few bills as possible, i.e. we want to give them change using 1 10$ bill and 1 5$ bill instead of 3 5$ bills if possible. This is so we can have more 5$ bills on hand for later transactions (5$ bills are used as change for all transactions regardless of amount, whereas $10 bills should be saved as change for customers that pay $20)\n numten -= 1\n numfive -= 1\n elif numfive >= 3:\n numfive -= 3\n else:\n return False\n return True\n \n", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n from collections import deque\n fives = deque()\n tens = deque()\n try:\n for i in bills:\n if i==5:\n fives.append(5)\n elif i==10:\n tens.append(10)\n fives.pop()\n else:\n if len(tens) !=0 and len(fives)!=0:\n tens.pop()\n fives.pop()\n else:\n fives.pop()\n fives.pop()\n fives.pop()\n except IndexError:\n return False\n return True\n\n", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n fives = 0\n tens = 0\n twenties = 0\n \n \n for i in bills:\n print(f'fives {fives}')\n print(f'tens {tens}')\n print(f'twenties {twenties}')\n if i == 5:\n fives += 1\n if i == 10:\n tens += 1\n if fives > 0:\n fives -= 1\n else:\n return False \n if i == 20:\n twenties += 1\n if tens > 0 and fives > 0:\n tens -= 1\n fives -= 1\n elif tens == 0 and fives > 2:\n fives -= 3\n else:\n return False\n return True\n\n \n \n\n \n \n", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n fives = 0\n tens = 0\n tweens = 0\n for bill in bills:\n if bill > 10:\n tweens+=1\n if tens > 0 and fives > 0:\n tens-=1\n fives-=1\n elif fives > 2:\n fives-=3\n else:\n return False\n elif bill == 10:\n tens+=1\n if fives > 0:\n fives-=1\n else:\n return False\n else:\n fives+=1\n return True\n", "class Solution:\n stack = {\n 5: 0,\n 10: 0,\n 20: 0\n }\n \n def change(self, value: int):\n self.stack[value] += 1\n res = True\n \n if value == 10:\n if self.stack[5] > 0:\n self.stack[5] -= 1\n else:\n res = False\n \n if value == 20:\n if self.stack[10] > 0 and self.stack[5] > 0:\n self.stack[10] -= 1\n self.stack[5] -= 1\n elif self.stack[5] > 2:\n self.stack[5] -= 3\n else:\n res = False\n \n# print(self.stack)\n return res\n \n \n def lemonadeChange(self, bills: List[int]) -> bool:\n self.stack = {\n 5: 0,\n 10: 0,\n 20: 0\n }\n \n res = False\n for b in bills:\n res = self.change(b)\n if not res:\n break\n return res", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n five = ten = 0\n for num in bills:\n if num == 5:\n five += 1\n elif num == 10 and five:\n ten += 1\n five -= 1\n elif num == 20 and five and ten:\n five -= 1\n ten -= 1\n elif num == 20 and five >= 3:\n five -= 3\n else:\n return False\n return True\n", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n five = ten = 0\n for coin in bills:\n if coin == 5:\n five += 1\n if coin == 10:\n ten += 1\n if five != 0:\n five -= 1\n else:\n return False\n if coin == 20:\n if five == 0:\n return False\n elif five < 3 and ten == 0:\n return False\n elif ten >= 1 and five >= 1:\n ten -= 1\n five -= 1\n elif five >= 3:\n five -= 3\n return True", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n # num=[0,0]\n # for i in bills:\n # if i ==5:\n # num[0]+=1\n # elif i==10 and num[0]>=1:\n # num[1]+=1\n # num[0]-=1\n # elif i==20:\n # if (num[0]>=1 and num[1]>=1):\n # num[1]-=1\n # num[0]-=1\n # elif num[0]>=3:\n # num[0]-=3\n # else:\n # return False\n # else:\n # return False\n # return True\n \n five = ten = 0\n for i in bills:\n if i == 5: five += 1\n elif i == 10: five, ten = five - 1, ten + 1\n elif ten > 0: five, ten = five - 1, ten - 1\n else: five -= 3\n if five < 0: return False\n return True", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n five = 0\n ten = 0\n\n for b in bills:\n if b == 5:\n five += 1\n \n if b == 10:\n if five > 0:\n five -= 1\n ten += 1\n else:\n return False\n \n if b == 20:\n if ten > 0 and five > 0:\n ten -= 1\n five -= 1\n elif ten == 0 and five >= 3:\n five -= 3\n else:\n return False\n \n return True\n \n \n \n", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n five = 0\n ten = 0\n for bill in bills:\n if bill == 5:\n five += 1\n elif bill == 10:\n if five == 0:\n return False\n else:\n ten += 1\n five -= 1\n elif bill == 20:\n if ten > 0 and five > 0:\n ten -= 1\n five -= 1 \n elif five > 2:\n five -= 3\n else:\n return False\n return True", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n cash = {5: 0, 10: 0, 20:0}\n \n for i in bills:\n cash[i] += 1 \n if i - 5 == 15: \n if (cash[5] < 3) and (cash[10] < 1 or cash[5] < 1 ): \n print('false')\n return False\n else: \n if cash[10] >= 1 and cash[5] >= 1 : \n cash[10] -= 1\n cash[5] -= 1\n elif cash[5] >= 3:\n cash[5] -= 3\n \n if i - 5 == 5:\n if cash[5] < 1: \n print('false')\n return False \n else:\n cash[5] -= 1 \n return True \n \n \n", "class Solution:\n \n def lemonadeChange(self, bills: List[int]) -> bool: \n# n5 = 0\n# n10 = 0\n# while True: \n# ind10 = bills.index(10) if 10 in bills else 10000\n# ind20 = bills.index(20) if 20 in bills else 10000 \n \n# ind = min(ind10, ind20) \n# if ind ==10000:\n# return True\n \n# bill_type =bills[ind]\n# n5 += bills[:ind].count(5) \n \n# if bill_type==10: \n# if n5==0:\n# return False\n# n10+=1 \n# n5 -=1 \n# elif bill_type ==20: \n# if n5<3 and n5>0 and n10>0:\n# n10 -= 1; n5 -=1\n# elif n5 >=3:\n# n5 -= 3 \n# else:\n# return False\n \n# bills = bills[ind+1:] \n# # print(bills)\n \n# else:\n# return True\n\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 else:\n n5 -=1\n n10 +=1\n else:\n if n10>0 and n5 >0:\n n10 -=1\n n5 -=1\n elif n5>=3:\n n5-=3\n else:\n return False\n else:\n return True\n \n \n \n \n \n \n \n \n \n\n# def deter(part_bill):\n# n5 = part_bill.count(5)\n# n10 = part_bill.count(10)\n# n20 = part_bill.count(20)\n\n# if (n5 >= n10) and ( (15*n20 <= (5*(n5-n10) + 10*n10)) and (n5-n10)>=n20 ):\n# result = True\n# else:\n# result = False\n \n# rest5 = n5-n10\n# rest10 = \n \n# return result, n5-n10, n\n\n \n \n \n \n \n \n# for i in bills:\n \n# if i == 5:\n# changes.append(5)\n \n# elif i == 10:\n# if 5 in changes:\n# changes.remove(5)\n# changes.append(10)\n# else:\n# return False\n \n# else:\n# if 5 in changes and 10 in changes:\n# changes.remove(5)\n# changes.remove(10)\n# elif changes.count(5) >=3:\n# changes.remove(5)\n# changes.remove(5)\n# changes.remove(5) \n# else:\n# return False\n \n# return True\n\n \n \n \n", "class Solution(object): #aw\n def lemonadeChange(self, bills):\n five = ten = 0\n for bill in bills:\n if bill == 5:\n five += 1\n elif bill == 10:\n if not five: return False\n five -= 1\n ten += 1\n else:\n if ten and five:\n ten -= 1\n five -= 1\n elif five >= 3:\n five -= 3\n else:\n return False\n return True", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n count_5 = 0\n count_10 = 0\n for bill in bills:\n if bill == 5:\n count_5 += 1\n elif bill == 10:\n if count_5 < 1:\n return False\n else:\n count_5 -= 1\n count_10 += 1\n else:\n if count_10 >= 1 and count_5 >= 1:\n count_10 -= 1\n count_5 -= 1\n elif count_5 >= 3:\n count_5 -= 3\n else:\n return False\n \n return True\n \n", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n five, ten = 0, 0\n for bill in bills:\n if bill == 5:\n five += 1\n elif bill == 10:\n ten += 1\n five -= 1\n elif ten > 0:\n five -= 1\n ten -= 1\n else:\n five -= 3\n if five < 0:\n return False\n return True", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n table = dict.fromkeys([5,10,20],0)\n for p in bills:\n table[p] = table.get(p)+1\n key = p-5\n if key!=0:\n if key==5:\n value = table.get(5)\n if value>0:\n table[5] = value-1\n else:\n return False\n elif key==15:\n value10 = table.get(10)\n value5 = table.get(5)\n if value10>0 and value5>0:\n table[10] = value10-1\n table[5]=value5-1\n elif value5>3:\n table[5]=value5-3\n else:\n return False\n return True\n \n", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n cash = {20: 0,\n 10: 0,\n 5: 0}\n for paid in bills:\n refund = paid - 5\n if refund == 0:\n cash[5] += 1\n continue\n flag = False\n for note in cash:\n if cash[note]>= refund//note:\n cash[note] -= refund // note\n refund -= (refund// note) *note\n flag = True\n if not flag or refund>0:\n return False\n cash[paid] += 1\n return True\n", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n # num=[0,0]\n # for i in bills:\n # if i ==5:\n # num[0]+=1\n # elif i==10 and num[0]>=1:\n # num[1]+=1\n # num[0]-=1\n # elif i==20:\n # if (num[0]>=1 and num[1]>=1):\n # num[1]-=1\n # num[0]-=1\n # elif num[0]>=3:\n # num[0]-=3\n # else:\n # return False\n # else:\n # return False\n # return True\n \n five = ten = 0\n for bill in bills:\n if bill == 5:\n five += 1\n elif bill == 10:\n if not five: return False\n five -= 1\n ten += 1\n else:\n if ten and five:\n ten -= 1\n five -= 1\n elif five >= 3:\n five -= 3\n else:\n return False\n return True", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n change_5 = 0\n change_10 = 0\n for b in bills:\n if b == 5:\n change_5+=1\n if b==10:\n if change_5>0:\n change_5-=1\n change_10+=1\n else:\n return False\n if b==20:\n if change_10>0 and change_5>0:\n change_5-=1\n change_10-=1\n elif change_5>2:\n change_5-=3\n else:\n return False\n return True\n", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n num=[0,0]\n for i in bills:\n if i ==5:\n num[0]+=1\n elif i==10 and num[0]>=1:\n num[1]+=1\n num[0]-=1\n elif i==20:\n if (num[0]>=1 and num[1]>=1):\n num[1]-=1\n num[0]-=1\n elif num[0]>=3:\n num[0]-=3\n else:\n return False\n else:\n return False\n return True", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n fives = tens = 0\n \n for bill in bills:\n if bill == 5:\n fives += 1\n if bill == 10:\n if fives < 1:\n return False\n tens += 1\n fives -= 1\n if bill == 20:\n if (tens < 1 and fives < 3) or (fives < 1):\n return False\n elif (tens < 1):\n fives -= 3\n else:\n tens -= 1\n fives -= 1\n \n return True", "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 # else:\n # n5 -=1\n # n10 +=1\n # else:\n # if n10>0 and n5 >0:\n # n10 -=1\n # n5 -=1\n # elif n5>=3:\n # n5-=3\n # else:\n # return False\n # else:\n # return True\n \n five = ten = 0\n for i in bills:\n if i == 5: \n five += 1\n elif i == 10: \n five, ten = five - 1, ten + 1\n elif ten > 0: \n five, ten = five - 1, ten - 1\n else: \n five -= 3\n \n if five < 0: return False\n return True\n \n \n \n \n", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n n5, n10 = 0, 0\n for i in bills:\n if i == 5: \n n5 += 1\n elif i == 10: \n n10 += 1; \n n5 -= 1\n elif n10 > 0: \n n10 -= 1; \n n5 -= 1\n else: \n n5 -= 3\n if n5 < 0: \n return False\n return True\n", "class Solution:\n def lemonadeChange(self, arr: List[int]) -> bool:\n five=0\n ten=0\n twen=0\n for i in arr:\n if i==5:\n five+=1\n elif i==10:\n if five>0:\n five-=1\n ten+=1\n else:\n return False\n else:\n s=min(five,ten)\n if s>0:\n five-=1\n ten-=1\n elif five>2:\n five-=3\n else:\n return False\n return True\n", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n amount = [0 for i in range(2)]\n for bill in bills:\n if bill == 5:\n amount[0] += 1\n elif bill == 10:\n if amount[0] == 0:\n return False\n else:\n amount[1] += 1\n amount[0] -= 1\n elif bill == 20:\n if amount[1] > 0 and amount[0] > 0:\n amount[1] -= 1\n amount[0] -= 1 \n elif amount[0]>2:\n amount[0] -= 3\n else:\n return False\n return True", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n dic={5:0,10:0,20:0}\n for i in bills:\n if i==5:\n dic[5]+=1\n if i==10:\n if dic[5]<1:\n return False\n dic[10]+=1\n dic[5]-=1\n if i==20:\n dic[20]+=1 \n if dic[10]>=1 and dic[5]>=1:\n dic[5]-=1\n dic[10]-=1\n elif dic[10]<1 and dic[5]>=3:\n dic[5]-=3\n else:\n return False\n print((i,dic))\n return True\n \n \n", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n pocket = {5:0, 10:0, 20:0}\n for x in bills:\n if x == 5:\n pocket[x] += 1\n else:\n back = x - 5\n for k in [10, 5]:\n if back > 0 and pocket[k] > 0:\n deduct = min(pocket[k] , (back // k))\n back -= k * deduct\n pocket[k] -= deduct \n pocket[x] += 1\n if back > 0:\n return False\n \n return True\n \n", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n counter, counter1, counter2, i = 0,0,0,0\n wallet = {\n 5 : 0,\n 10 : 0,\n 20 : 0\n }\n while i < len(bills):\n if bills[i] == 5:\n counter += 1\n wallet[5] = counter\n elif bills[i] == 10:\n counter -= 1\n wallet[5] = counter\n counter1 += 1\n wallet[10] = counter1\n if counter < 0:\n return False\n \n elif bills[i] == 20:\n if counter >= 1 and counter1 >= 1 :\n counter -= 1\n wallet[5] = counter\n counter1 -= 1\n wallet[10] = counter1\n counter2 += 1\n wallet[20] = counter2\n elif counter >= 3:\n counter -= 3\n wallet[5] = counter\n counter2 += 1\n wallet[20] = counter2\n else:\n return False\n if counter < 0 or counter1 < 0:\n return False\n i += 1\n return True\n \n \n", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n \n register = {}\n \n for bill in bills:\n if bill == 5:\n register[5] = register.get(5,0)+1\n elif bill == 10:\n if 5 in register and register[5]>=1:\n register[5]-=1\n register[10] = register.get(10,0)+1\n else:\n return False\n elif bill == 20:\n if 5 in register and 10 in register and register[10]>=1 and register[5]>=1:\n register[5]-=1\n register[10]-=1\n register[20] = register.get(20,0)+1\n elif 5 in register and register[5]>=3:\n register[5]-=3\n register[20] = register.get(20,0)+1\n else:\n return False\n return True", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n five = 0\n ten = 0\n twenty = 0\n for coin in bills:\n if coin == 5:\n five += 1\n if coin == 10:\n ten += 1\n if five != 0:\n five -= 1\n else:\n return False\n if coin == 20:\n twenty += 1\n if five == 0:\n return False\n elif five < 3 and ten == 0:\n return False\n elif ten >= 1 and five >= 1:\n ten -= 1\n five -= 1\n elif five >= 3:\n five -= 3\n return True", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n _5 = 0\n _10 = 0\n for eachBill in bills:\n if eachBill == 5:\n _5+=1\n elif eachBill == 10:\n if _5>=1:\n _5-=1\n else:\n return False\n _10+=1\n elif eachBill == 20:\n if _10>=1 and _5>=1:\n _10-=1\n _5-=1\n elif _5>=3:\n _5-=3\n else:\n return False\n print(_5,_10,eachBill)\n return True", "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 else:\n n5 -=1\n n10 +=1\n else:\n if n10>0 and n5 >0:\n n10 -=1\n n5 -=1\n elif n5>=3:\n n5-=3\n else:\n return False\n else:\n return True\n \n \n \n \n \n", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n coins = {5: 0, 10: 0, 20:0}\n\n for x in bills:\n if x == 20:\n if (coins[10]):\n coins[10] -= 1\n coins[5] -= 1\n else:\n coins[5] -= 3\n\n if coins[10] < 0 or coins[5] < 0:\n return False\n elif x == 10:\n coins[5] -= 1\n\n if coins[5] < 0:\n return False\n\n coins[x] += 1\n return True\n", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n five = ten = 0\n for i in range(len(bills)):\n if bills[i]== 5:\n five += 1\n elif bills[i] == 10:\n if five >=1:\n ten += 1\n five -= 1\n else:\n return False\n else:\n if ten>=1 and five >=1:\n ten -=1\n five -=1\n elif five >=3:\n five -=3\n else:\n return False\n return True\n \n \n \n \n", "class Solution:\n def lemonadeChange(self, A: List[int]) -> bool:\n \n \n if A[0]!=5:\n return False\n if len(A)==0:\n return True\n \n dk={5:0,10:0,20:0}\n \n for i in range(len(A)):\n if A[i] in dk:\n dk[A[i]]+=1\n else:\n dk[A[i]]=1\n \n if A[i]==10:\n if dk[5]<1:\n return False\n else:\n dk[5]-=1\n if A[i]==20:\n if dk[5]>=1 and dk[10]>=1:\n dk[5]-=1 \n dk[10]-=1\n continue\n elif dk[5]>=3:\n dk[5]-=3\n else:\n return False\n return True\n \n", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n in_hand = {5: 0, 10: 0, 20: 0}\n for amount in bills:\n to_return = amount - 5\n if to_return == 15:\n if in_hand[5] and in_hand[10]:\n in_hand[5] -= 1\n in_hand[10] -= 1\n elif in_hand[5] >= 3:\n in_hand[5] -= 3\n else:\n return False\n elif to_return == 10:\n if in_hand[10]:\n in_hand[10] -= 1\n elif in_hand[5] >= 2:\n in_hand[5] -= 2\n else:\n return False\n elif to_return == 5:\n if in_hand[5]:\n in_hand[5] -= 1\n else:\n return False\n in_hand[amount] += 1\n return True", "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n bill_dict = {5:0,10:0,20:0}\n for i in range(len(bills)):\n if bills[i] == 20:\n if bill_dict[10] == 0:\n bill_dict[20] += 1\n bill_dict[5] -= 3\n else: \n bill_dict[20] += 1\n bill_dict[10] -= 1\n bill_dict[5] -= 1\n elif bills[i] == 10:\n bill_dict[10] += 1\n bill_dict[5] -= 1\n else:\n bill_dict[5] += 1\n if bill_dict[5] < 0 or bill_dict[10] < 0 or bill_dict[20] < 0:\n return False\n return True\n \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 considered valid. Example 1: Input: "()" Output: true Example 2: Input: "()[]{}" Output: true Example 3: Input: "(]" Output: false Example 4: Input: "([)]" Output: false Example 5: Input: "{[]}" Output: true
["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 elif i in dict.keys():\n if stack == [] or dict[i] != stack.pop():\n return False\n else:\n return False\n return not stack", "class Solution:\n def isValid(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n stack, lookup = [], {\"(\": \")\", \"{\": \"}\", \"[\": \"]\"}\n for parenthese in s:\n #print(parenthese)\n if parenthese in lookup.keys():\n stack.append(parenthese)\n elif len(stack) == 0 or lookup[stack.pop()] != parenthese:\n return False\n #print(stack)\n return len(stack) == 0", "class Solution:\n \n import re\n \n def isValid(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n \n while(s!=\"\"):\n len_orig = len(s)\n s = s.replace('()', '')\n s = s.replace('[]', '')\n s = s.replace('{}', '')\n if len(s) == len_orig:\n return False\n \n return True\n \n", "class Solution:\n def isValid(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n l=list(s)\n stack=[]\n if l[0]==\")\" or l[0]==\"]\" or l[0]==\"}\" or len(l)<2:\n return False\n else:\n stack.append(l[0])\n l=l[1:]\n while stack!=[] or l!=[]:\n if l==[]:\n return False\n else:\n if l[0]==\"(\" or l[0]==\"[\" or l[0]==\"{\":\n stack.append(l[0])\n else:\n if stack==[]:\n return False\n elif stack[-1]==\"(\" and l[0]==\")\":\n stack.pop()\n elif stack[-1]==\"[\" and l[0]==\"]\":\n stack.pop()\n elif stack[-1]==\"{\" and l[0]==\"}\":\n stack.pop()\n else:\n return False\n l=l[1:]\n \n \n return True", "class Solution:\n def isValid(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n correct = ['()', '[]', '{}']\n out = \"\"\n a = s\n while self.contains(a, correct):\n for sym in correct: \n a = a.replace(sym, '')\n if len(a)==0:\n return True\n else: \n return False\n \n def contains(self, st, chars):\n for ch in chars: \n if ch in st: \n return True \n return False\n", "class Solution:\n def isValid(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n if len(s)==0:return True\n stack=[]\n for i in s:\n if i=='(' or i=='{'or i=='[':\n stack.append(i)\n else:\n if len(stack)==0:return False\n j=stack.pop()\n if (j=='('and i!=')')or(j=='['and i!=']')or(j=='{'and i!='}'):\n return False\n return len(stack)==0\n", "class Solution:\n def isValid(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n if len(s)%2 != 0:\n return(False)\n \n stack=[]\n for i in range(len(s)):\n stack.append(s[i])\n if stack[0] == ')' or stack[0] == ']' or stack[0] == '}':\n return(False)\n if stack[-1] == ')' :\n if stack[-2] =='(':\n stack.pop()\n stack.pop()\n elif stack[-1] == ']' :\n if stack[-2] =='[':\n stack.pop()\n stack.pop()\n elif stack[-1] == '}':\n if stack[-2] =='{':\n stack.pop()\n stack.pop()\n if stack == []:\n return(True)\n else:\n return(False)", "class Solution:\n def isValid(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n lefty = ['(', '{', '[']\n D = { ')':'(', '}':'{', ']':'[' }\n L = []\n for b in s:\n if b in lefty:\n L.append(b)\n else:\n if len(L)==0 or D[b]!=L.pop():\n return False\n if len(L)!=0:\n return False\n else:\n return True\n", "class Solution:\n def isValid(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n \n # ###method1\n # while \"()\" in s or \"[]\" in s or \"{}\" in s:\n # s = s.replace(\"()\",\"\").replace(\"[]\",\"\").replace(\"{}\",\"\")\n # return len(s)==0\n \n stack = []\n dict = {\")\":\"(\", \"]\":\"[\", \"}\":\"{\"}\n for char in s:\n if char in list(dict.values()):\n stack.append(char)\n elif char in list(dict.keys()):\n if stack==[] or dict[char] != stack.pop():\n return False\n else:\n return False\n return stack==[]\n \n \n", "class Solution:\n \n # stack approach\n def isValid(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n \n open_chars = set(['(', '[', '{'])\n \n # matching open char for given closing char\n open_match = {')':'(', ']':'[', '}':'{'}\n \n # open chars found in input with no matching\n # closing char yet\n open_stack = []\n \n for ch in s:\n \n if ch in open_chars:\n \n open_stack.append(ch)\n \n else:\n \n if not open_stack \\\n or open_stack[-1] != open_match[ch]:\n \n return False\n \n open_stack.pop()\n \n return not open_stack\n", "class Solution:\n def isValid(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n while \"()\" in s or \"[]\" in s or \"{}\" in s:\n s = s.replace(\"()\",\"\").replace(\"[]\",\"\").replace(\"{}\",\"\")\n return len(s)==0\n", "class Solution:\n def isValid(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n n = len(s)\n if n == 0:\n return True\n \n if n % 2 != 0:\n return False\n \n while '()' in s or '{}' in s or '[]' in s:\n s = s.replace('{}','').replace('()','').replace('[]','')\n \n if s == '':\n return True\n else:\n return False", "class Solution:\n def isValid(self, s):\n while '()' in s or '{}' in s or '[]' in s:\n s = s.replace('{}','').replace('()','').replace('[]','')\n \n if s == '':\n return True\n else:\n return False\n \n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n", "class Solution:\n \n # stack approach\n def isValid(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n \n open_chars = set(['(', '[', '{'])\n \n # matching open char for given closing char\n open_match = {')':'(', ']':'[', '}':'{'}\n \n # open chars found in input with no matching\n # closing char yet\n open_stack = []\n \n for ch in s:\n \n if ch in open_chars:\n \n open_stack.append(ch)\n \n else:\n \n if not open_stack \\\n or open_stack[-1] != open_match[ch]:\n \n return False\n \n open_stack.pop()\n \n return not open_stack\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 num = x\n count = 1\n return arr[len(arr)-1]", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n n = len(arr) // 4\n for i in range(len(arr)):\n if arr[i] == arr[i + n]:\n return arr[i]\n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n a = list(set(arr))\n print(a)\n per = 0\n i = 0\n while per <= 0.25:\n b = a[i]\n per = arr.count(a[i]) / len(arr)\n i += 1\n return(b)", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n for i in set(arr):\n if arr.count(i)>0.25*len(arr):\n return i", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n \n setter = set(arr)\n a_fourth = len(arr)/4\n for elem in setter:\n if arr.count(elem) > a_fourth:\n return elem", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n s=set(arr)\n perc_val=0.25*len(arr)\n for e in s:\n if arr.count(e)>perc_val:\n return e\n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n len_25 = len(arr) * .25\n for item in set(arr):\n if arr.count(item) > len_25:\n return item", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n x=len(arr)/4\n i=0\n while i<len(arr):\n y=arr.count(arr[i])\n print(i)\n if y>x:\n return arr[i]\n i+=y\n \n \n \n \n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n x=len(arr)/4\n for i in arr:\n y=arr.count(i)\n if y>x:\n return i\n \n \n \n \n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n for num in set(arr):\n if (arr.count(num) / len(arr)) * 100 > 25:\n return num", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n for i in arr:\n if arr.count(i) > len(arr) / 4:\n return i\n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n \n arrlen = len(arr)\n \n arrcnt = Counter(arr)\n \n for key, val in arrcnt.items():\n if val*4>arrlen:\n return key", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n for i in set(arr):\n if arr.count(i)>len(arr)/4:\n return i\n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n temp=list(set(arr))\n for i in range(len(temp)):\n if (arr.count(temp[i]))/len(arr)>0.25:\n return temp[i]\n\n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n sets = set(arr)\n \n for num in sets:\n s = arr.count(num)\n if s > len(arr) / 4:\n return num\n \n \n return None\n \n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n unique_nums = list(dict.fromkeys(arr))\n \n for unique_num in unique_nums:\n if (arr.count(unique_num) / len(arr)) > 0.25:\n return unique_num\n", "\nclass Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n val = len(arr)*0.25\n for i in set(arr):\n if arr.count(i)>val:\n return i\n break\n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n arrLen = len(arr)\n maxCount = 0\n maxCountNumber=0\n arrDict = {}\n for i in range(arrLen):\n if arr[i] not in arrDict:\n arrDict[arr[i]] = i\n numCount = arr.count(arr[i])\n if numCount > maxCount:\n maxCountNumber = arr[i]\n maxCount = numCount\n return maxCountNumber\n \n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n if len(arr) == 1:\n return arr[0]\n else:\n appear = -(-len(arr) // 4)\n dict ={}\n for i in arr:\n if i not in dict:\n dict[i] = 1\n else:\n dict[i] += 1\n if dict[i] > appear:\n return i", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n x=len(arr)/4\n i=0\n while i<len(arr):\n y=arr.count(arr[i])\n if y>x:\n return arr[i]\n i+=y\n \n \n \n \n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n return [i for i in set(arr) if arr.count(i) > len(arr)/4][0]\n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n quarter = len(arr) / 4\n count = 0\n temp = []\n \n for item in arr:\n if item not in temp:\n temp.append(item)\n \n for item in temp:\n count = arr.count(item)\n if count > quarter:\n return item", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n unique_values = list()\n for i in range(0, len(arr)):\n if arr[i] not in unique_values:\n unique_values.append(arr[i])\n for j in range(0, len(unique_values)):\n if arr.count(unique_values[j])/len(arr)>0.25:\n return unique_values[j]\n \n \n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n \n \n k = list(set(arr))\n\n#print(k)\n\n tmp = []\n\n size = len(arr)\n\n\n\n for i in k:\n tmp.append(arr.count(i))\n\n maximum = max(tmp)\n\n indexing = tmp.index(maximum)\n\n z = (maximum / size)*100\n\n if(z>=25):\n return (k[indexing])\n else:\n return 0", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n k=list(set(arr))\n tmp=[]\n for i in k:\n tmp.append(arr.count(i))\n max1=max(tmp)\n index=tmp.index(max1)\n print(k[index])\n if max1>(len(arr)/4):\n return k[index]", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n condensed = set(arr)\n counter = 0\n digit = 0\n print(condensed)\n for i in condensed:\n temp = arr.count(i)\n if counter < temp:\n counter = temp\n digit = i\n return (digit)\n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n '''\n # fisrt solution\n if len(arr)==1: return arr[0]\n step = 1 if len(arr)<8 else len(arr)//4 \n for i in range(len(arr)):\n if arr[i]==arr[i+step]: return arr[i]\n '''\n return max(set(arr), key = arr.count)", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n l = len(arr)//4\n for i in range(len(arr)-l):\n if arr[i]==arr[i+l]:\n return arr[i]", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n for ar in arr:\n a = self.find(arr, ar,True)\n b = self.find(arr, ar,False)\n if (b - a + 1) > len(arr) * 0.25:\n return ar\n\n def find(self, arr, value, fromLeft: bool):\n left = 0\n right = len(arr) - 1\n\n index = -1\n\n while left <= right:\n mid = (left + right) // 2\n midValue = arr[mid]\n\n if midValue == value:\n index = mid\n break\n\n if value < midValue:\n right = mid\n else:\n left = mid\n\n\n if fromLeft:\n while index > 0:\n if arr[index] == arr[index-1]:\n index -= 1\n else:\n break\n\n return index\n else:\n while index < (len(arr)-1):\n if arr[index] == arr[index + 1]:\n index += 1\n else:\n break\n\n\n return index", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n if(len(arr)==1):\n return arr[-1]\n \n k= int(len(arr)//4) + 1\n c=1\n for i in range(1,len(arr)):\n if(arr[i-1]==arr[i]):\n c+=1\n if(c>=k):\n return arr[i]\n else:\n c=1\n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n count = {}\n for num in arr:\n count[num] = count.get(num, 0) + 1\n if count[num] > len(arr) * 0.25:\n return num\n \n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n rate = len(arr) // 4\n \n count = [0 for i in range(100001)]\n \n for idx, value in enumerate(arr):\n count[value] += 1\n \n if count[value] > rate:\n return value\n \n return 0", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n \n goal_count = len(arr) *.25\n temp_list = []\n \n for num in arr:\n if len(arr) == 1:\n return arr[0]\n elif len(temp_list) > goal_count:\n return temp_list[0]\n elif num in temp_list:\n temp_list.append(num)\n else:\n temp_list.clear()\n temp_list.append(num)\n return temp_list[0]\n \n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n d = {}\n \n for num in arr:\n d[num] = d.get(num,0) + 1\n \n for idx,val in d.items():\n if val > len(arr)*0.25:\n return idx", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n arrLen = len(arr)\n delta = arrLen//4\n if arrLen == 1:\n return arr[0]\n \n pre = ''\n i = 0\n while i < arrLen - delta:\n if arr[i] != pre:\n pre = arr[i]\n if arr[i+delta] == pre:\n return pre\n i += 1\n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n if len(arr) == 1:\n return arr[0]\n \n limit = len(arr) // 4\n curr = arr[0]\n count = 1\n \n # print(len(arr), limit)\n \n for i in range(1, len(arr)):\n if arr[i] != curr:\n curr = arr[i]\n count = 1\n continue\n else:\n count += 1\n if count > limit:\n return curr\n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n if len(arr) <= 2:\n return arr[0]\n lim = len(arr) // 4\n count = 1\n for num1, num2 in zip(arr, arr[1:]):\n if num1 == num2:\n count += 1\n if count > lim:\n return num1\n else:\n count = 1", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n if len(arr) == 0:\n return -1 \n if len(arr) == 1:\n return arr[0]\n \n p1 = p2 = 0\n arrLen = len(arr)\n while p2 < arrLen:\n if arr[p2] != arr[p1]:\n if (p2 - p1) / arrLen > 0.25:\n return arr[p1]\n p1 = p2\n p2 += 1\n return arr[p2 - 1]", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n num_dict = {}\n for num in arr:\n if num in num_dict:\n num_dict[num] +=1\n else:\n num_dict[num] = 1\n \n return max(num_dict, key=lambda k: num_dict[k])", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n count = 0\n maxCount = 0\n maxInt = arr[0]\n currInt = arr[0]\n for x in arr:\n if x != currInt:\n if count > maxCount:\n maxCount = count\n maxInt = currInt\n currInt = x\n count = 1\n else:\n count += 1\n if count > maxCount:\n maxCount = count\n maxInt = currInt\n return maxInt", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n # get 25% length of arr.\n div = len(arr) // 4\n # go through array and use div to check if an element spans to that length, if it does, special integer found.\n for i in range(len(arr) - div):\n if arr[i] == arr[i + div]:\n return arr[i]", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n d = Counter(arr)\n d = sorted(list(d.items()), key = lambda x: x[1], reverse = True)\n return d[0][0]\n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n \n n = len(arr)//4\n for i in range(len(arr)):\n if arr[i] == arr[i+n]:\n return arr[i]\n \n", "from collections import Counter\nclass Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n # def bin_search_variant(low, high, prev_val):\n # mid = (high - low) // 2\n # if arr[mid] == prev_val:\n # return prev_val\n # elif arr[mid]:\n# if len(arr) == 1 or len(arr) == 2 or len(arr) == 3:\n# return arr[0]\n \n# cntr = Counter(arr).items()\n# for k, v in cntr:\n# if v > len(arr) / 4:\n# return k\n \n n = len(arr)\n if n <= 9: return self.findMode(arr)\n c = [\n arr[0],\n arr[(n-1)//8],\n arr[2*(n-1)//8],\n arr[3*(n-1)//8],\n arr[4*(n-1)//8],\n arr[5*(n-1)//8],\n arr[6*(n-1)//8],\n arr[7*(n-1)//8],\n arr[n-1]\n ]\n return self.findMode(c)\n \n def findMode(self, arr: List[int]) -> int:\n # this findMode can be furthur optimized given the input is also non-descending\n return collections.Counter(arr).most_common(1)[0][0]\n \n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n n = len(arr)\n d = n//4\n for i in range(n - 4):\n if arr[i] == arr[i+d]:\n return arr[i]\n return arr[-1]\n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n n = len(arr)/4\n freq ={}\n for i in arr:\n if i in freq:\n freq[i] += 1\n else:\n freq[i] = 1\n for k, v in list(freq.items()):\n if v > n:\n return k\n", "from collections import defaultdict\n\nclass Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n counts = defaultdict(int)\n for i in arr:\n counts[i] += 1\n return max(counts.items(), key=lambda x : x[1])[0]", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n d={}\n max1=0\n for i in arr:\n if i in d:\n d[i]=d[i]+1\n \n else:\n d[i]=1\n max1=max(d[i],max1)\n for i in d:\n if d[i]==max1:\n return i\n \n \n \n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n n = len(arr)\n threshold = n/4.0\n print (threshold)\n oldnum = None\n for num in arr:\n # print (oldnum, num)\n if oldnum==num: \n count += 1\n if count>threshold:\n return num\n else:\n count=1\n oldnum=num\n \n if count>threshold:\n return num", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n start = True\n \n d =0\n count=0\n \n if len(arr) == 1:\n return arr[0]\n \n for v in arr:\n if start:\n start=False\n d = v\n count = 1\n else:\n if v == d:\n count += 1\n if len(arr) % 4 == 0 and count > len(arr)/4:\n return v\n if len(arr) % 4 != 0 and count >= len(arr) // 4 + 1:\n return v\n else:\n d = v \n count = 1\n \n return 0\n", "from collections import defaultdict\nclass Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n \n \n count = 0\n \n thresh_count = int(.25*len(arr))\n dic = defaultdict(int)\n \n for ele in arr:\n dic[ele]+=1\n if dic[ele]> thresh_count:\n return ele\n \n \n \n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n b = {}\n for a in arr:\n if a not in b:\n b[a] = 1\n else:\n b[a] += 1\n c = [[k, v] for k, v in sorted(b.items(), key=lambda item: item[1])]\n return c[-1][0]", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n count = [0]*100001\n n = len(arr)\n for i in arr:\n count[i] += 1\n for i in range(len(count)):\n if(count[i] > int(0.25*n)):\n return i\n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n minCount = len(arr)//4\n temp = 0\n pp = 0\n for i in range(len(arr)):\n if pp == arr[i]:\n temp += 1\n else:\n temp = 0\n if temp >= minCount:\n return arr[i]\n pp = arr[i]\n \n \n \n \n # from collections import Counter\n # c = Counter(arr)\n # return list(c.most_common(1))[0][0]\n", "import numpy as np\nclass Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n # temp=np.unique(arr)\n # le = len(arr)\n # for i in temp:\n # if (arr.count(i)/le>0.25):\n # return i\n return collections.Counter(arr).most_common(1)[0][0]\n # print(collections.Counter(arr).most_common(1))\n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n from scipy import stats\n x=stats.mode(arr)\n y=int(x[1])*100/len(arr)\n if y>25:\n return int(x[0])\n \ns=Solution()\nprint(s.findSpecialInteger)", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n \n the_dict = {}\n for num in arr:\n the_dict[num] = the_dict.get(num, 0) + 1\n \n for item in list(the_dict.items()):\n if item[1] == max(the_dict.values()):\n return item[0]", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n cnt = collections.Counter(arr)\n \n for k, v in cnt.items():\n if v == max(cnt.values()):\n return k", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n from collections import Counter\n# p = len(arr)*0.25\n c = Counter(arr)\n# for i,j in c.items():\n# if float(j) > p:\n# return i\n for i,j in list(c.items()):\n if j==max(c.values()):\n return i\n \n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n len1 = int(len(arr)*0.25)\n count = 0\n sub =[]\n for i in arr:\n if i not in sub:\n sub.append(i)\n count = 1\n else:\n count+=1\n if count >len1:\n return i", "class Solution: # counters or 2 pointers\n from collections import Counter\n def findSpecialInteger(self, arr: List[int]) -> int:\n res = Counter(arr)\n ans = 0\n for key, value in list(res.items()): \n if value / sum(res.values()) > 0.25: # 25%\n ans = key\n return ans\n", "from collections import Counter\n\nclass Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n return [key for key, value in Counter(arr).items() if value > len(arr) // 4][0]", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n l = len(arr)\n bound = l/4\n s = set()\n for i in arr:\n if i not in s:\n if arr.count(i)>bound:\n return i\n s.add(i)", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n for i in range(len(arr)):\n if (arr.count(arr[i]) / len(arr)) > 0.25:\n s=arr[i]\n break\n return s \n \n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n uniq = list()\n [uniq.append(i) for i in arr if i not in uniq]\n occurs = {i:0 for i in arr}\n for i in arr:\n occurs[i] += 1\n return [key for key, val in list(occurs.items()) if val/len(arr) > 0.25][0]\n\n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n elem = 0\n for ar in arr:\n if arr.count(ar) > int(0.25*len(arr)):\n elem = ar\n break\n return elem", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n for i in arr:\n if arr.count(i) > len(arr)//4:\n return i", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n n=len(arr)//4\n for i in arr:\n if arr.count(i)>n:\n return i\n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n for i in arr:\n if arr.count(i) / len(arr) > 0.25:\n return i\n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n for i in arr:\n x = arr.count(i)\n perc = float(x)/float(len(arr))\n if perc > 0.25:\n return i\n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n for n in arr:\n if arr.count(n)/len(arr) > 0.25:\n return n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n quarter = len(arr)//4\n count = 1\n for i in range(len(arr)):\n if i==len(arr)-1:\n return arr[i]\n if arr[i]==arr[i+1]:\n count+=1\n if count>quarter:\n return arr[i]\n else:\n count=1\n \n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n for i in arr:\n if float(arr.count(i)/len(arr))>0.25:\n return i\n \n \n \n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n l=len(arr)\n l=l/4\n for i in arr:\n if arr.count(i)>l:\n return i\n \n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n for i in arr:\n if arr.count(i) > len(arr) // 4:\n return i\n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n mark = len(arr) // 4\n for x in arr:\n if mark < arr.count(x):\n return x", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n for i in arr:\n if float(arr.count(i)/len(arr))>0.25:\n return i", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n l=len(arr)\n a=l//4\n for i in arr:\n if arr.count(i)>a:\n return i\n return -1 ", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n largeArr = {}\n tempCount = 0\n for num in arr:\n if num in largeArr:\n tempCount = tempCount + 1\n largeArr[num] = tempCount\n else:\n tempCount = 1\n largeArr[num] = tempCount\n max1 = max(largeArr.values())\n for key in list(largeArr.keys()):\n if largeArr[key] == max(largeArr.values()):\n return key\n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n for i in arr:\n if(arr.count(i)>len(arr)*25//100):\n return(i)\n break", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n counts = dict()\n for i in arr:\n counts[i] = counts.get(i, 0) + 1\n \n return max(counts, key=counts.get)", "class Solution:\n def findSpecialInteger(self, l: List[int]) -> int:\n for i in l:\n if l.count(i)>len(l)/4:\n return i", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n cnt = len(arr) * 0.25\n for i in arr:\n if arr.count(i) > cnt:\n return i", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n num = 0.25*len(arr)\n for item in arr:\n if arr.count(item)>num:\n return item", "class Solution:\n def findSpecialInteger(self, nums: List[int]) -> int:\n percent = len(nums)*0.25\n for I in nums:\n if nums.count(I) > percent:\n return I\n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n for i in arr:\n if arr.count(i)/len(arr) > 0.25:\n return i", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n dic = Counter(arr)\n return [k for k,v in dic.items() if v==max(dic.values())][0]", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n\n threshold = len(arr)//4\n numdic = {}\n for num in arr:\n\n if str(num) not in numdic:\n numdic[str(num)] = 1\n else:\n numdic[str(num)] += 1\n\n if numdic[str(num)] > threshold:\n return num\n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n nums = list(set(arr))\n for i in nums:\n if(arr.count(i) >= (len(arr)//4) + 1):\n return i\n return False", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n arr1 = set(arr) #-- to remove duplicate for iteration purpose only\n \n cutoff = len(arr)*0.25\n \n for item in arr1:\n if arr.count(item) > cutoff:\n return(item)\n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n for num in set(arr):\n if arr.count(num)/len(arr) > 0.25:\n return num", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n for num in arr:\n if arr.count(num) > (len(arr)//4):\n return num", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n count = 0.25*len(arr)\n arr1 = list(set(arr))\n for ele in arr1:\n if arr.count(ele)>count:\n return ele \n \n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n unique = set(arr)\n for i in unique:\n if arr.count(i) > len(arr)//4:\n return i", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n for item in set(arr):\n l = len(arr)\n if arr.count(item) > l/4:\n return item", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n \n a = len(arr)*0.25\n value =0\n a1 = int(a)\n \n print(a1)\n \n dict1 ={}\n \n \n for i in arr:\n dict1[i] = dict1.get(i,0)+1\n \n for i in arr:\n if dict1.get(i) > a1:\n value = i\n \n return value", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n for num in set(arr):\n if arr.count(num) > len(arr) / 4:\n return num", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n arr1 = list(set(arr))\n for ele in arr1:\n if arr.count(ele)>(0.25*len(arr)):\n return ele \n \n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n\n for n in set(arr):\n if arr.count(n) > len(arr) * 0.25:\n return n\n\n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n c = len(arr) // 4\n for i in set(arr):\n if arr.count(i) > c:\n return i\n", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n n=int(len(arr)/4)\n for i in set(arr):\n if arr.count(i)>n:\n return i", "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n len_arr = len(arr)\n\n for n in set(arr):\n if arr.count(n) > len_arr * 0.25:\n return n\n\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.   Example 1: Input: n = 5 Output: 12 Explanation: For example [1,2,5,4,3] is a valid permutation, but [5,2,3,4,1] is not because the prime number 5 is at index 1. Example 2: Input: n = 100 Output: 682289015   Constraints: 1 <= n <= 100
["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 = sum(primes[2:])\n return math.factorial(cnt) * math.factorial(n - cnt) % (10**9 + 7) ", "class Solution:\n def numPrimeArrangements(self, n: int) -> int:\n # there are 25 primes from 1 to 100\n \n primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]\n \n for i in range(len(primes)):\n if primes[i] > n:\n break\n count = i\n print(count)\n return math.factorial(count) % (10**9 + 7) * math.factorial(n - count) % (10**9 + 7) \n \n", "class Solution:\n def numPrimeArrangements(self, n: int) -> int:\n p_nums = []\n c_nums = []\n dp = [True for _ in range(n+1)]\n dp[0] = False\n dp[1] = False\n for i in range(2, n+1):\n if dp[i] == True:\n cnt = 2\n while i*cnt < n+1:\n dp[i*cnt] = False\n cnt += 1\n \n for i in range(1, n+1):\n if dp[i]:\n p_nums += [i]\n else:\n c_nums += [i]\n\n #return (self.fact(len(p_nums))*self.fact(len(c_nums)))%(10**9+7) ===ok\n #\u6a21\u8fd0\u7b97\u89c4\u5219\uff1a(a * b) % m = ((a % m) * b) % m \u8bc1\u660e\u65b9\u6cd5\u8bf7\u81ea\u884c\u641c\u7d22\n return (self.fact(len(p_nums) % (10**9+7))*self.fact(len(c_nums)) % (10**9+7) )\n \n def fact(self, n):\n if n <= 1:\n return 1\n else:\n return n*self.fact(n-1)\n\n \n '''\n \u9898\u76ee\u63cf\u8ff0\n\n\u4e2d\u6587\uff1a\u8d28\u6570\u6392\u5217\n\u82f1\u8bed\uff1aPrime Arrangements\n\n\u89e3\u9898\u601d\u8def\n\n\u7406\u89e3\u9898\u610f\uff0c\u662f\u8981\u6c421\u5230n\u7684\u6392\u5217\u7ec4\u5408\u6570\uff0c\u4f46\u5e76\u4e0d\u662f\u5168\u6392\u5217\uff0c\u800c\u662f1\u5230n\u4e2d\u6240\u6709\u8d28\u6570\u4e2a\u6570\u7684\u9636\u4e58\u548c\u975e\u8d28\u6570\u4e2a\u6570\u7684\u9636\u4e58\u7684\u4e58\u79ef\u5e76\u5bf910^9 + 7\u53731000000007\u53d6\u6a21\u8fd0\u7b97\u7684\u7ed3\u679c\u3002\n\u4ee5n=5\u4e3a\u4f8b\uff0c1\u52305\u4e2d\u67092\u30013\u30015\u51713\u4e2a\u8d28\u6570\uff0c\u975e\u8d28\u6570\u5219\u67091\u30014\u51712\u4e2a\uff0c\u5219\u7ed3\u679c\u4e3a(3! * 2!) % 1000000007 = 12\n\n\u4ee3\u7801\u5982\u4e0b\n\n\u9700\u8981\u7406\u89e3\u7684\u70b9 \u6a21\u8fd0\u7b97\u89c4\u5219\uff1a(a * b) % m = ((a % m) * b) % m \u8bc1\u660e\u65b9\u6cd5\u8bf7\u81ea\u884c\u641c\u7d22\n\n\u5c06\u6570\u5b57\u5206\u4e3a\u8d28\u6570\u548c\u975e\u8d28\u6570\u4e24\u90e8\u5206\u3002\n\u5047\u8bbe\u6709 p\u4e2a\u8d28\u6570\uff0c\u7b54\u6848\u5c31\u662f p!\u22c5(n\u2212p)!\n\n '''\n", "class Solution:\n def numPrimeArrangements(self, n: int) -> int:\n def fac(m):\n result = 1\n for i in range(1,m+1):\n result *= i\n return result\n def PrimeTell(m):\n if m == 1 or m == 4:\n return False\n if m == 2 or m == 3:\n return True\n for j in range(2, m//2):\n if m%j == 0:\n return False\n return True\n Sum = 0\n for i in range(1,n+1):\n if PrimeTell(i):\n Sum += 1\n return fac(Sum)*fac(n-Sum)% (10**9 + 7)\n", "class Solution:\n def numPrimeArrangements(self, n: int) -> int:\n if n == 1: return 1\n p = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97]\n if n < 98:\n lo,hi = 0,24\n while lo <= hi:\n mid = (hi-lo)//2 + lo\n if p[mid] == n: \n idx = mid + 1\n break\n elif p[mid-1] < n and n < p[mid]:\n idx = mid\n break\n elif p[mid] > n:\n hi = mid-1\n else:\n lo = mid+1\n else:\n idx = 25\n \n #print(idx)\n \n p_prod = 1\n for i in range(1,idx+1):\n p_prod = (p_prod*(i%1000000007))%1000000007\n \n c_prod = 1\n for i in range(1,n-idx+1):\n c_prod = (c_prod*(i%1000000007))%1000000007\n \n return (p_prod*c_prod) % 1000000007", "class Solution:\n def numPrimeArrangements(self, n: int) -> int:\n primes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,\n 61,67,71,73,79,83,89,97]\n r = sum(1 for p in primes if p <= n)\n a = 10**9 + 7\n ans = 1\n for i in range(1, min(r, n-r)+1):\n ans *= (i % a)**2\n ans %= a\n for i in range(min(r, n-r)+1, max(r, n-r)+1):\n ans *= i\n ans %= a\n return ans"]
{"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. Example 1: Input: words = ["w","wo","wor","worl", "world"] Output: "world" Explanation: The word "world" can be built one character at a time by "w", "wo", "wor", and "worl". Example 2: Input: words = ["a", "banana", "app", "appl", "ap", "apply", "apple"] Output: "apple" Explanation: Both "apply" and "apple" can be built from other words in the dictionary. However, "apple" is lexicographically smaller than "apply". Note: All the strings in the input will only contain lowercase letters. The length of words will be in the range [1, 1000]. The length of words[i] will be in the range [1, 30].
["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 < result) and all(word[ : i] in wordSet for i in range(1, len(word))):\n result = word;\n \n return result;", "class Solution:\n def longestWord(self, words):\n \"\"\"\n :type words: List[str]\n :rtype: str\n \"\"\"\n if len(words) == 0:\n return \"\"\n \n words.sort(key = lambda x: (len(x), x))\n memo = set()\n maxlen = 0\n maxword = \"\"\n for word in words:\n if len(word) <= 1:\n memo.add(word)\n maxlen = 1\n if maxword == \"\":\n maxword = word\n else:\n if word[:-1] in memo:\n memo.add(word)\n if len(word) > maxlen:\n maxlen = len(word)\n maxword = word\n \n return maxword\n", "class Solution:\n def longestWord(self, words):\n \"\"\"\n :type words: List[str]\n :rtype: str\n \"\"\"\n words.sort()\n words_set = set([''])\n longest = ''\n \n for word in words:\n if word[:-1] in words_set:\n words_set.add(word)\n if len(word) > len(longest):\n longest = word\n return longest\n", "class Solution:\n def longestWord(self, words):\n \"\"\"\n :type words: List[str]\n :rtype: str\n \"\"\" \n wset = set([\"\"])\n ans = \"\"\n for word in sorted(words): \n if word[:-1] in wset:\n wset.add(word)\n if len(word) > len(ans):\n ans = word \n return ans\n \n", "class Solution:\n def longestWord(self, words):\n \"\"\"\n :type words: List[str]\n :rtype: str\n \"\"\"\n \n words.sort()\n words_set, longest_word = set(['']), ''\n for word in words:\n if word[:-1] in words_set:\n words_set.add(word)\n if len(word) > len(longest_word):\n longest_word = word\n return longest_word", "class Solution:\n def longestWord(self, words):\n \"\"\"\n :type words: List[str]\n :rtype: str\n \"\"\"\n valid = {''}\n for word in sorted(words):\n if word[:-1] in valid:\n valid.add(word)\n return max(sorted(valid), key = len)", "class Solution:\n def longestWord(self, words):\n \n \n words.sort()\n longest_word=''\n word_list=list()\n words_set=set([''])\n for word in words:\n \n if word[:-1] in words_set :\n \n words_set.add(word)\n \n if len(longest_word)<len(word):\n longest_word=word\n \n return longest_word\n \n", "class Solution:\n def longestWord(self, words):\n ret, m = '', {''}\n for w in sorted(words):\n if w[:-1] in m:\n m.add(w)\n ret = max(ret, w, key=len)\n return ret\n", "class Solution:\n def longestWord(self, words):\n \"\"\"\n :type words: List[str]\n :rtype: str\n \"\"\"\n wordSet = set(words)\n \n words.sort(key=lambda c: (-len(c), c))\n for word in words:\n if all(word[:k] in wordSet for k in range(1, len(word))):\n return word\n return \"\"\n", "class Solution:\n def longestWord(self, words):\n \"\"\"\n :type words: List[str]\n :rtype: str\n \"\"\"\n \n words.sort()\n words_set, longest_word = set(['']), ''\n for word in words:\n if word[:-1] in words_set:\n words_set.add(word)\n if len(word) > len(longest_word):\n longest_word = word\n return longest_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 >>> print s set([1, 2, 3, 6, 7, 8, 9]) >>> s.remove(0) KeyError: 0 .discard(x) This operation also removes element x from the set. If element x does not exist, it does not raise a KeyError. The .discard(x) operation returns None. Example >>> s = set([1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> s.discard(5) >>> print s set([1, 2, 3, 4, 6, 7, 8, 9]) >>> print s.discard(4) None >>> print s set([1, 2, 3, 6, 7, 8, 9]) >>> s.discard(0) >>> print s set([1, 2, 3, 6, 7, 8, 9]) .pop() This operation removes and return an arbitrary element from the set. If there are no elements to remove, it raises a KeyError. Example >>> s = set([1]) >>> print s.pop() 1 >>> print s set([]) >>> print s.pop() KeyError: pop from an empty set =====Problem Statement===== You have a non-empty set s, and you have to execute N commands given in N lines. The commands will be pop, remove and discard. =====Input Format===== The first line contains integer n, the number of elements in the set s. The second line contains n space separated elements of set s. All of the elements are non-negative integers, less than or equal to 9. The third line contains integer N, the number of commands. The next N lines contains either pop, remove and/or discard commands followed by their associated value. =====Constraints===== 0 < n < 20 0 < N < 20 =====Output Format==== Print the sum of the elements of set s on a single line.
["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 = int(input())\n s = set(map(int, input().split())) \n num_cmds = int(input())\n \n for _ in range(num_cmds):\n cmd = list(input().strip().split(' '))\n if cmd[0] == 'pop':\n s.pop()\n elif cmd[0] == 'remove':\n s.remove(int(cmd[1]))\n elif cmd[0] == 'discard':\n s.discard(int(cmd[1]))\n \n print((sum(s)))\n\n\n__starting_point()"]
{"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+)','[email protected]') >>> m.group(0) # The entire match '[email protected]' >>> m.group(1) # The first parenthesized subgroup. 'username' >>> m.group(2) # The second parenthesized subgroup. 'hackerrank' >>> m.group(3) # The third parenthesized subgroup. 'com' >>> m.group(1,2,3) # Multiple arguments give us a tuple. ('username', 'hackerrank', 'com') groups() A groups() expression returns a tuple containing all the subgroups of the match. Code >>> import re >>> m = re.match(r'(\w+)@(\w+)\.(\w+)','[email protected]') >>> m.groups() ('username', 'hackerrank', 'com') groupdict() A groupdict() expression returns a dictionary containing all the named subgroups of the match, keyed by the subgroup name. Code >>> m = re.match(r'(?P<user>\w+)@(?P<website>\w+)\.(?P<extension>\w+)','[email protected]') >>> m.groupdict() {'website': 'hackerrank', 'user': 'myname', 'extension': 'com'} =====Problem Statement===== You are given a string S. Your task is to find the first occurrence of an alphanumeric character in (read from left to right) that has consecutive repetitions. =====Input Format===== A single line of input containing the string S. =====Constraints===== 0<len(S)<100 =====Output Format===== Print the first occurrence of the repeating character. If there are no repeating characters, print -1.
["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 match else -1))\n\n__starting_point()"]
{"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 = 2)) [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)] >>> >>> print list(product([1,2,3],[3,4])) [(1, 3), (1, 4), (2, 3), (2, 4), (3, 3), (3, 4)] >>> >>> A = [[1,2,3],[3,4,5]] >>> print list(product(*A)) [(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 3), (3, 4), (3, 5)] >>> >>> B = [[1,2,3],[3,4,5],[7,8]] >>> print list(product(*B)) [(1, 3, 7), (1, 3, 8), (1, 4, 7), (1, 4, 8), (1, 5, 7), (1, 5, 8), (2, 3, 7), (2, 3, 8), (2, 4, 7), (2, 4, 8), (2, 5, 7), (2, 5, 8), (3, 3, 7), (3, 3, 8), (3, 4, 7), (3, 4, 8), (3, 5, 7), (3, 5, 8)] =====Problem Statement===== You are given a two lists A and B. Your task is to compute their cartesian product AXB. Example A = [1, 2] B = [3, 4] AxB = [(1, 3), (1, 4), (2, 3), (2, 4)] Note: A and B are sorted lists, and the cartesian product's tuples should be output in sorted order. =====Input Format===== The first line contains the space separated elements of list A. The second line contains the space separated elements of list B. Both lists have no duplicate integer elements. =====Constraints===== 0<A<30 0<B<30 =====Output Format===== Output the space separated tuples of the cartesian product.
["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 arr2 = list(map(int, input().strip().split(' ')))\n \n for el in product(arr1, arr2):\n print(\"{} \".format(el), end='')\n \n__starting_point()"]
{"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-------- ------e-d-e------ ----e-d-c-d-e---- --e-d-c-b-c-d-e-- e-d-c-b-a-b-c-d-e --e-d-c-b-c-d-e-- ----e-d-c-d-e---- ------e-d-e------ --------e-------- #size 10 ------------------j------------------ ----------------j-i-j---------------- --------------j-i-h-i-j-------------- ------------j-i-h-g-h-i-j------------ ----------j-i-h-g-f-g-h-i-j---------- --------j-i-h-g-f-e-f-g-h-i-j-------- ------j-i-h-g-f-e-d-e-f-g-h-i-j------ ----j-i-h-g-f-e-d-c-d-e-f-g-h-i-j---- --j-i-h-g-f-e-d-c-b-c-d-e-f-g-h-i-j-- j-i-h-g-f-e-d-c-b-a-b-c-d-e-f-g-h-i-j --j-i-h-g-f-e-d-c-b-c-d-e-f-g-h-i-j-- ----j-i-h-g-f-e-d-c-d-e-f-g-h-i-j---- ------j-i-h-g-f-e-d-e-f-g-h-i-j------ --------j-i-h-g-f-e-f-g-h-i-j-------- ----------j-i-h-g-f-g-h-i-j---------- ------------j-i-h-g-h-i-j------------ --------------j-i-h-i-j-------------- ----------------j-i-j---------------- ------------------j------------------ The center of the rangoli has the first alphabet letter a, and the boundary has the Nth alphabet letter (in alphabetical order). =====Input Format===== Only one line of input containing N, the size of the rangoli. =====Constraints===== 0 < N < 27 =====Output Format===== Print the alphabet rangoli in the format explained above.
["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_letter-1) / 2):\n letter_value = letter_value - 1\n else:\n letter_value = letter_value + 1 \n print((s.center(w,'-')))\n \n \n#bottom half\nfor i in range(n,0,-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_letter-1) / 2):\n letter_value = letter_value - 1\n else:\n letter_value = letter_value + 1 \n print((s.center(w,'-')))\n"]
{"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 contains the number of elements in set A. The second line of each test case contains the space separated elements of set A. The third line of each test case contains the number of elements in set B. The fourth line of each test case contains the space separated elements of set B. =====Constraints===== 0<T<21 0<Number of elements in each set<1001 =====Output Format===== Output True or False for each test case on separate lines.
["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 won't be counted. \n a = int(input()); A = set(input().split()) \n b = int(input()); B = set(input().split())\n print((len((A - B)) == 0))\n"]
{"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(lambda x, y : x + y,[1,2,3]) 6 You can also define an initial value. If it is specified, the function will assume initial value as the value given, and then reduce. It is equivalent to adding the initial value at the beginning of the list. For example: >>> reduce(lambda x, y : x + y, [1,2,3], -3) 3 >>> from fractions import gcd >>> reduce(gcd, [2,4,8], 3) 1 =====Input Format===== First line contains n, the number of rational numbers. The ith of next n lines contain two integers each, the numerator (N_i) and denominator (D_i) of the ith rational number in the list. =====Constraints===== 1≤n≤100 1≤N_i,D_i≤10^9 =====Output Format===== Print only one line containing the numerator and denominator of the product of the numbers in the list in its simplest form, i.e. numerator and denominator have no common divisor other than 1.
["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 result = product(fracs)\n print((*result))\n\n'''\n3\n1 2\n3 4\n10 6\n'''\n\n__starting_point()"]
{"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 = product(fracs) print(*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, 4: 2, 5: 1}) >>> >>> print Counter(myList).items() [(1, 3), (2, 4), (3, 4), (4, 2), (5, 1)] >>> >>> print Counter(myList).keys() [1, 2, 3, 4, 5] >>> >>> print Counter(myList).values() [3, 4, 4, 2, 1] =====Problem Statement===== Raghu is a shoe shop owner. His shop has X number of shoes. He has a list containing the size of each shoe he has in his shop. There are N number of customers who are willing to pay x_i amount of money only if they get the shoe of their desired size. Your task is to compute how much money Raghu earned. =====Input Format===== The first line contains X, the number of shoes. The second line contains the space separated list of all the shoe sizes in the shop. The third line contains N, the number of customers. The next N lines contain the space separated values of the shoe size desired by the customer and x_i, the price of the shoe. =====Constraints===== 0<X<10^3 0<N≤10^3 0<x_i<100 2<shoe size<20 =====Output Format===== Print the amount of money earned by Raghu.
["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 = int(input().strip())\n shoes = list(map(int, input().strip().split()))\n N = int(input().strip())\n result = 0\n \n warhs = Counter(shoes)\n for _ in range(N):\n size, money = map(int, input().strip().split(' '))\n \n if warhs[size] > 0:\n result += money\n warhs[size] -= 1\n \n print(result)\n__starting_point()"]
{"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. =====Input Format===== A single line of input consisting of the string S. =====Output Format===== A single line of output consisting of the modified string. =====Constraints===== All the characters of S denote integers between 0 and 9. 1≤|S|≤10^4 Sample Input 1222311 Sample Output (1, 1) (3, 2) (1, 3) (2, 1) Explanation First, the character occurs only once. It is replaced by . Then the character occurs three times, and it is replaced by and so on. Also, note the single space within each compression and between the compressions.
["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 itertools import groupby\n\ndef __starting_point():\n #in_data = input().strip().split(' ')\n \n for el, el_list in groupby(input()):\n print((len(list(el_list)), int(el)), end=' ')\n \n__starting_point()"]
{"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, 4]) print numpy.outer(A, B) #Output : [[0 0] # [3 4]] =====Problem Statement===== You are given two arrays: A and B. Your task is to compute their inner and outer product. =====Input Format===== The first line contains the space separated elements of array A. The second line contains the space separated elements of array B. =====Output Format===== First, print the inner product. Second, print the outer product.
["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().strip().split())))\n\nprint((np.inner(arr1, arr2)))\nprint((np.outer(arr1, arr2)))\n"]
{"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: [email protected] The username starts with an English alphabetical character, and any subsequent characters consist of one or more of the following: alphanumeric characters, -,., and _. The domain and extension contain only English alphabetical characters. The extension is 1, 2, or 3 characters in length. Given n pairs of names and email addresses as input, print each name and email address pair having a valid email address on a new line. Hint: Try using Email.utils() to complete this challenge. For example, this code: import email.utils print email.utils.parseaddr('DOSHI <[email protected]>') print email.utils.formataddr(('DOSHI', '[email protected]')) produces this output: ('DOSHI', '[email protected]') DOSHI <[email protected]> =====Input Format===== The first line contains a single integer, n, denoting the number of email address. Each line i of the n subsequent lines contains a name and an email address as two space-separated values following this format: name <[email protected]> =====Constraints===== 0<n<100 =====Output Format===== Print the space-separated name and email address pairs containing valid email addresses only. Each pair must be printed on a new line in the following format: name <[email protected]> You must print each valid email address in the same order as it was received as input.
["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 = int(input().strip())\nfor _ in range(t):\n name, email = input().strip().split()\n \n if re.match(r'<[A-Za-z](\\w|-|\\.|_)+@[A-Za-z]+\\.[A-Za-z]{1,3}>', email):\n print(\"{} {}\".format(name, email))"]
{"inputs": ["2\nDEXTER <[email protected]>\nVIRUS <virus!@variable.:p>"], "outputs": ["DEXTER <[email protected]>"]}
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 width. >>> width = 20 >>> print 'HackerRank'.center(width,'-') -----HackerRank----- .rjust(width) This method returns a right aligned string of length width. >>> width = 20 >>> print 'HackerRank'.rjust(width,'-') ----------HackerRank =====Problem Statement===== You are given a partial code that is used for generating the HackerRank Logo of variable thickness. Your task is to replace the blank (______) with rjust, ljust or center. =====Input Format===== A single line containing the thickness value for the logo. =====Constraints===== The thickness must be an odd number. 0 < thickness < 50 =====Output Format===== Output the desired logo.
["#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*thickness).center(thickness*6)))\n\n#Middle Belt\nfor i in range((thickness+1)//2):\n print(((c*thickness*5).center(thickness*6))) \n\n#Bottom Pillars\nfor i in range(thickness+1):\n print(((c*thickness).center(thickness*2)+(c*thickness).center(thickness*6))) \n\n#Bottom Cone\nfor i in range(thickness):\n print((((c*(thickness-i-1)).rjust(thickness)+c+(c*(thickness-i-1)).ljust(thickness)).rjust(thickness*6))) \n", "#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*thickness).center(thickness*6)))\n\n#Middle Belt\nfor i in range((thickness+1)//2):\n print(((c*thickness*5).center(thickness*6))) \n\n#Bottom Pillars\nfor i in range(thickness+1):\n print(((c*thickness).center(thickness*2)+(c*thickness).center(thickness*6))) \n\n#Bottom Cone\nfor i in range(thickness):\n print((((c*(thickness-i-1)).rjust(thickness)+c+(c*(thickness-i-1)).ljust(thickness)).rjust(thickness*6)))\n"]
{"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 HHHHH \n HHHHHHHHHHHHHHHHHHHHHHHHH \n HHHHHHHHHHHHHHHHHHHHHHHHH \n HHHHHHHHHHHHHHHHHHHHHHHHH \n HHHHH HHHHH \n HHHHH HHHHH \n HHHHH HHHHH \n HHHHH HHHHH \n HHHHH HHHHH \n HHHHH HHHHH \n HHHHHHHHH \n HHHHHHH \n HHHHH \n HHH \n H "]}
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).______(thickness*6)) #Middle Belt for i in range((thickness+1)//2): print((c*thickness*5).______(thickness*6)) #Bottom Pillars for i in range(thickness+1): print((c*thickness).______(thickness*2)+(c*thickness).______(thickness*6)) #Bottom Cone for i in range(thickness): print(((c*(thickness-i-1)).______(thickness)+c+(c*(thickness-i-1)).______(thickness)).______(thickness*6))
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.TextCalendar(firstweekday=6).formatyear(2015) 2015 January February March Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa 1 2 3 1 2 3 4 5 6 7 1 2 3 4 5 6 7 4 5 6 7 8 9 10 8 9 10 11 12 13 14 8 9 10 11 12 13 14 11 12 13 14 15 16 17 15 16 17 18 19 20 21 15 16 17 18 19 20 21 18 19 20 21 22 23 24 22 23 24 25 26 27 28 22 23 24 25 26 27 28 25 26 27 28 29 30 31 29 30 31 April May June Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa 1 2 3 4 1 2 1 2 3 4 5 6 5 6 7 8 9 10 11 3 4 5 6 7 8 9 7 8 9 10 11 12 13 12 13 14 15 16 17 18 10 11 12 13 14 15 16 14 15 16 17 18 19 20 19 20 21 22 23 24 25 17 18 19 20 21 22 23 21 22 23 24 25 26 27 26 27 28 29 30 24 25 26 27 28 29 30 28 29 30 31 July August September Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa 1 2 3 4 1 1 2 3 4 5 5 6 7 8 9 10 11 2 3 4 5 6 7 8 6 7 8 9 10 11 12 12 13 14 15 16 17 18 9 10 11 12 13 14 15 13 14 15 16 17 18 19 19 20 21 22 23 24 25 16 17 18 19 20 21 22 20 21 22 23 24 25 26 26 27 28 29 30 31 23 24 25 26 27 28 29 27 28 29 30 30 31 October November December Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa 1 2 3 1 2 3 4 5 6 7 1 2 3 4 5 4 5 6 7 8 9 10 8 9 10 11 12 13 14 6 7 8 9 10 11 12 11 12 13 14 15 16 17 15 16 17 18 19 20 21 13 14 15 16 17 18 19 18 19 20 21 22 23 24 22 23 24 25 26 27 28 20 21 22 23 24 25 26 25 26 27 28 29 30 31 29 30 27 28 29 30 31 =====Problem Statement===== You are given a date. Your task is to find what the day is on that date. =====Input Format===== A single line of input containing the space separated month, day and year, respectively, in MM DD YYYY format. =====Constraints===== 2000<year<3000 =====Output Format===== Output the correct day in capital letters.
["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[2], date[0], date[1])].upper())\n__starting_point()"]
{"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 is empty, it will return True. Code >>> all(['a'<'b','b'<'c']) True >>> all(['a'<'b','c'<'b']) False =====Problem Statement===== You are given a space separated list of integers. If all the integers are positive, then you need to check if any integer is a palindromic integer. =====Input Format===== The first line contains an integer N. N is the total number of integers in the list. The second line contains the space separated list of N integers. =====Constraints===== 0<N<100 =====Output Format===== Print True if all the conditions of the problem statement are satisfied. Otherwise, print False.
["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 arr = list(input().strip().split())\n print(all([all([int(x) > 0 for x in arr]), any([x == x[::-1] for x in arr])]))\n__starting_point()"]
{"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') None >>> print s set(['a', 'c', 'e', 'HackerRank', 'H', 'k', 'n', 'r', 'R']) =====Problem Statement===== Apply your knowledge of the .add() operation to help your friend Rupal. Rupal has a huge collection of country stamps. She decided to count the total number of distinct country stamps in her collection. She asked for your help. You pick the stamps one by one from a stack of N country stamps. Find the total number of distinct country stamps. =====Input Format===== The fist line contains an integer N, the total number of country stamps. The next N lines contains the name of the country where the stamp is from. =====Constraints===== 0<N<1000 =====Output Format===== Output the total number of distinct country stamps on a single line.
["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 stamps.add(stamp)\n \n print(len(stamps))\n__starting_point()"]
{"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. =====Input Format===== A single line of input containing the full name, S. =====Constraints===== 0<len(S)<1000 The string consists of alphanumeric characters and spaces. Note: in a word only the first character is capitalized. Example 12abc when capitalized remains 12abc. =====Output Format===== Print the capitalized string, S.
["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 integer n. =====Constraints===== 1≤n≤150 =====Output Format===== Print the list of integers from 1 through n as a string, without spaces.
["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 and then print the modified string. =====Example===== Example >>> string = "abracadabra" You can access an index by: >>> print string[5] a What if you would like to assign a value? >>> string[5] = 'k' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object does not support item assignment How would you approach this? One solution is to convert the string to a list and then change the value. Example >>> string = "abracadabra" >>> l = list(string) >>> l[5] = 'k' >>> string = ''.join(l) >>> print string abrackdabra Another approach is to slice the string and join it back. Example >>> string = string[:5] + "k" + string[6:] >>> print string abrackdabra =====Input Format===== The first line contains a string, S. The next line contains an integer i, denoting the index location and a character c separated by a space. =====Output Format===== Using any of the methods explained above, replace the character at index i with character c.
["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) This is very helpful in computations where you have to print the resultant % mod. Note: Here, a and b can be floats or negatives, but, if a third argument is present, b cannot be negative. Note: Python has a math module that has its own pow(). It takes two arguments and returns a float. Frankly speaking, we will never use math.pow(). =====Problem Statement===== You are given three integers: a, b, and m, respectively. Print two lines. The first line should print the result of pow(a,b). The second line should print the result of pow(a,b,m). =====Input Format===== The first line contains a, the second line contains b, and the third line contains m. =====Constraints===== 1≤a≤10 1≤b≤10 2≤m≤1000
["# 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 print(pow(a, b))\n print(pow(a, b, m))\n__starting_point()"]
{"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([ 3, 4 ]) print numpy.cross(A, B) #Output : -2 =====Problem Statement===== You are given two arrays A and B. Both have dimensions of NXN. Your task is to compute their matrix product. =====Input Format===== The first line contains the integer N. The next N lines contains N space separated integers of array A. The following N lines contains N space separated integers of array B. =====Output Format===== Print the matrix multiplication of A and B.
["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 numpy as np\n\nn = int(input().strip())\narr1 = np.array([[int(x) for x in input().strip().split()] for _ in range(n)])\narr2 = np.array([[int(x) for x in input().strip().split()] for _ in range(n)])\n\nprint(np.dot(arr1, arr2))"]
{"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 about re.sub(). Transformation of Strings Code import re #Squaring numbers def square(match): number = int(match.group(0)) return str(number**2) print re.sub(r"\d+", square, "1 2 3 4 5 6 7 8 9") Output 1 4 9 16 25 36 49 64 81 Replacements in Strings Code import re html = """ <head> <title>HTML</title> </head> <object type="application/x-flash" data="your-file.swf" width="0" height="0"> <!-- <param name="movie" value="your-file.swf" /> --> <param name="quality" value="high"/> </object> """ print re.sub("(<!--.*?-->)", "", html) #remove comment Output <head> <title>HTML</title> </head> <object type="application/x-flash" data="your-file.swf" width="0" height="0"> <param name="quality" value="high"/> </object> =====Problem Statement===== You are given a text of N lines. The text contains && and || symbols. Your task is to modify those symbols to the following: && → and || → or Both && and || should have a space " " on both sides. =====Input Format===== The first line contains the integer, N. The next N lines each contain a line of the text. =====Constraints===== 0<N<100 Neither && nor || occur in the start or end of each line. =====Output Format===== Output the modified text.
["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 return \"and\"\n elif symb == \"||\":\n return \"or\"\n \nn = int(input().strip())\nfor _ in range(n):\n print(re.sub(r'(?<= )(&&|\\|\\|)(?= )', change, input()))"]
{"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."], "outputs": ["a = 1;\nb = input();\n\nif a + b > 0 and a - b < 0:\n start()\nelif a*b > 10 or 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."]}
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] > Attribute_value2[2] Tag3 -> Attribute3[0] > Attribute_value3[0] The -> symbol indicates that the tag contains an attribute. It is immediately followed by the name of the attribute and the attribute value. The > symbol acts as a separator of attributes and attribute values. If an HTML tag has no attribute then simply print the name of the tag. Note: Do not detect any HTML tag, attribute or attribute value inside the HTML comment tags (<!-- Comments -->). Comments can be multiline. All attributes have an attribute value. =====Input Format===== The first line contains an integer N, the number of lines in the HTML code snippet. The next N lines contain HTML code. =====Constraints===== 0<N<100 =====Output Format===== Print the HTML tags, attributes and attribute values in order of their occurrence from top to bottom in the snippet. Format your answers as explained in the problem statement.
["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 print((\"-> {} > {}\".format(at[0], at[1])))\n\nhtml = \"\"\nfor i in range(int(input())):\n html += input().rstrip()\n html += '\\n'\n \nparser = MyHTMLParser()\nparser.feed(html)\nparser.close()\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/x-flash\n-> data > your-file.swf\n-> width > 0\n-> height > 0\nparam\n-> name > quality\n-> value > high"]}
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 text wrapped paragraph.
["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 characteristics: ► It must start with a 4, 5 or 6. ► It must contain exactly 16 digits. ► It must only consist of digits (0-9). ► It may have digits in groups of 4, separated by one hyphen "-". ► It must NOT use any other separator like ' ' , '_', etc. ► It must NOT have 4 or more consecutive repeated digits. =====Example===== Valid Credit Card Numbers 4253625879615786 4424424424442444 5122-2368-7954-3214 Invalid Credit Card Numbers 42536258796157867 #17 digits in card number → Invalid 4424444424442444 #Consecutive digits are repeating 4 or more times → Invalid 5122-2368-7954 - 3214 #Separators other than '-' are used → Invalid 44244x4424442444 #Contains non digit characters → Invalid 0525362587961578 #Doesn't start with 4, 5 or 6 → Invalid =====Input Format===== The first line of input contains an integer N. The next N lines contain credit card numbers. =====Constraints===== 0<N<100 =====Output Format===== Print 'Valid' if the credit card number is valid. Otherwise, print 'Invalid'. Do not print the quotes.
["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.findall(r'(?=(\\d)\\1\\1\\1)',credit_removed_hiphen))\n if length_16 == True or length_19 == True:\n if consecutive == True:\n valid=False\n else:\n valid = False \n if valid == True:\n print('Valid')\n else:\n print('Invalid')\n", "import re\n\ndef __starting_point():\n t = int(input().strip())\n \n for _ in range(t):\n num = \"\".join(input())\n if (re.match(r'^[456]', num) and\n (re.match(r'([\\d]{4}-){3}[\\d]{4}$', num) or\n re.match(r'[\\d]{16}', num)) and\n not re.search(r'(\\d)\\1{3,}', num.replace(\"-\", \"\"))):\n print(\"Valid\")\n else:\n print(\"Invalid\")\n\n__starting_point()"]
{"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 a new line. =====Example===== records = [["chi",20.0],["beta",50.0],["alpha",50.0]] The ordered list of scores is [20.0,50.0], so the second lowest score is 50.0. There are two students with that score: ["beta","alpha"]. Ordered alphabetically, the names are printed as: alpha beta =====Input Format===== The first line contains an integer, N, the number of students. The 2N subsequent lines describe each student over 2 lines. - The first line contains a student's name. - The second line contains their grade. =====Constraints===== 2≤N≤5 There will always be one or more students having the second lowest grade. =====Output Format===== Print the name(s) of any student(s) having the second lowest grade in. If there are multiple students, order their names alphabetically and print each one on a new line.
["# 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_val)\nval_ar.sort()\nsec_mark=val_ar[1]\n##print sec_mark \nfinal_ar=[]\nfor i in ar:\n if(sec_mark==ar[i]):\n final_ar.append(i)\n\nfinal_ar.sort()\nfor i in final_ar:\n print(i)\n", "def __starting_point():\n students = []\n for _ in range(int(input())):\n name = input()\n score = float(input())\n \n students.append([name, score])\n \n lowest = min([el[1] for el in students])\n second_low = min(list([a for a in [el[1] for el in students] if a > lowest]))\n \n out = [el[0] for el in students if (el[1] == second_low)]\n out.sort()\n \n print((\"\\n\".join(out)))\n\n__starting_point()"]
{"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 same type. import numpy a = numpy.array([1,2,3,4,5]) print a[1] #2 b = numpy.array([1,2,3,4,5],float) print b[1] #2.0 In the above example, numpy.array() is used to convert a list into a NumPy array. The second argument (float) can be used to set the type of array elements. =====Problem Statement===== You are given a space separated list of numbers. Your task is to print a reversed NumPy array with the element type float. =====Input Format===== A single line of input containing space separated numbers. =====Output Format===== Print the reverse NumPy array with type float.
["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. =====Input Format===== A single line of input contains the string S. =====Constraints===== 0<len(S)<1000 =====Output Format===== Output the sorted string S.
["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 '02468', x)), sep='')\n__starting_point()"]
{"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.] print numpy.add(a, b) #[ 6. 8. 10. 12.] print a - b #[-4. -4. -4. -4.] print numpy.subtract(a, b) #[-4. -4. -4. -4.] print a * b #[ 5. 12. 21. 32.] print numpy.multiply(a, b) #[ 5. 12. 21. 32.] print a / b #[ 0.2 0.33333333 0.42857143 0.5 ] print numpy.divide(a, b) #[ 0.2 0.33333333 0.42857143 0.5 ] print a % b #[ 1. 2. 3. 4.] print numpy.mod(a, b) #[ 1. 2. 3. 4.] print a**b #[ 1.00000000e+00 6.40000000e+01 2.18700000e+03 6.55360000e+04] print numpy.power(a, b) #[ 1.00000000e+00 6.40000000e+01 2.18700000e+03 6.55360000e+04] =====Problem Statement===== You are given two integer arrays, A and B of dimensions NXM. Your task is to perform the following operations: 1. Add (A + B) 2. Subtract (A - B) 3. Multiply (A * B) 4. Integer Division (A / B) 5. Mod (A % B) 6. Power (A ** B) =====Input Format===== The first line contains two space separated integers, N and M. The next N lines contains M space separated integers of array A. The following N lines contains M space separated integers of array B. =====Output Format===== Print the result of each operation in the given order under Task.
["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))\nprint((np_ar1 - np_ar2))\nprint((np_ar1 * np_ar2))\nprint((np_ar1 // np_ar2))\nprint((np_ar1 % np_ar2))\nprint((np_ar1 ** np_ar2))\n", "import numpy\n\nn, m = [int(x) for x in input().strip().split()]\n\na = numpy.array([[int(x) for x in input().strip().split()] for _ in range(n)])\nb = numpy.array([[int(x) for x in input().strip().split()] for _ in range(n)])\n\nprint((a + b))\nprint((a - b))\nprint((a * b))\nprint((a // b))\nprint((a % b))\nprint((a**b))\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, array_3)) #Output [1 2 3 4 5 6 7 8 9] If an array has more than one dimension, it is possible to specify the axis along which multiple arrays are concatenated. By default, it is along the first dimension. import numpy array_1 = numpy.array([[1,2,3],[0,0,0]]) array_2 = numpy.array([[0,0,0],[7,8,9]]) print numpy.concatenate((array_1, array_2), axis = 1) #Output [[1 2 3 0 0 0] [0 0 0 7 8 9]] =====Problem Statement===== You are given two integer arrays of size NXP and MXP (N & M are rows, and P is the column). Your task is to concatenate the arrays along axis 0. =====Input Format===== The first line contains space separated integers N, M and P . The next N lines contains the space separated elements of the P columns. After that, the next M lines contains the space separated elements of the P columns. =====Output Format===== Print the concatenated array of size (N + M)XP.
["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.concatenate((np_ar1,np_ar2),axis = 0)))\n", "import numpy\nn, m, p = [int(x) for x in input().strip().split()] \narr1 = []\narr2 = []\n\nfor _ in range(n):\n arr1.append([int(x) for x in input().strip().split()] )\n \nfor _ in range(m):\n arr2.append([int(x) for x in input().strip().split()] )\n \narr1 = numpy.array(arr1)\narr2 = numpy.array(arr2)\n\nprint(numpy.concatenate((arr1, arr2)))"]
{"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 >>> from itertools import combinations >>> >>> print list(combinations('12345',2)) [('1', '2'), ('1', '3'), ('1', '4'), ('1', '5'), ('2', '3'), ('2', '4'), ('2', '5'), ('3', '4'), ('3', '5'), ('4', '5')] >>> >>> A = [1,1,3,3,3] >>> print list(combinations(A,4)) [(1, 1, 3, 3), (1, 1, 3, 3), (1, 1, 3, 3), (1, 3, 3, 3), (1, 3, 3, 3)] =====Problem Statement===== You are given a string S. Your task is to print all possible combinations, up to size k, of the string in lexicographic sorted order. =====Constraints===== 0<k≤len(S) =====Input Format===== A single line containing the string S and integer value k separated by a space. =====Output Format===== Print the different combinations of string S on separate lines.
["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 lng in range(1, int(in_data[1])+1):\n for el in combinations(sorted(in_data[0]), lng):\n print(\"\".join(el))\n__starting_point()"]
{"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. 0.] [ 0. 0. 1.]] eye The eye tool returns a 2-D array with 1's as the diagonal and 0's elsewhere. The diagonal can be main, upper or lower depending on the optional parameter k. A positive k is for the upper diagonal, a negative k is for the lower, and a 0 k (default) is for the main diagonal. import numpy print numpy.eye(8, 7, k = 1) # 8 X 7 Dimensional array with first upper diagonal 1. #Output [[ 0. 1. 0. 0. 0. 0. 0.] [ 0. 0. 1. 0. 0. 0. 0.] [ 0. 0. 0. 1. 0. 0. 0.] [ 0. 0. 0. 0. 1. 0. 0.] [ 0. 0. 0. 0. 0. 1. 0.] [ 0. 0. 0. 0. 0. 0. 1.] [ 0. 0. 0. 0. 0. 0. 0.] [ 0. 0. 0. 0. 0. 0. 0.]] print numpy.eye(8, 7, k = -2) # 8 X 7 Dimensional array with second lower diagonal 1. =====Problem Statement===== Your task is to print an array of size NXM with its main diagonal elements as 1's and 0's everywhere else. =====Input Format===== A single line containing the space separated values of N and M. N denotes the rows. M denotes the columns. =====Output Format===== Print the desired NXM array.
["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 conditions are used to identify leap years: The year can be evenly divided by 4, is a leap year, unless: The year can be evenly divided by 100, it is NOT a leap year, unless: The year is also evenly divisible by 400. Then it is a leap year. This means that in the Gregorian calendar, the years 2000 and 2400 are leap years, while 1800, 1900, 2100, 2200, 2300 and 2500 are NOT leap years. Source Task Given a year, determine whether it is a leap year. If it is a leap year, return the Boolean True, otherwise return False. Note that the code stub provided reads from STDIN and passes arguments to the is_leap function. It is only necessary to complete the is_leap function. =====Input Format===== Read year, the year to test. =====Constraints===== 1900≤year≤10^5 =====Output Format===== The function must return a Boolean value (True/False). Output is handled by the provided code stub.
["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 the start and end of string k in S. =====Input Format===== The first line contains the string S. The second line contains the string k. =====Output Format===== Print the tuple in this format: (start_index, end_index) If no match is found, print (-1, -1).
["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_flag = True\nif found_flag == False:\n print('(-1, -1)')\n", "#!/usr/bin/env python3\n\nimport re\n\ndef __starting_point():\n string = input()\n sub = input()\n \n matches = list(re.finditer(r'(?={})'.format(sub), string))\n \n if matches:\n for match in matches:\n print((match.start(), match.end() + len(sub) - 1))\n else:\n print((-1, -1))\n__starting_point()"]
{"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 MyHTMLParser(HTMLParser): def handle_comment(self, data): print "Comment :", data .handle_data(data) This method is called to process arbitrary data (e.g. text nodes and the content of <script>...</script> and <style>...</style>). The data argument is the text content of HTML. from HTMLParser import HTMLParser class MyHTMLParser(HTMLParser): def handle_data(self, data): print "Data :", data =====Problem Statement===== You are given an HTML code snippet of N lines. Your task is to print the single-line comments, multi-line comments and the data. Print the result in the following format: >>> Single-line Comment Comment >>> Data My Data >>> Multi-line Comment Comment_multiline[0] Comment_multiline[1] >>> Data My Data >>> Single-line Comment: Note: Do not print data if data == '\n'. =====Input Format===== The first line contains integer N, the number of lines in the HTML code snippet. The next N lines contains HTML code. =====Constraints===== 0<N<100 =====Output Format===== Print the single-line comments, multi-line comments and the data in order of their occurrence from top to bottom in the snippet. Format the answers as explained in the problem statement.
["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():\n print(data)\n\n def handle_data(self, data):\n if data.strip():\n print(\">>> Data\")\n print(data)\n\nparser = CustomHTMLParser()\n\nn = int(input())\n\nhtml_string = ''\nfor i in range(n):\n html_string += input().rstrip()+'\\n'\n \nparser.feed(html_string)\nparser.close()\n", "from html.parser import HTMLParser\n\nclass MyHTMLParser(HTMLParser):\n def handle_comment(self, data):\n if data.count('\\n') > 0:\n print(\">>> Multi-line Comment\")\n else:\n print(\">>> Single-line Comment\")\n print(data)\n def handle_data(self, data):\n if len(data) > 1:\n print(\">>> Data\")\n print(data)\n\nhtml = \"\" \nfor i in range(int(input())):\n html += input().rstrip()\n html += '\\n'\n \nparser = MyHTMLParser()\nparser.feed(html)\nparser.close()\n"]
{"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<![endif]"]}
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 name. =====Constraints===== The length of the first and last name ≤ 10. =====Output Format===== Print the output as mentioned above.
["# 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 zero ValueError This error is raised when a built-in operation or function receives an argument that has the right type but an inappropriate value. >>> a = '1' >>> b = '#' >>> print int(a) / int(b) >>> ValueError: invalid literal for int() with base 10: '#' Handling Exceptions The statements try and except can be used to handle selected exceptions. A try statement may have more than one except clause to specify handlers for different exceptions. #Code try: print 1/0 except ZeroDivisionError as e: print "Error Code:",e Output Error Code: integer division or modulo by zero =====Problem Statement===== You are given two values a and b. Perform integer division and print a/b. =====Input Format===== The first line contains T, the number of test cases. The next T lines each contain the space separated values of a and b. =====Constraints===== 0<T<10 =====Output Format===== Print the value of a/b. In the case of ZeroDivisionError or ValueError, print the error code.
["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().strip().split(' ')\n \n try:\n print((int(a)//int(b)))\n except ZeroDivisionError as e:\n print((\"Error Code: {}\".format(e)))\n except ValueError as e:\n print((\"Error Code: {}\".format(e)))\n\n__starting_point()"]
{"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(my_array, axis = 1) #Output : [2 3 1 0] print numpy.min(my_array, axis = None) #Output : 0 print numpy.min(my_array) #Output : 0 By default, the axis value is None. Therefore, it finds the minimum over all the dimensions of the input array. max The tool max returns the maximum value along a given axis. import numpy my_array = numpy.array([[2, 5], [3, 7], [1, 3], [4, 0]]) print numpy.max(my_array, axis = 0) #Output : [4 7] print numpy.max(my_array, axis = 1) #Output : [5 7 3 4] print numpy.max(my_array, axis = None) #Output : 7 print numpy.max(my_array) #Output : 7 By default, the axis value is None. Therefore, it finds the maximum over all the dimensions of the input array. =====Problem Statement===== You are given a 2-D array with dimensions NXM. Your task is to perform the min function over axis 1 and then find the max of that. =====Input Format===== The first line of input contains the space separated values of N and M. The next N lines contains M space separated integers. =====Output Format===== Compute the min along axis 1 and then print the max of that result.
["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 x in input().strip().split()] for _ in range(n)])\nprint(np.max(np.min(array, axis = 1)))"]
{"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 = numpy.array([[1, 2],[3, 4],[6,5]]) print my_2D_array.shape #(3, 2) -> 3 rows and 2 columns (b). Using shape to change array dimensions import numpy change_array = numpy.array([1,2,3,4,5,6]) change_array.shape = (3, 2) print change_array #Output [[1 2] [3 4] [5 6]] reshape The reshape tool gives a new shape to an array without changing its data. It creates a new array and does not modify the original array itself. import numpy my_array = numpy.array([1,2,3,4,5,6]) print numpy.reshape(my_array,(3,2)) #Output [[1 2] [3 4] [5 6]] =====Problem Statement===== You are given a space separated list of nine integers. Your task is to convert this list into a 3X3 NumPy array. =====Input Format===== A single line of input containing 9 space separated integers. =====Output Format===== Print the 3X3 NumPy array.
["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 tool ceil returns the ceiling of the input element-wise. The ceiling of x is the smallest 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.ceil(my_array) #[ 2. 3. 4. 5. 6. 7. 8. 9. 10.] rint The rint tool rounds to the nearest integer of input element-wise. 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.rint(my_array) #[ 1. 2. 3. 4. 6. 7. 8. 9. 10.] =====Problem Statement===== You are given a 1-D array, A. Your task is to print the floor, ceil and rint of all the elements of A. =====Input Format===== A single line of input containing the space separated elements of array A. =====Output Format===== On the first line, print the floor of A. On the second line, print the ceil of A. On the third line, print the rint of A.
["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))\nprint(np.rint(array))"]
{"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 when both players have made all possible substrings. Scoring A player gets +1 point for each occurrence of the substring in the string S. =====Example===== String S = BANANA Kevin's vowel beginning word = ANA Here, ANA occurs twice in BANANA. Hence, Kevin will get 2 Points. Your task is to determine the winner of the game and their score. =====Input Format===== A single line of input containing the string S. Note: The string S will contain only uppercase letters: [A-Z]. =====Constraints===== 0 < len(S) < 10^6 =====Output Format===== Print one line: the name of the winner and their score separated by a space. If the game is a draw, print Draw.
["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 else:\n return 'Stuart '+str(player2)", "vowels = ['A', 'E', 'I', 'O', 'U']\n\ndef minion_game(string):\n score_kevin = 0\n score_stuart = 0\n \n for ind in range(len(string)):\n if string[ind] in vowels:\n score_kevin += len(string) - ind\n else:\n score_stuart += len(string) - ind\n \n if score_kevin > score_stuart:\n return 'Kevin '+ str(score_kevin)\n elif score_kevin < score_stuart:\n return 'Stuart '+ str(score_stuart)\n else:\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. =====Constraints===== 1≤n≤10^5 The sum of the lengths of all the words do not exceed 10^6 All the words are composed of lowercase English letters only. =====Input Format===== The first line contains the integer, n. The next n lines each contain a word. =====Output Format===== Output 2 lines. On the first line, output the number of distinct words from the input. On the second line, output the number of occurrences for each distinct word according to their appearance in the input.
["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=' ')\n", "#!/usr/bin/env python3\n\nfrom collections import OrderedDict\n\ndef __starting_point():\n num = int(input().strip())\n history = OrderedDict()\n \n for _ in range(num):\n word = str(input().strip().split())\n if word not in list(history.keys()):\n history[word] = 1\n else:\n history[word] += 1\n \n print((len(list(history.keys()))))\n print((\" \".join(map(str, list(history.values())))))\n\n__starting_point()"]
{"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 φ. If we convert complex number z to its polar coordinate, we find: r: Distance from z to origin, i.e., sqrt(x^2 + y^2) φ: Counter clockwise angle measured from the positive -axis to the line segment that joins z to the origin. Python's cmath module provides access to the mathematical functions for complex numbers. cmath.phase This tool returns the phase of complex number z (also known as the argument of z). >>> phase(complex(-1.0, 0.0)) 3.1415926535897931 abs This tool returns the modulus (absolute value) of complex number z. >>> abs(complex(-1.0, 0.0)) 1.0 =====Problem Statement===== You are given a complex z. Your task is to convert it to polar coordinates. =====Input Format===== A single line containing the complex number z. Note: complex() function can be used in python to convert the input as a complex number. =====Constraints===== Given number is a valid complex number =====Output Format===== Output two lines: The first line should contain the value of r. The second line should contain the value of φ.
["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']) >>> print set([1,2,1,2,3,4,5,6,0,9,12,22,3]) set([0, 1, 2, 3, 4, 5, 6, 9, 12, 22]) >>> print set((1,2,3,4,5,5)) set([1, 2, 3, 4, 5]) >>> print set(set(['H','a','c','k','e','r','r','a','n','k'])) set(['a', 'c', 'r', 'e', 'H', 'k', 'n']) >>> print set({'Hacker' : 'DOSHI', 'Rank' : 616 }) set(['Hacker', 'Rank']) >>> print set(enumerate(['H','a','c','k','e','r','r','a','n','k'])) set([(6, 'r'), (7, 'a'), (3, 'k'), (4, 'e'), (5, 'r'), (9, 'k'), (2, 'c'), (0, 'H'), (1, 'a'), (8, 'n')]) Basically, sets are used for membership testing and eliminating duplicate entries. =====Problem Statement===== Now, let's use our knowledge of sets and help Mickey. Ms. Gabriel Williams is a botany professor at District College. One day, she asked her student Mickey to compute the average of all the plants with distinct heights in her greenhouse. Formula used: Average = Sum of Distinct Heights / Total Number of Distinct Heights =====Input Format===== The first line contains the integer, N, the total number of plants. The second line contains the N space separated heights of the plants. =====Constraints===== 0<N≤100 =====Output Format===== Output the average height value on a single line.
["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 width of the binary value of n. =====Input Format===== A single integer denoting n. =====Constraints===== 1 ≤ n ≤ 99 =====Output Format===== Print n lines wehere each line i (in the range 1 ≤ i ≤ n) contains the respective decimal, octal, capitalized hexadecimal, and binary values of i. Each printed value must be formatted to the width of the binary value of n.
["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. =====Example===== Set([1,3,4]) is a strict superset of set([1,3]). Set([1,3,4]) is not a strict superset of set([1,3,4]). Set([1,3,4]) is not a strict superset of set(1,3,5). =====Input Format===== The first line contains the space separated elements of set A. The second line contains integer n, the number of other sets. The next n lines contains the space separated elements of the other sets. =====Constraints===== 0 < len(set(A)) < 501 0<N<21 0 < len(otherSets) < 101 =====Output Format===== Print True if set A is a strict superset of all other N sets. Otherwise, print False.
["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().strip())\n superset = True\n \n for _ in range(t):\n subset = set(map(int, input().strip().split(' ')))\n if len(subset - A) != 0 or len(A - subset) == 0:\n superset = False\n break\n \n print(superset)\n__starting_point()"]
{"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 written for you. You have to complete the print statement. Note: Using anything related to strings will give a score of 0. =====Input Format===== A single line containing integer, N. =====Constraints===== 1≤N≤9 =====Output Format===== Print N - 1 lines as explained above.
["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) #Output : 10 print numpy.sum(my_array) #Output : 10 By default, the axis value is None. Therefore, it performs a sum over all the dimensions of the input array. prod The prod tool returns the product of array elements over a given axis. import numpy my_array = numpy.array([ [1, 2], [3, 4] ]) print numpy.prod(my_array, axis = 0) #Output : [3 8] print numpy.prod(my_array, axis = 1) #Output : [ 2 12] print numpy.prod(my_array, axis = None) #Output : 24 print numpy.prod(my_array) #Output : 24 By default, the axis value is None. Therefore, it performs the product over all the dimensions of the input array. =====Problem Statement===== ou are given a 2-D array with dimensions NXM. Your task is to perform the sum tool over axis 0 and then find the product of that result. =====Output Format===== Compute the sum along axis 0. Then, print the product of that sum.
["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(x) for x in input().strip().split()] for _ in range(n)])\nprint(np.prod(np.sum(array, axis = 0)))"]
{"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 modulo operator is 177%10 => 7. Task Read in two integers, a and b, and print three lines. The first line is the integer division a//b (While using Python2 remember to import division from __future__). The second line is the result of the modulo operator: a%b. The third line prints the divmod of a and b. =====Input Format===== The first line contains the first integer, a, and the second line contains the second integer, b. =====Output Format===== Print the result as described above.
["# 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] [2 5] [3 6]] Flatten The tool flatten creates a copy of the input array flattened to one dimension. import numpy my_array = numpy.array([[1,2,3], [4,5,6]]) print my_array.flatten() #Output [1 2 3 4 5 6] =====Problem Statement===== You are given a NXM integer array matrix with space separated elements (N = rows and M = columns). Your task is to print the transpose and flatten results. =====Input Format===== The first line contains the space separated values of N and M. The next N lines contains the space separated elements of M columns. =====Output Format===== First, print the transpose array and then print the flatten.
["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 range(n):\n arr.append([int(x) for x in input().strip().split()])\nprint(numpy.array(arr).transpose())\nprint(numpy.array(arr).flatten())"]
{"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_array, axis = None) #Output : 2.5 print numpy.mean(my_array) #Output : 2.5 By default, the axis is None. Therefore, it computes the mean of the flattened array. var The var tool computes the arithmetic variance along the specified axis. import numpy my_array = numpy.array([ [1, 2], [3, 4] ]) print numpy.var(my_array, axis = 0) #Output : [ 1. 1.] print numpy.var(my_array, axis = 1) #Output : [ 0.25 0.25] print numpy.var(my_array, axis = None) #Output : 1.25 print numpy.var(my_array) #Output : 1.25 By default, the axis is None. Therefore, it computes the variance of the flattened array. std The std tool computes the arithmetic standard deviation along the specified axis. import numpy my_array = numpy.array([ [1, 2], [3, 4] ]) print numpy.std(my_array, axis = 0) #Output : [ 1. 1.] print numpy.std(my_array, axis = 1) #Output : [ 0.5 0.5] print numpy.std(my_array, axis = None) #Output : 1.118033988749895 print numpy.std(my_array) #Output : 1.118033988749895 By default, the axis is None. Therefore, it computes the standard deviation of the flattened array. =====Problem Statement===== You are given a 2-D array of size NXM. Your task is to find: The mean along axis 1 The var along axis 0 The std along axis None =====Input Format===== The first line contains the space separated values of N and M. The next N lines contains M space separated integers. =====Output Format===== First, print the mean. Second, print the var. Third, print the std.
["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 x in input().strip().split()]\narray = np.array([[int(x) for x in input().strip().split()] for _ in range(n)], dtype = float)\nprint(np.mean(array, axis = 1))\nprint(np.var(array, axis = 0))\nprint(np.std(array))"]
{"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 lexicographic sorted order. So, if the input iterable is sorted, the permutation tuples will be produced in a sorted order. Sample Code >>> from itertools import permutations >>> print permutations(['1','2','3']) <itertools.permutations object at 0x02A45210> >>> >>> print list(permutations(['1','2','3'])) [('1', '2', '3'), ('1', '3', '2'), ('2', '1', '3'), ('2', '3', '1'), ('3', '1', '2'), ('3', '2', '1')] >>> >>> print list(permutations(['1','2','3'],2)) [('1', '2'), ('1', '3'), ('2', '1'), ('2', '3'), ('3', '1'), ('3', '2')] >>> >>> print list(permutations('abc',3)) [('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a')] =====Problem Statement===== You are given a string S. Your task is to print all possible permutations of size k of the string in lexicographic sorted order. =====Input Format===== A single line containing the space separated string S and the integer value k. =====Output Format===== Print the permutations of the string S on separate lines.
["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 permutations(sorted(in_data[0]), int(in_data[1])):\n print(\"\".join(el))\n__starting_point()"]
{"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 integers each separated by a space. =====Constraints===== 2≤n≤10 -100≤A[i]≤ 100 =====Output Format===== Print the runner-up score.
["# 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, input().split()))\n first = max(arr)\n \n print((max(list([a for a in arr if a != first]))))\n\n__starting_point()"]
{"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]) #Output : [-1. 1.] polyint The polyint tool returns an antiderivative (indefinite integral) of a polynomial. print numpy.polyint([1, 1, 1]) #Output : [ 0.33333333 0.5 1. 0. ] polyder The polyder tool returns the derivative of the specified order of a polynomial. print numpy.polyder([1, 1, 1, 1]) #Output : [3 2 1] polyval The polyval tool evaluates the polynomial at specific value. print numpy.polyval([1, -2, 0, 2], 4) #Output : 34 polyfit The polyfit tool fits a polynomial of a specified order to a set of data using a least-squares approach. print numpy.polyfit([0,1,-1, 2, -2], [0,1,1, 4, 4], 2) #Output : [ 1.00000000e+00 0.00000000e+00 -3.97205465e-16] The functions polyadd, polysub, polymul, and polydiv also handle proper addition, subtraction, multiplication, and division of polynomial coefficients, respectively. =====Problem Statement===== You are given the coefficients of a polynomial P. Your task is to find the value of P at point x. =====Input Format===== The first line contains the space separated value of the coefficients in P. The second line contains the value of x. =====Output Format===== Print the desired value.
["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, your task is to find the top three most common characters in the string. Print the three most common characters along with their occurrence count. Sort in descending order of occurrence count. If the occurrence count is the same, sort the characters in alphabetical order. For example, according to the conditions described above, GOOGLE would have it's logo with the letters G, O, E. =====Input Format===== A single line of input containing the string S. =====Constraints===== 3≤len(S)≤10^4
["#!/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 are given a string. Split the string on a " " (space) delimiter and join using a - hyphen. =====Input Format===== The first line contains a string consisting of space separated words. =====Output Format===== Print the formatted string as explained above.
["# 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 .intersection() operation (or & operation). >>> s = set("Hacker") >>> print s.intersection("Rank") set(['a', 'k']) >>> print s.intersection(set(['R', 'a', 'n', 'k'])) set(['a', 'k']) >>> print s.intersection(['R', 'a', 'n', 'k']) set(['a', 'k']) >>> print s.intersection(enumerate(['R', 'a', 'n', 'k'])) set([]) >>> print s.intersection({"Rank":1}) set([]) >>> s & set("Rank") set(['a', 'k']) =====Problem Statement===== The students of District College have subscriptions to English and French newspapers. Some students have subscribed only to English, some have subscribed only to French, and some have subscribed to both newspapers. You are given two sets of student roll numbers. One set has subscribed to the English newspaper, one set has subscribed to the French newspaper. Your task is to find the total number of students who have subscribed to both newspapers. =====Input Format===== The first line contains n, the number of students who have subscribed to the English newspaper. The second line contains n space separated roll numbers of those students. The third line contains b, the number of students who have subscribed to the French newspaper. The fourth line contains b space separated roll numbers of those students. =====Constraints===== 0 < Total number of students in college < 1000 =====Output Format===== Output the total number of students who have subscriptions to both English and French newspapers.
["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 = set(map(int, input().strip().split(' ')))\n \n print(len(english.intersection(french)))\n__starting_point()"]
{"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 ones tool returns a new array with a given shape and type filled with 1's. import numpy print numpy.ones((1,2)) #Default type is float #Output : [[ 1. 1.]] print numpy.ones((1,2), dtype = numpy.int) #Type changes to int #Output : [[1 1]] =====Problem Statement===== You are given the shape of the array in the form of space-separated integers, each integer representing the size of different dimensions, your task is to print an array of the given shape and integer type using the tools numpy.zeros and numpy.ones. =====Input Format===== A single line containing the space-separated integers. =====Constraints===== 1≤each integer≤3 =====Output Format===== First, print the array using the numpy.zeros tool and then print the array with the numpy.ones tool.
["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.int))"]
{"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 only line contains the integer, n. =====Constraints===== 1≤n≤20 =====Output Format===== Print lines, one corresponding to each i.
["# 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 >>> s = set("Hacker") >>> print s.union("Rank") set(['a', 'R', 'c', 'r', 'e', 'H', 'k', 'n']) >>> print s.union(set(['R', 'a', 'n', 'k'])) set(['a', 'R', 'c', 'r', 'e', 'H', 'k', 'n']) >>> print s.union(['R', 'a', 'n', 'k']) set(['a', 'R', 'c', 'r', 'e', 'H', 'k', 'n']) >>> print s.union(enumerate(['R', 'a', 'n', 'k'])) set(['a', 'c', 'r', 'e', (1, 'a'), (2, 'n'), 'H', 'k', (3, 'k'), (0, 'R')]) >>> print s.union({"Rank":1}) set(['a', 'c', 'r', 'e', 'H', 'k', 'Rank']) >>> s | set("Rank") set(['a', 'R', 'c', 'r', 'e', 'H', 'k', 'n']) =====Problem Statement===== The students of District College have subscriptions to English and French newspapers. Some students have subscribed only to English, some have subscribed to only French and some have subscribed to both newspapers. You are given two sets of student roll numbers. One set has subscribed to the English newspaper, and the other set is subscribed to the French newspaper. The same student could be in both sets. Your task is to find the total number of students who have subscribed to at least one newspaper. =====Input Format===== The first line contains an integer, n, the number of students who have subscribed to the English newspaper. The second line contains n space separated roll numbers of those students. The third line contains b, the number of students who have subscribed to the French newspaper. The fourth line contains b space separated roll numbers of those students. =====Constraints===== 0 < Total number of students in college < 1000 =====Output Format===== Output the total number of students who have at least one subscription.
["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(map(int, input().strip().split(' ')))\n \n print((len(english.union(french))))\n \n\n__starting_point()"]
{"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 four numbers, a, b, c, and d, and print the result of a^b + c^d. =====Input Format===== Integers a, b, c, and d are given on four separate lines, respectively. =====Constraints===== 1≤a≤1000 1≤b≤1000 1≤c≤1000 1≤d≤1000 =====Output Format===== Print the result of a^b + c^d on one line.
["# 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 = int(input().strip())\n \n print(pow(a, b) + pow(c, d))\n__starting_point()"]
{"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 decimal value. For example: ✖ 12. ✔12.0 Number must have exactly one . symbol. Number must not give any exceptions when converted using float(N). =====Input Format===== The first line contains an integer T, the number of test cases. The next T line(s) contains a string N. =====Constraints===== 0<T<10 =====Output Format===== Output True or False for each test case.
["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 range(t):\n print(bool(re.match(pattern, input())))\n__starting_point()"]
{"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.hackerrank.com' =====Problem Statement===== You are given a polynomial P of a single indeterminate (or variable), x. You are also given the values of x and k. Your task is to verify if P(x) = k. =====Output Format===== Print True if P(x) = k. Otherwise, print False.
["#!/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 last element from the list. 7. reverse: Reverse the list. Initialize your list and read in the value of n followed by n lines of commands where each command will be 7 of the types listed above. Iterate through each command in order and perform the corresponding operation on your list. =====Example===== N = 4 append 1 append 2 insert 3 1 print append 1: Append 1 to the list, arr = [1]. append 2: Append 2 to the list, arr = [1,2]. insert 3 1: Insert 3 at index 1, arr = [1,3,2]. print: Print the array Output: [1, 3, 2] =====Input Format===== The first line contains an integer, n, denoting the number of commands. Each line i of the subsequent n lines contains one of the commands described above. =====Constraints===== The elements added to the list must be integers =====Output Format===== For each command of type print, print the list on a new line.
["# 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\"):\n ar.reverse()\n elif(cmd==\"pop\"):\n ar.pop()\n elif(cmd==\"count\"):\n val=int(tmp_str_ar[1])\n ar.count(val)\n elif(cmd==\"index\"):\n val=int(tmp_str_ar[1])\n ar.index(val)\n elif(cmd==\"remove\"):\n val=int(tmp_str_ar[1])\n ar.remove(val) \n elif(cmd==\"append\"):\n val=int(tmp_str_ar[1])\n ar.append(val) \n elif(cmd==\"insert\"):\n pos=int(tmp_str_ar[1])\n val=int(tmp_str_ar[2])\n ar.insert(pos,val)\n", "def __starting_point():\n N = int(input())\n outlist = []\n for _ in range(N):\n args = input().strip().split(' ')\n cmd = args[0]\n if cmd == 'insert':\n outlist.insert(int(args[1]), int(args[2]))\n elif cmd == 'remove':\n outlist.remove(int(args[1]))\n elif cmd == 'append':\n outlist.append(int(args[1]))\n elif cmd == 'print':\n print(outlist)\n elif cmd == 'sort':\n outlist.sort()\n elif cmd == 'pop':\n outlist.pop()\n elif cmd == 'reverse':\n outlist.reverse()\n \n \n \n\n__starting_point()"]
{"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 uppercase English alphabet characters. It must contain at least 3 digits (0-9). It should only contain alphanumeric characters (a-z, A-Z & 0-9). No character should repeat. There must be exactly 10 characters in a valid UID. =====Input Format===== The first line contains an integer T, the number of test cases. The next T lines contains an employee's UID. =====Output Format===== For each test case, print 'Valid' if the UID is valid. Otherwise, print 'Invalid', on separate lines. Do not print the quotation marks.
["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_result = bool(re.match(digit_check,uid_string))\n alphanumeric_and_length_check_result = bool(re.match(alphanumeric_and_length_check,uid_string))\n repeat_check_result = bool(re.match(repeat_check,uid_string)) \n if upper_check_result and digit_check_result and alphanumeric_and_length_check_result and not repeat_check_result:\n print('Valid')\n else:\n print('Invalid')\n", "import re\n\ndef __starting_point():\n t = int(input().strip())\n \n for _ in range(t):\n uid = \"\".join(sorted(input()))\n if (len(uid) == 10 and\n re.match(r'', uid) and \n re.search(r'[A-Z]{2}', uid) and\n re.search(r'\\d\\d\\d', uid) and\n not re.search(r'[^a-zA-Z0-9]', uid) and\n not re.search(r'(.)\\1', uid)):\n print(\"Valid\")\n else:\n print(\"Invalid\")\n\n__starting_point()"]
{"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 = 3 b = 5 The result of the integer division 3//5 = 0. The result of the float division is 3/5 = 0.6. Print: 0 0.6 =====Input Format===== The first line contains the first integer, a. The second line contains the second integer, b. =====Output Format===== Print the two lines as described above.
["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 >>> from collections import deque >>> d = deque() >>> d.append(1) >>> print d deque([1]) >>> d.appendleft(2) >>> print d deque([2, 1]) >>> d.clear() >>> print d deque([]) >>> d.extend('1') >>> print d deque(['1']) >>> d.extendleft('234') >>> print d deque(['4', '3', '2', '1']) >>> d.count('1') 1 >>> d.pop() '1' >>> print d deque(['4', '3', '2']) >>> d.popleft() '4' >>> print d deque(['3', '2']) >>> d.extend('7896') >>> print d deque(['3', '2', '7', '8', '9', '6']) >>> d.remove('2') >>> print d deque(['3', '7', '8', '9', '6']) >>> d.reverse() >>> print d deque(['6', '9', '8', '7', '3']) >>> d.rotate(3) >>> print d deque(['8', '7', '3', '6', '9']) =====Problem Statement===== Perform append, pop, popleft and appendleft methods on an empty deque d. =====Input Format===== The first line contains an integer N, the number of operations. The next N lines contains the space separated names of methods and their values. =====Constraints===== 0<N≤100 =====Output Format===== Print the space separated elements of deque d.
["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':\n d.appendleft(int(cmd[1]))\nfor i in d:\n print(i,end=' ')\n\n \n", "#!/usr/bin/env python3\n\nfrom collections import deque\n\ndef __starting_point():\n num = int(input().strip())\n deq = deque()\n \n for _ in range(num):\n args = input().strip().split()\n \n if args[0] == 'append':\n deq.append(args[1])\n elif args[0] == 'appendleft':\n deq.appendleft(args[1])\n elif args[0] == 'pop':\n deq.pop()\n elif args[0] == 'popleft':\n deq.popleft()\n \n out = []\n for el in deq:\n out.append(el)\n \n print(\" \".join(map(str, out)))\n__starting_point()"]
{"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 Captain was given a separate room, and the rest were given one room per group. Mr. Anant has an unordered list of randomly arranged room entries. The list consists of the room numbers for all of the tourists. The room numbers will appear K times per group except for the Captain's room. Mr. Anant needs you to help him find the Captain's room number. The total number of tourists or the total number of groups of families is not known to you. You only know the value of K and the room number list. =====Input Format===== The first consists of an integer, K, the size of each group. The second line contains the unordered elements of the room number list. =====Constraints===== 1<K<1000 =====Output Format===== Output the Captain's room number.
["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 print(i)\n break\n", "#!/usr/bin/env python3\n\ndef __starting_point():\n k = int(input().strip())\n numbers = list(map(int, input().strip().split(' ')))\n \n print((sum(set(numbers))*k - sum(numbers))//(k-1))\n__starting_point()"]
{"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 add -1 to your happiness. Otherwise, your happiness does not change. Output your final happiness at the end. Note: Since A and B are sets, they have no repeated elements. However, the array might contain duplicate elements. =====Constraints===== 1≤n≤10^5 1≤m≤10^5 1≤Any integer in the input≤10^9 =====Input Format===== The first line contains integers n and m separated by a space. The second line contains n integers, the elements of the array. The third and fourth lines contain m integers, A and B, respectively. =====Output Format===== Output a single integer, your total happiness.
["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\nfor element in intersect_ar_a:\n result += ar_counter[element]\nfor element in intersect_ar_b:\n result -= ar_counter[element]\n \nprint(result)\n", "#!/usr/bin/env python3\n\ndef __starting_point():\n happiness = 0\n n, m = map(int, input().strip().split(' '))\n arr = list(map(int, input().strip().split(' ')))\n \n good = set(map(int, input().strip().split(' ')))\n bad = set(map(int, input().strip().split(' ')))\n \n for el in arr:\n if el in good:\n happiness += 1\n elif el in bad:\n happiness -= 1\n \n print(happiness)\n__starting_point()"]
{"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