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
2c7c63f2f10f748d5610fefef52f87a6
UNKNOWN
Consider the range `0` to `10`. The primes in this range are: `2, 3, 5, 7`, and thus the prime pairs are: `(2,2), (2,3), (2,5), (2,7), (3,3), (3,5), (3,7),(5,5), (5,7), (7,7)`. Let's take one pair `(2,7)` as an example and get the product, then sum the digits of the result as follows: `2 * 7 = 14`, and `1 + 4 = 5`. We see that `5` is a prime number. Similarly, for the pair `(7,7)`, we get: `7 * 7 = 49`, and `4 + 9 = 13`, which is a prime number. You will be given a range and your task is to return the number of pairs that revert to prime as shown above. In the range `(0,10)`, there are only `4` prime pairs that end up being primes in a similar way: `(2,7), (3,7), (5,5), (7,7)`. Therefore, `solve(0,10) = 4)` Note that the upperbound of the range will not exceed `10000`. A range of `(0,10)` means that: `0 <= n < 10`. Good luck! If you like this Kata, please try [Simple Prime Streaming](https://www.codewars.com/kata/5a908da30025e995880000e3) [Prime reduction](https://www.codewars.com/kata/59aa6567485a4d03ff0000ca) [Dominant primes](https://www.codewars.com/kata/59ce11ea9f0cbc8a390000ed)
["import itertools\n\ndef solve(a, b):\n primes = set([2] + [n for n in range(3, b, 2) if all(n % r for r in range(3, int(n**0.5)+1, 2))])\n return sum( sum(map(int, str(x*y))) in primes for x, y in itertools.combinations_with_replacement([p for p in primes if a <= p < b], 2) )", "from bisect import bisect_left\n\ndef sieve(n):\n sieve, primes = [0]*(n+1), []\n for i in range(2, n+1):\n if not sieve[i]:\n primes.append(i)\n for j in range(i**2, n+1, i): sieve[j] = 1\n return primes\n\nPRIMES = sieve(10000)\nSET_PRIMES = set(PRIMES)\n\ndef solve(a,b):\n p1, p2 = bisect_left(PRIMES, a), bisect_left(PRIMES, b)\n return sum( sum(map(int, str(p*q))) in SET_PRIMES for i,p in enumerate(PRIMES[p1:p2],p1) for q in PRIMES[i:p2])", "from itertools import combinations_with_replacement as replacements\n\n\nprimes = {2}\nsieve = [True] * 5000\nfor i in range(3, 102, 2):\n if sieve[i // 2]:\n sieve[i * i // 2 :: i] = [False] * ((10001 - i * i - 1) // (2 * i) + 1)\nprimes.update((2 * i + 1) for i in range(1, 5000) if sieve[i])\n\n\ndef solve(a, b):\n pairs = replacements(set(range(a, b)) & primes, 2)\n return sum(1 for p, q in pairs if sum(int(d) for d in str(p * q)) in primes)\n", "from itertools import compress, combinations_with_replacement\nimport numpy as np\n\n\ns = np.ones(10001)\ns[:2] = s[4::2] = 0\nfor i in range(3, int(len(s)**0.5)+1, 2):\n if s[i]:\n s[i*i::i] = 0\nPRIMES = list(compress(list(range(len(s))), s))\n\ndef solve(a, b):\n i, j = np.searchsorted(PRIMES, a), np.searchsorted(PRIMES, b)\n return sum(s[sum(map(int, str(x * y)))] for x, y in combinations_with_replacement(PRIMES[i:j], 2))\n", "from itertools import combinations_with_replacement\nfind_prime=lambda n:all(n % i for i in range(2, int(n ** .5) + 1)) and n > 1\nsolve=lambda s,e:len([1for i in combinations_with_replacement([i for i in range(s,e)if find_prime(i)],2)if find_prime(sum(map(int,str(i[0]*i[1]))))])", "import math\nimport itertools\n\ndef is_prime(num):\n return num > 1 and all(num % i for i in range(2, num if num < 53 else math.ceil(math.sqrt(num)) + 1))\n\ndef solve(a,b):\n return len([cb for cb in itertools.combinations_with_replacement([i for i in range(a, b) if is_prime(i)], 2) if is_prime(sum([int(c) for c in str(cb[0] * cb[1])]))])", "from itertools import combinations_with_replacement\ndef solve(a,b):\n return sum( sum(digits(p1*p2)) in setprimes for p1,p2 in combinations_with_replacement(sprime(a,b),r=2) )\n\ndef digits(n):\n while n:\n yield (n%10)\n n //=10\n\nprimes = [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,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997,1009,1013,1019,1021,1031,1033,1039,1049,1051,1061,1063,1069,1087,1091,1093,1097,1103,1109,1117,1123,1129,1151,1153,1163,1171,1181,1187,1193,1201,1213,1217,1223,1229,1231,1237,1249,1259,1277,1279,1283,1289,1291,1297,1301,1303,1307,1319,1321,1327,1361,1367,1373,1381,1399,1409,1423,1427,1429,1433,1439,1447,1451,1453,1459,1471,1481,1483,1487,1489,1493,1499,1511,1523,1531,1543,1549,1553,1559,1567,1571,1579,1583,1597,1601,1607,1609,1613,1619,1621,1627,1637,1657,1663,1667,1669,1693,1697,1699,1709,1721,1723,1733,1741,1747,1753,1759,1777,1783,1787,1789,1801,1811,1823,1831,1847,1861,1867,1871,1873,1877,1879,1889,1901,1907,1913,1931,1933,1949,1951,1973,1979,1987,1993,1997,1999,2003,2011,2017,2027,2029,2039,2053,2063,2069,2081,2083,2087,2089,2099,2111,2113,2129,2131,2137,2141,2143,2153,2161,2179,2203,2207,2213,2221,2237,2239,2243,2251,2267,2269,2273,2281,2287,2293,2297,2309,2311,2333,2339,2341,2347,2351,2357,2371,2377,2381,2383,2389,2393,2399,2411,2417,2423,2437,2441,2447,2459,2467,2473,2477,2503,2521,2531,2539,2543,2549,2551,2557,2579,2591,2593,2609,2617,2621,2633,2647,2657,2659,2663,2671,2677,2683,2687,2689,2693,2699,2707,2711,2713,2719,2729,2731,2741,2749,2753,2767,2777,2789,2791,2797,2801,2803,2819,2833,2837,2843,2851,2857,2861,2879,2887,2897,2903,2909,2917,2927,2939,2953,2957,2963,2969,2971,2999,3001,3011,3019,3023,3037,3041,3049,3061,3067,3079,3083,3089,3109,3119,3121,3137,3163,3167,3169,3181,3187,3191,3203,3209,3217,3221,3229,3251,3253,3257,3259,3271,3299,3301,3307,3313,3319,3323,3329,3331,3343,3347,3359,3361,3371,3373,3389,3391,3407,3413,3433,3449,3457,3461,3463,3467,3469,3491,3499,3511,3517,3527,3529,3533,3539,3541,3547,3557,3559,3571,3581,3583,3593,3607,3613,3617,3623,3631,3637,3643,3659,3671,3673,3677,3691,3697,3701,3709,3719,3727,3733,3739,3761,3767,3769,3779,3793,3797,3803,3821,3823,3833,3847,3851,3853,3863,3877,3881,3889,3907,3911,3917,3919,3923,3929,3931,3943,3947,3967,3989,4001,4003,4007,4013,4019,4021,4027,4049,4051,4057,4073,4079,4091,4093,4099,4111,4127,4129,4133,4139,4153,4157,4159,4177,4201,4211,4217,4219,4229,4231,4241,4243,4253,4259,4261,4271,4273,4283,4289,4297,4327,4337,4339,4349,4357,4363,4373,4391,4397,4409,4421,4423,4441,4447,4451,4457,4463,4481,4483,4493,4507,4513,4517,4519,4523,4547,4549,4561,4567,4583,4591,4597,4603,4621,4637,4639,4643,4649,4651,4657,4663,4673,4679,4691,4703,4721,4723,4729,4733,4751,4759,4783,4787,4789,4793,4799,4801,4813,4817,4831,4861,4871,4877,4889,4903,4909,4919,4931,4933,4937,4943,4951,4957,4967,4969,4973,4987,4993,4999,5003,5009,5011,5021,5023,5039,5051,5059,5077,5081,5087,5099,5101,5107,5113,5119,5147,5153,5167,5171,5179,5189,5197,5209,5227,5231,5233,5237,5261,5273,5279,5281,5297,5303,5309,5323,5333,5347,5351,5381,5387,5393,5399,5407,5413,5417,5419,5431,5437,5441,5443,5449,5471,5477,5479,5483,5501,5503,5507,5519,5521,5527,5531,5557,5563,5569,5573,5581,5591,5623,5639,5641,5647,5651,5653,5657,5659,5669,5683,5689,5693,5701,5711,5717,5737,5741,5743,5749,5779,5783,5791,5801,5807,5813,5821,5827,5839,5843,5849,5851,5857,5861,5867,5869,5879,5881,5897,5903,5923,5927,5939,5953,5981,5987,6007,6011,6029,6037,6043,6047,6053,6067,6073,6079,6089,6091,6101,6113,6121,6131,6133,6143,6151,6163,6173,6197,6199,6203,6211,6217,6221,6229,6247,6257,6263,6269,6271,6277,6287,6299,6301,6311,6317,6323,6329,6337,6343,6353,6359,6361,6367,6373,6379,6389,6397,6421,6427,6449,6451,6469,6473,6481,6491,6521,6529,6547,6551,6553,6563,6569,6571,6577,6581,6599,6607,6619,6637,6653,6659,6661,6673,6679,6689,6691,6701,6703,6709,6719,6733,6737,6761,6763,6779,6781,6791,6793,6803,6823,6827,6829,6833,6841,6857,6863,6869,6871,6883,6899,6907,6911,6917,6947,6949,6959,6961,6967,6971,6977,6983,6991,6997,7001,7013,7019,7027,7039,7043,7057,7069,7079,7103,7109,7121,7127,7129,7151,7159,7177,7187,7193,7207,7211,7213,7219,7229,7237,7243,7247,7253,7283,7297,7307,7309,7321,7331,7333,7349,7351,7369,7393,7411,7417,7433,7451,7457,7459,7477,7481,7487,7489,7499,7507,7517,7523,7529,7537,7541,7547,7549,7559,7561,7573,7577,7583,7589,7591,7603,7607,7621,7639,7643,7649,7669,7673,7681,7687,7691,7699,7703,7717,7723,7727,7741,7753,7757,7759,7789,7793,7817,7823,7829,7841,7853,7867,7873,7877,7879,7883,7901,7907,7919,7927,7933,7937,7949,7951,7963,7993,8009,8011,8017,8039,8053,8059,8069,8081,8087,8089,8093,8101,8111,8117,8123,8147,8161,8167,8171,8179,8191,8209,8219,8221,8231,8233,8237,8243,8263,8269,8273,8287,8291,8293,8297,8311,8317,8329,8353,8363,8369,8377,8387,8389,8419,8423,8429,8431,8443,8447,8461,8467,8501,8513,8521,8527,8537,8539,8543,8563,8573,8581,8597,8599,8609,8623,8627,8629,8641,8647,8663,8669,8677,8681,8689,8693,8699,8707,8713,8719,8731,8737,8741,8747,8753,8761,8779,8783,8803,8807,8819,8821,8831,8837,8839,8849,8861,8863,8867,8887,8893,8923,8929,8933,8941,8951,8963,8969,8971,8999,9001,9007,9011,9013,9029,9041,9043,9049,9059,9067,9091,9103,9109,9127,9133,9137,9151,9157,9161,9173,9181,9187,9199,9203,9209,9221,9227,9239,9241,9257,9277,9281,9283,9293,9311,9319,9323,9337,9341,9343,9349,9371,9377,9391,9397,9403,9413,9419,9421,9431,9433,9437,9439,9461,9463,9467,9473,9479,9491,9497,9511,9521,9533,9539,9547,9551,9587,9601,9613,9619,9623,9629,9631,9643,9649,9661,9677,9679,9689,9697,9719,9721,9733,9739,9743,9749,9767,9769,9781,9787,9791,9803,9811,9817,9829,9833,9839,9851,9857,9859,9871,9883,9887,9901,9907,9923,9929,9931,9941,9949,9967,9973,10007]\nsetprimes = set(primes)\ndef sprime(a,b):\n for p in primes:\n if p>= b: break\n if p>= a: yield p", "from itertools import combinations_with_replacement\ndef solve(a,b):\n return sum(sum(c for c in digits(p1*p2)) in setprimes for p1,p2 in combinations_with_replacement(sprime(a,b),r=2))\n\ndef digits(n):\n while n:\n yield (n%10)\n n //=10\n\nprimes = [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,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997,1009,1013,1019,1021,1031,1033,1039,1049,1051,1061,1063,1069,1087,1091,1093,1097,1103,1109,1117,1123,1129,1151,1153,1163,1171,1181,1187,1193,1201,1213,1217,1223,1229,1231,1237,1249,1259,1277,1279,1283,1289,1291,1297,1301,1303,1307,1319,1321,1327,1361,1367,1373,1381,1399,1409,1423,1427,1429,1433,1439,1447,1451,1453,1459,1471,1481,1483,1487,1489,1493,1499,1511,1523,1531,1543,1549,1553,1559,1567,1571,1579,1583,1597,1601,1607,1609,1613,1619,1621,1627,1637,1657,1663,1667,1669,1693,1697,1699,1709,1721,1723,1733,1741,1747,1753,1759,1777,1783,1787,1789,1801,1811,1823,1831,1847,1861,1867,1871,1873,1877,1879,1889,1901,1907,1913,1931,1933,1949,1951,1973,1979,1987,1993,1997,1999,2003,2011,2017,2027,2029,2039,2053,2063,2069,2081,2083,2087,2089,2099,2111,2113,2129,2131,2137,2141,2143,2153,2161,2179,2203,2207,2213,2221,2237,2239,2243,2251,2267,2269,2273,2281,2287,2293,2297,2309,2311,2333,2339,2341,2347,2351,2357,2371,2377,2381,2383,2389,2393,2399,2411,2417,2423,2437,2441,2447,2459,2467,2473,2477,2503,2521,2531,2539,2543,2549,2551,2557,2579,2591,2593,2609,2617,2621,2633,2647,2657,2659,2663,2671,2677,2683,2687,2689,2693,2699,2707,2711,2713,2719,2729,2731,2741,2749,2753,2767,2777,2789,2791,2797,2801,2803,2819,2833,2837,2843,2851,2857,2861,2879,2887,2897,2903,2909,2917,2927,2939,2953,2957,2963,2969,2971,2999,3001,3011,3019,3023,3037,3041,3049,3061,3067,3079,3083,3089,3109,3119,3121,3137,3163,3167,3169,3181,3187,3191,3203,3209,3217,3221,3229,3251,3253,3257,3259,3271,3299,3301,3307,3313,3319,3323,3329,3331,3343,3347,3359,3361,3371,3373,3389,3391,3407,3413,3433,3449,3457,3461,3463,3467,3469,3491,3499,3511,3517,3527,3529,3533,3539,3541,3547,3557,3559,3571,3581,3583,3593,3607,3613,3617,3623,3631,3637,3643,3659,3671,3673,3677,3691,3697,3701,3709,3719,3727,3733,3739,3761,3767,3769,3779,3793,3797,3803,3821,3823,3833,3847,3851,3853,3863,3877,3881,3889,3907,3911,3917,3919,3923,3929,3931,3943,3947,3967,3989,4001,4003,4007,4013,4019,4021,4027,4049,4051,4057,4073,4079,4091,4093,4099,4111,4127,4129,4133,4139,4153,4157,4159,4177,4201,4211,4217,4219,4229,4231,4241,4243,4253,4259,4261,4271,4273,4283,4289,4297,4327,4337,4339,4349,4357,4363,4373,4391,4397,4409,4421,4423,4441,4447,4451,4457,4463,4481,4483,4493,4507,4513,4517,4519,4523,4547,4549,4561,4567,4583,4591,4597,4603,4621,4637,4639,4643,4649,4651,4657,4663,4673,4679,4691,4703,4721,4723,4729,4733,4751,4759,4783,4787,4789,4793,4799,4801,4813,4817,4831,4861,4871,4877,4889,4903,4909,4919,4931,4933,4937,4943,4951,4957,4967,4969,4973,4987,4993,4999,5003,5009,5011,5021,5023,5039,5051,5059,5077,5081,5087,5099,5101,5107,5113,5119,5147,5153,5167,5171,5179,5189,5197,5209,5227,5231,5233,5237,5261,5273,5279,5281,5297,5303,5309,5323,5333,5347,5351,5381,5387,5393,5399,5407,5413,5417,5419,5431,5437,5441,5443,5449,5471,5477,5479,5483,5501,5503,5507,5519,5521,5527,5531,5557,5563,5569,5573,5581,5591,5623,5639,5641,5647,5651,5653,5657,5659,5669,5683,5689,5693,5701,5711,5717,5737,5741,5743,5749,5779,5783,5791,5801,5807,5813,5821,5827,5839,5843,5849,5851,5857,5861,5867,5869,5879,5881,5897,5903,5923,5927,5939,5953,5981,5987,6007,6011,6029,6037,6043,6047,6053,6067,6073,6079,6089,6091,6101,6113,6121,6131,6133,6143,6151,6163,6173,6197,6199,6203,6211,6217,6221,6229,6247,6257,6263,6269,6271,6277,6287,6299,6301,6311,6317,6323,6329,6337,6343,6353,6359,6361,6367,6373,6379,6389,6397,6421,6427,6449,6451,6469,6473,6481,6491,6521,6529,6547,6551,6553,6563,6569,6571,6577,6581,6599,6607,6619,6637,6653,6659,6661,6673,6679,6689,6691,6701,6703,6709,6719,6733,6737,6761,6763,6779,6781,6791,6793,6803,6823,6827,6829,6833,6841,6857,6863,6869,6871,6883,6899,6907,6911,6917,6947,6949,6959,6961,6967,6971,6977,6983,6991,6997,7001,7013,7019,7027,7039,7043,7057,7069,7079,7103,7109,7121,7127,7129,7151,7159,7177,7187,7193,7207,7211,7213,7219,7229,7237,7243,7247,7253,7283,7297,7307,7309,7321,7331,7333,7349,7351,7369,7393,7411,7417,7433,7451,7457,7459,7477,7481,7487,7489,7499,7507,7517,7523,7529,7537,7541,7547,7549,7559,7561,7573,7577,7583,7589,7591,7603,7607,7621,7639,7643,7649,7669,7673,7681,7687,7691,7699,7703,7717,7723,7727,7741,7753,7757,7759,7789,7793,7817,7823,7829,7841,7853,7867,7873,7877,7879,7883,7901,7907,7919,7927,7933,7937,7949,7951,7963,7993,8009,8011,8017,8039,8053,8059,8069,8081,8087,8089,8093,8101,8111,8117,8123,8147,8161,8167,8171,8179,8191,8209,8219,8221,8231,8233,8237,8243,8263,8269,8273,8287,8291,8293,8297,8311,8317,8329,8353,8363,8369,8377,8387,8389,8419,8423,8429,8431,8443,8447,8461,8467,8501,8513,8521,8527,8537,8539,8543,8563,8573,8581,8597,8599,8609,8623,8627,8629,8641,8647,8663,8669,8677,8681,8689,8693,8699,8707,8713,8719,8731,8737,8741,8747,8753,8761,8779,8783,8803,8807,8819,8821,8831,8837,8839,8849,8861,8863,8867,8887,8893,8923,8929,8933,8941,8951,8963,8969,8971,8999,9001,9007,9011,9013,9029,9041,9043,9049,9059,9067,9091,9103,9109,9127,9133,9137,9151,9157,9161,9173,9181,9187,9199,9203,9209,9221,9227,9239,9241,9257,9277,9281,9283,9293,9311,9319,9323,9337,9341,9343,9349,9371,9377,9391,9397,9403,9413,9419,9421,9431,9433,9437,9439,9461,9463,9467,9473,9479,9491,9497,9511,9521,9533,9539,9547,9551,9587,9601,9613,9619,9623,9629,9631,9643,9649,9661,9677,9679,9689,9697,9719,9721,9733,9739,9743,9749,9767,9769,9781,9787,9791,9803,9811,9817,9829,9833,9839,9851,9857,9859,9871,9883,9887,9901,9907,9923,9929,9931,9941,9949,9967,9973,10007,10009,10037,10039,10061,10067,10069,10079,10091,10093,10099,10103,10111,10133,10139,10141,10151,10159,10163,10169,10177,10181,10193,10211,10223,10243,10247,10253,10259,10267,10271,10273,10289,10301,10303,10313,10321,10331,10333,10337,10343,10357,10369,10391,10399,10427,10429,10433,10453,10457,10459,10463,10477,10487,10499,10501,10513,10529,10531,10559,10567,10589,10597,10601,10607,10613,10627,10631,10639,10651,10657,10663,10667,10687,10691,10709,10711,10723,10729,10733,10739,10753,10771,10781,10789,10799,10831,10837,10847,10853,10859,10861,10867,10883,10889,10891,10903,10909,10937,10939,10949,10957,10973,10979,10987,10993,11003,11027,11047,11057,11059,11069,11071,11083,11087,11093,11113,11117,11119,11131,11149,11159,11161,11171,11173,11177,11197,11213,11239,11243,11251,11257,11261,11273,11279,11287,11299,11311,11317,11321,11329,11351,11353,11369,11383,11393,11399,11411,11423,11437,11443,11447,11467,11471,11483,11489,11491,11497,11503,11519,11527,11549,11551,11579,11587,11593,11597,11617,11621,11633,11657,11677,11681,11689,11699,11701,11717,11719,11731,11743,11777,11779,11783,11789,11801,11807,11813,11821,11827,11831,11833,11839,11863,11867,11887,11897,11903,11909,11923,11927,11933,11939,11941,11953,11959,11969,11971,11981,11987,12007,12011,12037,12041,12043,12049,12071,12073,12097,12101,12107,12109,12113,12119,12143,12149,12157,12161,12163,12197,12203,12211,12227,12239,12241,12251,12253,12263,12269,12277,12281,12289,12301,12323,12329,12343,12347,12373,12377,12379,12391,12401,12409,12413,12421,12433,12437,12451,12457,12473,12479,12487,12491,12497,12503,12511,12517,12527,12539,12541,12547,12553,12569,12577,12583,12589,12601,12611,12613,12619,12637,12641,12647,12653,12659,12671,12689,12697,12703,12713,12721,12739,12743,12757,12763,12781,12791,12799,12809,12821,12823,12829,12841,12853,12889,12893,12899,12907,12911,12917,12919,12923,12941,12953,12959,12967,12973,12979,12983,13001,13003,13007,13009,13033,13037,13043,13049,13063,13093,13099,13103,13109,13121,13127,13147,13151,13159,13163,13171,13177,13183,13187,13217,13219,13229,13241,13249,13259,13267,13291,13297,13309,13313,13327,13331,13337,13339,13367,13381,13397,13399,13411,13417,13421,13441,13451,13457,13463,13469,13477,13487,13499,13513,13523,13537,13553,13567,13577,13591,13597,13613,13619,13627,13633,13649,13669,13679,13681,13687,13691,13693,13697,13709,13711,13721,13723,13729,13751,13757,13759,13763,13781,13789,13799,13807,13829,13831,13841,13859,13873,13877,13879,13883,13901,13903,13907,13913,13921,13931,13933,13963,13967,13997,13999,14009,14011,14029,14033,14051,14057,14071,14081,14083,14087,14107,14143,14149,14153,14159,14173,14177,14197,14207,14221,14243,14249,14251,14281,14293,14303,14321,14323,14327,14341,14347,14369,14387,14389,14401,14407,14411,14419,14423,14431,14437,14447,14449,14461,14479,14489,14503,14519,14533,14537,14543,14549,14551,14557,14561,14563,14591,14593,14621,14627,14629,14633,14639,14653,14657,14669,14683,14699,14713,14717,14723,14731,14737,14741,14747,14753,14759,14767,14771,14779,14783,14797,14813,14821,14827,14831,14843,14851,14867,14869,14879,14887,14891,14897,14923,14929,14939,14947,14951,14957,14969,14983,15013,15017,15031,15053,15061,15073,15077,15083,15091,15101,15107,15121,15131,15137,15139,15149,15161,15173,15187,15193,15199,15217,15227,15233,15241,15259,15263,15269,15271,15277,15287,15289,15299,15307,15313,15319,15329,15331,15349,15359,15361,15373,15377,15383,15391,15401,15413,15427,15439,15443,15451,15461,15467,15473,15493,15497,15511,15527,15541,15551,15559,15569,15581,15583,15601,15607,15619,15629,15641,15643,15647,15649,15661,15667,15671,15679,15683,15727,15731,15733,15737,15739,15749,15761,15767,15773,15787,15791,15797,15803,15809,15817,15823,15859,15877,15881,15887,15889,15901,15907,15913,15919,15923,15937,15959,15971,15973,15991,16001,16007,16033,16057,16061,16063,16067,16069,16073,16087,16091,16097,16103,16111,16127,16139,16141,16183,16187,16189,16193,16217,16223,16229,16231,16249,16253,16267,16273,16301,16319,16333,16339,16349,16361,16363,16369,16381,16411,16417,16421,16427,16433,16447,16451,16453,16477,16481,16487,16493,16519,16529,16547,16553,16561,16567,16573,16603,16607,16619,16631,16633,16649,16651,16657,16661,16673,16691,16693,16699,16703,16729,16741,16747,16759,16763,16787,16811,16823,16829,16831,16843,16871,16879,16883,16889,16901,16903,16921,16927,16931,16937,16943,16963,16979,16981,16987,16993,17011,17021,17027,17029,17033,17041,17047,17053,17077,17093,17099,17107,17117,17123,17137,17159,17167,17183,17189,17191,17203,17207,17209,17231,17239,17257,17291,17293,17299,17317,17321,17327,17333,17341,17351,17359,17377,17383,17387,17389,17393,17401,17417,17419,17431,17443,17449,17467,17471,17477,17483,17489,17491,17497,17509,17519,17539,17551,17569,17573,17579,17581,17597,17599,17609,17623,17627,17657,17659,17669,17681,17683,17707,17713,17729,17737,17747,17749,17761,17783,17789,17791,17807,17827,17837,17839,17851,17863,17881,17891,17903,17909,17911,17921,17923,17929,17939,17957,17959,17971,17977,17981,17987,17989,18013,18041,18043,18047,18049,18059,18061,18077,18089,18097,18119,18121,18127,18131,18133,18143,18149,18169,18181,18191,18199,18211,18217,18223,18229,18233,18251,18253,18257,18269,18287,18289,18301,18307,18311,18313,18329,18341,18353,18367,18371,18379,18397,18401,18413,18427,18433,18439,18443,18451,18457,18461,18481,18493,18503,18517,18521,18523,18539,18541,18553,18583,18587,18593,18617,18637,18661,18671,18679,18691,18701,18713,18719,18731,18743,18749,18757,18773,18787,18793,18797,18803,18839,18859,18869,18899,18911,18913,18917,18919,18947,18959,18973,18979,19001,19009,19013,19031,19037,19051,19069,19073,19079,19081,19087,19121,19139,19141,19157,19163,19181,19183,19207,19211,19213,19219,19231,19237,19249,19259,19267,19273,19289,19301,19309,19319,19333,19373,19379,19381,19387,19391,19403,19417,19421,19423,19427,19429,19433,19441,19447,19457,19463,19469,19471,19477,19483,19489,19501,19507,19531,19541,19543,19553,19559,19571,19577,19583,19597,19603,19609,19661,19681,19687,19697,19699,19709,19717,19727,19739,19751,19753,19759,19763,19777,19793,19801,19813,19819,19841,19843,19853,19861,19867,19889,19891,19913,19919,19927,19937,19949,19961,19963,19973,19979,19991,19993,19997,20011,20021,20023,20029,20047,20051,20063,20071,20089,20101,20107,20113,20117,20123,20129,20143,20147,20149,20161,20173,20177,20183,20201,20219,20231,20233,20249,20261,20269,20287,20297,20323,20327,20333,20341,20347,20353,20357,20359,20369,20389,20393,20399,20407,20411,20431,20441,20443,20477,20479,20483,20507,20509,20521,20533,20543,20549,20551,20563,20593,20599,20611,20627,20639,20641,20663,20681,20693,20707,20717,20719,20731,20743,20747,20749,20753,20759,20771,20773,20789,20807,20809,20849,20857,20873,20879,20887,20897,20899,20903,20921,20929,20939,20947,20959,20963,20981,20983,21001,21011,21013,21017,21019,21023,21031,21059,21061,21067,21089,21101,21107,21121,21139,21143,21149,21157,21163,21169,21179,21187,21191,21193,21211,21221,21227,21247,21269,21277,21283,21313,21317,21319,21323,21341,21347,21377,21379,21383,21391,21397,21401,21407,21419,21433,21467,21481,21487,21491,21493,21499,21503,21517,21521,21523,21529,21557,21559,21563,21569,21577,21587,21589,21599,21601,21611,21613,21617,21647,21649,21661,21673,21683,21701,21713,21727,21737,21739,21751,21757,21767,21773,21787,21799,21803,21817,21821,21839,21841,21851,21859,21863,21871,21881,21893,21911,21929,21937,21943,21961,21977,21991,21997,22003,22013,22027,22031,22037,22039,22051,22063,22067,22073,22079,22091,22093,22109,22111,22123,22129,22133,22147,22153,22157,22159,22171,22189,22193,22229,22247,22259,22271,22273,22277,22279,22283,22291,22303,22307,22343,22349,22367,22369,22381,22391,22397,22409,22433,22441,22447,22453,22469,22481,22483,22501,22511,22531,22541,22543,22549,22567,22571,22573,22613,22619,22621,22637,22639,22643,22651,22669,22679,22691,22697,22699,22709,22717,22721,22727,22739,22741,22751,22769,22777,22783,22787,22807,22811,22817,22853,22859,22861,22871,22877,22901,22907,22921,22937,22943,22961,22963,22973,22993,23003,23011,23017,23021,23027,23029,23039,23041,23053,23057,23059,23063,23071,23081,23087,23099,23117,23131,23143,23159,23167,23173,23189,23197,23201,23203,23209,23227,23251,23269,23279,23291,23293,23297,23311,23321,23327,23333,23339,23357,23369,23371,23399,23417,23431,23447,23459,23473,23497,23509,23531,23537,23539,23549,23557,23561,23563,23567,23581,23593,23599,23603,23609,23623,23627,23629,23633,23663,23669,23671,23677,23687,23689,23719,23741,23743,23747,23753,23761,23767,23773,23789,23801,23813,23819,23827,23831,23833,23857,23869,23873,23879,23887,23893,23899,23909,23911,23917,23929,23957,23971,23977,23981,23993,24001,24007,24019,24023,24029,24043,24049,24061,24071,24077,24083,24091,24097,24103,24107,24109,24113,24121,24133,24137,24151,24169,24179,24181,24197,24203,24223,24229,24239,24247,24251,24281,24317,24329,24337,24359,24371,24373,24379,24391,24407,24413,24419,24421,24439,24443,24469,24473,24481,24499,24509,24517,24527,24533,24547,24551,24571,24593,24611,24623,24631,24659,24671,24677,24683,24691,24697,24709,24733,24749,24763,24767,24781,24793,24799,24809,24821,24841,24847,24851,24859,24877,24889,24907,24917,24919,24923,24943,24953,24967,24971,24977,24979,24989,25013,25031,25033,25037,25057,25073,25087,25097,25111,25117,25121,25127,25147,25153,25163,25169,25171,25183,25189,25219,25229,25237,25243,25247,25253,25261,25301,25303,25307,25309,25321,25339,25343,25349,25357,25367,25373,25391,25409,25411,25423,25439,25447,25453,25457,25463,25469,25471,25523,25537,25541,25561,25577,25579,25583,25589,25601,25603,25609,25621,25633,25639,25643,25657,25667,25673,25679,25693,25703,25717,25733,25741,25747,25759,25763,25771,25793,25799,25801,25819,25841,25847,25849,25867,25873,25889,25903,25913,25919,25931,25933,25939,25943,25951,25969,25981,25997,25999,26003,26017,26021,26029,26041,26053,26083,26099,26107,26111,26113,26119,26141,26153,26161,26171,26177,26183,26189,26203,26209,26227,26237,26249,26251,26261,26263,26267,26293,26297,26309,26317,26321,26339,26347,26357,26371,26387,26393,26399,26407,26417,26423,26431,26437,26449,26459,26479,26489,26497,26501,26513,26539,26557,26561,26573,26591,26597,26627,26633,26641,26647,26669,26681,26683,26687,26693,26699,26701,26711,26713,26717,26723,26729,26731,26737,26759,26777,26783,26801,26813,26821,26833,26839,26849,26861,26863,26879,26881,26891,26893,26903,26921,26927,26947,26951,26953,26959,26981,26987,26993,27011,27017,27031,27043,27059,27061,27067,27073,27077,27091,27103,27107,27109,27127,27143,27179,27191,27197,27211,27239,27241,27253,27259,27271,27277,27281,27283,27299,27329,27337,27361,27367,27397,27407,27409,27427,27431,27437,27449,27457,27479,27481,27487,27509,27527,27529,27539,27541,27551,27581,27583,27611,27617,27631,27647,27653,27673,27689,27691,27697,27701,27733,27737,27739,27743,27749,27751,27763,27767,27773,27779,27791,27793,27799,27803,27809,27817,27823,27827,27847,27851,27883,27893,27901,27917,27919,27941,27943,27947,27953,27961,27967,27983,27997,28001,28019,28027,28031,28051,28057,28069,28081,28087,28097,28099,28109,28111,28123,28151,28163,28181,28183,28201,28211,28219,28229,28277,28279,28283,28289,28297,28307,28309,28319,28349,28351,28387,28393,28403,28409,28411,28429,28433,28439,28447,28463,28477,28493,28499,28513,28517,28537,28541,28547,28549,28559,28571,28573,28579,28591,28597,28603,28607,28619,28621,28627,28631,28643,28649,28657,28661,28663,28669,28687,28697,28703,28711,28723,28729,28751,28753,28759,28771,28789,28793,28807,28813,28817,28837,28843,28859,28867,28871,28879,28901,28909,28921,28927,28933,28949,28961,28979,29009,29017,29021,29023,29027,29033,29059,29063,29077,29101,29123,29129,29131,29137,29147,29153,29167,29173,29179,29191,29201,29207,29209,29221,29231,29243,29251,29269,29287,29297,29303,29311,29327,29333,29339,29347,29363,29383,29387,29389,29399,29401,29411,29423,29429,29437,29443,29453,29473,29483,29501,29527,29531,29537,29567,29569,29573,29581,29587,29599,29611,29629,29633,29641,29663,29669,29671,29683,29717,29723,29741,29753,29759,29761,29789,29803,29819,29833,29837,29851,29863,29867,29873,29879,29881,29917,29921,29927,29947,29959,29983,29989,30011,30013,30029,30047,30059,30071,30089,30091,30097,30103,30109,30113,30119,30133,30137,30139,30161,30169,30181,30187,30197,30203,30211,30223,30241,30253,30259,30269,30271,30293,30307,30313,30319,30323,30341,30347,30367,30389,30391,30403,30427,30431,30449,30467,30469,30491,30493,30497,30509,30517,30529,30539,30553,30557,30559,30577,30593,30631,30637,30643,30649,30661,30671,30677,30689,30697,30703,30707,30713,30727,30757,30763,30773,30781,30803,30809,30817,30829,30839,30841,30851,30853,30859,30869,30871,30881,30893,30911,30931,30937,30941,30949,30971,30977,30983,31013,31019,31033,31039,31051,31063,31069,31079,31081,31091,31121,31123,31139,31147,31151,31153,31159,31177,31181,31183,31189,31193,31219,31223,31231,31237,31247,31249,31253,31259,31267,31271,31277,31307,31319,31321,31327,31333,31337,31357,31379,31387,31391,31393,31397,31469,31477,31481,31489,31511,31513,31517,31531,31541,31543,31547,31567,31573,31583,31601,31607,31627,31643,31649,31657,31663,31667,31687,31699,31721,31723,31727,31729,31741,31751,31769,31771,31793,31799,31817,31847,31849,31859,31873,31883,31891,31907,31957,31963,31973,31981,31991,32003,32009,32027,32029,32051,32057,32059,32063,32069,32077,32083,32089,32099,32117,32119,32141,32143,32159,32173,32183,32189,32191,32203,32213,32233,32237,32251,32257,32261,32297,32299,32303,32309,32321,32323,32327,32341,32353,32359,32363,32369,32371,32377,32381,32401,32411,32413,32423,32429,32441,32443,32467,32479,32491,32497,32503,32507,32531,32533,32537,32561,32563,32569,32573,32579,32587,32603,32609,32611,32621,32633,32647,32653,32687,32693,32707,32713,32717,32719,32749,32771,32779,32783,32789,32797,32801,32803,32831,32833,32839,32843,32869,32887,32909,32911,32917,32933,32939,32941,32957,32969,32971,32983,32987,32993,32999,33013,33023,33029,33037,33049,33053,33071,33073,33083,33091,33107,33113,33119,33149,33151,33161,33179,33181,33191,33199,33203,33211,33223,33247,33287,33289,33301,33311,33317,33329,33331,33343,33347,33349,33353,33359,33377,33391,33403,33409,33413,33427,33457,33461,33469,33479,33487,33493,33503,33521,33529,33533,33547,33563,33569,33577,33581,33587,33589,33599,33601,33613,33617,33619,33623,33629,33637,33641,33647,33679,33703,33713,33721,33739,33749,33751,33757,33767,33769,33773,33791,33797,33809,33811,33827,33829,33851,33857,33863,33871,33889,33893,33911,33923,33931,33937,33941,33961,33967,33997,34019,34031,34033,34039,34057,34061,34123,34127,34129,34141,34147,34157,34159,34171,34183,34211,34213,34217,34231,34253,34259,34261,34267,34273,34283,34297,34301,34303,34313,34319,34327,34337,34351,34361,34367,34369,34381,34403,34421,34429,34439,34457,34469,34471,34483,34487,34499,34501,34511,34513,34519,34537,34543,34549,34583,34589,34591,34603,34607,34613,34631,34649,34651,34667,34673,34679,34687,34693,34703,34721,34729,34739,34747,34757,34759,34763,34781,34807,34819,34841,34843,34847,34849,34871,34877,34883,34897,34913,34919,34939,34949,34961,34963,34981,35023,35027,35051,35053,35059,35069,35081,35083,35089,35099,35107,35111,35117,35129,35141,35149,35153,35159,35171,35201,35221,35227,35251,35257,35267,35279,35281,35291,35311,35317,35323,35327,35339,35353,35363,35381,35393,35401,35407,35419,35423,35437,35447,35449,35461,35491,35507,35509,35521,35527,35531,35533,35537,35543,35569,35573,35591,35593,35597,35603,35617,35671,35677,35729,35731,35747,35753,35759,35771,35797,35801,35803,35809,35831,35837,35839,35851,35863,35869,35879,35897,35899,35911,35923,35933,35951,35963,35969,35977,35983,35993,35999,36007,36011,36013,36017,36037,36061,36067,36073,36083,36097,36107,36109,36131,36137,36151,36161,36187,36191,36209,36217,36229,36241,36251,36263,36269,36277,36293,36299,36307,36313,36319,36341,36343,36353,36373,36383,36389,36433,36451,36457,36467,36469,36473,36479,36493,36497,36523,36527,36529,36541,36551,36559,36563,36571,36583,36587,36599,36607,36629,36637,36643,36653,36671,36677,36683,36691,36697,36709,36713,36721,36739,36749,36761,36767,36779,36781,36787,36791,36793,36809,36821,36833,36847,36857,36871,36877,36887,36899,36901,36913,36919,36923,36929,36931,36943,36947,36973,36979,36997,37003,37013,37019,37021,37039,37049,37057,37061,37087,37097,37117,37123,37139,37159,37171,37181,37189,37199,37201,37217,37223,37243,37253,37273,37277,37307,37309,37313,37321,37337,37339,37357,37361,37363,37369,37379,37397,37409,37423,37441,37447,37463,37483,37489,37493,37501,37507,37511,37517,37529,37537,37547,37549,37561,37567,37571,37573,37579,37589,37591,37607,37619,37633,37643,37649,37657,37663,37691,37693,37699,37717,37747,37781,37783,37799,37811,37813,37831,37847,37853,37861,37871,37879,37889,37897,37907,37951,37957,37963,37967,37987,37991,37993,37997,38011,38039,38047,38053,38069,38083,38113,38119,38149,38153,38167,38177,38183,38189,38197,38201,38219,38231,38237,38239,38261,38273,38281,38287,38299,38303,38317,38321,38327,38329,38333,38351,38371,38377,38393,38431,38447,38449,38453,38459,38461,38501,38543,38557,38561,38567,38569,38593,38603,38609,38611,38629,38639,38651,38653,38669,38671,38677,38693,38699,38707,38711,38713,38723,38729,38737,38747,38749,38767,38783,38791,38803,38821,38833,38839,38851,38861,38867,38873,38891,38903,38917,38921,38923,38933,38953,38959,38971,38977,38993,39019,39023,39041,39043,39047,39079,39089,39097,39103,39107,39113,39119,39133,39139,39157,39161,39163,39181,39191,39199,39209,39217,39227,39229,39233,39239,39241,39251,39293,39301,39313,39317,39323,39341,39343,39359,39367,39371,39373,39383,39397,39409,39419,39439,39443,39451,39461,39499,39503,39509,39511,39521,39541,39551,39563,39569,39581,39607,39619,39623,39631,39659,39667,39671,39679,39703,39709,39719,39727,39733,39749,39761,39769,39779,39791,39799,39821,39827,39829,39839,39841,39847,39857,39863,39869,39877,39883,39887,39901,39929,39937,39953,39971,39979,39983,39989,40009,40013,40031,40037,40039,40063,40087,40093,40099,40111,40123,40127,40129,40151,40153,40163,40169,40177,40189,40193,40213,40231,40237,40241,40253,40277,40283,40289,40343,40351,40357,40361,40387,40423,40427,40429,40433,40459,40471,40483,40487,40493,40499,40507,40519,40529,40531,40543,40559,40577,40583,40591,40597,40609,40627,40637,40639,40693,40697,40699,40709,40739,40751,40759,40763,40771,40787,40801,40813,40819,40823,40829,40841,40847,40849,40853,40867,40879,40883,40897,40903,40927,40933,40939,40949,40961,40973,40993,41011,41017,41023,41039,41047,41051,41057,41077,41081,41113,41117,41131,41141,41143,41149,41161,41177,41179,41183,41189,41201,41203,41213,41221,41227,41231,41233,41243,41257,41263,41269,41281,41299,41333,41341,41351,41357,41381,41387,41389,41399,41411,41413,41443,41453,41467,41479,41491,41507,41513,41519,41521,41539,41543,41549,41579,41593,41597,41603,41609,41611,41617,41621,41627,41641,41647,41651,41659,41669,41681,41687,41719,41729,41737,41759,41761,41771,41777,41801,41809,41813,41843,41849,41851,41863,41879,41887,41893,41897,41903,41911,41927,41941,41947,41953,41957,41959,41969,41981,41983,41999,42013,42017,42019,42023,42043,42061,42071,42073,42083,42089,42101,42131,42139,42157,42169,42179,42181,42187,42193,42197,42209,42221,42223,42227,42239,42257,42281,42283,42293,42299,42307,42323,42331,42337,42349,42359,42373,42379,42391,42397,42403,42407,42409,42433,42437,42443,42451,42457,42461,42463,42467,42473,42487,42491,42499,42509,42533,42557,42569,42571,42577,42589,42611,42641,42643,42649,42667,42677,42683,42689,42697,42701,42703,42709,42719,42727,42737,42743,42751,42767,42773,42787,42793,42797,42821,42829,42839,42841,42853,42859,42863,42899,42901,42923,42929,42937,42943,42953,42961,42967,42979,42989,43003,43013,43019,43037,43049,43051,43063,43067,43093,43103,43117,43133,43151,43159,43177,43189,43201,43207,43223,43237,43261,43271,43283,43291,43313,43319,43321,43331,43391,43397,43399,43403,43411,43427,43441,43451,43457,43481,43487,43499,43517,43541,43543,43573,43577,43579,43591,43597,43607,43609,43613,43627,43633,43649,43651,43661,43669,43691,43711,43717,43721,43753,43759,43777,43781,43783,43787,43789,43793,43801,43853,43867,43889,43891,43913,43933,43943,43951,43961,43963,43969,43973,43987,43991,43997,44017,44021,44027,44029,44041,44053,44059,44071,44087,44089,44101,44111,44119,44123,44129,44131,44159,44171,44179,44189,44201,44203,44207,44221,44249,44257,44263,44267,44269,44273,44279,44281,44293,44351,44357,44371,44381,44383,44389,44417,44449,44453,44483,44491,44497,44501,44507,44519,44531,44533,44537,44543,44549,44563,44579,44587,44617,44621,44623,44633,44641,44647,44651,44657,44683,44687,44699,44701,44711,44729,44741,44753,44771,44773,44777,44789,44797,44809,44819,44839,44843,44851,44867,44879,44887,44893,44909,44917,44927,44939,44953,44959,44963,44971,44983,44987,45007,45013,45053,45061,45077,45083,45119,45121,45127,45131,45137,45139,45161,45179,45181,45191,45197,45233,45247,45259,45263,45281,45289,45293,45307,45317,45319,45329,45337,45341,45343,45361,45377,45389,45403,45413,45427,45433,45439,45481,45491,45497,45503,45523,45533,45541,45553,45557,45569,45587,45589,45599,45613,45631,45641,45659,45667,45673,45677,45691,45697,45707,45737,45751,45757,45763,45767,45779,45817,45821,45823,45827,45833,45841,45853,45863,45869,45887,45893,45943,45949,45953,45959,45971,45979,45989,46021,46027,46049,46051,46061,46073,46091,46093,46099,46103,46133,46141,46147,46153,46171,46181,46183,46187,46199,46219,46229,46237,46261,46271,46273,46279,46301,46307,46309,46327,46337,46349,46351,46381,46399,46411,46439,46441,46447,46451,46457,46471,46477,46489,46499,46507,46511,46523,46549,46559,46567,46573,46589,46591,46601,46619,46633,46639,46643,46649,46663,46679,46681,46687,46691,46703,46723,46727,46747,46751,46757,46769,46771,46807,46811,46817,46819,46829,46831,46853,46861,46867,46877,46889,46901,46919,46933,46957,46993,46997,47017,47041,47051,47057,47059,47087,47093,47111,47119,47123,47129,47137,47143,47147,47149,47161,47189,47207,47221,47237,47251,47269,47279,47287,47293,47297,47303,47309,47317,47339,47351,47353,47363,47381,47387,47389,47407,47417,47419,47431,47441,47459,47491,47497,47501,47507,47513,47521,47527,47533,47543,47563,47569,47581,47591,47599,47609,47623,47629,47639,47653,47657,47659,47681,47699,47701,47711,47713,47717,47737,47741,47743,47777,47779,47791,47797,47807,47809,47819,47837,47843,47857,47869,47881,47903,47911,47917,47933,47939,47947,47951,47963,47969,47977,47981,48017,48023,48029,48049,48073,48079,48091,48109,48119,48121,48131,48157,48163,48179,48187,48193,48197,48221,48239,48247,48259,48271,48281,48299,48311,48313,48337,48341,48353,48371,48383,48397,48407,48409,48413,48437,48449,48463,48473,48479,48481,48487,48491,48497,48523,48527,48533,48539,48541,48563,48571,48589,48593,48611,48619,48623,48647,48649,48661,48673,48677,48679,48731,48733,48751,48757,48761,48767,48779,48781,48787,48799,48809,48817,48821,48823,48847,48857,48859,48869,48871,48883,48889,48907,48947,48953,48973,48989,48991,49003,49009,49019,49031,49033,49037,49043,49057,49069,49081,49103,49109,49117,49121,49123,49139,49157,49169,49171,49177,49193,49199,49201,49207,49211,49223,49253,49261,49277,49279,49297,49307,49331,49333,49339,49363,49367,49369,49391,49393,49409,49411,49417,49429,49433,49451,49459,49463,49477,49481,49499,49523,49529,49531,49537,49547,49549,49559,49597,49603,49613,49627,49633,49639,49663,49667,49669,49681,49697,49711,49727,49739,49741,49747,49757,49783,49787,49789,49801,49807,49811,49823,49831,49843,49853,49871,49877,49891,49919,49921,49927,49937,49939,49943,49957,49991,49993,49999]\nsetprimes = set(primes)\ndef sprime(a,b):\n for p in primes:\n if p>= b: break\n if p>= a: yield p"]
{"fn_name": "solve", "inputs": [[0, 20], [2, 200], [2, 2000], [1000, 3000], [2000, 5000]], "outputs": [[14], [457], [17705], [12801], [25005]]}
INTRODUCTORY
PYTHON3
CODEWARS
38,443
def solve(a, b):
d206b5c6968cf7ec092410de72f4ad4c
UNKNOWN
In this kata, you will write a function that returns the positions and the values of the "peaks" (or local maxima) of a numeric array. For example, the array `arr = [0, 1, 2, 5, 1, 0]` has a peak at position `3` with a value of `5` (since `arr[3]` equals `5`). ~~~if-not:php,cpp,java,csharp The output will be returned as an object with two properties: pos and peaks. Both of these properties should be arrays. If there is no peak in the given array, then the output should be `{pos: [], peaks: []}`. ~~~ ~~~if:php The output will be returned as an associative array with two key-value pairs: `'pos'` and `'peaks'`. Both of them should be (non-associative) arrays. If there is no peak in the given array, simply return `['pos' => [], 'peaks' => []]`. ~~~ ~~~if:cpp The output will be returned as an object of type `PeakData` which has two members: `pos` and `peaks`. Both of these members should be `vector`s. If there is no peak in the given array then the output should be a `PeakData` with an empty vector for both the `pos` and `peaks` members. `PeakData` is defined in Preloaded as follows: ~~~ ~~~if:java The output will be returned as a ``Map>` with two key-value pairs: `"pos"` and `"peaks"`. If there is no peak in the given array, simply return `{"pos" => [], "peaks" => []}`. ~~~ ~~~if:csharp The output will be returned as a `Dictionary>` with two key-value pairs: `"pos"` and `"peaks"`. If there is no peak in the given array, simply return `{"pos" => new List(), "peaks" => new List()}`. ~~~ Example: `pickPeaks([3, 2, 3, 6, 4, 1, 2, 3, 2, 1, 2, 3])` should return `{pos: [3, 7], peaks: [6, 3]}` (or equivalent in other languages) All input arrays will be valid integer arrays (although it could still be empty), so you won't need to validate the input. The first and last elements of the array will not be considered as peaks (in the context of a mathematical function, we don't know what is after and before and therefore, we don't know if it is a peak or not). Also, beware of plateaus !!! `[1, 2, 2, 2, 1]` has a peak while `[1, 2, 2, 2, 3]` does not. In case of a plateau-peak, please only return the position and value of the beginning of the plateau. For example: `pickPeaks([1, 2, 2, 2, 1])` returns `{pos: [1], peaks: [2]}` (or equivalent in other languages) Have fun!
["def pick_peaks(arr):\n pos = []\n prob_peak = False\n for i in range(1, len(arr)):\n if arr[i] > arr[i-1]:\n prob_peak = i\n elif arr[i] < arr[i-1] and prob_peak:\n pos.append(prob_peak)\n prob_peak = False\n return {'pos':pos, 'peaks':[arr[i] for i in pos]}", "def pick_peaks(arr):\n peak, pos = [], []\n res = { \"peaks\":[], \"pos\":[] }\n \n for i in range(1, len(arr)) :\n if arr[i]>arr[i-1] :\n peak, pos = [arr[i]], [i]\n \n elif arr[i]<arr[i-1] :\n res[\"peaks\"] += peak\n res[\"pos\"] += pos\n peak, pos = [], []\n \n return res", "def pick_peaks(arr):\n \n def add_peak(p):\n peaks[\"pos\"].append(p)\n peaks[\"peaks\"].append(arr[p])\n \n def is_peak(p):\n return arr[p-1] < arr[p] > arr[p+1]\n \n def is_plateau_start(p):\n return arr[p-1] < arr[p] == arr[p+1]\n \n def does_plateau_end_lower(p):\n return next((val for val in arr[p+1:] if val != arr[p]), arr[p]) < arr[p]\n\n peaks = {\"pos\":[], \"peaks\":[]}\n for p in range(1, len(arr)-1):\n if is_peak(p):\n add_peak(p)\n elif is_plateau_start(p) and does_plateau_end_lower(p):\n add_peak(p)\n \n return peaks", "def pick_peaks(arr):\n peaks = []\n pos = []\n current_pos = None\n \n for i in range(len(arr)-1):\n if arr[i] < arr[i+1]:\n current_pos = i+1\n elif arr[i] > arr[i+1] and i != 0 and current_pos is not None:\n pos += [current_pos]\n peaks += [arr[current_pos]]\n current_pos = None\n \n return {\"pos\":pos, \"peaks\":peaks}", "\n\n\ndef pick_peaks(a):\n deltas = [(i, x2 - x1) for i, (x1, x2) in enumerate(zip(a, a[1:]), 1) if x1 != x2]\n indexes = [i for (i, dx1), (_, dx2) in zip(deltas, deltas[1:]) if dx1 > 0 > dx2]\n return dict(pos=indexes, peaks=[a[i] for i in indexes])\n", "def pick_peaks(arr):\n peaks = {\"pos\":[], \"peaks\":[]}\n for i in range(1, len(arr)):\n next_num = next((num for num in arr[i:] if num != arr[i]), float(\"inf\"))\n if arr[i-1] < arr[i] and next_num < arr[i]:\n peaks[\"pos\"].append(i)\n peaks[\"peaks\"].append(arr[i])\n return peaks\n", "def pick_peaks(arr):\n\n PairList = []\n\n for i,e in enumerate(arr):\n \n if arr[i-1] >= e or i == 0:\n \n continue\n \n for k in arr[i:]:\n \n if k == e:\n \n continue\n \n elif k > e:\n \n break\n \n else:\n \n PairList.append([i,e])\n break \n \n return {'pos':[k[0] for k in PairList], 'peaks':[k[1] for k in PairList]}", "def pick_peaks(arr):\n prev_dex = prev_val = None\n result = {'pos': [], 'peaks': []}\n upwards = False\n for i, a in enumerate(arr):\n if prev_val == a:\n continue\n elif prev_val is None or prev_val < a:\n upwards = True\n else:\n if prev_dex and upwards:\n result['pos'].append(prev_dex)\n result['peaks'].append(prev_val)\n upwards = False\n prev_dex = i\n prev_val = a\n return result\n", "import re\n\ndef pick_peaks(arr):\n slope = \"\".join(\"u\" if b > a else \"d\" if a > b else \"p\" for a, b in zip(arr, arr[1:]))\n positions = [m.start() + 1 for m in re.finditer(r\"up*d\", slope)]\n peaks = [arr[pos] for pos in positions]\n return {\"pos\": positions, \"peaks\": peaks}", "def pick_peaks(arr):\n cast = []\n \n for i,e in enumerate(arr):\n if cast and e == cast[-1][0]:#\n continue\n cast.append((e,i))\n \n doc = {\"pos\":[], \"peaks\":[]}#\n \n for i in range(1,len(cast)-1):\n if cast[i-1][0] < cast[i][0] > cast[i+1][0]:\n doc['peaks'].append(cast[i][0])\n doc['pos'].append(cast[i][1])\n \n return doc", "# In this kata, you will write a function that returns the positions\n# and the values of the \"peaks\" (or local maxima) of a numeric array.\n# For example, the array arr = [0, 1, 2, 5, 1, 0] has a peak\n# at position 3 with a value of 5 (since arr[3] equals 5).\n# The output will be returned as an object with two properties: pos and peaks.\n# Both of these properties should be arrays. If there is no peak\n# in the given array, then the output should be {pos: [], peaks: []}.\n# Example: pickPeaks([3, 2, 3, 6, 4, 1, 2, 3, 2, 1, 2, 3])\n# should return {pos: [3, 7], peaks: [6, 3]} (or equivalent in other languages)\n# All input arrays will be valid integer arrays (although it could still\n# be empty), so you won't need to validate the input.\n# The first and last elements of the array will not be considered as peaks\n# (in the context of a mathematical function, we don't know what is after\n# and before and therefore, we don't know if it is a peak or not).\n# Also, beware of plateaus !!! [1, 2, 2, 2, 1] has a peak while\n# [1, 2, 2, 2, 3] does not. In case of a plateau-peak, please only\n# return the position and value of the beginning of the plateau.\n# For example: pickPeaks([1, 2, 2, 2, 1]) returns {pos: [1], peaks: [2]}\n# (or equivalent in other languages)\n\ndef sign(x):\n if x>0:\n return 1\n elif x<0:\n return -1\n elif x==0:\n return 0\n\ndef pick_peaks(arr):\n pos = []\n peaks = []\n l = len(arr)\n# Calculate differential array \n diff_arr = []\n for i in range (0, l-1):\n diff_arr.append(sign(arr[i+1] - arr[i]))\n# Pick_Peaks\n i = 0\n while i < l-2:\n k = 1\n while sign(diff_arr[i+k]) == 0 and i+k < l-2:\n k += 1\n if (sign(diff_arr[i+k]) < sign(diff_arr[i]) and\n sign(diff_arr[i]) != 0 and sign(diff_arr[i+k]) != 0):\n pos.append(i+1)\n peaks.append(arr[i+1])\n i += k\n# Create Dictionary! \n d_pos_peaks = dict(pos=pos, peaks=peaks) \n return d_pos_peaks", "def pick_peaks(arr):\n redic = { \"pos\":[], \"peaks\":[] }\n for i in range(1,len(arr)-1):\n if all(( arr[i] > arr[i-1], arr[i] >= arr[i+1])):\n j = i\n while arr[j] == arr[i] and j < len(arr)-1:\n j += 1\n if arr[j] < arr[i]:\n redic['pos'].append(i)\n redic['peaks'].append(arr[i])\n return redic", "def pick_peaks(arr):\n result = {'pos': [], 'peaks':[]}\n increasing = False\n for i in range(1, len(arr)):\n if arr[i] > arr[i-1]:\n increasing = True\n tmpk = arr[i]\n tmpindx = i\n elif arr[i] < arr[i-1]:\n if increasing:\n result['pos'].append(tmpindx)\n result['peaks'].append(tmpk)\n increasing = False\n return result", "def pick_peaks(a):\n a=[int(i) for i in a]\n pred = 0\n prov = False\n peaks = []\n pos = []\n count = 0\n spusk = True\n\n for i in range(len(a)):\n if pred == a[i] and spusk==False:\n count+=1\n prov = True\n continue\n if pred > a[i]:\n if prov==True:\n peaks.append(a[i-1])\n pos.append(i-1-count)\n prov=False\n spusk=True\n elif i!=0 and pred < a[i]:\n prov = True\n spusk=False\n pred = a[i]\n count = 0\n d = {\"pos\": pos, \"peaks\" : peaks}\n\n return d", "def pick_peaks(arr):\n i, pos = len(arr) - 2, []\n while i > 0:\n while i > 0 and arr[i + 1] >= arr[i]:\n i -= 1\n while i > 0 and arr[i + 1] <= arr[i]:\n i -= 1\n if arr[i + 1] > arr[i]:\n pos.append(i + 1)\n return {'peaks': [arr[i] for i in pos[::-1]], 'pos': pos[::-1]}", "def pick_peaks(arr):\n result = {'pos': [], 'peaks': []}\n pos = 0\n for i in range(1, len(arr) - 1):\n if arr[i] != arr[pos]:\n pos = i\n if pos and arr[pos - 1] < arr[pos] > arr[i + 1]:\n result['pos'].append(pos)\n result['peaks'].append(arr[pos])\n return result", "def pick_peaks(arr):\n print(arr)\n peaks = {'pos':[], 'peaks': []}\n enum_arr = list(enumerate(arr))\n possible_peaks = enum_arr[1:-1]\n for point in possible_peaks:\n current_p, current_v = point[0], point[1]\n prior_p, prior_v = enum_arr[current_p - 1]\n next_p, next_v = enum_arr[current_p + 1]\n is_peak = prior_v < current_v > next_v\n if is_peak:\n peaks['pos'].append(current_p)\n peaks['peaks'].append(current_v)\n is_plateau = prior_v == current_v or current_v == next_v\n if is_plateau:\n is_peak = prior_v < current_v\n i = current_p\n while is_peak:\n try:\n next = enum_arr[i + 1][1]\n curr = enum_arr[i][1]\n except IndexError:\n break\n next_plateau = next == curr\n if not next_plateau:\n peak_end = next < curr\n if peak_end:\n peaks['pos'].append(current_p)\n peaks['peaks'].append(current_v)\n is_peak = False\n else:\n break\n i += 1\n return peaks", "def pick_peaks(arr):\n pos_delta = [pd for pd in enumerate((b - a for a, b in zip(arr, arr[1:])), 1) if pd[1]]\n positions = [a[0] for a, b in zip(pos_delta, pos_delta[1:]) if a[1] > 0 and b[1] < 0]\n return {'pos': positions, 'peaks': [arr[p] for p in positions]}\n", "def pick_me(arr):\n plateau = None\n\n for i, p in enumerate(arr[1:-1]):\n # peak as is\n if arr[i] < p > arr[i+2]:\n yield(i+1, p)\n plateau = None\n\n # start of potential plateau\n if arr[i] < p == arr[i+2]:\n plateau = (i+1, p)\n\n # found end of plateau\n if plateau and arr[i] == p > arr[i+2]:\n yield plateau\n plateau = None\n\n\ndef pick_peaks(arr):\n picked = list(zip(*pick_me(arr)))\n pos, peaks = picked if picked else ([], [])\n\n return {\n \"pos\": list(pos), \n \"peaks\": list(peaks)\n }\n", "def pick_peaks(arr):\n res = {'pos': [], 'peaks': []}\n for i in range(1, len(arr) - 1):\n if arr[i - 1] < arr[i] > arr[[n for n in range(i, len(arr)) if arr[n] != arr[i] or n == len(arr) - 1][0]]:\n res.update({'pos': res.get('pos') + [i]})\n res.update({'peaks': res.get('peaks') + [arr[i]]})\n return res", "def pick_peaks(arr):\n lastind = -1\n pos = list()\n peaks = list()\n status = 'init'\n for i in range(1, len(arr)):\n if arr[i] > arr[i-1]:\n status = 'rising'\n lastind = i\n elif arr[i] < arr[i-1]:\n if status=='rising':\n pos.append(lastind)\n peaks.append(arr[i-1])\n status = 'lol'\n return {\"pos\": pos, \"peaks\": peaks}", "def pick_peaks(arr):\n if not arr:\n return {\"pos\": [], \"peaks\": []}\n \n pos = []\n peaks = []\n arr_iter = enumerate(arr)\n curr_pos, curr_peak = next(arr_iter)\n climbing = False\n \n for index, value in arr_iter:\n if value > curr_peak:\n curr_pos, curr_peak = index, value\n climbing = True\n elif value < curr_peak:\n if climbing:\n pos.append(curr_pos)\n peaks.append(curr_peak)\n climbing = False\n curr_pos, curr_peak = index, value\n \n return {\"pos\": pos, \"peaks\": peaks}\n", "def pick_peaks (nums):\n pp_dict = {'pos': [], 'peaks': []}\n size = len(nums)\n i = 1\n \n for i in range (1, size - 1):\n if nums[i] > nums[i - 1]:\n plateau_start = i\n try:\n while nums[i] == nums[i + 1]:\n i += 1\n if nums[i] > nums[i + 1]:\n pp_dict['pos'].append (plateau_start)\n pp_dict['peaks'].append (nums[plateau_start])\n except LookupError:\n break\n \n return pp_dict\n \n", "def pick_peaks(arr):\n coords = {'pos': [i for i in range(1, len(arr) - 1) if arr[i - 1] < arr[i] >\n arr[[x for x in range(i, len(arr)) if arr[x] != arr[i] or x == len(arr) - 1][0]]]}\n coords.update({'peaks':[arr[elem] for elem in coords.get('pos') ]})\n return coords", "def pick_peaks(arr):\n # compress arr, keeping track of position of the first occurance of a value\n ppos = [i for i, x in enumerate(arr) if i == 0 or arr[i-1] != arr[i]]\n pos = [ppos[i] for i in range(1,len(ppos)-1) \\\n if arr[ppos[i]] > arr[ppos[i-1]] and arr[ppos[i]] > arr[ppos[i+1]] ]\n return {'pos': pos, 'peaks': [arr[i] for i in pos]}\n", "def pick_peaks(arr):\n maximas, positions = [], []\n for i, num in enumerate(arr):\n same_as_num = [x == num for x in arr[i:]]\n end = not all(same_as_num) and i + same_as_num.index(False) - 1\n local_max = end and num > arr[i - 1] and num > arr[end + 1]\n \n if not (i == 0 or i == len(arr) - 1) and local_max:\n maximas.append(arr[i])\n positions.append(i)\n\n return {\"pos\": positions, \"peaks\": maximas}\n", "def pick_peaks(arr):\n pos = []\n for i in range(1, len(arr)-1):\n # next index with a value != current_value\n next_i = next((n for n, v in enumerate(arr[i:]) if v != arr[i]), None)\n if arr[i-1] < arr[i] and next_i and arr[i] > arr[i:][next_i]:\n pos.append(i)\n return {\n 'pos': pos,\n 'peaks': [arr[po] for po in pos], \n }", "def next_different_value(arr, index):\n next_index = index + 1\n while arr[index] == arr[next_index] and next_index != len(arr) - 1:\n next_index += 1\n return arr[index] > arr[next_index]\n\ndef pick_peaks(arr):\n res = {'pos': [], 'peaks': []}\n if len(arr) < 3:\n return res\n def fill_res(pos, peaks):\n res['pos'].append(pos)\n res['peaks'].append(peaks)\n for index, value in enumerate(arr):\n if index not in [0, len(arr) - 1]:\n if arr[index] > arr[index - 1] and next_different_value(arr, index):\n fill_res(index, value)\n return res", "def pick_peaks(arr):\n p = []\n z = []\n res = {\"pos\": [], \"peaks\": []}\n for i, k in enumerate(arr[1:-1]):\n if k > arr[i] and k > arr[i+2]:\n p.append(i+1)\n z.append(k)\n elif k == arr[i+2] and k > arr[i]:\n n = 1\n while True:\n n += 1\n if k != arr[i+n] or i+n == len(arr)-1:\n break\n if k > arr[i+n]:\n p.append(i+1)\n z.append(k)\n res[\"pos\"] = p\n res[\"peaks\"] = z\n return res", "def pick_peaks(arr):\n out = {}\n i, wait_pick, temp_pick = 1, 0, 0\n while i < len(arr) - 1:\n if arr[i] == arr[i+1] and arr[i] > arr[i-1]:\n temp_pick = i\n wait_pick = 1\n i += 1 \n continue\n if wait_pick == 1:\n if arr[i] > arr[i+1]:\n out[temp_pick] = arr[temp_pick]\n wait_pick = 0\n elif arr[i] < arr[i+1]:\n wait_pick = 0\n i += 1\n else:\n if arr[i] > arr[i-1] and arr[i] > arr[i+1]:\n out[i] = arr[i]\n i += 1\n return {\"pos\": list(out.keys()), \"peaks\": list(out.values())}", "def pick_peaks(arr):\n pos = []\n peaks = []\n i = 1\n while i < len(arr)-1:\n if arr[i-1] < arr[i] and arr[i] > arr[i+1]: #case when there is a simple peak\n pos.append(i); peaks.append(arr[i])\n elif arr[i-1] < arr[i] < arr[i+1]: #case when the value of each number is incrementing\n pass\n elif arr[i-1] < arr[i]: #the case when we have a plato\n if i < len(arr): #to avoid the situation of i value greater then arr len\n for j in range(i,len(arr)-1): #we check all number to len(arr)-1 \n if arr[j] == arr[j+1]: #to understand when and where the plato ends\n continue #plato continues\n elif arr[j] < arr[j+1]: #case when we meet the number which is greater\n i = j - 1 #then each plato's number\n break\n elif arr[j] > arr[j+1]: #case when the plato has ended we simply add \n pos.append(i) #the i and its value to lists\n peaks.append(arr[i])\n i = j - 1\n break\n i+=1\n\n return {'pos': pos, 'peaks': peaks}", "def pick_peaks(a):\n po, pe = 'pos', 'peaks'\n d = { po: [], pe: [] }\n for n in range(2, len(a)):\n b, P, e = n-2, n-1, n \n if a[ b ] < a[ P ] >= a[ e ]: \n if len(a[ P : ]) != a[ P : ].count(a[ P ]): \n if max( a[ P : ] ) >= a[ P ] :\n if d[po]:\n if min( a[ d[po][-1] : P ] ) >= d[pe][-1]:\n d[po] = d[po][ : -1]\n d[pe] = d[pe][ : -1]\n d[po].append( P )\n d[pe].append( a[ P ] )\n return d", "def pick_peaks(array):\n peaks, pos = [], []\n platpos = platpeaks = \"\"\n\n for i in range(1, len(array) - 1):\n if array[i - 1] < array[i] > array[i + 1]:\n peaks.append(array[i]), pos.append(i)\n elif array[i - 1] < array[i] == array[i + 1]:\n platpos, platpeaks = i, array[i]\n elif array[i - 1] == array[i] > array[i + 1] and platpos != \"\":\n pos.append(platpos), peaks.append(platpeaks)\n\n return{\"pos\": pos, \"peaks\": peaks}", "def pick_peaks(arr):\n peaks = []\n pos = []\n i = 0\n clean = list(arr)\n \n while i < len(clean)-1:\n if i == 0 or i == len(clean)-1:\n i = i + 1\n pass\n else:\n c = 1\n while clean[i] == clean[i+c] and i+c<len(clean)-1:\n c = c+1\n \n if clean[i] > clean[i-1] and clean[i] > clean[i+c]:\n peaks.append (clean[i])\n pos.append(i)\n \n i = i+c\n\n return {\"pos\":pos, \"peaks\":peaks}\n", "def pick_peaks(arr):\n peak = []\n pos = []\n prev = 0\n growing = False\n for i in range(1,len(arr)):\n if arr[prev] > arr[i] and growing:\n peak.append(arr[prev])\n pos.append(prev)\n growing = False\n elif arr[prev] < arr[i]:\n growing = True\n if arr[prev] == arr[i]:\n prev = prev\n else:\n prev = i\n return { 'pos' : pos, 'peaks' : peak}\n", "def pick_peaks(arr):\n pos = []\n peaks = []\n for x, num in enumerate(arr):\n if x == 0 or x == len(arr)-1:\n continue\n if arr[x-1] < num and arr[x+1] < num:\n pos.append(x)\n peaks.append(num)\n elif arr[x-1] < num and arr[x+1] == num:\n # checks for plateau peaks\n i = x\n plateau = True\n while plateau:\n i+= 1\n try:\n if arr[i] < num:\n pos.append(x)\n peaks.append(num)\n plateau = False\n elif arr[i] > num:\n plateau = False\n except IndexError:\n plateau = False\n \n return {'pos':pos, 'peaks': peaks}\n \n \n \n", "def pick_peaks(arr):\n pos = []\n peaks = []\n i = 1\n while i < len(arr) - 1:\n if arr[i - 1] < arr[i]:\n j = i + 1\n while j < len(arr):\n print(arr[i], arr[j])\n if arr[i] > arr[j]:\n pos.append(i)\n peaks.append(arr[i])\n break\n elif arr[i] == arr[j]:\n j += 1\n else:\n break\n i += 1\n return {\"pos\": pos, \"peaks\": peaks}", "from itertools import groupby\ndef pick_peaks(arr):\n# remove plateaus using groupby and just remember the first occurrence position\n# build a new list called \"sequence\"\n start = 0\n sequence = []\n for key, group in groupby(arr):\n sequence.append((key, start)) # adds tuples for key and first occurrence\n start += sum(1 for element in group) # start plus number of consequtive occurrences\n \n peaks = []\n pos = [] \n# b like before tuple(value, original index), m like middle, a like after \n for (b, bi), (m, mi), (a, ai) in zip(sequence, sequence[1:], sequence[2:]):\n if b < m and a < m:\n pos.append(mi)\n peaks.append(m)\n# Build result \n result = {}\n result['pos'] = pos\n result['peaks'] = peaks\n return result\n", "def pick_peaks(arr):\n real = [arr[x] for x in range(len(arr) -1) if arr[x] != arr[x+1]]\n track = [x for x in range(len(arr)-1) if arr[x] == arr[x+1]]\n if real:\n real.append(arr[-1])\n pos = [x for x in range(1, len(real)-1) if (real[x] > real[x-1]) and (real[x] > real[x+1])]\n posn = [x+1 for x in range(1,)]\n peak = [real[x] for x in range(1, len(real)-1) if (real[x] > real[x-1]) and (real[x] > real[x+1])]\n new = []\n count = 0\n a = 0\n for i in range(len(real)):\n if arr[i+count] != real[i]:\n skip = 0\n while arr[i+count] != real[i]:\n count += 1\n skip += 1\n if new:\n new.append([i + new[-1][1], skip])\n else:\n new.append([i, skip])\n for j in range(len(new)):\n for k in range(len(pos)):\n if pos[k] >= new[j][0]:\n pos[k] = pos[k] + new[j][1]\n\n total = {\"pos\": pos, \"peaks\": peak}\n return total", "def pick_peaks(arr):\n #your code here\n pos = []\n peaks = []\n plateau = []\n\n numbers = len(arr)\n print(\"length of array: \"+str(numbers))\n print(\"list:\")\n print(arr)\n\n for number in range(numbers):\n if number == 0 or number == (numbers - 1):\n pass\n else:\n candidate = arr[number]\n pre = arr[(number - 1)]\n post = arr[(number + 1)]\n if candidate > pre and candidate > post:\n pos.append(number)\n peaks.append(candidate)\n elif number == 1 or number == (numbers - 2):\n pass\n# elif candidate == post and candidate == arr[(number + 2)] and number != (number - 1):\n elif candidate > pre and candidate == post: \n if candidate >= arr[(number + 2)] and number != (number - 1) and candidate != arr[(numbers - 1)]:\n pos.append(number)\n peaks.append(candidate)\n else:\n pass\n print(\"plateau:\")\n print(plateau)\n answer = {}\n answer[\"pos\"] = pos\n answer[\"peaks\"] = peaks\n print(answer)\n return answer", "def pick_peaks(arr):\n start = 0\n sequence = []\n ind,val=[],[]\n posPeaks = {\n \"pos\": [],\n \"peaks\": [], }\n\n from itertools import groupby\n\n for key, group in groupby(arr):\n sequence.append((key, start))\n start += sum(1 for _ in group)\n\n for (b, bi), (m, mi), (a, ai) in zip(sequence, sequence[1:], sequence[2:]):\n if b < m and a < m:\n ind.append(mi)\n val.append(m)\n \n posPeaks[\"pos\"]=ind\n posPeaks[\"peaks\"]=val\n return (posPeaks)", "def pick_peaks(arr):\n result = {\"pos\":[],\"peaks\":[]}\n for i in range(1,len(arr)-1):\n if arr[i]>arr[i-1] and arr[i]>arr[i+1]:\n result[\"pos\"].append(i)\n result[\"peaks\"].append(arr[i])\n \n elif arr[i]>arr[i-1] and arr[i]==arr[i+1]:\n for k in range(i+2,len(arr)):\n if arr[i]>arr[k]:\n result[\"pos\"].append(i)\n result[\"peaks\"].append(arr[i])\n break\n elif arr[k]>arr[i]:\n break\n return result\n", "def pick_peaks(arr):\n #your code here\n result=[]\n resultIndex=[]\n for element in range(len(arr)):\n if element>0 and element!=(len(arr)-1):\n if arr[element]>arr[element-1] and arr[element]>arr[element+1]:\n peak=arr[element]\n result.append(peak)\n resultIndex.append(element)\n elif(arr[element]>arr[element-1] and arr[element]==arr[element+1] ):\n curr=arr[element]\n currIndex=element\n for next in range(element+1,len(arr)-1):\n if(arr[next]>arr[next+1]):\n result.append(curr)\n resultIndex.append(currIndex)\n break\n elif(arr[next]==arr[next+1]):\n continue\n else:\n break\n return {\"pos\":resultIndex,\"peaks\":result}", "def pick_peaks(arr):\n #your code here\n result = {'pos':[], 'peaks':[]}\n flagIndex = -1\n for i in range(1, len(arr)-1):\n if arr[i-1] < arr[i] > arr[i+1]:\n result['pos'].append(i)\n result['peaks'].append(arr[i])\n elif arr[i-1] < arr[i] == arr[i+1]:\n flagIndex = i\n elif flagIndex != -1:\n if arr[i] > arr[i+1]:\n result['pos'].append(flagIndex)\n result['peaks'].append(arr[flagIndex])\n flagIndex = -1\n elif arr[i] < arr[i+1]:\n flagIndex = -1\n \n return result", "def pick_peaks(arr):\n output = {\"pos\": [], \"peaks\": []}\n topPos = 0\n if len(arr) > 0:\n topPeak = arr[0]\n for i in range(1, len(arr)):\n if arr[i] > arr[i-1]:\n topPos = i\n topPeak = arr[i]\n elif arr[i] < arr[i-1]:\n \"\"\" It's help to know if there was a climbing previously \"\"\"\n if topPos > 0:\n output[\"pos\"].append(topPos)\n output[\"peaks\"].append(topPeak)\n topPos = 0\n return output", "\n\ndef pick_peaks(arr):\n out = {\n 'pos': [],\n 'peaks': []\n }\n if len(arr) == 0:\n return out\n last_i = arr[0]\n latest_maxima = None\n latest_maxima_pos = None\n for pos in range(len(arr)):\n i = arr[pos]\n if i > last_i:\n latest_maxima = i\n latest_maxima_pos = pos\n if i < last_i and latest_maxima is not None:\n out['pos'].append(latest_maxima_pos)\n out['peaks'].append(latest_maxima)\n latest_maxima = None\n latest_maxima_pos = None\n last_i = i\n return out", "def pick_peaks(arr):\n dict = {\"pos\": [], \"peaks\": []}\n \n for i in range(1, len(arr)-1):\n if(arr[i-1] < arr[i] and arr[i] > arr[i+1]):\n dict[\"pos\"].append(i)\n dict[\"peaks\"].append(arr[i])\n \n elif(arr[i-1] < arr[i] and (arr[i] == arr[i+1])):\n cur = i+1\n while cur+1 < len(arr):\n if(arr[cur] > arr[cur+1]):\n dict[\"pos\"].append(i)\n dict[\"peaks\"].append(arr[i])\n break\n if(arr[cur] < arr[cur+1]):\n break\n cur+=1\n \n \n return dict", "def pick_peaks(a):\n ind = []\n val = []\n for i in range(1, len(a)-1):\n if a[i-1] < a[i] and a[i] > a[i+1]:\n ind.append(i)\n val.append(a[i])\n elif a[i] > a[i-1] and a[i] == a[i+1]:\n for j in range(i+1, len(a)-1):\n if a[j] == a[i] and a[j]<a[j+1]:\n break\n elif a[j] == a[i] and a[j+1]<a[j]:\n ind.append(i)\n val.append(a[i])\n break\n return {'pos': ind, 'peaks': val}", "def pick_peaks(arr):\n local_peaks = {\n 'pos': [],\n 'peaks': []\n }\n count = 1\n length = len(arr)\n while count < length - 1:\n\n value = arr[count]\n add_node = False\n if value >= arr[count + 1] and value > arr[count - 1]:\n if value == arr[count + 1]:\n #checking if value eventually goes down\n for i in range(2, length - count):\n if arr[count + i] > value:\n break\n elif arr[count + i] < value:\n add_node = True\n \n else:\n add_node = True\n \n if add_node:\n local_peaks['pos'].append(count)\n local_peaks['peaks'].append(value) \n count += 1\n\n return local_peaks", "def pick_peaks(arr): \n l=[]\n t=[]\n for i in range(len(arr)-2):\n if arr[i+1]>arr[i]:\n k=0\n while k+i+1<len(arr):\n if arr[k+i+1]>arr[i+1]:\n break\n if arr[k+i+1]<arr[i+1]:\n l.append(arr[i+1])\n t.append(i+1)\n break\n k=k+1\n return {'pos':t,'peaks':l}", "def pick_peaks(a):\n pos = []\n try:\n for k in range(1, len(a) - 1):\n if a[k] > a[k - 1] and a[k] > a[k + 1]:\n pos.append(k)\n elif a[k] > a[k - 1] and a[k] == a[k + 1]:\n i = k + 2\n while i < len(a) - 1 and a[i] == a[k]:\n i += 1\n \n if a[i] < a[k]:\n pos.append(k)\n else:\n k = i\n \n peaks = [a[i] for i in pos]\n return {'pos': pos, 'peaks': peaks}\n except IndexError:\n print(a)\n print('i=', i)", "def pick_peaks(arr):\n d = {\"pos\" : [], \"peaks\" : []}\n i = 0\n print(arr)\n if len(arr) > 2 and arr[0] >= arr[1]:\n while arr[i] >= arr[i+1] and i < len(arr)-2:\n i += 1 \n while i < len(arr)-1:\n if arr[i] < arr[i+1]:\n pass \n elif arr[i] == arr[i+1]:\n temp = i\n while arr[i] == arr[i+1] and i < len(arr)-2:\n i+=1\n if arr[i] > arr[i+1]:\n d[\"pos\"].append(temp)\n d[\"peaks\"].append(arr[temp])\n while arr[i] >= arr[i+1] and i < len(arr)-2:\n i += 1\n else:\n d[\"pos\"].append(i)\n d[\"peaks\"].append(arr[i])\n while arr[i] >= arr[i+1] and i < len(arr)-2:\n i += 1\n i+=1\n return d", "def pick_peaks(arr):\n #your code here\n a_1 = []\n a_2 = []\n\n result_ab = {'pos': a_1, 'peaks': a_2}\n\n for i in range(0, (len(arr)-1)):\n if (i != 0) and (i != len(arr)-1):\n if (arr[i] > arr[i-1]) and (arr[i] > arr[i+1]):\n a_1.append(i)\n a_2.append(arr[i]) \n elif (arr[i] > arr[i-1]) and (arr[i] == arr[i+1]):\n # elem = i\n copy_arr = arr[:]\n while (copy_arr[i] == copy_arr[i+1]):\n del copy_arr[i+1]\n if i != len(copy_arr)-1:\n if (copy_arr[i] > copy_arr[i+1]): # !!!\n a_1.append(i)\n a_2.append(arr[i]) \n break\n elif (copy_arr[i] == copy_arr[i+1]):\n continue\n else:\n break\n else:\n break\n else:\n pass\n else:\n pass\n\n return result_ab\n", "def isPeak(arr, pos):\n if pos == 0 or pos == len(arr) - 1:\n return False\n if arr[pos - 1] >= arr[pos]:\n return False\n for nextElem in arr[pos + 1:]:\n if nextElem > arr[pos]:\n return False\n if nextElem < arr[pos]:\n return True\n\ndef pick_peaks(arr):\n result = {\"pos\": [], \"peaks\": []}\n for pos, val in enumerate(arr):\n if isPeak(arr, pos):\n result[\"pos\"].append(pos)\n result[\"peaks\"].append(val)\n return result\n", "def pick_peaks(arr):\n out = {}\n pos = []\n peaks = []\n temp = []\n for i, x in enumerate(arr[1:-1], start=1):\n prev = arr[i-1]\n nxt = arr[i+1]\n if x > prev:\n temp = [i, x]\n if x < prev and temp or x > nxt and temp:\n pos.append(temp[0])\n peaks.append(temp[1])\n temp.clear()\n\n out['pos'] = pos\n out['peaks'] = peaks\n return out", "from itertools import groupby\n\ndef pick_peaks(arr):\n\n result = {'pos':[], 'peaks':[]}\n if not arr: return result\n \n arr = dict(enum(list(j) for i,j in groupby(arr))) \n keys = sorted(arr.keys())\n \n for i in arr: \n if i != keys[0] and i != keys[-1]: \n curr = arr[i][0]\n prev = arr[keys[keys.index(i) + 1]][0]\n post = arr[keys[keys.index(i) - 1]][0]\n \n if curr > post and curr > prev:\n result['pos'] = result['pos'] + [i]\n result['peaks'] = result['peaks'] + [arr[i][0]]\n return result\n \ndef enum(listA):\n value = 0\n for j in listA:\n if len(j) == 1:\n yield(value,j)\n value += 1\n else:\n yield(value, j)\n value += len(j) ", "def pick_peaks(arr):\n obj = {\"pos\": [], \"peaks\": []}\n \n if len(arr) == 0:\n return obj\n \n upward = True if arr[0] < arr[1] else False\n pos = 1\n plateau = 0\n \n while pos < len(arr) - 1:\n if upward:\n if arr[pos] == arr[pos+1]:\n plateau += 1\n elif arr[pos] > arr[pos+1] and arr[pos] >= arr[pos-1]:\n obj[\"pos\"].append(pos-plateau)\n obj[\"peaks\"].append(arr[pos])\n upward = False\n plateau = 0\n else:\n plateau = 0\n pos += 1\n else:\n if arr[pos] < arr[pos+1]:\n upward = True\n pos += 1\n \n return obj", "def pick_peaks(arr):\n a = []\n b = []\n for i in range(1, len(arr)-1):\n for l in range(i, len(arr)-1):\n if arr[l+1] > arr[i]:\n break\n if arr[l+1] < arr[i]:\n if arr[i-1] < arr[i] and arr[i+1] <= arr[i]:\n a.append(i)\n b.append(arr[i])\n break\n return {\"pos\":a,\"peaks\":b}", "def pick_peaks(arr):\n print(arr)\n obj = {\"pos\": [], \"peaks\": []}\n if len(arr) == 0:\n return obj\n upward = True if arr[0] < arr[1] else False\n pos = 1\n plateau = 0\n \n while pos < len(arr) - 1:\n if upward:\n if arr[pos] == arr[pos+1]:\n plateau += 1\n elif arr[pos] > arr[pos+1] and arr[pos] >= arr[pos-1]:\n obj[\"pos\"].append(pos-plateau)\n obj[\"peaks\"].append(arr[pos])\n upward = False\n plateau = 0\n else:\n plateau = 0\n pos += 1\n else:\n if arr[pos] < arr[pos+1]:\n upward = True\n pos += 1\n \n return obj\n \n \n", "def pick_peaks(arr):\n #your code here\n pos = []\n prob_peak = False\n for i in range(1, len(arr)):\n if arr[i] > arr[i-1]:\n prob_peak = i\n elif prob_peak and arr[prob_peak] > arr[i]:\n pos.append(prob_peak)\n prob_peak = False\n return {\"pos\":pos, \"peaks\":[arr[i] for i in pos]}", "def pick_peaks(arr):\n #your code here\n pos, peaks = [], []\n for i in range(len(arr)-2):\n a, b, c = list(range(i, i+3))\n if pos and peaks[-1] == arr[b]:\n condition = True\n for i in range(pos[-1], b):\n condition = condition and arr[i] == arr[b]\n if condition is True:\n continue\n while arr[a] == arr[b] and a > 0:\n a -= 1\n while arr[b] == arr[c] and c < len(arr)-1:\n c += 1\n if arr[a] < arr[b] and arr[b] > arr[c]:\n pos += [b]\n peaks += [arr[b]]\n return {\"pos\":pos, \"peaks\":peaks}\n", "def pick_peaks(arr):\n peaks = {'peaks': [], 'pos': []}\n if len(arr) == 0:\n return peaks\n p = min(arr)\n pos = 0\n for i in range(2, len(arr)):\n if arr[i-1] > arr[i-2] and arr[i-1] >= arr[i]:\n p = arr[i-1]\n pos = i-1\n if arr[i] < p:\n peaks['peaks'].append(p)\n peaks['pos'].append(pos)\n p = min(arr)\n pos = 0\n return peaks", "def pick_peaks(arr):\n pos = []\n peaks = []\n if len(arr) > 0:\n n = 0\n peak_start = 0\n curr_height = arr[0]\n is_descending = True\n for p in arr:\n if p > curr_height:\n is_descending = False\n curr_height = p\n peak_start = n\n elif p == curr_height:\n pass\n elif p < curr_height:\n if not is_descending:\n pos.append(peak_start)\n peaks.append(curr_height)\n is_descending = True\n curr_height = p\n else:\n raise Error\n n += 1\n return {\"pos\": pos, \"peaks\": peaks}", "def pick_peaks(arr):\n posPeaks = {'pos': [] , 'peaks': []}\n for i in range(1, len(arr)-1):\n if arr[i] > arr[i-1]:\n if arr[i] > arr[i+1]:\n posPeaks['pos'].append(i)\n posPeaks['peaks'].append(arr[i])\n if arr[i] == arr[i+1]:\n for x in range(i+2, len(arr)):\n if arr[x] < arr[i]:\n posPeaks['pos'].append(i)\n posPeaks['peaks'].append(arr[i])\n break\n if arr[x] > arr[i]:\n break\n return posPeaks", "def pick_peaks(arr):\n ans = {\"pos\":[],\"peaks\":[]}\n for i in range(1,len(arr)-1):\n start = None\n end = None\n if arr[i-1] == arr[i]:\n for x in range(i,0,-1):\n while arr[i-x] != arr[i]:\n start = i-x+1\n break\n if arr[i+1] == arr[i]:\n for y in range(i,len(arr)-1):\n if arr[y] != arr[i]:\n end = y -1\n break\n else:\n end = y\n if start == None: start = i\n if end == None: end = i\n if arr[start-1]< arr[start] and arr[end+1] < arr[end]:\n if start not in ans[\"pos\"]:\n ans[\"pos\"].append(start)\n ans[\"peaks\"].append(arr[start])\n return ans", "def pick_peaks(arr):\n ans = {\"peaks\" :[] ,\"pos\": []}\n point = False\n for i in range(len(arr)):\n if arr[i]> arr[i-1]:\n point = i\n elif arr[i] < arr[i-1] and point:\n ans[\"pos\"].append(point)\n ans[\"peaks\"].append(arr[point])\n point = False\n return ans\n #your code here\n", "def pick_peaks(arr):\n print(arr)\n ans = {\"pos\":[],\"peaks\":[]}\n for i in range(1,len(arr)-1):\n start = None\n end = None\n if arr[i-1] == arr[i]:\n for x in range(i,0,-1):\n while arr[i-x] != arr[i]:\n start = i-x+1\n break\n if arr[i+1] == arr[i]:\n for y in range(i,len(arr)-1):\n if arr[y] != arr[i]:\n end = y -1\n break\n else:\n end = y\n if start == None: start = i\n if end == None: end = i\n if arr[start-1]< arr[start] and arr[end+1] < arr[end]:\n if start not in ans[\"pos\"]:\n ans[\"pos\"].append(start)\n ans[\"peaks\"].append(arr[start])\n print(\"i:\",i,\"val:\",arr[i],start,end)\n return ans", "import operator\n\ndef pick_peaks(arr):\n pos = []\n peaks = []\n if len(arr) < 3:\n return { \"pos\" : [], \"peaks\" : []}\n\n # substract\n diff = list(map(operator.sub, arr[1:], arr[:-1]))\n\n # deal with plateue\n for i in range(len(diff) - 1, 0, -1):\n if diff[i-1] == 0:\n diff[i-1] = diff[i]\n \n # find peaks\n is_peak = lambda a,b: 1 if a*b<0 and a>b else 0\n muld = list(map(is_peak, diff[:-1], diff[1:]))\n\n # get positions\n pos = [i+1 for i,v in enumerate(muld) if v == 1]\n \n # get peaks\n for i in pos:\n peaks.append(arr[i])\n\n return { \"pos\" : pos, \"peaks\" : peaks}\n", "def pick_peaks(arr):\n pospeaks = {\"pos\":[], \"peaks\":[]}\n \n for i in range(1, len(arr) - 1):\n lowerbefore = arr[i - 1] < arr[i]\n lowerafter = False\n for j in arr[i:]:\n if j == arr[i]:\n continue\n elif j < arr[i]:\n lowerafter = True\n break\n elif j > arr[i]:\n break\n if lowerbefore and lowerafter:\n pospeaks[\"pos\"].append(i)\n pospeaks[\"peaks\"].append(arr[i])\n \n return pospeaks", "def pick_peaks(lst):\n res = {'pos': [], 'peaks': []}\n idx = 0\n for i in range(1, len(lst) - 1):\n if lst[i] != lst[idx]:\n idx = i\n if idx and lst[idx - 1] < lst[idx] > lst[i + 1]:\n res['pos'].append(idx)\n res['peaks'].append(lst[idx])\n return res", "def pick_peaks(arr):\n dict = {'pos':[],'peaks':[]}\n for i in range(1,len(arr)-1):\n if arr[i] > arr[i-1] and arr[i] >= arr[i+1]:\n add = True\n if arr[i] == arr[i+1]:\n j = i\n done = False\n while j < len(arr) and add and not done:\n if arr[j] > arr[i]:\n add = False\n elif arr[j] < arr[i]:\n done = True\n j += 1\n if not done:\n add = False\n if add:\n dict['pos'].append(i)\n dict['peaks'].append(arr[i])\n return dict", "def pick_peaks(arr):\n pos = []\n peaks = []\n n = 0\n\n for i in range(1, len(arr) - 1):\n if arr[i] > arr[i - 1] and arr[i] > arr[i + 1]:\n pos.append(i)\n peaks.append(arr[i])\n\n # checking plateau cases\n elif arr[i] > arr[i - 1] and arr[i] == arr[i + 1]:\n n = 0\n for j in range(i + 1, len(arr)):\n # for the values that come after the possible plateau value\n # check to see that it decreases after staying constant\n\n if arr[j] == arr[i]:\n n += 1\n\n else:\n break\n\n if i + n + 1 < len(arr) and arr[i + n + 1] < arr[i]:\n\n pos.append(i)\n peaks.append(arr[i])\n\n return {\"pos\": pos, \"peaks\": peaks}", "def pick_peaks(arr):\n set = {'pos' : [], 'peaks' : []}\n for i in range(1, len(arr)-1):\n if arr[i] > arr[i-1] and arr[i] > arr[i+1]:\n set['pos'].append(i)\n set['peaks'].append(arr[i])\n if arr[i] == arr[i+1] and arr[i] > arr[i-1]:\n for x in range(i+2, len(arr)):\n if arr[i]<arr[x]:\n break\n if arr[i]>arr[x]:\n set['pos'].append(i)\n set['peaks'].append(arr[i])\n break\n return set", "def pick_peaks(arr):\n \n print('input:{}'.format(arr))\n if len(arr) < 1:\n return {\"pos\":[],\"peaks\":[]}\n \n #your code here\n UP = 0\n DOWN = 1\n FLAT = 2\n trends = [\"UP\",\"DOWN\",\"FLAT\"]\n \n if arr[0] == arr[1]:\n trend = FLAT\n elif arr[0] > arr[1]:\n trend = DOWN\n else:\n trend = UP\n\n prev = arr[0] \n pos = []\n peaks=[]\n \n local_max = None \n for i in range(1,len(arr)):\n if trend == UP:\n if arr[i] == prev:\n trend = FLAT\n local_max = i-1 #\n elif arr[i] < prev:\n trend = DOWN\n pos.append(i-1)\n peaks.append(prev)\n elif trend ==DOWN:\n if arr[i] == prev:\n trend = FLAT\n local_max = None\n elif arr[i] > prev:\n trend = UP\n elif trend == FLAT:\n if arr[i] > prev:\n trend = UP\n elif arr[i] < prev:\n if local_max != None:\n pos.append(local_max)\n peaks.append(prev)\n trend = DOWN\n \n prev = arr[i]\n \n #terminated with flat\n if trend == FLAT:\n pos=pos[0:]\n peaks=peaks[0:]\n return {\"pos\":pos,\"peaks\":peaks}", "def pick_peaks(arr):\n res = { \"pos\" : [], \"peaks\" : [] }\n flag = False\n \n for i in range( 1, len(arr) - 1 ):\n if flag:\n if arr[i] == arr[i+1]:\n continue\n elif arr[i] > arr[i+1]:\n res[\"pos\"].append(temp)\n res[\"peaks\"].append(arr[i])\n flag = False\n else:\n flag = False\n \n elif arr[i] > arr[i-1]:\n if arr[i] > arr[i+1]:\n res[\"pos\"].append(i)\n res[\"peaks\"].append(arr[i])\n elif arr[i] == arr[i+1]:\n temp = i\n flag = True\n \n return res\n", "def pick_peaks(arr):\n r = {'pos' : [], 'peaks' : []}\n state = 'none'\n c = 1\n for i in range(1, len(arr)):\n if arr[i] > arr[i-1]:\n state = 'up'\n elif arr[i] == arr[i-1]:\n if state == 'still':\n c+=1\n if state == 'up':\n state = 'still'\n elif arr[i] < arr[i-1]:\n if state == 'up':\n r['pos'].append(i-1)\n r['peaks'].append(arr[i-1])\n elif state == 'still':\n r['pos'].append(i-c-1)\n r['peaks'].append(arr[i-c-1])\n state = 'down'\n return r", "def pick_peaks(arr):\n pos = []\n peaks = []\n if arr:\n cur = arr[0]\n cur_pos = 0\n for i in range(1, len(arr)):\n if arr[i] > arr[i-1]:\n cur = arr[i]\n cur_pos = i\n elif arr[i] < cur and cur_pos != 0:\n pos.append(cur_pos)\n peaks.append(cur)\n cur_pos = 0\n return {\n 'pos': pos,\n 'peaks': peaks\n }", "def pick_peaks(arr):\n pos, peaks = [], []\n\n for i in range(1, len(arr) - 1):\n if arr[i] >= arr[i + 1]:\n k = i\n while k < len(arr) - 2 and arr[k] == arr[k + 1]:\n k += 1\n if arr[i - 1] < arr[i] and arr[i] > arr[k + 1]:\n pos.append(i)\n peaks.append(arr[i])\n \n return {\"pos\": pos, \"peaks\": peaks}\n", "def pick_peaks(arr):\n out = {'pos': [], 'peaks': []}\n \n for i in range(1, len(arr) - 1):\n plateau_idx = i+1\n if arr[i-1] < arr[i] == arr[i+1]: # might be at a plateau peak\n while plateau_idx < len(arr):\n if arr[plateau_idx] == arr[i]:\n plateau_idx += 1\n else:\n break\n if plateau_idx < len(arr) and arr[i-1] < arr[i] > arr[plateau_idx]: # unique peak\n out['pos'].append(i)\n out['peaks'].append(arr[i])\n return out", "def pick_peaks(a):\n #your code here\n \n previous = 0 \n current = 0\n \n pos = []\n peaks = []\n \n for next in range(1,len(a)):\n if a[next] > a[current]:\n previous = current\n current = next\n else:\n if a[next] < a[current]:\n if a[previous] < a[current]:\n pos.append(current)\n peaks.append(a[current])\n previous = current\n current = next\n \n \n \n \n return {\"pos\": pos, \"peaks\": peaks}\n \n \n", "\ndef pick_peaks(arr):\n pos = []\n peaks = []\n for x in range(len(arr)):\n if x != 0 and x!= len(arr)-1:\n if arr[x] > arr[x-1] and arr[x] > arr[x+1]:\n pos.append(x)\n peaks.append(arr[x])\n elif arr[x] > arr[x-1] and arr[x] >= arr[x+1]:\n \n \n for y in arr[x:]:\n print((y, x, arr[x], arr[x:]))\n if arr[x] > y:\n pos.append(x)\n peaks.append(arr[x])\n break\n elif arr[x]< y:\n break\n \n\n return {\"pos\": pos, \"peaks\":peaks}\n \n", "def pick_peaks(arr):\n pos = []\n peaker = None\n for i in range(1 ,len(arr)):\n if arr[i-1] < arr[i]:\n peaker = i\n elif arr[i-1] > arr[i] and peaker:\n pos.append(peaker)\n peaker = None\n return {'pos':pos, 'peaks':[arr[i] for i in pos]}", "def pick_peaks(arr):\n return_dict = {\"pos\": [], \"peaks\": []}\n fall = False\n peak = False\n plateaus_after_peak = False\n plateaus = False\n plateaus_pos = 0\n\n for position, current in enumerate(arr):\n\n if position == 0:\n print(f\"[{position}] {current} - START\")\n elif position == len(arr) - 1:\n print(f\"[{position}] {current} - END\")\n\n else:\n\n next = arr[position + 1]\n previous = arr[position - 1]\n\n if previous > current < next:\n fall = True\n peak = False\n plateaus_after_peak = False\n plateaus = False\n print(f\"[{position}] {current} - Fell!\")\n\n elif previous > current > next:\n fall = True\n peak = False\n plateaus_after_peak = False\n plateaus = False\n print(f\"[{position}] {current} - Falling...\")\n\n elif previous < current < next:\n fall = False\n peak = False\n plateaus_after_peak = False\n plateaus = False\n print(f\"[{position}] {current} - Rising...\")\n\n elif previous < current == next:\n fall = False\n peak = True\n plateaus_after_peak = False\n plateaus = True\n plateaus_pos = position\n print(f\"[{position}] {current} - Plateaus start!\")\n\n elif previous == current > next:\n\n if position == 1:\n print(f\"[{position}] {current} - End of starting plateaus!\")\n\n # je\u015bli nie drugi i nie przedostatni\n elif position != 1 and position != len(arr) - 2:\n\n if plateaus_after_peak:\n fall = True\n peak = False\n plateaus_after_peak = False\n plateaus = False\n print(f\"[{position}] {current} - Plateus End after peak - Falling...\")\n\n else:\n fall = True\n peak = False\n plateaus_after_peak = False\n plateaus = False\n print(f\"[{position}] {current} - End of plateaus! Falling, saving the start of plateaus!\")\n return_dict[\"pos\"].append(plateaus_pos)\n return_dict[\"peaks\"].append(current)\n elif position == len(arr) - 2 and current > next and not plateaus_after_peak:\n fall = True\n peak = False\n plateaus_after_peak = False\n plateaus = False\n print(f\"[{position}] {current} - End of plateaus! Falling, saving the start of plateaus!\")\n return_dict[\"pos\"].append(plateaus_pos)\n return_dict[\"peaks\"].append(current)\n\n elif previous > current == next:\n fall = False\n peak = False\n plateaus_after_peak = True\n plateaus = True\n print(f\"[{position}] {current} - Plateus start after a peak!\")\n\n elif previous < current > next:\n fall = False\n peak = True\n plateaus_after_peak = False\n plateaus = False\n print(f\"[{position}] {current} - Its a peak! Saving\")\n return_dict[\"pos\"].append(position)\n return_dict[\"peaks\"].append(current)\n\n elif previous == current == next:\n fall = False\n plateaus = True\n print(f\"[{position}] {current} - Plateus Flat!\")\n elif previous == current < next:\n if plateaus_after_peak:\n fall = True\n peak = False\n plateaus_after_peak = False\n plateaus = False\n print(f\"[{position}] {current} - Plateus End after peak - Rising...\")\n elif plateaus:\n if position + 1 == len(arr) - 1: #jesli nie jest przedostatni\n if not plateaus_after_peak:\n fall = False\n peak = True\n plateaus_after_peak = False\n plateaus = False\n print(f\"[{position}] {current} - Plateus Before End\")\n return_dict[\"pos\"].append(plateaus_pos)\n return_dict[\"peaks\"].append(current)\n else:\n print(f\"[{position}] {current} - X1!\")\n else:\n print(f\"[{position}] {current} - X2!\")\n\n else:\n print(f\"[{position}] {current} - OUTSIDE!\")\n\n return return_dict", "def pick_peaks(arr):\n pos = []\n peak = []\n peaking = False\n platu = None\n for (count, item) in enumerate(arr):\n try:\n if arr[count] < arr[count + 1]:\n peaking = True\n platu = None\n elif arr[count] == arr[count + 1] and peaking:\n platu = count\n peaking = False\n elif peaking:\n pos.append(count)\n peak.append(item)\n peaking = False\n elif platu and arr[count+1] > arr[count]:\n platu = None\n peaking = True\n elif platu and arr[count+1] < arr[count]:\n pos.append(platu)\n peak.append(arr[platu])\n platu = None\n peaking = False\n else:\n pass\n except IndexError:\n break\n return {'pos': pos, 'peaks': peak}\n", "def pick_peaks(arr):\n dct = {\"pos\": [], \"peaks\": []}\n for i in range(1, len(arr) - 1):\n if arr[i-1] < arr[i] and arr[i] > arr[i+1]:\n dct[\"pos\"].append(i)\n plateau_peak(arr, dct)\n dct[\"pos\"].sort()\n dct[\"peaks\"] = [arr[x] for x in dct[\"pos\"]]\n return dct\n\ndef plateau_peak(arr, dct):\n last = 0\n for i in range(1, len(arr) - 1):\n if arr[i] == arr[i+1]:\n continue\n elif arr[i] > arr[i+1] and arr[i] == arr[i-1] and arr[i] > arr[last]:\n dct[\"pos\"].append(last+1)\n last = i\n else:\n last = i", "def pick_peaks(arr):\n if not arr: \n return {\"pos\":[],\"peaks\":[]}\n else: \n peak_pos = []\n peak_value = []\n value = 0\n for i in range(1,len(arr)-1):\n if (arr[i-1] < arr[i]) and (arr[i+1] < arr[i]):\n peak_pos.append(i)\n peak_value.append(arr[i])\n if (arr[i-1] < arr[i]) and (arr[i+1] == arr[i]):\n for j in range(i+1,len(arr)):\n if (arr[j] < arr[i]):\n peak_pos.append(i)\n peak_value.append(arr[i]) \n print(('value added',i,j))\n break\n if (arr[j] > arr[i]):\n break\n \n \n return {\"pos\":peak_pos,\"peaks\":peak_value}\n \n", "def check(arr, n):\n for num in arr:\n if num < n: return True\n elif num > n: return False\n return False\n \ndef pick_peaks(arr):\n data = {\"pos\": [], \"peaks\": []}\n for i, n in enumerate(arr[1:-1], 1):\n if arr[i-1] < n >= arr[i+1] and check(arr[i:], n):\n data[\"pos\"] += [i]\n data[\"peaks\"] += [n]\n\n return data", "def pick_peaks(arr):\n pos = []\n peaks = []\n \n local_max = 0\n for i in range(1, len(arr) - 1):\n if arr[i - 1] < arr[i]:\n local_max = i\n \n if arr[i - 1] <= arr[i] > arr[i + 1] and local_max not in pos and local_max != 0:\n pos.append(local_max)\n peaks.append(arr[local_max])\n \n return {'pos': pos, 'peaks': peaks}", "def pick_peaks(arr):\n\n pos=list()\n peaks=list()\n j=0\n \n for i in range(1, len(arr)-1):\n \n if (arr[i-1]<arr[i]) and (arr[i+1]<arr[i]):\n pos.append(i)\n peaks.append(arr[i])\n\n elif arr[i-1]<arr[i] and arr[i]==arr[i+1] and i+1<len(arr)-1:\n pos.append(i)\n peaks.append(arr[i])\n j=1\n\n elif j==1 and ((arr[i-1]==arr[i] and arr[i]<arr[i+1]) or \\\n (arr[i]==arr[i+1] and i+1==len(arr)-1)):\n pos.pop()\n peaks.pop()\n j=0\n\n return {'pos': pos, 'peaks': peaks}\n", "def pick_peaks(arr):\n results = {'pos': [], 'peaks': []}\n \n for i in range(1, len(arr)-1):\n if is_peak(arr, i):\n results['pos'].append(i)\n results['peaks'].append(arr[i])\n \n return results\n\n\ndef get_direction(last, i):\n if i > last:\n return 1\n elif i == last:\n return 0\n else:\n return -1\n \n \ndef is_peak(arr, index):\n result = False\n cur_val = arr[index]\n \n if get_direction(cur_val, arr[index -1]) < 0:\n for i in range(index, len(arr)):\n dir = get_direction(cur_val, arr[i])\n if dir < 0:\n result = True\n break\n elif dir > 0:\n result = False\n break\n \n return result\n", "def pick_peaks(arr):\n result = {\n \"pos\": [],\n \"peaks\": []\n }\n\n for pos, val in enumerate(arr):\n if pos == 0 or pos == len(arr) - 1:\n continue\n if arr[pos+1] > val:\n continue\n if arr[pos-1] == val:\n continue\n if arr[pos+1] == val and arr[pos-1] < val:\n for i in range(pos+1, len(arr)):\n if arr[i] == val:\n continue\n elif arr[i] > val:\n break\n else:\n result['pos'].append(pos)\n result['peaks'].append(val)\n break\n continue\n if arr[pos-1] < val:\n result['pos'].append(pos)\n result['peaks'].append(val)\n \n return result\n \n", "def pick_peaks(arr):\n setThis = False\n pos = []\n peaks = []\n print([x for x in range(len(arr))])\n print(arr)\n for i in range(1,len(arr)-1):\n if arr[i] > arr[i-1] and arr[i] > arr[i+1]:\n pos.append(i)\n peaks.append(arr[i])\n elif arr[i] > arr[i-1] and arr[i] == arr[i+1]:\n j = i+1\n while arr[j] == arr[i] and j < len(arr)-1:\n j += 1\n if j == len(arr) or arr[j] < arr[i] :\n pos.append(i)\n peaks.append(arr[i])\n i = j\n print(pos)\n print(peaks)\n res = { \"pos\": pos, \"peaks\": peaks}\n return res"]
{"fn_name": "pick_peaks", "inputs": [[[1, 2, 3, 6, 4, 1, 2, 3, 2, 1]], [[3, 2, 3, 6, 4, 1, 2, 3, 2, 1, 2, 3]], [[3, 2, 3, 6, 4, 1, 2, 3, 2, 1, 2, 2, 2, 1]], [[2, 1, 3, 1, 2, 2, 2, 2, 1]], [[2, 1, 3, 1, 2, 2, 2, 2]], [[2, 1, 3, 2, 2, 2, 2, 5, 6]], [[2, 1, 3, 2, 2, 2, 2, 1]], [[1, 2, 5, 4, 3, 2, 3, 6, 4, 1, 2, 3, 3, 4, 5, 3, 2, 1, 2, 3, 5, 5, 4, 3]], [[]], [[1, 1, 1, 1]]], "outputs": [[{"pos": [3, 7], "peaks": [6, 3]}], [{"pos": [3, 7], "peaks": [6, 3]}], [{"pos": [3, 7, 10], "peaks": [6, 3, 2]}], [{"pos": [2, 4], "peaks": [3, 2]}], [{"pos": [2], "peaks": [3]}], [{"pos": [2], "peaks": [3]}], [{"pos": [2], "peaks": [3]}], [{"pos": [2, 7, 14, 20], "peaks": [5, 6, 5, 5]}], [{"pos": [], "peaks": []}], [{"pos": [], "peaks": []}]]}
INTRODUCTORY
PYTHON3
CODEWARS
62,332
def pick_peaks(arr):
ee4a3beb6bca7ade6fe0fde59ef6aead
UNKNOWN
# Task In ChessLand there is a small but proud chess bishop with a recurring dream. In the dream the bishop finds itself on an `n × m` chessboard with mirrors along each edge, and it is not a bishop but a ray of light. This ray of light moves only along diagonals (the bishop can't imagine any other types of moves even in its dreams), it never stops, and once it reaches an edge or a corner of the chessboard it reflects from it and moves on. Given the initial position and the direction of the ray, find its position after `k` steps where a step means either moving from one cell to the neighboring one or reflecting from a corner of the board. # Example For `boardSize = [3, 7], initPosition = [1, 2], initDirection = [-1, 1] and k = 13,` the output should be `[0, 1]`. Here is the bishop's path: ``` [1, 2] -> [0, 3] -(reflection from the top edge) -> [0, 4] -> [1, 5] -> [2, 6] -(reflection from the bottom right corner) -> [2, 6] ->[1, 5] -> [0, 4] -(reflection from the top edge) -> [0, 3] ->[1, 2] -> [2, 1] -(reflection from the bottom edge) -> [2, 0] -(reflection from the left edge) -> [1, 0] -> [0, 1]``` ![](https://codefightsuserpics.s3.amazonaws.com/tasks/chessBishopDream/img/example.png?_tm=1472324389202) # Input/Output - `[input]` integer array `boardSize` An array of two integers, the number of `rows` and `columns`, respectively. Rows are numbered by integers from `0 to boardSize[0] - 1`, columns are numbered by integers from `0 to boardSize[1] - 1` (both inclusive). Constraints: `1 ≤ boardSize[i] ≤ 20.` - `[input]` integer array `initPosition` An array of two integers, indices of the `row` and the `column` where the bishop initially stands, respectively. Constraints: `0 ≤ initPosition[i] < boardSize[i]`. - `[input]` integer array `initDirection` An array of two integers representing the initial direction of the bishop. If it stands in `(a, b)`, the next cell he'll move to is `(a + initDirection[0], b + initDirection[1])` or whichever it'll reflect to in case it runs into a mirror immediately. Constraints: `initDirection[i] ∈ {-1, 1}`. - `[input]` integer `k` Constraints: `1 ≤ k ≤ 1000000000`. - `[output]` an integer array The position of the bishop after `k` steps.
["def chess_bishop_dream(b,p,d,k):\n yq,yr=divmod(p[0]+k*d[0],2*b[0])\n xq,xr=divmod(p[1]+k*d[1],2*b[1])\n return [min(yr, 2*b[0]-yr-1), min(xr, 2*b[1]-xr-1)]", "chess_bishop_dream=lambda b,p,d,k:[c-abs((q+k*e)%(2*c)-c+.5)-.5for c,q,e in zip(b,p,d)]", "def chess_bishop_dream(board_size, init_position, init_direction, k):\n l, (m, n), (x, y), (dx, dy) = 0, board_size, init_position, init_direction\n while k:\n k -= 1; l += 1; x += dx; y += dy\n if x < 0 or x == m: dx = -dx; x += dx\n if y < 0 or y == n: dy = -dy; y += dy\n if [x, y] == init_position and [dx, dy] == init_direction: k %= l\n return [x, y]", "def chess_bishop_dream(b,p,d,k):\n yq,yr=divmod(p[0]+k*d[0],b[0])\n xq,xr=divmod(p[1]+k*d[1],b[1])\n if yq<0:\n yq=-yq\n yr=b[0]-yr-1\n if xq<0:\n xq=-xq\n xr=b[1]-xr-1\n return [(b[0]-yr-1 if yq%2==(d[0]>0) else yr),(b[1]-xr-1 if xq%2==(d[1]>0) else xr)]\n", "def chess_bishop_dream(bs, init_pos, init_dir, k):\n \n pos, dir = init_pos[:], init_dir[:]\n n, start = k, (init_pos, init_dir)\n while n:\n pos = [x+dx for x,dx in zip(pos, dir)]\n for i in range(2):\n if not (0 <= pos[i] < bs[i]):\n dir[i] *= -1\n pos[i] = [0, bs[i]-1][ pos[i]>0 ]\n n -= 1\n if start == (pos, dir): n %= k-n\n \n return pos", "chess_bishop_dream=lambda b,p,d,k:[(lambda q,r:[r,c-r-1][q%2])(*divmod(q+k*e,c))for c,q,e in zip(b,p,d)]", "def chess_bishop_dream(board_size, init_position, init_direction, k):\n (h, w), (i, j), (di, dj) = board_size, init_position, init_direction\n (qi, ri), (qj, rj) = divmod(i + di * k, h), divmod(j + dj * k, w)\n return [h - 1 - ri if qi % 2 else ri, w - 1 - rj if qj % 2 else rj]", "def chess_bishop_dream(board_size, pos, dir, k):\n k %= ((board_size[0])*(board_size[1])*2)\n steps = 0\n while steps < k:\n print(pos,steps,k,dir)\n rows_to_go = pos[0] if dir[0] == -1 else (board_size[0] - pos[0] - 1)\n cols_to_go = pos[1] if dir[1] == -1 else (board_size[1] - pos[1] - 1)\n n = min(rows_to_go, cols_to_go, k - steps)\n steps += n\n pos = [pos[0] + n*dir[0], pos[1] + n*dir[1]]\n if steps == k:\n break\n next_pos = [pos[0] + dir[0], pos[1] + dir[1]]\n valid_row = (0 <= next_pos[0] < board_size[0])\n valid_col = (0 <= next_pos[1] < board_size[1])\n if valid_col:\n dir[0] *= -1\n pos[1] = next_pos[1] \n elif valid_row:\n dir[1] *= -1\n pos[0] = next_pos[0] \n else:\n dir[0] *= -1\n dir[1] *= -1\n steps += 1\n return pos", "def chess_bishop_dream(board_size, init_position, init_direction, k):\n m,n=board_size\n x,y=init_position\n dx,dy=init_direction\n r=[[x,y]]\n while(True):\n x,y=x+dx,y+dy\n if not (0<=x<m):\n x+=-dx\n dx=-dx\n if not (0<=y<n):\n y+=-dy\n dy=-dy\n r.append([x,y])\n if len(r)>2 and r[:2]==r[-2:]:\n break\n r=r[:-2]\n return r[k%len(r)]", "def chess_bishop_dream(size, init_pos, init_dir, k):\n pos = init_pos.copy()\n dir = init_dir.copy()\n i = k\n while i > 0:\n check = [0 <= pos[0]+dir[0] < size[0],0 <= pos[1]+dir[1] < size[1]]\n pos[0] += dir[0]*check[0]\n pos[1] += dir[1]*check[1]\n dir[0] *= int((int(check[0])-0.5)*2)\n dir[1] *= int((int(check[1])-0.5)*2)\n i -= 1\n if pos == init_pos and dir == init_dir:\n i %= k-i\n return pos"]
{"fn_name": "chess_bishop_dream", "inputs": [[[3, 7], [1, 2], [-1, 1], 13], [[1, 2], [0, 0], [1, 1], 6], [[2, 2], [1, 0], [1, 1], 12], [[1, 1], [0, 0], [1, -1], 1000000000], [[2, 3], [1, 2], [-1, -1], 41], [[17, 19], [14, 8], [1, -1], 239239], [[17, 19], [16, 18], [1, 1], 239239239]], "outputs": [[[0, 1]], [[0, 1]], [[1, 0]], [[0, 0]], [[0, 2]], [[4, 17]], [[10, 2]]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,616
def chess_bishop_dream(board_size, init_position, init_direction, k):
980cf4d4e75e7248f6608b25656eaf57
UNKNOWN
For all x in the range of integers [0, 2 ** n), let y[x] be the binary exclusive-or of x and x // 2. Find the sum of all numbers in y. Write a function sum_them that, given n, will return the value of the above sum. This can be implemented a simple loop as shown in the initial code. But once n starts getting to higher numbers, such as 2000 (which will be tested), the loop is too slow. There is a simple solution that can quickly find the sum. Find it! Assume that n is a nonnegative integer. Hint: The complete solution can be written in two lines.
["def sum_them(n):\n return 2 ** (n - 1) * (2 ** n - 1)", "sum_them=lambda n: int('1'*n, 2)*(int('1'*n, 2)+1)//2 if n else 0", "def sum_them(n):\n return 2 ** (n*2-1) - 2 ** (n-1)", "sum_them=lambda n:int(n*'1'+~-n*'0'or'0',2)", "def sum_them(n):\n return 2**n*(2**n-1)>>1", "def sum_them(n):\n return n and int('1' * n + '0' * (n-1), 2)", "sum_them=lambda n:~-2**n*2**~-n", "def sum_them(n):\n return ((1 << n) - 1) << (n - 1) if n > 0 else 0", "def sum_them(n):\n n=2**n\n return (n*(n-1))//2", "def sum_them(n):\n return (1 << n) - 1 << (n - 1 if n else 0)\n \n"]
{"fn_name": "sum_them", "inputs": [[0], [1], [2], [3], [4]], "outputs": [[0], [1], [6], [28], [120]]}
INTRODUCTORY
PYTHON3
CODEWARS
592
def sum_them(n):
4bcc6806b5b5e60d1f6fa293dc13bdcd
UNKNOWN
Lеt's create function to play cards. Our rules: We have the preloaded `deck`: ``` deck = ['joker','2♣','3♣','4♣','5♣','6♣','7♣','8♣','9♣','10♣','J♣','Q♣','K♣','A♣', '2♦','3♦','4♦','5♦','6♦','7♦','8♦','9♦','10♦','J♦','Q♦','K♦','A♦', '2♥','3♥','4♥','5♥','6♥','7♥','8♥','9♥','10♥','J♥','Q♥','K♥','A♥', '2♠','3♠','4♠','5♠','6♠','7♠','8♠','9♠','10♠','J♠','Q♠','K♠','A♠'] ``` We have 3 arguments: `card1` and `card2` - any card of our deck. `trump` - the main suit of four ('♣', '♦', '♥', '♠'). If both cards have the same suit, the big one wins. If the cards have different suits (and no one has trump) return 'Let's play again.' If one card has `trump` unlike another, wins the first one. If both cards have `trump`, the big one wins. If `card1` wins, return 'The first card won.' and vice versa. If the cards are equal, return 'Someone cheats.' A few games: ``` ('3♣', 'Q♣', '♦') -> 'The second card won.' ('5♥', 'A♣', '♦') -> 'Let us play again.' ('8♠', '8♠', '♣') -> 'Someone cheats.' ('2♦', 'A♠', '♦') -> 'The first card won.' ('joker', 'joker', '♦') -> 'Someone cheats.' ``` P.S. As a card you can also get the string 'joker' - it means this card always wins.
["vals='2345678910JQKA'\ndef card_game(card_1, card_2, trump):\n print((card_1, card_2, trump))\n if card_1==card_2: return 'Someone cheats.'\n elif 'joker' in [card_1,card_2]:\n return ['The first card won.', 'The second card won.'][card_1!='joker']\n elif card_1[-1]==card_2[-1]:\n return ['The first card won.', 'The second card won.'][vals.index(card_2[0])>vals.index(card_1[0])]\n elif card_1[-1]!=trump!=card_2[-1]:\n return 'Let us play again.'\n else:\n return ['The first card won.', 'The second card won.'][card_1[-1]!=trump]", "ORDERS = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']\nRESULTS = ['Let us play again.', 'The first card won.', 'The second card won.', 'Someone cheats.']\n\ndef f(c1, c2, trump):\n if c1 == c2:\n return -1\n\n if c1 == 'joker':\n return 1\n elif c2 == 'joker':\n return 2\n\n cards = c1, c2\n n1, n2 = (ORDERS.index(c[:-1]) for c in cards)\n s1, s2 = (c[-1] for c in cards)\n won = 0\n if s1 == s2:\n if n1 > n2:\n return 1\n elif n1 < n2:\n return 2\n elif s1 == trump:\n return 1\n elif s2 == trump:\n return 2\n return 0\n\n\ndef card_game(card_1, card_2, trump):\n return RESULTS[f(card_1, card_2, trump)]", "def card_game(card_1, card_2, trump):\n card_1_wins, card_2_wins, cards = \"The first card won.\", \"The second card won.\", {'J': 11, 'Q': 12, 'K': 13, 'A': 14}\n if card_1 == card_2:\n return \"Someone cheats.\"\n if card_1 == \"joker\":\n return card_1_wins\n if card_2 == \"joker\":\n return card_2_wins\n if card_1[-1] == card_2[-1]:\n card_1_value = cards[card_1[0:-1]] if card_1[0:-1].isalpha() else int(card_1[0:-1])\n card_2_value = cards[card_2[0:-1]] if card_2[0:-1].isalpha() else int(card_2[0:-1])\n return card_1_wins if card_1_value > card_2_value else card_2_wins\n return card_1_wins if card_1[-1] == trump else card_2_wins if card_2[-1] == trump else \"Let us play again.\"", "def card_game(c1, c2, trump):\n if c1 == c2 :\n return \"Someone cheats.\"\n if 'joker' in [c1,c2]:\n return get_win(c2 =='joker')\n if all((c1[-1] != c2[-1], any((c1[-1]==trump, c2[-1]==trump)) )):\n return get_win(c2[-1] == trump)\n if c1[-1] == c2[-1]:\n c1 , c2 = [ '234567891JQKA'.index(e) for e in [c1[0],c2[0]] ]\n return get_win( c2 > c1 )\n return \"Let us play again.\"\n \nget_win = lambda bool : \"The {} card won.\".format( ['first','second'][bool] ) ", "value = {'J':11, 'Q':12, 'K':13, 'A':14}\nget_val = lambda x: value[x] if x in value else int(x)\n\ndef card_game(card_1, card_2, trump):\n if card_1 == card_2: return \"Someone cheats.\"\n if card_1 == \"joker\": return \"The first card won.\"\n if card_2 == \"joker\": return \"The second card won.\"\n if card_1[-1] == card_2[-1]:\n return \"The first card won.\" if get_val(card_1[:-1]) > get_val(card_2[:-1]) else \"The second card won.\"\n if card_1[-1] == trump: return \"The first card won.\"\n if card_2[-1] == trump: return \"The second card won.\"\n return \"Let us play again.\"", "def card_game(card_1, card_2, t):\n if card_1 == card_2:\n return \"Someone cheats.\"\n if card_1 == 'joker':\n return \"The first card won.\"\n if card_2 == 'joker':\n return \"The second card won.\"\n f_val = lambda v: int(v) if v.isdigit() else 10 + ' JQKA'.index(v)\n c1, t1 = f_val(card_1[:-1]), card_1[-1]\n c2, t2 = f_val(card_2[:-1]), card_2[-1]\n if t1 in [t, t2]:\n return f'The {[\"first\", \"second\"][t2 == t1 and c2 > c1]} card won.'\n return \"The second card won.\" if t2 == t else \"Let us play again.\"", "deck = ['joker','2\u2663','3\u2663','4\u2663','5\u2663','6\u2663','7\u2663','8\u2663','9\u2663','10\u2663','J\u2663','Q\u2663','K\u2663','A\u2663',\n '2\u2666','3\u2666','4\u2666','5\u2666','6\u2666','7\u2666','8\u2666','9\u2666','10\u2666','J\u2666','Q\u2666','K\u2666','A\u2666',\n '2\u2665','3\u2665','4\u2665','5\u2665','6\u2665','7\u2665','8\u2665','9\u2665','10\u2665','J\u2665','Q\u2665','K\u2665','A\u2665',\n '2\u2660','3\u2660','4\u2660','5\u2660','6\u2660','7\u2660','8\u2660','9\u2660','10\u2660','J\u2660','Q\u2660','K\u2660','A\u2660']\n\ndef card_game(card_1, card_2, trump):\n if card_1 == card_2:\n return \"Someone cheats.\"\n ordinal, trumps = [\"first\", \"second\"], f\"{card_1}{card_2}\".count(trump)\n if \"joker\" in (card_1, card_2):\n winner = ordinal[card_2 == \"joker\"]\n elif trumps == 1:\n winner = ordinal[trump in card_2]\n elif card_1[-1] == card_2[-1]:\n winner = ordinal[deck.index(card_2) > deck.index(card_1)]\n elif trumps == 0:\n return \"Let us play again.\"\n return f\"The {winner} card won.\"", "d = '2 3 4 5 6 7 8 9 10 J Q K A'.split()\nret = lambda fn,c1,c2,t:f\"The {['first','second'][eval(fn)]} card won.\" if fn else \"Let us play again.\"\ndef card_game(c1,c2,t):\n return ret('d.index(c1[:-1])<d.index(c2[:-1])' if c1[-1] == c2[-1] else\\\n 'c2==\"joker\"' if 'joker' in [c1,c2] else\\\n 'c2[-1]==t' if t in [c1[-1],c2[-1]] else \\\n '',c1,c2,t) if c1 != c2 else \"Someone cheats.\" #no effeciency due to eval :(", "def card_game(card_1, card_2, trump):\n deck_dict = {'J':11, 'Q':12, 'K':13, 'A':14}\n suit_1 = card_1[-1]\n suit_2 = card_2[-1]\n if card_1 == card_2: return 'Someone cheats.'\n elif card_1 == 'joker': return 'The first card won.'\n elif card_2 == 'joker': return 'The second card won.'\n rank_1 = card_1[0:-1]\n rank_2 = card_2[0:-1]\n rank_1 = int(deck_dict.get(rank_1,rank_1))\n rank_2 = int(deck_dict.get(rank_2,rank_2))\n\n if suit_1 == suit_2 and rank_1 > rank_2: return 'The first card won.'\n elif suit_1 == suit_2 and rank_1 < rank_2: return 'The second card won.'\n\n elif suit_1 != suit_2 and suit_1 != trump and suit_2 != trump: return 'Let us play again.'\n\n elif suit_1 == trump: return 'The first card won.'\n elif suit_2 == trump: return 'The second card won.'\n\n return 'Oops'\n"]
{"fn_name": "card_game", "inputs": [["Q\u2663", "3\u2663", "\u2666"], ["3\u2663", "Q\u2663", "\u2666"], ["5\u2665", "A\u2663", "\u2666"], ["8\u2660", "8\u2660", "\u2663"], ["2\u2666", "A\u2660", "\u2666"], ["A\u2660", "2\u2666", "\u2666"], ["joker", "joker", "\u2666"], ["joker", "10\u2663", "\u2660"], ["10\u2663", "joker", "\u2660"]], "outputs": [["The first card won."], ["The second card won."], ["Let us play again."], ["Someone cheats."], ["The first card won."], ["The second card won."], ["Someone cheats."], ["The first card won."], ["The second card won."]]}
INTRODUCTORY
PYTHON3
CODEWARS
6,266
def card_game(card_1, card_2, trump):
6918bb5f25cd942f21ae24bf8354b6bd
UNKNOWN
Write a function that takes two arguments, and returns a new array populated with the elements **that only appear once, in either one array or the other, taken only once**; display order should follow what appears in arr1 first, then arr2: ```python hot_singles([1, 2, 3, 3], [3, 2, 1, 4, 5]) # [4, 5] hot_singles(["tartar", "blanket", "cinnamon"], ["cinnamon", "blanket", "domino"]) # ["tartar", "domino"] hot_singles([77, "ciao"], [78, 42, "ciao"]) # [77, 78, 42] hot_singles([1, 2, 3, 3], [3, 2, 1, 4, 5, 4]) # [4,5] ``` SPECIAL THANKS: @JulianKolbe !
["def hot_singles(arr1, arr2):\n a = []\n for x in arr1 + arr2:\n if x in set(arr1) ^ set(arr2) and x not in a: a.append(x)\n return a", "from collections import OrderedDict\nfrom itertools import chain\n\n\ndef hot_singles(arr1, arr2):\n diff = set(arr1).symmetric_difference(arr2)\n return [a for a in OrderedDict.fromkeys(chain(arr1, arr2)) if a in diff]", "def hot_singles(lst1, lst2):\n return sorted(set(lst1) ^ set(lst2), key=(lst1 + lst2).index)", "def ordered(l, arr1,arr2):\n return [l,arr2.index(l) + len(arr1) if l in arr2 else arr1.index(l)]\n\ndef hot_singles(arr1, arr2):\n L = [ ordered(l,arr1,arr2) for l in set(arr1) ^ set(arr2)]\n return list(map(lambda l: l[0], sorted(L , key=lambda l: l[1])))", "def hot_singles(arr1, arr2):\n vals = arr1 + arr2\n return sorted(set(arr1).symmetric_difference(arr2), key=vals.index)\n", "def hot_singles(arr1, arr2):\n result = []\n for i in arr1:\n if i not in arr2 and i not in result:\n result.append(i)\n for i in arr2:\n if i not in arr1 and i not in result:\n result.append(i)\n \n return result\n #your code here\n", "hot_singles=lambda a,b:sorted(set(a)^set(b),key=(a+b).index)", "hot_singles=lambda A,B:sorted(set(A)^set(B),key=(A+B).index)", "def hot_singles(arr1, arr2):\n return sorted(set(arr1).symmetric_difference(set(arr2)), key=(arr1+arr2).index)", "def hot_singles(arr1, arr2):\n return sorted(set(arr1) ^ set(arr2), key=lambda x: ((arr1+arr2).index(x)))"]
{"fn_name": "hot_singles", "inputs": [[["tartar", "blanket", "domino"], ["blanket"]], [[77, "basketweave"], [78, 42, "basketweave"]], [[100, 45, "ciao"], [100, 2, 3, 45, 5]], [[10, 200, 30], [10, 20, 3, 4, 5, 5, 5, 200]], [[1, 2, 3, 3], [3, 2, 1, 4, 5, 4]]], "outputs": [[["tartar", "domino"]], [[77, 78, 42]], [["ciao", 2, 3, 5]], [[30, 20, 3, 4, 5]], [[4, 5]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,537
def hot_singles(arr1, arr2):
beddde85cfb89b4f01a7ee74619cb2f0
UNKNOWN
Gigi is a clever monkey, living in the zoo, his teacher (animal keeper) recently taught him some knowledge of "0". In Gigi's eyes, "0" is a character contains some circle(maybe one, maybe two). So, a is a "0",b is a "0",6 is also a "0",and 8 have two "0" ,etc... Now, write some code to count how many "0"s in the text. Let us see who is smarter? You ? or monkey? Input always be a string(including words numbers and symbols),You don't need to verify it, but pay attention to the difference between uppercase and lowercase letters. Here is a table of characters: one zeroabdegopq069DOPQR         () <-- A pair of braces as a zerotwo zero%&B8 Output will be a number of "0".
["def countzero(s):\n return sum(1 if c in 'abdegopq069DOPQR' else 2 if c in '%&B8' else 0 for c in s.replace('()', '0'))", "def countzero(string):\n return sum(1 if c in 'abdegopq069DOPQR' else 2 if c in '%&B8' else 0 for c in string) + string.count('()')", "def countzero(string):\n return sum(map(\"abdegopq069DOPQR%&B8%&B8\".count, string.replace(\"()\", \"0\")))", "D = {**{c:1 for c in \"abdegopq069DOPQR\"},\n **{c:2 for c in \"%&B8\"}}\n\ndef countzero(string):\n return sum(D.get(c, string[i:i+2] == '()') for i,c in enumerate(string))", "two = \"%&B8\"\nsome = f\"abdegopq069DOPQR{two}\"\n\ndef countzero(string):\n return sum(2 if c in two else 1 for c in string.replace(\"()\", \"0\") if c in some)", "ONE_ZERO = 'abdegopq069DOPQR'\nTWO_ZERO = '%&B8'\ndef countzero(string):\n string = string.replace('()', '0')\n return sum(1 if c in ONE_ZERO else 2 if c in TWO_ZERO else 0 for c in string)", "zeroes = {}\nfor c in 'abdegopq069DOPQR':\n zeroes[c] = 1\nfor c in '%&B8':\n zeroes[c] = 2\n\ndef countzero(string):\n string = string.replace('()', '0')\n return sum(map(lambda c: zeroes.get(c, 0), string))", "def countzero(string):\n n = 0\n for i in string:\n if i in \"069abdeopqDOPQRg(\":\n n += 1\n elif i in \"8%&B\":\n n += 2\n \n return n", "countzero = lambda s: sum((c in \"%&B8\") * 2 + (c in \"abdegopq069DOPQR\") * 1 for c in s) + s.count(\"()\")", "def countzero(string):\n counter = 0\n for x in string:\n if x in 'abdegopq069DOPQR':\n counter += 1\n elif x in '%&B8':\n counter += 2\n else:\n pass\n return counter + string.count('()')\n \n"]
{"fn_name": "countzero", "inputs": [[""], ["0"], ["0oO0oO"], ["1234567890"], ["abcdefghijklmnopqrstuvwxyz"], ["()"], ["E"], ["aA"], ["BRA"], ["%%"]], "outputs": [[0], [1], [6], [5], [8], [1], [0], [1], [3], [4]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,726
def countzero(string):
eb21649d4f304052a8e2719c60595146
UNKNOWN
Write a comparator for a list of phonetic words for the letters of the [greek alphabet](https://en.wikipedia.org/wiki/Greek_alphabet). A comparator is: > *a custom comparison function of two arguments (iterable elements) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument* *(source: https://docs.python.org/2/library/functions.html#sorted)* The greek alphabet is preloded for you as `greek_alphabet`: ```python greek_alphabet = ( 'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', 'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu', 'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma', 'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega') ``` ## Examples ```python greek_comparator('alpha', 'beta') < 0 greek_comparator('psi', 'psi') == 0 greek_comparator('upsilon', 'rho') > 0 ```
["def greek_comparator(lhs, rhs):\n greek_alphabet = [\n 'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta',\n 'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu',\n 'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma',\n 'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega']\n l = len(greek_alphabet)\n k = 0\n v = 0\n i = 0\n for i in range(l):\n if lhs == greek_alphabet[i]:\n k = i\n i += 1\n i = 0\n for i in range(l):\n if rhs == greek_alphabet[i]:\n v = i\n i += 1\n b = k - v\n return b", "def greek_comparator(lhs, rhs):\n return 0 if lhs == rhs else -1 if greek_alphabet.index(lhs) < greek_alphabet.index(rhs) else 1", "def greek_comparator(lhs, rhs):\n if lhs == rhs:\n return 0\n\n greek_alphabet = (\n 'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', \n 'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu', \n 'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma',\n 'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega')\n\n return 1 if greek_alphabet.index(lhs) > greek_alphabet.index(rhs) else -1\n", "def greek_comparator(lhs, rhs):\n alfawita = {\"alpha\": 1, \n \"beta\": 2, \n \"gamma\": 3,\n \"delta\": 4,\n \"epsilon\": 5,\n \"zeta\": 6,\n \"eta\": 7,\n \"theta\": 8,\n \"iota\": 9,\n \"kappa\": 10,\n \"lambda\": 11,\n \"mu\": 12,\n \"nu\": 13,\n \"xi\": 14,\n \"omicron\": 15,\n \"pi\": 16,\n \"rho\": 17,\n \"sigma\": 18,\n \"tau\": 19,\n \"upsilon\": 20,\n \"phi\": 21,\n \"chi\": 22,\n \"psi\": 23,\n \"omega\": 24}\n return alfawita[lhs]-alfawita[rhs]", "greek_alphabet = ('alpha', \n'beta', \n'gamma', \n'delta', \n'epsilon', \n'zeta', \n'eta', \n'theta', \n'iota', \n'kappa', \n'lambda', \n'mu', \n'nu', \n'xi', \n'omicron', \n'pi', \n'rho', \n'sigma', \n'tau', \n'upsilon', \n'phi', \n'chi', \n'psi', \n'omega')\n\ndef greek_comparator(lhs, rhs):\n x = greek_alphabet.index(lhs)\n y = greek_alphabet.index(rhs)\n if x < y:\n return -1\n elif x == y:\n return 0\n else:\n return 1", "greek_alphabet = (\n 'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', \n 'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu', \n 'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma',\n 'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega')\ndef greek_comparator(lhs, rhs):\n # the tuple greek_alphabet is defined in the nonlocal namespace\n x = greek_alphabet.index(lhs) - greek_alphabet.index(rhs)\n return x", "def greek_comparator(lhs, rhs):\n # the tuple greek_alphabet is defined in the nonlocal namespace\n if lhs == rhs:\n return 0\n if greek_alphabet.index(lhs) < greek_alphabet.index(rhs):\n return -1\n if greek_alphabet.index(lhs) > greek_alphabet.index(rhs):\n return 1", "greek_alphabet = (\n 'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', \n 'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu', \n 'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma',\n 'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega')\n\ndef greek_comparator(lhs, rhs):\n result = 0\n if greek_alphabet.index(lhs) > greek_alphabet.index(rhs):\n result = 1\n elif greek_alphabet.index(lhs) < greek_alphabet.index(rhs):\n result = -1\n return result", "def greek_comparator(lhs, rhs):\n # the tuple greek_alphabet is defined in the nonlocal namespace\n if lhs == rhs:\n return 0\n for pair in list(enumerate(greek_alphabet)):\n if pair[1] == lhs:\n valL = pair[0]\n if pair[1] == rhs:\n valR = pair[0]\n return -1 if valL < valR else 1", "def greek_comparator(lhs, rhs):\n greek_alphabet = (\n 'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', \n 'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu', \n 'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma',\n 'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega')\n\n \n lhs = greek_alphabet.index(lhs)\n rhs = greek_alphabet.index(rhs)\n if lhs < rhs:\n return -1\n elif lhs == rhs:\n return 0\n elif lhs > rhs:\n return 1\n", "greek_alphabet = (\n 'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta',\n 'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu',\n 'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma',\n 'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega')\n\n\ndef greek_comparator(lhs, rhs):\n # the tuple greek_alphabet is defined in the nonlocal namespace\n if greek_alphabet.index(lhs) < greek_alphabet.index(rhs):\n return -(greek_alphabet.index(rhs) - greek_alphabet.index(lhs))\n elif greek_alphabet.index(lhs) == greek_alphabet.index(rhs):\n return 0\n else:\n return greek_alphabet.index(lhs) - greek_alphabet.index(rhs)", "def greek_comparator(lhs, rhs):\n greek_alphabet = (\n 'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', \n 'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu', \n 'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma',\n 'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega')\n a, b = greek_alphabet.index(lhs), greek_alphabet.index(rhs)\n if a<b: return a-b\n return a+b if a>b else 0", "def greek_comparator(lhs, rhs):\n if lhs == rhs:\n return 0\n l, r = 0, 0\n for i, a in enumerate(greek_alphabet):\n if lhs == a:\n l = i\n if rhs == a:\n r = i\n return -1 if l < r else 1\n", "def greek_comparator(lhs, rhs):\n greek = (\n 'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', \n 'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu', \n 'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma',\n 'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega')\n \n return greek.index(lhs) - greek.index(rhs)", "def greek_comparator(lhs, rhs):\n ga = [\n 'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', \n 'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu', \n 'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma',\n 'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega']\n return -1 if ga.index(lhs)<ga.index(rhs) else 0 if ga.index(lhs)==ga.index(rhs) else 1", "def greek_comparator(lhs, rhs):\n # the tuple greek_alphabet is defined in the nonlocal namespace\n greek_alphabet = (\n 'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', \n 'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu', \n 'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma',\n 'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega')\n \n dict_old=dict(enumerate(greek_alphabet))\n dict_new={value:key for key, value in dict_old.items()}\n \n if dict_new[lhs]<dict_new[rhs]:\n return -1\n elif dict_new[lhs]==dict_new[rhs]:\n return 0\n else:\n return +1", "def greek_comparator(lhs, rhs):\n greek_alphabet = (\n 'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', \n 'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu', \n 'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma',\n 'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega')\n \n return 1 if greek_alphabet.index(lhs) > greek_alphabet.index(rhs) else \\\n 0 if greek_alphabet.index(lhs) == greek_alphabet.index(rhs) else \\\n -1", "def greek_comparator(l, r):\n gt = (\n 'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', \n 'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu', \n 'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma',\n 'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega')\n return gt.index(l)- gt.index(r)", "def greek_comparator(lhs, rhs):\n if lhs == rhs: \n return 0\n a = [greek_alphabet.index(x) for x in [lhs, rhs]]\n if a[0] > a[1]:\n return 1\n else:\n return -1", "def greek_comparator(l, r):\n greek_alphabet = (\n 'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', \n 'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu', \n 'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma',\n 'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega')\n if greek_alphabet.index(l) < greek_alphabet.index(r) : \n return -1\n elif greek_alphabet.index(l) == greek_alphabet.index(r) :\n return 0\n return 1\n", "greek_alphabet = (\n 'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', \n 'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu', \n 'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma',\n 'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega')\n\ndef greek_comparator(lhs, rhs):\n index_lhs, index_rhs = map(greek_alphabet.index, (lhs, rhs))\n return int(index_lhs > index_rhs) or -int(index_lhs < index_rhs)", "def greek_comparator(lhs, rhs):\n # the tuple greek_alphabet is defined in the nonlocal namespace\n greek_alphabet = (\n 'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', \n 'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu', \n 'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma',\n 'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega')\n \n if greek_alphabet.index(lhs) > greek_alphabet.index(rhs):\n return greek_alphabet.index(lhs) - greek_alphabet.index(rhs)\n elif greek_alphabet.index(lhs) < greek_alphabet.index(rhs) :\n return greek_alphabet.index(lhs) - greek_alphabet.index(rhs)\n return 0", "def greek_comparator(lhs, rhs):\n greek_alphabet = ['alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', \n 'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu', \n 'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma',\n 'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega']\n a = greek_alphabet.index(lhs)\n b = greek_alphabet.index(rhs)\n c=a-b\n return c", "def greek_comparator(lhs, rhs):\n g = (\n 'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', \n 'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu', \n 'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma',\n 'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega')\n a = g.index(lhs)\n b = g.index(rhs)\n if a == b:\n return 0\n if a > b:\n return 1\n if a < b:\n return -1\n \n", "def greek_comparator(lhs, rhs):\n greek_alphabet = {\n 'alpha': 1,\n 'beta': 2,\n 'gamma': 3,\n 'delta': 4,\n 'epsilon': 5,\n 'zeta': 6,\n 'eta': 7,\n 'theta': 8,\n 'iota': 9,\n 'kappa': 10,\n 'lambda': 11,\n 'mu': 12,\n 'nu': 13,\n 'xi': 14,\n 'omicron': 15,\n 'pi': 16,\n 'rho': 17,\n 'sigma': 18,\n 'tau': 19,\n 'upsilon': 20,\n 'phi': 21,\n 'chi': 22,\n 'psi': 23,\n 'omega': 24\n }\n a = greek_alphabet.get(lhs) - greek_alphabet.get(rhs)\n return a", "t = [\n 'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', \n 'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu', \n 'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma',\n 'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega']\ndef greek_comparator(l, r):\n return t.index(l) - t.index(r)"]
{"fn_name": "greek_comparator", "inputs": [["chi", "chi"]], "outputs": [[0]]}
INTRODUCTORY
PYTHON3
CODEWARS
11,206
def greek_comparator(lhs, rhs):
019b0ab59bc6e5a35a17f784e28f5e9f
UNKNOWN
You are the Dungeon Master for a public DnD game at your local comic shop and recently you've had some trouble keeping your players' info neat and organized so you've decided to write a bit of code to help keep them sorted! The goal of this code is to create an array of objects that stores a player's name and contact number from a given string. The method should return an empty array if the argument passed is an empty string or `nil`/`None`/`null`. ## Examples ```ruby player_manager("John Doe, 8167238327, Jane Doe, 8163723827") returns [{player: "John Doe", contact: 8167238327}, {player: "Jane Doe", contact: 8163723827}] player_manager(nil) returns [] player_manager("") returns [] ``` ```python player_manager("John Doe, 8167238327, Jane Doe, 8163723827") returns [{"player": "John Doe", "contact": 8167238327}, {"player": "Jane Doe", "contact": 8163723827}] player_manager(None) returns [] player_manager("") returns [] ``` ``` playerManager("John Doe, 8167238327, Jane Doe, 8163723827") returns [{player: "John Doe", contact: 8167238327}, {player: "Jane Doe", contact: 8163723827}] playerManager(null) returns [] playerManager("") returns [] ``` Have at thee!
["import re\n\ndef player_manager(players):\n return players and [ {'player': who, 'contact': int(num)}\n for who,num in re.findall(r'(.+?), (\\d+)(?:, )?', players)] or []", "def player_manager(players):\n return [{'player': a, 'contact': int(b)} for a, b in zip(*[iter(players.split(', '))] * 2)] if players else []", "def player_manager(players):\n if not players: \n return []\n lst = players.split(', ')\n return [{'player': name, 'contact': int(num)} for name, num in zip(lst[::2], lst[1::2])]", "def player_manager(plrs):\n if not plrs: return []\n output = []\n contact, player = plrs.split(', ')[1::2], plrs.split(', ')[::2]\n \n for x in range(len(contact)):\n output.append({'player': player[x], 'contact': int(contact[x])})\n \n return output", "def player_manager(players):\n return [{'player':p.strip(), 'contact':int(c)} for p, c in zip(players.split(',')[::2], players.split(',')[1::2])] if players else []", "import re\ndef player_manager(players):\n manager = []\n if players:\n players_list = re.findall(r\"(?P<name>[a-zA-Z ]+), (?P<number>[0-9]+)\", players)\n \n for name, number in players_list:\n manager.append({'player' : name.strip(), 'contact' : int(number)})\n return manager\n", "def player_manager(players):\n result = []\n if not players:\n return []\n players = players.split(', ')\n for i, x in enumerate(players):\n if i % 2 == 0:\n result.append({})\n result[-1][\"player\"] = x\n else:\n result[-1][\"contact\"] = int(x)\n return result", "def player_manager(players):\n if not players:return []\n players=players.split(\", \")\n return [{\"player\":player,\"contact\":int(contact)} for player,contact in zip(players[::2],players[1::2])]\n", "def player_manager(players):\n if not players: return []\n p = players.split(', ')\n return [{'player': p[i], 'contact': int(p[i + 1])} for i in range(0, len(p) - 1, 2)]"]
{"fn_name": "player_manager", "inputs": [["a, 5"], ["jane, 801, dave, 123"], ["Amelia, 8165254325, Jessie, 9187162345, Marcus Kaine, 8018273245"], [""], [null]], "outputs": [[[{"player": "a", "contact": 5}]], [[{"player": "jane", "contact": 801}, {"player": "dave", "contact": 123}]], [[{"player": "Amelia", "contact": 8165254325}, {"player": "Jessie", "contact": 9187162345}, {"player": "Marcus Kaine", "contact": 8018273245}]], [[]], [[]]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,055
def player_manager(players):
8a806b008cb6d4dbd8e2c75921865cea
UNKNOWN
Chuck has lost count of how many asses he has kicked... Chuck stopped counting at 100,000 because he prefers to kick things in the face instead of counting. That's just who he is. To stop having to count like a mere mortal chuck developed his own special code using the hairs on his beard. You do not need to know the details of how it works, you simply need to know that the format is as follows: 'A8A8A8A8A8.-A%8.88.' In Chuck's code, 'A' can be any capital letter and '8' can be any number 0-9 and any %, - or . symbols must not be changed. Your task, to stop Chuck beating your ass with his little finger, is to use regex to verify if the number is a genuine Chuck score. If not it's probably some crap made up by his nemesis Bruce Lee. Return true if the provided count passes, and false if it does not. ```Javascript Example: 'A8A8A8A8A8.-A%8.88.' <- don't forget final full stop :D\n Tests: 'A2B8T1Q9W4.-F%5.34.' == true; 'a2B8T1Q9W4.-F%5.34.' == false; (small letter) 'A2B8T1Q9W4.-F%5.3B.' == false; (last char should be number) 'A2B8T1Q9W4.£F&5.34.' == false; (symbol changed from - and %) ``` The pattern only needs to appear within the text. The full input can be longer, i.e. the pattern can be surrounded by other characters... Chuck loves to be surrounded! Ready, steady, VERIFY!!
["from re import search\n\n\ndef body_count(code):\n return bool(search(r'(?:[A-Z]\\d){5}\\.-[A-Z]%\\d\\.\\d{2}\\.', code))", "import re\n\npattern = re.compile('A8A8A8A8A8.-A%8.88.'.replace('A', '[A-Z]').replace('8', '[0-9]').replace('.', r'\\.'))\n\ndef body_count(code):\n return bool(pattern.search(code))", "import re;body_count=lambda s:bool(re.search('([A-Z]\\d){5}\\.-[A-Z]%\\d\\.\\d\\d\\.',s))", "import re\n\npattern = re.compile(r\"([A-Z]\\d){5}\\.-[A-Z]%\\d\\.\\d\\d\\.\")\n\ndef body_count(code):\n return bool(pattern.search(code))\n", "check = __import__(\"re\").compile(r\"(?:[A-Z]\\d){5}\\.\\-[A-Z]\\%\\d\\.\\d\\d\\.\").search\n\ndef body_count(code):\n return bool(check(code))", "import re\n\ndef body_count(code):\n reg = re.compile(r'([A-Z][0-9]){5}\\.\\-[A-Z]\\%[0-9]\\.([0-9]){2}\\.')\n return bool(re.search(reg, code))", "body_count=lambda s:bool(__import__('re').search(r'(?:[A-Z]\\d){5}\\.-[A-Z]%\\d\\.\\d\\d\\.',s))", "from re import search\n\ndef body_count(code):\n return bool(search(r\"([A-Z]\\d){5}\\.-[A-Z]%\\d\\.\\d{2}\\.\",code))", "from re import search\ndef body_count(code):\n return bool(search(\"([A-Z]\\d){5}\\.\\-[A-Z]%\\d\\.\\d\\d\\.\",code))"]
{"fn_name": "body_count", "inputs": [["A6C2E5Z9A4.-F%8.08."], ["PP P6A6T5F5S3.-Z%1.11.hgr"], ["A6A1E3A8M2.-Q%8.88."], ["d G8H1E2O9N3.-W%8.56. f"], ["B4A1D1I8B4.-E%8.76."], ["ffr65A C8K4D9U7V5.-Y%8.00."], [" 76 B2L4D0A8C6.-T%8.90. lkd"], ["B2L4D0A8C6.-T%8.90"], ["B2L4D0AFC6.-T%8.90."], ["B4A1D1I8B4"], ["B4A6666..."], ["B4A1D1I000.-E%0.00.)"], [".-E%8.76."], ["B4A1t6I7.-E%8.76."], ["b4A1D1I8B4.-E%8.76."]], "outputs": [[true], [true], [true], [true], [true], [true], [true], [false], [false], [false], [false], [false], [false], [false], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,212
def body_count(code):
be9d17cf49c6c75c5a0642fe129d46ad
UNKNOWN
Implement a function which behaves like the uniq command in UNIX. It takes as input a sequence and returns a sequence in which all duplicate elements following each other have been reduced to one instance. Example: ``` ["a", "a", "b", "b", "c", "a", "b", "c"] => ["a", "b", "c", "a", "b", "c"] ```
["from itertools import groupby\n\ndef uniq(seq): \n return [k for k,_ in groupby(seq)]", "def uniq(seq):\n if len(seq) == 0:\n return []\n rez = [seq[0]]\n for i in range(1, len(seq)):\n if seq[i] != rez[-1]:\n rez.append(seq[i])\n return rez", "from itertools import groupby\n\ndef uniq(a):\n return [x for x, _ in groupby(a)]", "def uniq(seq):\n return [c for i, c in enumerate(seq) if i == 0 or seq[i-1] != c]", "def uniq(seq): \n return ([seq[0]] + [seq[i] for i in range(1, len(seq)) if seq[i] != seq[i-1]] if seq else [])", "def uniq(seq): \n result = []\n for q in seq:\n if result and result[-1] == q:\n continue\n result.append(q)\n return result", "def uniq(seq): \n ans = []\n p = ''\n for i in seq:\n if i != p:\n ans.append(i)\n p = i\n return ans if len(seq)>1 else seq", "from itertools import groupby\nfrom operator import itemgetter\n\n# Just for fun, it's better to use list comprehension\ndef uniq(seq):\n return list(map(itemgetter(0), groupby(seq)))", "from itertools import groupby\nfrom operator import itemgetter\n\ndef uniq(seq):\n return list(map(itemgetter(0), groupby(seq)))", "from itertools import groupby\n\ndef uniq(seq): \n return [k[0] for k in groupby(seq)]"]
{"fn_name": "uniq", "inputs": [[["a", "a", "b", "b", "c", "a", "b", "c", "c"]], [["a", "a", "a", "b", "b", "b", "c", "c", "c"]], [[]], [["foo"]], [["bar"]], [[""]], [[null, "a", "a"]]], "outputs": [[["a", "b", "c", "a", "b", "c"]], [["a", "b", "c"]], [[]], [["foo"]], [["bar"]], [[""]], [[null, "a"]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,326
def uniq(seq):
2b001b335711ba8142ad7fffd7b242d2
UNKNOWN
Do you have in mind the good old TicTacToe? Assuming that you get all the data in one array, you put a space around each value, `|` as a columns separator and multiple `-` as rows separator, with something like `["O", "X", " ", " ", "X", " ", "X", "O", " "]` you should be returning this structure (inclusive of new lines): ``` O | X | ----------- | X | ----------- X | O | ``` Now, to spice up things a bit, we are going to expand our board well beyond a trivial `3` x `3` square and we will accept rectangles of big sizes, still all as a long linear array. For example, for `"O", "X", " ", " ", "X", " ", "X", "O", " ", "O"]` (same as above, just one extra `"O"`) and knowing that the length of each row is `5`, you will be returning ``` O | X | | | X ------------------- | X | O | | O ``` And worry not about missing elements, as the array/list/vector length is always going to be a multiple of the width.
["def display_board(board, width):\n board = [c.center(3) for c in board]\n rows = [\"|\".join(board[n:n+width]) for n in range(0, len(board), width)]\n return (\"\\n\" + \"-\"*(4*width - 1) + \"\\n\").join(rows)", "def display_board(board, width):\n line = f'\\n{\"-\"*(4*width-1)}\\n'\n return line.join( '|'.join(f' {c} ' for c in row)\n for row in (board[i:i+width] for i in range(0,len(board),width)))", "def display_board(board, width):\n output = ''\n separator = (width*3)+(width-1)\n for i in range(len(board)):\n output += f' {board[i]} '\n if i+1 < len(board):\n if (i+1) % width == 0:\n output += '\\n' + ('-'*separator) + '\\n'\n else:\n output += '|'\n return output", "def display_board(board, width):\n row = lambda i: f\" {' | '.join(board[i:i+width])} \"\n sep = f\"\\n{'':-^{4 * width - 1}}\\n\"\n return sep.join(row(i) for i in range(0, len(board), width))", "def display_board(board, width):\n return (\"\\n\" + (\"-\"*(4*width - 1)) + \"\\n\").join([\"|\".join([\" \" + board[(i * width) + j] + \" \" for j in range(width)]) for i in range(int(len(board)/width))])", "def display_board(board, width):\n lines = [' ' + ' | '.join(board[i:i+width]) + ' ' for i in range(0, len(board), width)]\n return ('\\n' + '-' * len(lines[0]) + '\\n').join(lines)", "def display_board(board, w):\n re=[ ]\n for i in range(0,len(board),w):\n re.append( '|'.join( ' {} '.format(e) for e in board[i:i+w] ))\n return ('\\n'+'-'*len(re[0])+'\\n').join(re)\n \n", "def display_board(board, width):\n n = int(len(board) / width)\n sep = \"\\n\" + \"-\" * (4*width-1) + \"\\n\"\n return sep.join([ \" \" + \" | \".join(board[i*width:(i+1)*width]) + \" \" for i in range(n)] ) \n \n \n", "display_board=lambda a,n:' %s '%(' \\n'+(4*n-1)*'-'+'\\n ').join(map(' | '.join,zip(*[iter(a)]*n)))", "display_board=lambda b,w:f\"\\n{'-'*(4*w-1)}\\n\".join([\"|\".join(\" \"+c+\" \" for c in b[i:i+w]) for i in range(0,len(b)-1,w)])\n"]
{"fn_name": "display_board", "inputs": [[["O", "X", "X", "O"], 2], [["O", "X", " ", " ", "X", " ", "X", "O", " "], 3], [["O", "X", " ", " ", "X", " ", "X", "O", " ", "O"], 5], [["O", "X", " ", " ", "X", " ", "X", "O", " ", "O"], 2], [["1", "2", "3", "4", "5", "1", "2", "3", "4", "5", "1", "2", "3", "4", "5", "1", "2", "3", "4", "5", "1", "2", "3", "4", "5", "1", "2", "3", "4", "5", "1", "2", "3", "4", "5", "1"], 6]], "outputs": [[" O | X \n-------\n X | O "], [" O | X | \n-----------\n | X | \n-----------\n X | O | "], [" O | X | | | X \n-------------------\n | X | O | | O "], [" O | X \n-------\n | \n-------\n X | \n-------\n X | O \n-------\n | O "], [" 1 | 2 | 3 | 4 | 5 | 1 \n-----------------------\n 2 | 3 | 4 | 5 | 1 | 2 \n-----------------------\n 3 | 4 | 5 | 1 | 2 | 3 \n-----------------------\n 4 | 5 | 1 | 2 | 3 | 4 \n-----------------------\n 5 | 1 | 2 | 3 | 4 | 5 \n-----------------------\n 1 | 2 | 3 | 4 | 5 | 1 "]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,093
def display_board(board, width):
90d50c5357a370b840e1c481a375077e
UNKNOWN
# Task You are the manager of the famous rescue team: The Knights. Your task is to assign your knights to a rescue missions on an infinite 2D-plane. Your knights can move only by `n-knight` jumps. For example, if a knight has n = 2, they can only move exactly as a knight on a chess board. If n = 3, they can move from (0, 0) to one of the following 8 points: `(3, 1) (3, -1), ( -3, 1), (-3, -1), (1, 3), (1, -3), (-1, 3) or (-1, -3).` You are given an array containing the `n`s of all of your knights `n-knight` jumps, and the coordinates (`x`, `y`) of a civilian who need your squad's help. Your head quarter is located at (0, 0). Your must determine if `at least one` of your knight can reach that point `(x, y)`. # Input/Output - `[input]` integer array `N` The ways your knights move. `1 <= N.length <=20` - `[input]` integer `x` The x-coordinate of the civilian - `[input]` integer `y` The y-coordinate of the civilian - `[output]` a boolean value `true` if one of your knights can reach point (x, y), `false` otherwise.
["def knight_rescue(N,x,y):\n return (y - x) % 2 == 0 or any(n % 2 == 0 for n in N)\n", "def knight_rescue(N, x, y):\n return (x - y) % 2 == 0 or any(n % 2 == 0 for n in N)", "def knight_rescue(N,x,y):\n if x%2 == 0 and y%2==0:\n return True if any([i%2!=0 for i in N]) else (True if all([i%2==0 for i in N]) else False)\n elif x%2 != 0 and y%2!=0:\n return True if all([i%2!=0 for i in N]) else (True if any([i%2==0 for i in N]) else False)\n return True if any([i%2==0 for i in N]) else False", "def knight_rescue(N,x,y):\n for n in N:\n if n%2==0:\n return True\n return (x+y)%2==0", "def knight_rescue(N,x,y):\n return not all(n&1 and (x+y)&1 for n in N)", "def knight_rescue(N,x,y):\n return any(i%2==0 for i in N) or (x+y)%2==0", "def knight_rescue(N,x,y):\n\n return not ((x+y)%2 and all(n%2 for n in N))", "def knight_rescue(N, x, y):\n even = (x + y) % 2 == 0\n for step in N:\n if step & 1 == 0 or even:\n return True\n return False", "def knight_rescue(N,x,y):\n e=any(i%2==0 for i in N)\n return e or (x+y)%2==0", "def knight_rescue(ns,x,y):\n return any(n%2==0 or n>0 and x%2==y%2 for n in ns)"]
{"fn_name": "knight_rescue", "inputs": [[[2], 2, 1], [[1], 10, 10], [[1], 1, 0], [[1, 2], 1, 0], [[1, 2, 3], 456546, 23532], [[1, 5, 3, 7, 9], 7, 8], [[1, 1, 1, 1, 1, 1, 1, 1, 1], 0, 1]], "outputs": [[true], [true], [false], [true], [true], [false], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,200
def knight_rescue(N,x,y):
9cdeb481a1f456f5641ed1b89fdc5355
UNKNOWN
You are given a sequence of a journey in London, UK. The sequence will contain bus **numbers** and TFL tube names as **strings** e.g. ```python ['Northern', 'Central', 243, 1, 'Victoria'] ``` Journeys will always only contain a combination of tube names and bus numbers. Each tube journey costs `£2.40` and each bus journey costs `£1.50`. If there are `2` or more adjacent bus journeys, the bus fare is capped for sets of two adjacent buses and calculated as one bus fare for each set. Your task is to calculate the total cost of the journey and return the cost `rounded to 2 decimal places` in the format (where x is a number): `£x.xx`
["def london_city_hacker(journey): \n # your code here\n tube = 2.40\n bus = 1.50\n total_cost = 0.00\n count = 0\n for link in journey:\n if isinstance(link, str):\n total_cost += tube\n count = 0\n else:\n if count == 0:\n total_cost += bus\n count +=1\n else:\n count = 0\n return '\u00a3{:.2f}'.format(total_cost)\n", "def london_city_hacker(journey): \n vehicle = \"\".join(\"t\" if isinstance(j, str) else \"b\" for j in journey).replace(\"bb\", \"b\")\n return f\"\u00a3{sum(2.4 if v == 't' else 1.5 for v in vehicle):.2f}\"", "def london_city_hacker(journey):\n prices = []\n \n for stop in journey:\n prices.append(2.4 if type(stop) is str else 1.5)\n if prices[-2:] == [1.5, 1.5]:\n prices[-1] = 0\n \n return f\"\u00a3{sum(prices):.2f}\"", "from itertools import groupby\ndef london_city_hacker(journey):\n tube_fare = lambda n: 2.4 * n\n bus_fare = lambda n: 1.5 * sum(divmod(n, 2))\n s = sum([bus_fare, tube_fare][a](len(list(g))) for a, g in groupby(map(lambda a: isinstance(a, str), journey)))\n return f'\u00a3{s:.2f}'", "def london_city_hacker(journey): #Jai Shree Ram\n total=0.0\n l=[]\n for i in range(len(journey)):\n if type(journey[i])==str:\n total+=2.40\n else:\n if i<len(journey)-1 and type(journey[i+1])==int:\n l.append(journey[i])\n if len(l)==2:\n total+=1.50 \n l=[] \n else:\n total+=1.50\n l=[]\n total=round(total,2)\n return '\u00a3'+str(total)+'0'", "from itertools import groupby\n\ndef london_city_hacker(journey): \n return f\"\u00a3{sum(2.4 * len(list(l)) if k is str else (len(list(l)) + 1) // 2 * 1.5 for k,l in groupby(journey, type)):.2f}\"", "def london_city_hacker(journey):\n bus_counter = 0\n bus_price = 0\n tube_price = 0\n for i in journey:\n if type(i) is int:\n bus_counter += 1\n if bus_counter > 1:\n bus_counter = 0\n bus_price += 0\n else:\n bus_price += 1.5\n if type(i) is str:\n bus_counter = 0\n tube_price += 2.40\n return f\"\u00a3{tube_price + bus_price:.2f}\"", "def london_city_hacker(journey): \n \n sum = 0.0 \n isBus = False\n \n for i in journey :\n if len(str(i)) <= 3:\n if isBus :\n isBus = 0 \n else :\n sum += 1.50\n isBus = 1\n else :\n sum += 2.40\n isBus = 0\n \n sum = round(sum * 100) / 100\n \n return f'\u00a3{str(sum)}0'", "def london_city_hacker(journey): \n total_cost = 0\n adjacent_bus_tour = 0\n for tour in journey:\n if type(tour) == str:\n adjacent_bus_tour = 0\n total_cost += 2.40\n else:\n adjacent_bus_tour += 1\n if adjacent_bus_tour == 2:\n adjacent_bus_tour = 0\n else:\n total_cost += 1.50\n return f'\u00a3{total_cost:.2f}'", "from itertools import groupby\n\ndef london_city_hacker(journey): \n arr = list(map(type,journey))\n s = 0\n for k,g in groupby(arr):\n g = len(list(g))\n if k==str:\n s += 2.4*g\n else:\n s += 1.5*(g//2+(1 if g%2 else 0) if g>1 else g)\n return f'\u00a3{round(s,2):.2f}'"]
{"fn_name": "london_city_hacker", "inputs": [[[12, "Central", "Circle", 21]], [["Piccidilly", 56]], [["Northern", "Central", "Circle"]], [["Piccidilly", 56, 93, 243]], [[386, 56, 1, 876]], [[]]], "outputs": [["\u00a37.80"], ["\u00a33.90"], ["\u00a37.20"], ["\u00a35.40"], ["\u00a33.00"], ["\u00a30.00"]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,574
def london_city_hacker(journey):
befed8f4f4d1b2e43cfefbc89c529f52
UNKNOWN
Your friend has invited you to a party, and tells you to meet them in the line to get in. The one problem is it's a masked party. Everyone in line is wearing a colored mask, including your friend. Find which people in line could be your friend. Your friend has told you that he will be wearing a `RED` mask, and has **TWO** other friends with him, both wearing `BLUE` masks. Input to the function will be an array of strings, each representing a colored mask. For example: ```python line = ['blue','blue','red','red','blue','green'] ``` The output of the function should be the number of people who could possibly be your friend. ```python friend_find(['blue','blue','red','red','blue','green','chipmunk']) # return 1 ```
["def redWith2Blues(i, line):\n return any(line[i-2+x:i+1+x].count('blue')==2 for x in range(3))\n\ndef friend_find(line):\n return sum( p=='red' and redWith2Blues(i,line) for i,p in enumerate(line))", "def friend_find(line):\n N = len(line)\n A = lambda i: line[i] == \"red\" and B(i)\n B = lambda i: C(i) or D(i) or E(i)\n C = lambda i: i < N-2 and line[i+1] == line[i+2] == \"blue\"\n D = lambda i: 0 < i < N-1 and line[i-1] == line[i+1] == \"blue\"\n E = lambda i: 1 < i and line[i-2] == line[i-1] == \"blue\"\n return sum(map(A, range(N)))", "friend_find = lambda arr:sum([1 for i in range(len(arr)) if arr[i] == \"red\" if (i > 1 and arr[i - 1] == \"blue\" and arr[i - 2] == \"blue\" ) or (i > 0 and i < len(arr) - 1 and arr[i - 1] == \"blue\" and arr[i + 1] == \"blue\") or (i < len(arr) - 2 and arr[i + 1] == \"blue\" and arr[i + 2] == \"blue\" )])", "import re\ndef friend_find(line):\n s = ' '.join(line)\n return len(re.findall(r'\\bblue blue red\\b|\\bblue red (?=blue\\b)|\\bred (?=blue blue\\b)', s))", "friend_find=lambda L:sum(p=='red'and any(L[x:x+3].count('blue')==2 for x in range(max(0,i-2),i+1))for i,p in enumerate(L))", "def friend_find(line):\n s = ''.join([[c[0],'y'][c not in ['red','green','blue']] for c in line])\n r = ''\n c = 0\n for i in s:\n if len(r) < 3:\n r += i\n else:\n r = (r+i)[1:]\n if [r.count('r'),r.count('b')] == [1,2]:\n c += 1\n n = ''\n for i in r:\n if i == 'r':\n n += 'x'\n else:\n n += i\n r = n[:]\n return c", "def friend_find(line):\n possible_combo = (['blue','blue','red'], ['blue','red', 'blue'], ['red', 'blue', 'blue'])\n return len({i + line[i:i+3].index('red') for i in range(len(line)) if line[i:i+3] in possible_combo})\n", "def friend_find(line):\n posssible_combo = (['blue','blue','red'], ['blue','red', 'blue'], ['red', 'blue', 'blue'])\n return len({i + line[i:i+3].index('red') for i in range(len(line)) if line[i:i+3] in posssible_combo})\n", "from itertools import permutations\ndef friend_find(line):\n p=list(set(permutations(['red','blue','blue'],3)))\n f=i=0\n while i<len(line):\n x=tuple(line[i:i+3])\n if x in p:\n f+=1\n i+=x.index('red')\n i+=1\n return f\n", "def friend_find(line):\n s=0\n for i in range(0,len(line)-2):\n f1,f2,f3=line[i],line[i+1],line[i+2]\n if [f1,f2,f3]==[\"red\",\"blue\",\"blue\"]:s+=1\n elif [f1,f2,f3]==[\"blue\",\"red\",\"blue\"]:\n s+=1\n line[i+1]=\"\"\n elif [f1,f2,f3]==[\"blue\",\"blue\",\"red\"]:\n s+=1\n line[i+2]=\"\"\n return s"]
{"fn_name": "friend_find", "inputs": [[["blue", "blue", "red", "red", "blue", "green"]], [["blue", "red", "blue", "blue", "red", "blue", "red"]], [["brown", "brown", "red", "green"]], [["red", "blue", "blue", "red"]], [["red", "blue"]], [["blue", "green", "red", "green", "blue", "blue", "red"]], [["blue", "blue", "blue", "blue", "blue", "blue", "blue"]], [["blue", "red", "blue", "red", "red", "blue", "red"]]], "outputs": [[1], [2], [0], [2], [0], [1], [0], [1]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,802
def friend_find(line):
3cffdcff08e3688a31c9fd013e4955b7
UNKNOWN
Pig Latin is an English language game where the goal is to hide the meaning of a word from people not aware of the rules. So, the goal of this kata is to wite a function that encodes a single word string to pig latin. The rules themselves are rather easy: 1) The word starts with a vowel(a,e,i,o,u) -> return the original string plus "way". 2) The word starts with a consonant -> move consonants from the beginning of the word to the end of the word until the first vowel, then return it plus "ay". 3) The result must be lowercase, regardless of the case of the input. If the input string has any non-alpha characters, the function must return None, null, Nothing (depending on the language). 4) The function must also handle simple random strings and not just English words. 5) The input string has no vowels -> return the original string plus "ay". For example, the word "spaghetti" becomes "aghettispay" because the first two letters ("sp") are consonants, so they are moved to the end of the string and "ay" is appended.
["VOWELS = set('aeiou')\n\ndef pig_latin(st):\n s = st.lower()\n if s.isalpha():\n if set(s) & VOWELS:\n if s[0] in VOWELS:\n s += 'w'\n while s[0] not in VOWELS:\n s = s[1:] + s[:1]\n return s + 'ay'", "def pig_latin(s):\n vowels = ['a', 'e', 'i', 'o', 'u']\n word = s.lower()\n if not word.isalpha(): # Check for non alpha character\n return None\n if word[0] in vowels: # Check if word starts with a vowel\n return word + 'way'\n for i, letter in enumerate(word): # Find the first vowel and add the beginning to the end \n if letter in vowels:\n return word[i:]+word[:i]+'ay'\n return word + 'ay' # No vowels", "import re\ndef pig_latin(s):\n s = s.lower()\n if re.findall('[\\d\\W]',s) or s == '':\n return None\n elif s.startswith(('a','e','i','o','u')):\n return s + 'way'\n else:\n return re.sub('(^[^aeiou]+)(\\w*)','\\g<2>\\g<1>ay',s)", "def pig_latin(s):\n if s.isalpha():\n s = s.lower()\n if s[0] in 'aeiou':\n return s + 'way'\n for i in range(len(s)):\n s = s[1:] + s[0]\n if s[0] in 'aeiou':\n break\n return s + 'ay'\n \n", "def pig_latin(s):\n if not s.isalpha(): return None\n s = s.lower()\n iV = next((i for i,c in enumerate(s) if c in \"aeiou\"), len(s))\n return s[iV:] + (s[:iV] or 'w') + \"ay\"", "def pig_latin(s):\n prev, s = '', s.lower()\n if any(ord(x)not in range(ord('a'),ord('z')+1) for x in s) or not s: return\n while s and s[0] not in 'aeiou':\n prev += s[0]\n s = s[1:]\n return f'{s}{prev}{(\"\", \"w\")[not prev]}ay'", "def pig_latin(s):\n a = ''\n if not s.isalpha(): return None\n s = s.lower()\n for i in s:\n if i in 'aeiou':\n break\n a+= i\n return s + 'way' if s[0] in 'aeiou' else s[len(a):] + a + 'ay'", "def pig_latin(s):\n if not s.isalpha():\n return None\n s = s.lower()\n if s.startswith(('a', 'e', 'i', 'o', 'u')):\n s += 'w'\n i = 0\n else:\n i = next((i for i, c in enumerate(s) if c in 'aeiou'), 0)\n return s[i:] + s[:i] + 'ay'\n", "def pig_latin(s):\n if not s.isalpha(): return None\n s =s.lower()\n if s[0] in 'aeiou': return s+'way'\n for n,i in enumerate(s):\n if i in 'aeiou':\n return s[n:]+s[0:n]+'ay'\n return s+'ay'"]
{"fn_name": "pig_latin", "inputs": [["Hello"], ["CCCC"], ["tes3t5"], ["ay"], [""], ["YA"], ["123"], ["ya1"], ["yaYAya"], ["YayayA"]], "outputs": [["ellohay"], ["ccccay"], [null], ["ayway"], [null], ["ayay"], [null], [null], ["ayayayay"], ["ayayayay"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,493
def pig_latin(s):
f4c4a84ca483a5d3c65d96e78ca3b40b
UNKNOWN
Mrs Jefferson is a great teacher. One of her strategies that helped her to reach astonishing results in the learning process is to have some fun with her students. At school, she wants to make an arrangement of her class to play a certain game with her pupils. For that, she needs to create the arrangement with **the minimum amount of groups that have consecutive sizes**. Let's see. She has ```14``` students. After trying a bit she could do the needed arrangement: ```[5, 4, 3, 2]``` - one group of ```5``` students - another group of ```4``` students - then, another one of ```3``` - and finally, the smallest group of ```2``` students. As the game was a success, she was asked to help to the other classes to teach and show the game. That's why she desperately needs some help to make this required arrangements that make her spend a lot of time. To make things worse, she found out that there are some classes with some special number of students that is impossible to get that arrangement. Please, help this teacher! Your code will receive the number of students of the class. It should output the arrangement as an array with the consecutive sizes of the groups in decreasing order. For the special case that no arrangement of the required feature is possible the code should output ```[-1] ``` The value of n is unknown and may be pretty high because some classes joined to to have fun with the game. You may see more example tests in the Example Tests Cases Box.
["def shortest_arrang(n):\n # For odd n, we can always construct n with 2 consecutive integers.\n if n % 2 == 1:\n return [n//2 + 1, n//2]\n\n # For even n, n is the sum of either an odd number or even number of\n # consecutive positive integers. Moreover, this property is exclusive.\n\n for i in range(3, n // 2):\n if i % 2 == 1 and n % i == 0:\n # For odd i, if n / i is an integer, then the sequence, which has\n # odd length, is centered around n / i.\n return list(range(n//i + i//2, n//i - i//2 - 1, -1))\n elif i % 2 == 0 and n % i == i // 2:\n # For even i, if the remainder of n / i is 1/2, then the sequence\n # (even length) is centered around n / i.\n return list(range(n//i + i//2, n//i - i//2, -1))\n\n # If none of the above are satisfied, then n is a power of 2 and we cannot\n # write it as the sum of two consecutive integers.\n return [-1]\n", "def shortest_arrang(n):\n k = 1\n while n >= 0:\n n -= k\n k += 1\n d, m = divmod(n, k)\n if not m:\n return list(range(d + k - 1, d - 1, -1))\n return [-1]", "def shortest_arrang(n):\n nGrpMax = int( ((1+8*n)**.5-1)/2 )\n for nGrp in range(2, nGrpMax+1):\n maxInG = (2*n + nGrp**2 - nGrp) / (2*nGrp)\n if maxInG == int(maxInG):\n maxInG = int(maxInG)\n return list(range(maxInG, maxInG-nGrp, -1))\n return [-1]", "def shortest_arrang(n):\n r = n // 2 + 2\n a = [i for i in range(r, 0, -1)]\n for i in range(r):\n for j in range(r + 1):\n if sum(a[i:j]) == n:\n return a[i:j]\n return [-1]\n", "def shortest_arrang(n):\n a = n // 2\n b = a + 1\n \n while a:\n total = sum(range(a, b+1))\n if total == n:\n return list(range(b, a-1, -1))\n \n if total > n:\n b -= 1\n a = b-1\n else:\n a -= 1\n else:\n return [-1]", "def shortest_arrang(num):\n for n in reversed(range((num+3) // 2)):\n for j in reversed(range(n)):\n x = range(j, n+1)\n if sum(x) == num:\n return list(reversed(x))\n return [-1] ", "def shortest_arrang(n):\n for i in range(2,n):\n if (n/i)*2<i: break\n if i%2==0 and (n/i)%1==0.5: return [n//i-i//2+1+j for j in range(0,i)[::-1]]\n if i%2==1 and (n/i)%1==0: return [n//i-(i-1)//2+j for j in range(0,i)[::-1]]\n return [-1]\n", "shortest_arrang=lambda n:(lambda ngm:next(((lambda x:list(range(x,x-ng,-1)))(int((2*n+ng**2-ng)/(2*ng)))for ng in range(2,ngm+1)if not((2*n+ng**2-ng)/(2*ng))%1),[-1]))(int(((1+8*n)**.5-1)/2)) "]
{"fn_name": "shortest_arrang", "inputs": [[10], [14], [16], [22], [65]], "outputs": [[[4, 3, 2, 1]], [[5, 4, 3, 2]], [[-1]], [[7, 6, 5, 4]], [[33, 32]]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,721
def shortest_arrang(n):
58295868b8a262b4a521aed4f8efc51f
UNKNOWN
Your retro heavy metal band, VÄxën, originally started as kind of a joke, just because why would anyone want to use the crappy foosball table in your startup's game room when they could be rocking out at top volume in there instead? Yes, a joke, but now all the top tech companies are paying you top dollar to play at their conferences and big product-release events. And just as how in the early days of the Internet companies were naming everything "i"-this and "e"-that, now that VÄxënmänïä has conquered the tech world, any company that doesn't use Hëävÿ Mëtäl Ümläüts in ëvëry pössïblë pläcë is looking hopelessly behind the times. Well, with great power chords there must also come great responsibility! You need to help these companies out by writing a function that will guarantee that their web sites and ads and everything else will RÖCK ÄS MÜCH ÄS PÖSSÏBLË! Just think about it -- with the licensing fees you'll be getting from Gööglë, Fäcëböök, Äpplë, and Ämäzön alone, you'll probably be able to end world hunger, make college and Marshall stacks free to all, and invent self-driving bumper cars. Sö lët's gët röckïng and röllïng! Pëdal tö thë MËTÄL! Here's a little cheatsheet that will help you write your function to replace the so-last-year letters a-e-i-o-u-and-sometimes-y with the following totally rocking letters: ``` A = Ä = \u00c4 E = Ë = \u00cb I = Ï = \u00cf O = Ö = \u00d6 U = Ü = \u00dc Y = Ÿ = \u0178 a = ä = \u00e4 e = ë = \u00eb i = ï = \u00ef o = ö = \u00f6 u = ü = \u00fc y = ÿ = \u00ff ``` ### Python issues First, Python in the Codewars environment has some codec/encoding issues with extended ASCII codes like the umlaut-letters required above. With Python 2.7.6, when writing your solution you can just copy the above umlaut-letters (instead of the unicode sequences) and paste them into your code, but I haven't found something yet that will work for *both* 2.7.6 and 3.4.3 -- hopefully I will find something soon (answers/suggestions are welcome!), and hopefully that part will also be easier with other languages when I add them. Second, along the same lines, don't bother trying to use string translate() and maketrans() to solve this in Python 2.7.6, because maketrans will see the character-mapping strings as being different lengths. Use a different approach instead.
["UMLAUTS = {'A': '\u00c4', 'E': '\u00cb', 'I': '\u00cf', 'O': '\u00d6', 'U': '\u00dc', 'Y': '\u0178',\n 'a': '\u00e4', 'e': '\u00eb', 'i': '\u00ef', 'o': '\u00f6', 'u': '\u00fc', 'y': '\u00ff'}\n\n\ndef heavy_metal_umlauts(s):\n return ''.join(UMLAUTS.get(a, a) for a in s)", "# -*- coding: utf-8 -*-\ndef heavy_metal_umlauts(boring_text):\n return boring_text.translate(str.maketrans('AEIOUYaeiouy','\u00c4\u00cb\u00cf\u00d6\u00dc\u0178\u00e4\u00eb\u00ef\u00f6\u00fc\u00ff'))", "def heavy_metal_umlauts(boring_text):\n return boring_text.translate(str.maketrans(\"aeiouyAEIOUY\", \"\u00e4\u00eb\u00ef\u00f6\u00fc\u00ff\u00c4\u00cb\u00cf\u00d6\u00dc\u0178\"))\n", "# -*- coding: utf-8 -*-\ndef heavy_metal_umlauts(boring_text):\n return boring_text.translate(str.maketrans('oOIiAaEeUuYy','\u00f6\u00d6\u00cf\u00ef\u00c4\u00e4\u00cb\u00eb\u00dc\u00fc\u0178\u00ff'))\n", "def heavy_metal_umlauts(boring_text):\n rtext = ['A', 'E', 'I', 'O', 'U', 'Y', 'a', 'e', 'i', 'o', 'u', 'y']\n htext = ['\u00c4', '\u00cb', '\u00cf', '\u00d6', '\u00dc', '\u0178', '\u00e4', '\u00eb', '\u00ef', '\u00f6', '\u00fc', '\u00ff']\n out = ''\n for i in boring_text:\n if i in rtext:\n out += htext[rtext.index(i)]\n else:\n out += i\n return out", "# -*- coding: utf-8 -*-\ndef heavy_metal_umlauts(boring_text):\n a = 'AOaoEUeuIYiy'\n b = '\u00c4\u00d6\u00e4\u00f6\u00cb\u00dc\u00eb\u00fc\u00cf\u0178\u00ef\u00ff'\n return boring_text.translate(str.maketrans(a, b))\n", "# -*- coding: utf-8 -*-\ndef heavy_metal_umlauts(boring_text):\n d = {'A': '\u00c4', 'O': '\u00d6', 'a': '\u00e4', 'E': '\u00cb',\n 'U': '\u00dc', 'e': '\u00eb', 'u': '\u00fc', 'I': '\u00cf',\n 'Y': '\u0178', 'i': '\u00ef', 'y': '\u00ff', 'o': '\u00f6'}\n return ''.join(i if i not in d else d[i] for i in boring_text)\n", "# -*- coding: utf-8 -*-\n\nd = {\n 'A':'\u00c4','E':'\u00cb','I':'\u00cf','O':'\u00d6','U':'\u00dc','Y':'\u0178',\n 'a':'\u00e4','e':'\u00eb','i':'\u00ef','o':'\u00f6','u':'\u00fc','y':'\u00ff'\n \n }\n \ndef heavy_metal_umlauts(boring_text):\n\n s = \"\"\n\n for i in range(len(boring_text)):\n \n if boring_text[i] in list(d.keys()):\n \n s+= d[boring_text[i]]\n \n else:\n \n s+= boring_text[i]\n\n return s\n \n", "T = str.maketrans('AOaoEUeuIYiy', '\u00c4\u00d6\u00e4\u00f6\u00cb\u00dc\u00eb\u00fc\u00cf\u0178\u00ef\u00ff')\ndef heavy_metal_umlauts(s):\n return s.translate(T)\n"]
{"fn_name": "heavy_metal_umlauts", "inputs": [["Announcing the Macbook Air Guitar"], ["Facebook introduces new heavy metal reaction buttons"], ["Strong sales of Google's VR Metalheadsets send tech stock prices soaring"], ["Vegan Black Metal Chef hits the big time on Amazon TV"]], "outputs": [["\u00c4nn\u00f6\u00fcnc\u00efng th\u00eb M\u00e4cb\u00f6\u00f6k \u00c4\u00efr G\u00fc\u00eft\u00e4r"], ["F\u00e4c\u00ebb\u00f6\u00f6k \u00efntr\u00f6d\u00fcc\u00ebs n\u00ebw h\u00eb\u00e4v\u00ff m\u00ebt\u00e4l r\u00eb\u00e4ct\u00ef\u00f6n b\u00fctt\u00f6ns"], ["Str\u00f6ng s\u00e4l\u00ebs \u00f6f G\u00f6\u00f6gl\u00eb's VR M\u00ebt\u00e4lh\u00eb\u00e4ds\u00ebts s\u00ebnd t\u00ebch st\u00f6ck pr\u00efc\u00ebs s\u00f6\u00e4r\u00efng"], ["V\u00ebg\u00e4n Bl\u00e4ck M\u00ebt\u00e4l Ch\u00ebf h\u00efts th\u00eb b\u00efg t\u00efm\u00eb \u00f6n \u00c4m\u00e4z\u00f6n TV"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,558
def heavy_metal_umlauts(boring_text):
2531aba3fb65f54cb26ff41c9ce1e2d7
UNKNOWN
*This kata is based on [Project Euler Problem #349](https://projecteuler.net/problem=349). You may want to start with solving [this kata](https://www.codewars.com/kata/langtons-ant) first.* --- [Langton's ant](https://en.wikipedia.org/wiki/Langton%27s_ant) moves on a regular grid of squares that are coloured either black or white. The ant is always oriented in one of the cardinal directions (left, right, up or down) and moves according to the following rules: - if it is on a black square, it flips the colour of the square to white, rotates 90 degrees counterclockwise and moves forward one square. - if it is on a white square, it flips the colour of the square to black, rotates 90 degrees clockwise and moves forward one square. Starting with a grid that is **entirely white**, how many squares are black after `n` moves of the ant? **Note:** `n` will go as high as 10^(20) --- ## My other katas If you enjoyed this kata then please try [my other katas](https://www.codewars.com/collections/katas-created-by-anter69)! :-) #### *Translations are welcome!*
["move = [lambda p: (p[0]+1, p[1]), lambda p: (p[0], p[1]+1), lambda p: (p[0]-1, p[1]), lambda p: (p[0], p[1]-1)]\nstart, loop, size = 9977, 104, 12\n\ndef langtons_ant(n):\n pos, d, black, res = (0, 0), 0, set(), 0\n if n > start:\n x = (n - start)%loop\n res = size * (n-start-x)//loop\n n = start + x\n for i in range(n):\n if pos in black:\n black.remove(pos)\n d = (d+1)%4\n else:\n black.add(pos)\n d = (d-1)%4\n pos = move[d](pos)\n return res + len(black)", "# precalculate results\nLIMIT = 11000 # > 9977 + 104\nCACHE = [0]\nGRID = set() # empty grid\nx , y = 0, 0 # ant's position\ndx, dy = 1, 0 # direction\n\nfor _ in range(LIMIT +1):\n if (x, y) in GRID: # square is black\n GRID.remove((x, y))\n dx, dy = -dy, dx\n else: # square is white\n GRID.add((x, y))\n dx, dy = dy, -dx\n\n # move forward\n x += dx\n y += dy\n \n # store number of black squares\n CACHE.append(len(GRID))\n\n\ndef langtons_ant(n):\n if n < LIMIT:\n return CACHE[n]\n \n # a(n+104) = a(n) + 12 for n > 9976\n x = (n - LIMIT) // 104 + 1\n return CACHE[n-x*104] + x*12\n", "M, B, r, c, d, N = [0], set(), 0, 0, 0, 10000\nfor _ in range(N+104):\n d, _ = ((d - 1) % 4, B.discard((r, c))) if (r, c) in B else ((d + 1) % 4, B.add((r, c)))\n r, c = r + [-1, 0, 1, 0][d], c + [0, 1, 0, -1][d]\n M.append(len(B))\n \ndef langtons_ant(n):\n return M[n] if n < N else 12 * ((n - N) // 104) + M[N + ((n - N) % 104)] ", "l, m = 10082, 104\na, d, s, t = 0, 1, {}, [0]\nfor _ in range(l + m - 1):\n s[a] = 1 - s.get(a, 0)\n v = (-1) ** -~s[a]\n d *= 1j * v\n a += d\n t.append(t[-1] + v)\n\ndef langtons_ant(n):\n if n < l: return t[n]\n q, r = divmod(n - l, m)\n return 12 * q + t[l + r]", "def langtons_ant(n):\n k = (n - 11000) // 104 if n > 11000 else 0\n blacks = set()\n x, y = 0, 0\n dx, dy = 0, 1\n for _ in range(n - k * 104):\n if (x, y) in blacks:\n blacks.remove((x, y))\n dx, dy = dy, -dx\n else:\n blacks.add((x, y))\n dx, dy = -dy, dx\n x, y = x + dx, y + dy\n \n \n return len(blacks) + k * 12", "def langtons_ant(n):\n if n == 0: return 0\n \n width, height, i, j = 150, 150, 75, 75\n \n grid = [[1] * width for i in range(height)]\n \n directions = list(range(4))\n \n d, count, s, black = 0, 0, 0, []\n \n while count < n and 0 <= i < height and 0 <= j < width: \n cell = grid[i][j]\n turn = -1 if cell == 0 else 1\n \n if cell: \n grid[i][j] = 0\n s += 1 \n else: \n grid[i][j] = 1\n s -= 1\n \n black.append(s)\n d = directions[(4 + d + turn) % 4]\n \n if d == 0: i -= 1\n elif d == 1: j -= 1\n elif d == 2: i += 1\n elif d == 3: j += 1 \n \n count += 1\n \n limit, period = 10000, 104\n \n if count <= limit + period + 1: return black[-1]\n \n diff = black[limit + period] - black[limit]\n cycles, r = divmod(n - 1 - limit, period)\n \n return black[limit + r] + cycles * diff", "move_y = [1, 0, -1, 0]\nmove_x = [0, 1, 0, -1]\n\ndef langtons_ant(n):\n grid_size = 128\n grid = [[0 for i in range(grid_size)] for j in range(grid_size)]\n \n pos_x = int(grid_size/2)\n pos_y = int(grid_size/2)\n dir = 0\n \n cnt_blk = 0\n step_cnt = 0\n prev_cnt = []\n while step_cnt < n:\n \n # Check if reached steady state for step count > 10000 \n # and when remaining steps evenly divisible by cycle of 104\n if step_cnt > 1e4 and step_cnt % 104 == n%104:\n prev_cnt.append(cnt_blk)\n \n # If previous 5 black square counts have same difference, \n # assume in cycle\n if len(prev_cnt) == 6:\n prev_cnt.pop(0)\n diff = prev_cnt[-1]-prev_cnt[-2]\n cycle_flg = True\n for i in range(len(prev_cnt)-2,0,-1):\n if prev_cnt[i]-prev_cnt[i-1] != diff:\n cycle_flg = False\n break\n \n # If in cycle, add up difference for however many steps \n # left until n and then break out of walk simulation\n if cycle_flg:\n cnt_blk += int(diff * (n-step_cnt)//104)\n break\n \n # If on white square, flip to black and turn clockwise\n if grid[pos_x][pos_y] == 0:\n cnt_blk += 1\n grid[pos_x][pos_y] = 1\n dir = (dir+1)%4\n # If on black square, flip to white and turn counter-clockwise\n else:\n cnt_blk -= 1\n grid[pos_x][pos_y] = 0\n dir = (dir+4-1)%4\n \n # Advance one square based on new direction\n pos_x += move_x[dir]\n pos_y += move_y[dir]\n \n # Increment step counter\n step_cnt += 1\n return cnt_blk", "def langtons_ant(n):\n grid = [[0]]\n column = 0\n row = 0\n direction = 0\n move = {\n 0: (-1, 0),\n 1: ( 0, 1),\n 2: ( 1, 0),\n 3: ( 0,-1),\n }\n rows = len(grid)\n cols = len(grid[0])\n ap = (row, column)\n dir = direction\n n_black = 0\n \n max_simple_range = 11000\n n_black_highway_ref = []\n ref = 0\n \n for i in range(1, n + 1): \n if (grid[ap[0]][ap[1]]) == 1:\n grid[ap[0]][ap[1]] = 0\n dir = (dir + 1) % 4\n n_black -= 1\n else:\n grid[ap[0]][ap[1]] = 1\n dir = (dir - 1) % 4\n n_black += 1\n ap = (ap[0] + move[dir][0], ap[1] + move[dir][1])\n \n if ap[0] >= rows:\n grid = grid + ([[0]*cols])\n rows += 1\n elif ap[0] < 0:\n grid = ([[0]*cols]) + grid\n rows += 1\n ap = (0, ap[1])\n \n if ap[1] >= cols:\n for j, r in enumerate(grid):\n grid[j] = r + [0]\n cols += 1\n elif ap[1] < 0:\n for j, r in enumerate(grid):\n grid[j] = [0] + r\n cols += 1\n \n ap = (ap[0], 0)\n \n if i >= max_simple_range:\n if i == max_simple_range:\n ref = n_black\n n_black_highway_ref.append(n_black - ref)\n \n if i == (max_simple_range + 104):\n break\n \n if n > (max_simple_range + 104):\n n_black += (n_black_highway_ref[-1] * (((n - max_simple_range) // 104) - 1)) \n n_black += (n_black_highway_ref[((n - max_simple_range) % 104)]) \n return n_black", "def langtons_ant(n):\n\n def ant(n):\n di=\"ULDR\"\n tbl={(0,0):0}\n # 1= clock 0 = anticlock\n turn=1\n pos=di[0]\n x,y=0,0\n for i in range(n):\n #print(\"curr\",x,y)\n\n if (x,y) not in tbl.keys():\n tbl[(x,y)]=0\n cur=tbl[(x,y)]\n #print(\"color\",cur)\n\n turn = 1 if cur==1 else 0\n cur = 0 if cur == 1 else 1\n #print((4 + di.index(pos) + (1 if turn else -1)) % 4)\n \n pos = di[(4 + di.index(pos) + (-1 if turn else 1)) % 4]\n #print(pos)\n tbl[x,y]=cur\n\n if pos == \"U\": y -= 1\n elif pos == \"R\": x -= 1\n elif pos == \"D\": y += 1\n elif pos == \"L\": x += 1\n rez=(sum(tbl.values()))\n return rez\n\n if n>10000:\n y=(n-10000)%104\n yy=(n-10000)//104\n #print(y+10000)\n x=(yy*12+ant(y+10000))\n else:\n x=ant(n)\n\n return x", "def ant(G,c,r,n,d=0,R=range,L=len,P=(-1,0,1,0)):\n for _ in R(n):\n h,w,v=L(G),L(G[0]),G[r][c]\n G[r][c]=(v+1)%2\n d+=(-1,1)[v]\n r,c=r+P[d%4],c+P[::-1][d%4]\n if w==c:\n for i in R(L(G)):G[i]+=[1]\n if h==r:G+=[[1]*w]\n if c<0:\n for i in R(L(G)):G[i]=[1]+G[i]\n c=c+1\n if r<0:G,r=[[1]*w]+G,0\n return G\n \ndef langtons_ant(n,z=0):\n if 11000<n:\n z=(n-11000)//104*12\n n=(n-11000)%104+11000\n return sum(ant([[1]],0,0,n,d=0,R=range,L=len,P=(-1,0,1,0)),[]).count(0)+z"]
{"fn_name": "langtons_ant", "inputs": [[0], [1], [2], [10], [100], [1000], [10000], [100000], [1000000], [10000000]], "outputs": [[0], [1], [2], [6], [20], [118], [720], [11108], [114952], [1153412]]}
INTRODUCTORY
PYTHON3
CODEWARS
8,487
def langtons_ant(n):
0e6cb51e7fdba2d3af05a6f696795118
UNKNOWN
**Introduction**  Little Petya very much likes sequences. However, recently he received a sequence as a gift from his mother.  Petya didn't like it at all! He decided to make a single replacement. After this replacement, Petya would like to the sequence in increasing order.  He asks himself: What is the lowest possible value I could have got after making the replacement and sorting the sequence? **About the replacement**  Choose exactly one element from the sequence and replace it with another integer > 0. You are **not allowed** to replace a number with itself, or to change no number at all. **Task**  Find the lowest possible sequence after performing a valid replacement, and sorting the sequence. **Input:**  Input contains sequence with `N` integers. All elements of the sequence > 0. The sequence will never be empty. **Output:**  Return sequence with `N` integers — which includes the lowest possible values of each sequence element, after the single replacement and sorting has been performed. **Examples**: ``` ([1,2,3,4,5]) => [1,1,2,3,4] ([4,2,1,3,5]) => [1,1,2,3,4] ([2,3,4,5,6]) => [1,2,3,4,5] ([2,2,2]) => [1,2,2] ([42]) => [1] ```
["def sort_number(a): \n a = sorted(a)\n return [1]+a if a.pop()!=1 else a+[2]", "def sort_number(a): \n if max(a) != 1:\n a.remove(max(a))\n a.append(1)\n else:\n a.remove(max(a))\n a.append(2)\n \n return sorted(a)\n", "def sort_number(a): \n a = sorted(a)\n m = a.pop(-1)\n return [[1] + a, a + [2]][m==1]", "def sort_number(a):\n a = sorted(a)\n a[-1] = 2 if a[-1] == 1 else 1\n return sorted(a)", "sort_number = lambda a: sum(a)/len(a)!=1 and [1]+sorted(a)[:-1] or a[:-1]+[2]", "def sort_number(a):\n a.sort()\n return a[:-1]+[2] if set(a) == {1} else [] if len(a) == 0 else [1] if len(a) == 0 else [1] + a[:-1]", "def sort_number(a): \n a.sort()\n if a==[1]*len(a):\n del a[-1]\n a.append(2)\n return a\n l=[1]\n a.remove(max(a))\n for i in range(len(a)):\n l.append(a[i])\n return l", "def sort_number(a): \n a = sorted(a)\n if a[len(a)-1] != 1:\n a[len(a)-1] = 1\n else:\n a[len(a)-1] = 2\n \n return sorted(a)", "import heapq\n\ndef sort_number(a):\n l = a[:]\n heapq._heapify_max(l)\n mx = heapq.heappop(l)\n heapq.heappush(l, 2 if mx == 1 else 1)\n return heapq.nsmallest(len(a), l)", "def sort_number(a):\n if a==[1,1,1]:\n return [1,1,2]\n if a==[1]:\n return [2]\n l=sorted(a)[:-1]\n l.append(1)\n return sorted(l)"]
{"fn_name": "sort_number", "inputs": [[[1, 2, 3, 4, 5]], [[4, 2, 1, 3, 5]], [[2, 3, 4, 5, 6]], [[2, 2, 2]], [[42]], [[5, 6, 1, 2, 3, 1, 3, 45, 7, 1000000000]], [[1, 1, 1]], [[1]], [[134]]], "outputs": [[[1, 1, 2, 3, 4]], [[1, 1, 2, 3, 4]], [[1, 2, 3, 4, 5]], [[1, 2, 2]], [[1]], [[1, 1, 1, 2, 3, 3, 5, 6, 7, 45]], [[1, 1, 2]], [[2]], [[1]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,423
def sort_number(a):
31d9b98a6ea7611f705a043b5534ddb9
UNKNOWN
Your task is to generate the Fibonacci sequence to `n` places, with each alternating value as `"skip"`. For example: `"1 skip 2 skip 5 skip 13 skip 34"` Return the result as a string You can presume that `n` is always a positive integer between (and including) 1 and 64.
["def skiponacci(n):\n s = '1'\n num = 1\n prv = 0\n for i in range(1,n):\n new = num + prv\n prv = num\n num = new\n if i%2 == 0:\n s = s + ' ' + str(num)\n else:\n s += ' skip'\n\n return s", "def skiponacci(n):\n fib = [1, 1][:n]\n for _ in range(n-2):\n fib.append(sum(fib[-2:]))\n return \" \".join(str(n) if i % 2 else \"skip\" for i, n in enumerate(fib, 1))", "def skiponacci(n):\n result = [\"1\",\"skip\"]\n suite = [1,1]\n for i in range(2,n):\n suite.append(suite[i-2]+suite[i-1])\n if i % 2 != 0:\n result.append(\"skip\")\n else:\n result.append(str(suite[i]))\n return \" \".join(result[0:n])", "fib, result = [1, 1], [\"1\", \"skip\"]\nfor i in range(100):\n fib.append(fib[-1] + fib[-2])\n result.append(\"skip\" if i&1 else str(fib[-1]))\n\ndef skiponacci(n):\n return ' '.join(result[:n])", "from scipy.constants import golden as \u03c6\n\ndef skiponacci(n):\n fib = lambda n: int(round((\u03c6**n - (1-\u03c6)**n) / 5**.5))\n return ' '.join('skip' if n%2 else str(fib(n+1)) for n in range(n))\n", "def gen_fib():\n a, b = 1, 1\n yield a\n yield b\n while True:\n a, b = b, a + b\n yield b\n \ndef skiponacci(n):\n result = []\n for i, f in enumerate(gen_fib()):\n if i == n:\n break\n result.append(str(f) if i % 2 == 0 else 'skip')\n return ' '.join(result)", "def skiponacci(n):\n res = []\n a, b = 0, 1\n\n for i in range(n):\n a, b = a + b, a\n res.append('skip' if i%2 else str(a))\n\n return ' '.join(res)", "def skiponacci(n):\n res = []\n a, b = 0, 1\n\n for i in range(n):\n a, b = a + b, a\n if i%2:\n res.append('skip')\n else:\n res.append(str(a)) \n return ' '.join(res)", "def skiponacci(n):\n fib = [1, 1][:n]\n for _ in range(n - 2):\n fib.append(sum(fib[-2:]))\n return ' '.join('skip' if c % 2 else str(a) for c, a in enumerate(fib))", "def skiponacci(n):\n mas = []\n fib1, fib2 = 0, 1\n for i in range(n):\n fib1, fib2 = fib2, fib1 + fib2\n mas.append(fib1)\n sas = []\n for i in range(0, len(mas), 2):\n sas.append(str(mas[i]))\n if n % 2 == 0:\n return \" skip \".join(sas) + \" skip\"\n else:\n return \" skip \".join(sas)"]
{"fn_name": "skiponacci", "inputs": [[1], [5], [7]], "outputs": [["1"], ["1 skip 2 skip 5"], ["1 skip 2 skip 5 skip 13"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,452
def skiponacci(n):
0b7b9a08ee154bb15d6201794076bd88
UNKNOWN
What is an anagram? Well, two words are anagrams of each other if they both contain the same letters. For example: ``` 'abba' & 'baab' == true 'abba' & 'bbaa' == true 'abba' & 'abbba' == false 'abba' & 'abca' == false ``` Write a function that will find all the anagrams of a word from a list. You will be given two inputs a word and an array with words. You should return an array of all the anagrams or an empty array if there are none. For example: anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']) => ['aabb', 'bbaa'] anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']) => ['carer', 'racer'] anagrams('laser', ['lazing', 'lazy', 'lacer']) => []
["def anagrams(word, words): return [item for item in words if sorted(item)==sorted(word)]", "from collections import Counter\n\ndef anagrams(word, words):\n counts = Counter(word)\n return [w for w in words if Counter(w) == counts]", "def anagrams(word, words):\n match = sorted(word)\n return [w for w in words if match == sorted(w)]", "def anagrams(word, words):\n return [w for w in words if sorted(word)==sorted(w)]", "from collections import Counter\n\n\ndef anagrams(word, words):\n n, c = len(word), Counter(word)\n return [w for w in words if len(w) == n and Counter(w) == c]\n", "def anagrams(word, words):\n letter = { x : word.count(x) for x in word }\n result = []\n \n for i in words:\n letters = { x : i.count(x) for x in i }\n if letters == letter:\n result.append(i)\n \n return result", "def anagrams(word, words):\n return [el for el in words if sorted(word) == sorted(el)]", "from collections import Counter\ndef anagrams(word, words):\n main = Counter(word)\n return [wor for wor in words if Counter(wor) == main]", "def anagrams(word, words):\n return [x for x in words if sorted(x) == sorted(word)]", "def anagrams(word, words):\n return [w for w in words if list(sorted(w)) == list(sorted(word))]", "def anagrams(word, words):\n def lettercount(inputword):\n wordarr = list(inputword)\n worddict = {}\n for letter in wordarr:\n if letter not in worddict:\n worddict[letter] = wordarr.count(letter)\n return worddict\n \n return [astring for astring in words if lettercount(astring) == lettercount(word)] \n \n \n", "from collections import Counter\n\ndef anagrams(word, words):\n return [w for w in words if Counter(word) == Counter(w)]", "def anagrams(word, words):\n return [x for x in words if sorted(word) == sorted(x)]", "def anagrams(word, words):\n lst = []\n for elem in words:\n if sorted(word) == sorted(elem):\n lst.append(elem)\n return lst\n #your code here\n", "def anagrams(word, words):\n word=sorted(word)\n return list(filter(lambda ele: sorted(ele)==word ,words))", "def anagrams(word, words):\n return [trial for trial in words if sorted(trial) == sorted(word)]", "def anagrams(word, words):\n return [w for w in words if sorted(w) == sorted(word)]", "def anagrams(word: str, words: list) -> list: return list(filter(lambda x: sorted(x) == sorted(word), words))", "anagrams = lambda _,__: list([s for s in __ if sorted(s) == sorted(_)])\n", "anagrams=lambda word, words:list(w for w in words if sorted(list(w))==sorted(list(word)))", "def anagrams(word, words):\n ans = []\n or1 = 0\n or2 = 0\n for i in word:\n or1 += ord(i)\n for i in words:\n or2 = 0\n for x in i :\n or2 += ord(x)\n if or1 == or2:\n ans += [i]\n return ans", "# What is an anagram? Well, two words are anagrams of each other\n# if they both contain the same letters. For example:\n# 'abba' & 'baab' == true ; 'abba' & 'bbaa' == true \n# 'abba' & 'abbba' == false ; 'abba' & 'abca' == false\n# Write a function that will find all the anagrams of a word from a list.\n# You will be given two inputs a word and an array with words.\n# You should return an array of all the anagrams or an empty array\n# if there are none. For example:\n# anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']) => ['aabb', 'bbaa']\n# anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']) =>\n# ['carer', 'racer']\n# anagrams('laser', ['lazing', 'lazy', 'lacer']) => []\n\ndef anagrams(word, words):\n w_buff = []\n w_out = []\n for w_t in words :\n if len(w_t) == len(word):\n w_buff.append(w_t)\n w_w = list(word)\n w_w.sort()\n for w_t in w_buff:\n w_buff_l = list(w_t)\n w_buff_l.sort()\n if w_buff_l == w_w :\n w_out.append(w_t)\n return w_out", "def anagrams(word, words):\n #your code here\n list = []\n word = sorted(word)\n for i in range(len(words)):\n if word == sorted(words[i]):\n list.append(words[i])\n else:\n pass\n return(list)", "from collections import Counter\ndef anagrams(word, words):\n # your code here\n return [w for w in words if sorted(sorted(Counter(word).items())) == sorted(sorted(Counter(w).items()))]", "def anagrams(word, words):\n\n l = [letter for letter in word]\n anagram_list = []\n \n for item in words:\n l_item = [letter for letter in item]\n if sorted(l) == sorted(l_item):\n temp_list = [i for i in l + l_item if i not in l_item]\n if len(temp_list) == 0:\n anagram_list.append(item)\n else:\n continue\n return anagram_list", "def anagrams(word, words):\n return [anagram for anagram in words if sum([ord(c) for c in anagram]) == sum([ord(c) for c in word])]\n", "def anagrams(word, words):\n #your code here\n wordnum=sum(ord(ch) for ch in word)\n res=[]\n if not words :\n return []\n for item in words:\n if sum(ord(ch) for ch in item)==wordnum:\n res.append(item)\n return res"]
{"fn_name": "anagrams", "inputs": [["abba", ["aabb", "abcd", "bbaa", "dada"]], ["racer", ["crazer", "carer", "racar", "caers", "racer"]], ["a", ["a", "b", "c", "d"]], ["ab", ["cc", "ac", "bc", "cd", "ab", "ba", "racar", "caers", "racer"]], ["abba", ["a", "b", "c", "d", "aabb", "bbaa", "abab", "baba", "baab", "abcd", "abbba", "baaab", "abbab", "abbaa", "babaa"]], ["big", ["gig", "dib", "bid", "biig"]]], "outputs": [[["aabb", "bbaa"]], [["carer", "racer"]], [["a"]], [["ab", "ba"]], [["aabb", "bbaa", "abab", "baba", "baab"]], [[]]]}
INTRODUCTORY
PYTHON3
CODEWARS
5,256
def anagrams(word, words):
9b35c12f15a69569a51c76f1500fa6a2
UNKNOWN
You need to swap the head and the tail of the specified array: the head (the first half) of array moves to the end, the tail (the second half) moves to the start. The middle element (if it exists) leaves on the same position. Return new array. For example: ``` [ 1, 2, 3, 4, 5 ] => [ 4, 5, 3, 1, 2 ] \----/ \----/ head tail [ -1, 2 ] => [ 2, -1 ] [ 1, 2, -3, 4, 5, 6, -7, 8 ] => [ 5, 6, -7, 8, 1, 2, -3, 4 ] ```
["def swap_head_tail(a):\n r, l = (len(a)+1)//2, len(a)//2\n return a[r:] + a[l:r] + a[:l]", "def swap_head_tail(lst):\n n, d = divmod(len(lst), 2)\n return lst[n+d:] + [lst[n]] * d + lst[:n]", "def swap_head_tail(arr):\n if len(arr) == 1: return arr\n n = len(arr)//2\n res,res2 = arr[:n],arr[-n:]\n if len(arr) % 2 == 1: res.insert(0,arr[n])\n return res2 + res", "def swap_head_tail(arr):\n m = len(arr) // 2\n return arr[-m:] + arr[m:-m] + arr[:m]", "def swap_head_tail(arr):\n middle, odd = divmod(len(arr), 2)\n return arr[middle + odd:] + arr[middle:middle+odd] + arr[:middle]", "swap_head_tail = lambda a: a[len(a)+1>>1:] + a[len(a)>>1:len(a)+1>>1] + a[:len(a)>>1]", "swap_head_tail=lambda a:(lambda m:a[-m:]+a[m:-m]+a[:m])(len(a)//2)", "def swap_head_tail(arr):\n print(arr)\n list_arr = [*arr[int(len(arr)/2):], *arr[:(int(len(arr)/2))]]\n list1 = arr[int(len(arr)/2 + 1):]\n list2 = arr[:(int(len(arr)/2))]\n middle = [arr[int(len(arr) / 2)]]\n return list_arr if len(arr) % 2 == 0 else [*list1, *middle, *list2]"]
{"fn_name": "swap_head_tail", "inputs": [[[-1, 2]], [[1, 2, -3, 4, 5, 6, -7, 8]]], "outputs": [[[2, -1]], [[5, 6, -7, 8, 1, 2, -3, 4]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,083
def swap_head_tail(arr):
af230fa7cb16b2535aec2ef87c422410
UNKNOWN
# Task Given a square `matrix`, your task is to reverse the order of elements on both of its longest diagonals. The longest diagonals of a square matrix are defined as follows: * the first longest diagonal goes from the top left corner to the bottom right one; * the second longest diagonal goes from the top right corner to the bottom left one. # Example For the matrix ``` 1, 2, 3 4, 5, 6 7, 8, 9 ``` the output should be: ``` 9, 2, 7 4, 5, 6 3, 8, 1 ``` # Input/Output - `[input]` 2D integer array `matrix` Constraints: `1 ≤ matrix.length ≤ 10, matrix.length = matrix[i].length, 1 ≤ matrix[i][j] ≤ 1000` - `[output]` 2D integer array Matrix with the order of elements on its longest diagonals reversed.
["def reverse_on_diagonals(matrix):\n copy = [ line[:] for line in matrix ]\n for i in range(len(matrix)):\n copy[i][i] = matrix[-1-i][-1-i]\n copy[i][-1-i] = matrix[-1-i][i]\n \n return copy", "def reverse_on_diagonals(matrix):\n l = len(matrix)\n for i in range(l // 2):\n j = l - i - 1\n matrix[i][i], matrix[j][j] = matrix[j][j], matrix[i][i]\n matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]\n return matrix", "def reverse_on_diagonals(matrix):\n # Modifies the matrix in place. Only way to get O(n)\n diag1 = [matrix[i][i] for i in range(len(matrix))]\n diag2 = [matrix[i][~i] for i in range(len(matrix))]\n for i, n in enumerate(reversed(diag1)):\n matrix[i][i] = n\n for i, n in enumerate(reversed(diag2)):\n matrix[i][~i] = n\n return matrix\n", "from copy import deepcopy\n\ndef reverse_on_diagonals(matrix):\n matrix = deepcopy(matrix)\n n = len(matrix)\n for y in range(n // 2):\n x = n - y - 1\n matrix[y][y], matrix[x][x] = matrix[x][x], matrix[y][y]\n matrix[y][x], matrix[x][y] = matrix[x][y], matrix[y][x]\n return matrix", "def reverse_on_diagonals(a):\n for i in range(len(a)//2):\n j = -1-i\n a[i][i], a[j][j], a[i][j], a[j][i] = a[j][j], a[i][i], a[j][i], a[i][j]\n return a", "def reverse_on_diagonals(mx):\n dl = []\n dr = []\n for i in range(len(mx)):\n dl.append(mx[i][i])\n dr.append(mx[i][-i-1])\n for i in range(len(mx)):\n mx[i][i] = dl.pop()\n mx[i][-i-1] = dr.pop()\n return mx", "r=reversed;x=enumerate;reverse_on_diagonals=lambda m:[[f if i==j or len(m[i])-(i+j+1)==0 else m[i][j]for j,f in x(e)]for i,e in x([list(r(e))for e in r(m)])]", "def reverse_on_diagonals(matrix):\n diagonals = [(row[idx], row[-idx-1]) for idx, row in enumerate(matrix)] \n \n for idx, ch in enumerate(reversed(diagonals)):\n matrix[idx][idx], matrix[idx][-idx-1] = ch\n \n return matrix \n", "def reverse_on_diagonals(matrix):\n for i in range(int(len(matrix)/2)):\n matrix[i][i],matrix[len(matrix)-1-i][len(matrix)-1-i] = matrix[len(matrix)-1-i][len(matrix)-1-i],matrix[i][i]\n matrix[len(matrix)-1-i][i],matrix[i][len(matrix)-1-i] = matrix[i][len(matrix)-1-i],matrix[len(matrix)-1-i][i]\n return matrix", "def reverse_on_diagonals(matrix):\n n = len(matrix)\n for i in range(n//2):\n matrix[i][i], matrix[n-i-1][n-i-1] = matrix[n-i-1][n-i-1], matrix[i][i]\n \n matrix[i][n-i-1], matrix[n-i-1][i] = matrix[n-i-1][i], matrix[i][n-i-1] \n \n return matrix"]
{"fn_name": "reverse_on_diagonals", "inputs": [[[[1, 2, 3], [4, 5, 6], [7, 8, 9]]], [[[239]]], [[[1, 10], [100, 1000]]], [[[43, 455, 32, 103], [102, 988, 298, 981], [309, 21, 53, 64], [2, 22, 35, 291]]]], "outputs": [[[[9, 2, 7], [4, 5, 6], [3, 8, 1]]], [[[239]]], [[[1000, 100], [10, 1]]], [[[291, 455, 32, 2], [102, 53, 21, 981], [309, 298, 988, 64], [103, 22, 35, 43]]]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,653
def reverse_on_diagonals(matrix):
adc356bf148e17597e515e395db98350
UNKNOWN
Implement function which will return sum of roots of a quadratic equation rounded to 2 decimal places, if there are any possible roots, else return **None/null/nil/nothing**. If you use discriminant,when discriminant = 0, x1 = x2 = root => return sum of both roots. There will always be valid arguments. Quadratic equation - https://en.wikipedia.org/wiki/Quadratic_equation
["def roots(a,b,c):\n if b**2>=4*a*c:\n return round(-b/a,2)", "def roots(a,b,c):\n import math\n d = b ** 2 - 4 * a * c\n if d > 0:\n return round(-2 * b / (2 * a), 2)\n elif d == 0:\n x = -b / (2 * a)\n return x * 2\n else:\n return None", "def roots(a,b,c):\n return round(-b / a, 2) if b * b - 4 * a * c >= 0 else None \n", "def roots(a,b,c):\n # your code\n d = b**2 - 4*a*c\n if d < 0:\n return None\n elif d == 0:\n return (-b + d**0.5)/(2*a) * 2\n else:\n x1 = (-b + d**0.5)/(2*a)\n x2 = (-b - d**0.5)/(2*a)\n return round(x1 + x2, 2)\n\n", "def roots(a ,b, c):\n d = b**2 - 4*a*c\n if d >= 0:\n return round(-b / a, 2)", "roots=lambda a,b,c:None if b*b<a*c*4else round(-b/a,2)", "def roots(a,b,c):\n # your code\n D = b**2-4*a*c\n if D<0:\n #No solution in the set of real numbers\n return None\n if D==0:\n #Same \"double\" solution\n x= (-b+D**0.5)/(2*a)\n return round(x*2,2)\n if D>0:\n #Two different solutions\n x1 = (-b+D**0.5)/(2*a)\n x2 = (-b-D**0.5)/(2*a)\n return round((x1+x2),2)", "import math\n\ndef roots(a,b,c):\n dis = b ** 2 - 4 * a * c\n if dis < 0: return None\n return round(((-b + math.sqrt(dis)) / (2*a)) + ((-b - math.sqrt(dis)) / (2*a)), 2)", "roots=lambda a, b, c: round(-(b/(2*a))*2, 2) if (b**2)-(4*a*c) >= 0 else None", "import math\ndef roots(a,b,c):\n d=round(b*b-4*a*c,2) \n if d<0 :\n return None\n return round(-b/a,2) "]
{"fn_name": "roots", "inputs": [[1, -35, -23], [6, 0, -24], [-5, 21, 0], [6, 4, 8], [1, 5, -24], [3, 11, 6], [2, 2, 9], [1, -1.6666666666666667, -26], [1, 6, 10], [7, -2, -5], [1, 8, 20], [2, 3, -2], [1, 4, 12], [3, -2, -5], [3, 4, 9], [5, 4, 0], [4, -5, 0], [1, 4, 9], [1, 0, -49], [2, 8, 8], [1, 0, -0.16], [1, 6, 12], [1, 0, -9], [-3, 0, 12], [1, 3, 9], [3, 7, 0], [5, 3, 6], [1, 4, 4], [-1, 0, 5.29], [1, 12, 36], [1, 0, -0.09], [2, 5, 11], [3, 0, -15], [1, -3, 0], [1, 8, 16], [2, 6, 9], [-1, 36, 0], [5, -8, 0], [1, 5, 12], [-14, 0, 0], [1, 7, 20], [1, -6, 0], [1, -11, 30], [1, 3, 12], [1, 6, 9], [8, 47, 41]], "outputs": [[35], [0], [4.2], [null], [-5], [-3.67], [null], [1.67], [null], [0.29], [null], [-1.5], [null], [0.67], [null], [-0.8], [1.25], [null], [0], [-4], [0], [null], [0], [0], [null], [-2.33], [null], [-4], [0], [-12], [0], [null], [0], [3], [-8], [null], [36], [1.6], [null], [0], [null], [6], [11], [null], [-6], [-5.88]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,587
def roots(a,b,c):
e3275599138bacedbeb430dc2d25941e
UNKNOWN
## Story There are four warriors, they need to go through a dark tunnel. Tunnel is very narrow, every time only can let two warriors through, and there are lot of dangerous traps. Fortunately, they have a lamp that can illuminate the tunnel to avoid being trapped by the trap. In order to pass this tunnel, they need five steps: 1. Two people go through the tunnel with the lamp 2. And then one people come back with the lamp 3. And then two people go through the tunnel with the lamp 4. And then one people come back with the lamp 5. And then two people go through the tunnel with the lamp Each warrior has his own walking speed, we need to calculate the shortest time they have to cross the tunnel. For example: Four warriors is `a,b,c,d`. Their speed are `[3,4,5,6]`. It means they need 3 minutes, 4 minutes, 5 minutes and 6 minutes to cross the tunnel. The shortest crossing time should be 21 minutes, the method is as follows: ``` a and b go through the tunnel ---> Spend 4 minutes (Time spent should be calculated by the person who is slow) a come back ---> Spend 3 minutes a and c go through the tunnel ---> Spend 5 minutes a come back ---> Spend 3 minutes a and d go through the tunnel ---> Spend 6 minutes ``` Do you have any other better way? ## Task Complete function `shortestTime()` that accepts 1 argument: `speed` that are the spent time of four warriors. Returns the shortest time that all warriors go through the tunnel. **Note: The method in example above is not always the best way.** ## Example
["def shortest_time(speed):\n a,b,c,d = sorted(speed)\n return a+b+d + min(2*b, a+c)", "from itertools import combinations\n\ndef shortest_time(xs, ys=[]):\n if len(xs) == 2:\n return max(xs)\n result = 999999999\n for i, j in combinations(range(len(xs)), 2):\n m = max(xs[i], xs[j])\n xs2 = xs[:i] + xs[i+1:j] + xs[j+1:]\n ys2 = ys + [xs[i], xs[j]]\n for k, y in enumerate(ys2):\n result = min(m + y + shortest_time(xs2+[y], ys2[:k] + ys2[k+1:]), result)\n return result", "shortest_time=lambda a:a.sort()or a[0]+a[1]+min(2*a[1],a[0]+a[2])+a[3]", "def shortest_time(speed):\n import itertools\n from collections import Counter\n times=[]\n for elem in itertools.combinations(speed,2): \n end1 = [x for x in elem] \n base1 = list((Counter(speed)-Counter(end1)).elements()) \n for i in itertools.combinations(end1,1): \n base2 = [x for x in base1+[i[0]]] \n if sum(end1)!= 2*end1[0]:\n end2 = [x for x in end1 if x != i[0]]\n else:\n end2 = [end1[0]] \n for j in itertools.combinations(base2,2): \n end3 = [x for x in end2 +[j[0],j[1]]]\n base3 = list((Counter(base2)-Counter(j)).elements())\n for k in itertools.combinations(end3,1): \n base4 = [x for x in base3+[k[0]]] \n times += [max(elem)+ i[0]+max(j)+k[0]+max(base4)] \n return min(times)", "from math import inf\nfrom itertools import chain, combinations, combinations_with_replacement\n\n# thanks to \"The capacity-C torch problem\" by Roland Backhouse, Hai Truong\n# https://www.sciencedirect.com/science/article/pii/S0167642315000118\n\ndef shortest_time(speed: [int]):\n forward_trips_num = 3 # for len(speed) == 4\n best_time = inf\n# path = []\n for forward_trips in combinations_with_replacement(list(combinations(speed, 2)), forward_trips_num):\n # not all people made at least one forward trip\n if any(list(chain(*forward_trips)).count(s) < speed.count(s) for s in set(speed)):\n continue\n sum_forward = sum([max(trip[0], trip[1]) for trip in forward_trips]) # time of all forward trips\n sum_return = 0 # time of all return trips\n # number of return trips for each speed\n # (if there are several people with equal speed, the sum of all their return trips);\n returns = {s: 0 for s in set(speed)}\n for s in set(speed):\n # for every person the number of forward trips is one more than the number of return trips\n returns[s] += sum([trip.count(s) for trip in forward_trips]) - speed.count(s)\n sum_return += returns[s]*s\n\n if best_time > sum_forward+sum_return:\n best_time = sum_forward + sum_return\n# path = list(forward_trips) + list(chain(*[[(s,)]*returns[s] for s in set(speed)]))\n# print(path)\n return best_time", "def shortest_time(speed):\n speed.sort()\n [a,b,c,d]=speed\n return min(a+3*b+d,2*a+b+c+d)", "def shortest_time(speed):\n speed.sort()\n return speed[0]+speed[1]+speed[3] + min(2*speed[1],speed[0]+speed[2])", "def shortest_time(speed):\n speed.sort()\n o = 3*speed[1]+speed[0]+speed[3]\n t = sum(speed[1:])+(len(speed)-2)*speed[0]\n return o if o<=t else t", "def shortest_time(speed):\n \n copy = speed\n copy.sort()\n y = copy[0] + copy[1] * 3 + copy[3]\n minimum = copy.pop(0)\n answers = list()\n x = sum(copy) + minimum * (len(copy)-1)\n answers.append(x)\n answers.append(y)\n \n return min(answers)", "def shortest_time(speed):\n speed = sorted(speed)\n return min(speed[1]*3+speed[0]+speed[3],speed[0]+sum(speed))"]
{"fn_name": "shortest_time", "inputs": [[[3, 4, 5, 6]], [[3, 7, 10, 18]], [[5, 5, 6, 7]], [[5, 6, 30, 40]]], "outputs": [[21], [41], [27], [63]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,068
def shortest_time(speed):
58a9934f072e619853deb9b26567841d
UNKNOWN
In this Kata, you will be given two positive integers `a` and `b` and your task will be to apply the following operations: ``` i) If a = 0 or b = 0, return [a,b]. Otherwise, go to step (ii); ii) If a ≥ 2*b, set a = a - 2*b, and repeat step (i). Otherwise, go to step (iii); iii) If b ≥ 2*a, set b = b - 2*a, and repeat step (i). Otherwise, return [a,b]. ``` `a` and `b` will both be lower than 10E8. More examples in tests cases. Good luck! Please also try [Simple time difference](https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2)
["def solve(a,b):\n if not (a and b): return [a, b]\n if a >= 2*b: return solve(a%(2*b), b)\n if b >= 2*a: return solve(a, b%(2*a))\n return [a, b]", "def solve(a,b):\n '''\n Used the % operator instead of repeated subtraction of a - 2*b or b - 2*a\n Because as long as a > 2*b, the repeated subtraction has to be done and it will \n eventually give a % 2*b. Repeated subtration in recursion has the problem of\n exceeding the recursion depth, so this approach is better\n '''\n if a == 0 or b == 0:\n return [a,b]\n elif a >= 2*b:\n return solve(a % (2*b), b)\n elif b >= 2*a:\n return solve(a, b % (2*a))\n else:\n return [a,b]\n", "def solve(a, b):\n while a and b:\n if a >= b * 2:\n a %= 2 * b\n elif b >= a * 2:\n b %= 2 * a\n else:\n break\n return [a, b]", "def solve(a,b):\n return ([a,b] if not a or not b else\n solve(a%(2*b),b) if a>=2*b else\n solve(a,b%(2*a)) if b>=2*a else\n [a,b])", "def solve(a, b):\n while a and b:\n if a >= b*2 : a = a%(b*2)\n elif b >= a * 2 : b = b%(a*2)\n else : break\n return [a,b]", "def solve(a,b):\n return [a,b] if a*b==0 or .5<a/b<2 else solve(a%(2*b), b%(2*a))", "def solve(a,b):\n for _ in range(0,25):\n if b: a %= 2 * b\n if a: b %= 2 * a\n return [a,b]", "def solve(a,b):\n while a and b and (a >= 2*b or b >= 2*a):\n if b: a %= 2 * b\n if a: b %= 2 * a\n return [a,b]", "def solve(a,b):\n while a and b:\n if a >= 2*b:\n a -= (a//(2*b))*(2*b)\n print(a)\n elif b >= 2*a:\n b -= (b//(2*a))*(2*a)\n else:\n break\n return [a,b] ", "def solve(a,b):\n if not (a and b):\n return [a, b]\n return solve(a % (2 * b), b) if a >= 2 * b else solve(a, b % (2 * a)) if b >= 2 * a else [a, b]\n\n"]
{"fn_name": "solve", "inputs": [[6, 19], [2, 1], [22, 5], [2, 10], [8796203, 7556], [7, 11], [19394, 19394]], "outputs": [[[6, 7]], [[0, 1]], [[0, 1]], [[2, 2]], [[1019, 1442]], [[7, 11]], [[19394, 19394]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,987
def solve(a,b):
94909da5ff62857a6e88dc74b1fcee78
UNKNOWN
Some languages like Chinese, Japanese, and Thai do not have spaces between words. However, most natural languages processing tasks like part-of-speech tagging require texts that have segmented words. A simple and reasonably effective algorithm to segment a sentence into its component words is called "MaxMatch". ## MaxMatch MaxMatch starts at the first character of a sentence and tries to find the longest valid word starting from that character. If no word is found, the first character is deemed the longest "word", regardless of its validity. In order to find the rest of the words, MaxMatch is then recursively invoked on all of the remaining characters until no characters remain. A list of all of the words that were found is returned. So for the string `"happyday"`, `"happy"` is found because `"happyday"` is not a valid word, nor is `"happyda"`, nor `"happyd"`. Then, MaxMatch is called on `"day"`, and `"day"` is found. The output is the list `["happy", "day"]` in that order. ## The Challenge ```if:javascript Write `maxMatch`, which takes an alphanumeric, spaceless, lowercased `String` as input and returns an `Array` of all the words found, in the order they were found. **All valid words are in the** `Set` `VALID_WORDS`, which only contains around 500 English words. ``` ```if:haskell Write `maxMatch`, which takes an alphanumeric, spaceless, lowercased `String` as input and returns a `[String]` of all the words found, in the order they were found. All valid words are in the `[String]` `validWords`, which only contains around 500 English words. ``` ```if:java Write `maxMatch`, which takes an alphanumeric, spaceless, lowercased `String` as input and returns a `List` of `String`s which are all the words found, in the order they were found. All valid words are in the `Set` `Preloaded.VALID_WORDS`, , which only contains around 500 English words. ``` ```if:python Write `max_match`, which takes an alphanumeric, spaceless, lowercased `String` as input and returns a `List` of `String`s of all the words found, in the order they were found. **All valid words are in the** `Set` `VALID_WORDS`, which only contains around 500 English words. ``` ```if:ruby Write `max_match`, which takes an alphanumeric, spaceless, lowercased `String` as input and returns an `Array` of `String`s of all the words found, in the order they were found. All valid words are in the `Array` `VALID_WORDS`, which only contains around 500 English words. ``` ```if:kotlin Write `maxMatch`, which takes an alphanumeric, spaceless, lowercased `String` as input and returns a `List` of `String`s which are all the words found, in the order they were found. All valid words are in the `Set` `VALID_WORDS`, which only contains around 500 English words. ``` **Note:** This algorithm is simple and operates better on Chinese text, so accept the fact that some words will be segmented wrongly. Happy coding :)
["def max_match(s):\n result = []\n \n while s:\n for size in range(len(s), 0, -1):\n word = s[:size]\n if word in VALID_WORDS:\n break\n \n result.append(word)\n s = s[size:]\n \n return result", "# KenKamau's solution\ndef max_match(st):\n for i in range(len(st),0,-1): \n if i == 1 or st[:i] in VALID_WORDS:\n return [st[:i]] + max_match(st[i:])\n return []", "def max_match(sentence):\n found = []\n while sentence:\n for i in range(len(sentence), 0, -1):\n chunk = sentence[:i]\n if chunk in VALID_WORDS:\n break\n found.append(chunk)\n sentence = sentence[i:]\n return found", "def max_match(sentence):\n word = sentence\n if word is \"\":\n return []\n if len(word) > 1:\n while not (word in VALID_WORDS):\n word = word[:-1]\n if len(word) ==1:\n break;\n return [word] + max_match(sentence.replace(word, \"\", 1))\n", "def max_match(sentence: str):\n if not sentence:\n return []\n\n word, i = next(filter(lambda w: w[0] in VALID_WORDS, ((sentence[:i], i) for i in range(len(sentence) + 1, 1, -1))),\n (sentence[0], 1))\n\n return [word] + max_match(sentence[i:])"]
{"fn_name": "max_match", "inputs": [[""]], "outputs": [[[]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,348
def max_match(sentence):
973b08434c6e2ec9ed55eeaa3e2fff36
UNKNOWN
# Task Imagine `n` horizontal lines and `m` vertical lines. Some of these lines intersect, creating rectangles. How many rectangles are there? # Examples For `n=2, m=2,` the result should be `1`. there is only one 1x1 rectangle. For `n=2, m=3`, the result should be `3`. there are two 1x1 rectangles and one 1x2 rectangle. So `2 + 1 = 3`. For n=3, m=3, the result should be `9`. there are four 1x1 rectangles, two 1x2 rectangles, two 2x1 rectangles and one 2x2 rectangle. So `4 + 2 + 2 + 1 = 9`. # Input & Output - `[input]` integer `n` Number of horizontal lines. Constraints: `0 <= n <= 100` - `[input]` integer `m` Number of vertical lines. Constraints: `0 <= m <= 100` - `[output]` an integer Number of rectangles.
["def rectangles(n, m):\n return m * n * (m - 1) * (n - 1) / 4", "def rectangles(n, m):\n return n*m*(n-1)*(m-1)//4", "rectangles=lambda n,m:n*~-n*m*~-m//4", "def rectangles(n, m):\n return ((m-1) * (n-1) * n * m) / 4;", "def rectangles(n, m):\n result = 0\n \n if n < 2 or m < 2:\n return result\n\n for i in range(n):\n for j in range(m):\n result += i*j\n \n return result", "from math import factorial\n\ndef rectangles(n, m):\n return 0 if n <= 1 or m <= 1 else round(factorial(n)/factorial(n-2)/2 * factorial(m)/factorial(m-2)/2)\n", "def rectangles(m, n):\n return (m-1)*(n-1)*m*n/4", "def rectangles(n, m):\n OneOnOneRects = (n-1) * (m-1)\n sumOfM = sum(range(1, m-1))\n sumOfN = sum(range(1, n-1))\n OneAndSome = (n-1) * sumOfM\n SomeAndOne = (m-1) * sumOfN\n\n SomeAndSome = 0\n for i in range(2, n):\n for j in range(2, m):\n SomeAndSome = SomeAndSome + (n-i)*(m-j)\n\n return OneOnOneRects + OneAndSome + SomeAndOne + SomeAndSome", "import scipy.special as math\n\ndef rectangles(n, m):\n return int(math.comb(n,2)*math.comb(m,2))"]
{"fn_name": "rectangles", "inputs": [[2, 3], [2, 2], [1, 1], [0, 1], [3, 3], [100, 100]], "outputs": [[3], [1], [0], [0], [9], [24502500]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,131
def rectangles(n, m):
32b6c8287e1b40ff6d859015667eee0e
UNKNOWN
You will be given a fruit which a farmer has harvested, your job is to see if you should buy or sell. You will be given 3 pairs of fruit. Your task is to trade your harvested fruit back into your harvested fruit via the intermediate pair, you should return a string of 3 actions. if you have harvested apples, you would buy this fruit pair: apple_orange, if you have harvested oranges, you would sell that fruit pair. (In other words, to go from left to right (apples to oranges) you buy, and to go from right to left you sell (oranges to apple)) e.g. apple_orange, orange_pear, apple_pear 1. if you have harvested apples, you would buy this fruit pair: apple_orange 2. Then you have oranges, so again you would buy this fruit pair: orange_pear 3. After you have pear, but now this time you would sell this fruit pair: apple_pear 4. Finally you are back with the apples So your function would return a list: [“buy”,”buy”,”sell”] If any invalid input is given, "ERROR" should be returned
["def buy_or_sell(pairs, harvested_fruit):\n \n currentFruit = harvested_fruit\n actions = list()\n \n for pair in pairs:\n \n if currentFruit not in pair: return 'ERROR'\n \n if currentFruit == pair[0]:\n \n actions.append('buy')\n currentFruit = pair[1]\n \n else:\n \n actions.append('sell')\n currentFruit = pair[0]\n \n return actions", "def buy_or_sell(pairs, fruit):\n result = []\n for pair in pairs:\n if pair[0] == fruit:\n result.append(\"buy\")\n fruit = pair[1]\n elif pair[1] == fruit:\n result.append(\"sell\")\n fruit = pair[0]\n else:\n return 'ERROR'\n return result", "def buy_or_sell(pairs, fruit):\n res = []\n for b, s in pairs:\n if fruit == b:\n fruit = s\n res.append(\"buy\")\n elif fruit == s:\n fruit = b\n res.append(\"sell\")\n else:\n return \"ERROR\"\n return res", "def buy_or_sell(pairs, fruit):\n def trade(pair):\n nonlocal fruit\n ret = ['buy', 'sell'][pair.index(fruit)]\n fruit = (set(pair) - set([fruit])).pop()\n return ret\n try:\n return [trade(pair) for pair in pairs]\n except ValueError:\n return 'ERROR'", "def buy_or_sell(p, hf):\n act=[]\n for f in p:\n if hf not in f:\n return \"ERROR\"\n elif hf==f[0]:\n act.append(\"buy\")\n hf=f[1]\n else:\n act.append(\"sell\")\n hf=f[0]\n return act", "def buy_or_sell(pairs, want):\n r = []\n for buy, sell in pairs:\n if want not in [buy, sell]: return 'ERROR'\n r, want = (r + ['buy'], sell) if buy == want else (r + ['sell'], buy)\n \n return r ", "def buy_or_sell(pairs, harvested_fruit):\n result = []\n fruit = harvested_fruit\n for a, b in pairs:\n if fruit == a:\n result.append('buy')\n fruit = b\n elif fruit == b:\n result.append('sell')\n fruit = a\n else:\n return 'ERROR'\n if fruit != harvested_fruit:\n return 'ERROR'\n return result\n", "def buy_or_sell(pairs,f):\n out=[]\n for pair in pairs:\n if pair[0]==f:\n f=pair[1]\n out.append(\"buy\")\n elif pair[1]==f:\n f=pair[0]\n out.append(\"sell\")\n else:return \"ERROR\"\n return out", "def buy_or_sell(pairs, harvested_fruit):\n fruit = harvested_fruit\n acts = []\n try:\n for pair in pairs:\n act = pair.index(fruit)\n acts.append([\"buy\", \"sell\"][act])\n fruit = pair[1 - act]\n return acts\n except:\n return \"ERROR\"", "def buy_or_sell(pairs, harvested_fruit):\n result= []\n for i in pairs:\n if i[0] == harvested_fruit:\n result.append(\"buy\")\n harvested_fruit = i[1]\n elif i[1] == harvested_fruit:\n result.append(\"sell\")\n harvested_fruit = i[0]\n else:\n return \"ERROR\"\n return result"]
{"fn_name": "buy_or_sell", "inputs": [[[["apple", "orange"], ["orange", "pear"], ["apple", "pear"]], "apple"], [[["orange", "apple"], ["orange", "pear"], ["pear", "apple"]], "apple"], [[["apple", "orange"], ["pear", "orange"], ["apple", "pear"]], "apple"], [[["orange", "apple"], ["pear", "orange"], ["pear", "apple"]], "apple"], [[["orange", "apple"], ["orange", "pear"], ["apple", "pear"]], "apple"], [[["apple", "orange"], ["pear", "orange"], ["pear", "apple"]], "apple"], [[["apple", "orange"], ["orange", "pear"], ["pear", "apple"]], "apple"], [[["orange", "apple"], ["pear", "orange"], ["apple", "pear"]], "apple"], [[["orange", "apple"], ["pear", "orange"], ["apple", "paer"]], "apple"]], "outputs": [[["buy", "buy", "sell"]], [["sell", "buy", "buy"]], [["buy", "sell", "sell"]], [["sell", "sell", "buy"]], [["sell", "buy", "sell"]], [["buy", "sell", "buy"]], [["buy", "buy", "buy"]], [["sell", "sell", "sell"]], ["ERROR"]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,259
def buy_or_sell(pairs, harvested_fruit):
b8adfd4249e66c4590a74709d699d27b
UNKNOWN
Maya writes weekly articles to a well known magazine, but she is missing one word each time she is about to send the article to the editor. The article is not complete without this word. Maya has a friend, Dan, and he is very good with words, but he doesn't like to just give them away. He texts Maya a number and she needs to find out the hidden word. The words can contain only the letter: "a", "b", "d", "e", "i", "l", "m", "n", "o", and "t". Luckily, Maya has the key: "a" - 6 "b" - 1 "d" - 7 "e" - 4 "i" - 3 "l" - 2 "m" - 9 "n" - 8 "o" - 0 "t" - 5 You can help Maya by writing a function that will take a number between 100 and 999999 and return a string with the word. The input is always a number, contains only the numbers in the key. The output should be always a string with one word, all lowercase. Maya won't forget to thank you at the end of her article :)
["hidden=lambda n: \"\".join(\"oblietadnm\"[int(d)] for d in str(n))", "trans = dict(zip('6174329805','abdeilmnot'))\n\ndef hidden(num):\n return ''.join( trans[char] for char in str(num) )", "def hidden(num):\n return str(num).translate(str.maketrans(\"6174329805\", \"abdeilmnot\"))", "def hidden(num):\n d = 'oblietadnm'\n return ''.join([d[int(i)] for i in str(num)])", "def hidden(num):\n num_by_char = {\n '6': \"a\",\n '1': \"b\",\n '7': \"d\",\n '4': \"e\",\n '3': \"i\",\n '2': \"l\",\n '9': \"m\",\n '8': \"n\",\n '0': \"o\",\n '5': \"t\",\n }\n \n return ''.join(num_by_char[n] for n in str(num))\n", "def hidden(num):\n dic = {\"6\": \"a\", \"1\": \"b\", \"7\": \"d\",\n \"4\": \"e\", \"3\": \"i\", \"2\": \"l\",\n \"9\": \"m\", \"8\": \"n\", \"0\": \"o\", \"5\": \"t\"}\n \n return ''.join(dic[i] for i in str(num))", "def hidden(num):\n KEY = { \n 6: \"a\",\n 1: \"b\",\n 7: \"d\",\n 4: \"e\",\n 3: \"i\",\n 2: \"l\",\n 9: \"m\",\n 8: \"n\",\n 0: \"o\",\n 5: \"t\",\n }\n \n return ''.join(KEY.get(int(n)) for n in str(num))", "def hidden(num):\n key = {6:\"a\", 1:\"b\", 7:\"d\", 4:\"e\", 3: \"i\", 2:\"l\", 9:\"m\", 8:\"n\", 0:\"o\", 5:\"t\"}\n out = \"\"\n while num>0:\n out += key[num%10]\n num //= 10\n return out[::-1]\n", "a = \"\"\"\"a\" - 6 \"b\" - 1 \"d\" - 7 \"e\" - 4 \"i\" - 3 \"l\" - 2 \"m\" - 9 \"n\" - 8 \"o\" - 0 \"t\" - 5\"\"\"\nd = {k: v for v, k in __import__(\"re\").findall(r\"\\\"(\\w)\\\"\\s-\\s(\\d)\", a)}\nhidden = lambda n: \"\".join(d.get(x, \"\") for x in str(n))"]
{"fn_name": "hidden", "inputs": [[637], [7468], [49632], [1425], [6250], [12674], [4735], [7345], [3850], [2394], [2068], [137], [1065], [6509], [3549], [5394], [56124], [968], [103247], [67935], [7415], [2687], [261], [8054], [942547]], "outputs": [["aid"], ["dean"], ["email"], ["belt"], ["alto"], ["blade"], ["edit"], ["diet"], ["into"], ["lime"], ["loan"], ["bid"], ["boat"], ["atom"], ["item"], ["time"], ["table"], ["man"], ["boiled"], ["admit"], ["debt"], ["land"], ["lab"], ["note"], ["melted"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,766
def hidden(num):
809e72f70a5088d9015abd0bb7563e82
UNKNOWN
# Task Call two arms equally strong if the heaviest weights they each are able to lift are equal. Call two people equally strong if their strongest arms are equally strong (the strongest arm can be both the right and the left), and so are their weakest arms. Given your and your friend's arms' lifting capabilities find out if you two are equally strong. # Example For `yourLeft = 10, yourRight = 15, friendsLeft = 15 and friendsRight = 10`, the output should be `true`; For `yourLeft = 15, yourRight = 10, friendsLeft = 15 and friendsRight = 10`, the output should be `true`; For `yourLeft = 15, yourRight = 10, friendsLeft = 15 and friendsRight = 9,` the output should be `false`. # Input/Output - `[input]` integer `yourLeft` A non-negative integer representing the heaviest weight you can lift with your left arm. - `[input]` integer `yourRight` A non-negative integer representing the heaviest weight you can lift with your right arm. - `[input]` integer `friendsLeft` A non-negative integer representing the heaviest weight your friend can lift with his or her left arm. - `[input]` integer `friendsRight` A non-negative integer representing the heaviest weight your friend can lift with his or her right arm. - `[output]` a boolean value
["def are_equally_strong(your_left, your_right, friends_left, friends_right):\n return sorted([your_left, your_right]) == sorted([friends_left, friends_right])", "def are_equally_strong(yl,yr,fl,fr):\n return (yl==fl and yr==fr) or (yl==fr and yr==fl)", "def are_equally_strong(yl, yr, fl, fr):\n return {yl, yr} == {fl, fr}", "def are_equally_strong(yl, yr, fl, fr):\n return sorted([yl, yr]) == sorted([fl, fr])", "def are_equally_strong(yl, yr, fl, fr):\n return sorted((yl, yr)) == sorted((fl, fr))", "def are_equally_strong(yL, yR, fL, fR):\n return (yL+yR) == (fL+fR) and yL in (fL,fR)", "def are_equally_strong(your_left, your_right, friends_left, friends_right):\n #coding and coding..\n return {your_left, your_right} == {friends_left, friends_right}", "def are_equally_strong(l1,r1,l2,r2):\n return max(l1,r1)==max(l2,r2) and min(l1,r1)==min(l2,r2)", "def are_equally_strong(l1, r1, l2, r2):\n return sorted([l1, r1]) == sorted([l2, r2])", "def are_equally_strong(your_left, your_right, friends_left, friends_right):\n \n m = (your_left+your_right)\n \n f = (friends_left+friends_right)\n \n \n if your_left==friends_left and your_right==friends_right or your_left==friends_right and your_right==friends_left :\n \n return True\n \n else:\n \n return False\n"]
{"fn_name": "are_equally_strong", "inputs": [[10, 15, 15, 10], [15, 10, 15, 10], [10, 10, 10, 10], [15, 10, 15, 9], [10, 5, 5, 10], [1, 10, 10, 0], [10, 5, 11, 4]], "outputs": [[true], [true], [true], [false], [true], [false], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,321
def are_equally_strong(your_left, your_right, friends_left, friends_right):
f3db9368aca19f978ff7128d419f0197
UNKNOWN
One of the first algorithm used for approximating the integer square root of a positive integer `n` is known as "Hero's method", named after the first-century Greek mathematician Hero of Alexandria who gave the first description of the method. Hero's method can be obtained from Newton's method which came 16 centuries after. We approximate the square root of a number `n` by taking an initial guess `x`, an error `e` and repeatedly calculating a new approximate *integer* value `x` using: `(x + n / x) / 2`; we are finished when the previous `x` and the `new x` have an absolute difference less than `e`. We supply to a function (int_rac) a number `n` (positive integer) and a parameter `guess` (positive integer) which will be our initial `x`. For this kata the parameter 'e' is set to `1`. Hero's algorithm is not always going to come to an exactly correct result! For instance: if n = 25 we get 5 but for n = 26 we also get 5. Nevertheless `5` is the *integer* square root of `26`. The kata is to return the count of the progression of integer approximations that the algorithm makes. Reference: Some examples: ``` int_rac(25,1): follows a progression of [1,13,7,5] so our function should return 4. int_rac(125348,300): has a progression of [300,358,354] so our function should return 3. int_rac(125348981764,356243): has a progression of [356243,354053,354046] so our function should return 3. ``` # You can use Math.floor (or similar) for each integer approximation. # Note for JavaScript, Coffescript, Typescript: Don't use the double bitwise NOT ~~ at each iteration if you want to have the same results as in the tests and the other languages.
["def int_rac(n, guess):\n \"\"\"Integer Square Root of an Integer\"\"\"\n x = guess\n cnt = 1\n while True:\n newx = (x + n // x) // 2 \n if abs(x - newx) < 1:\n return cnt\n x = newx\n cnt += 1", "def int_rac(n, guess):\n cnt = 0\n \n while True:\n cnt += 1\n next_guess = (guess + n // guess) // 2\n \n if next_guess == guess:\n return cnt\n \n guess = next_guess\n", "def int_rac(n, guess):\n count, x = 1, (guess + n / guess) // 2\n while abs(guess - x) >= 1:\n guess, x, count = x, (x + n / x) // 2, count + 1\n return count", "def int_rac(n, guess):\n t = 0\n while True:\n new = (guess + n//guess)//2\n t += 1\n if new == guess:\n break\n guess = new\n return t", "def int_rac(n, guess, e = 1):\n loop = 0\n while True:\n loop += 1\n old = guess\n guess = (guess+n/guess)//2\n if abs(old-guess)<e:\n break\n return loop", "int_rac=lambda n, x, c=1: int_rac(n, (x+n/x)/2 ,c+1) if abs(int(n**0.5)-x)>=1 else c"]
{"fn_name": "int_rac", "inputs": [[25, 1], [125348, 300], [125348981764, 356243], [236, 12], [48981764, 8000], [6999, 700], [16000, 400], [16000, 100], [2500, 60], [250000, 600], [95367431640625, 1], [9094947017729282379150390625, 1], [835871232077058, 1], [246391990316004, 1], [403832254158749, 1], [217414278071071, 1], [639593178334873, 1], [646895994940989, 1], [346147532294375, 1], [871397668454373, 1], [711652869429165, 1], [828061341209011, 1]], "outputs": [[4], [3], [3], [2], [3], [6], [5], [3], [2], [3], [28], [52], [30], [29], [29], [29], [29], [29], [29], [30], [29], [30]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,145
def int_rac(n, guess):
5485f24441a9afbbe90f3da1a989ef48
UNKNOWN
This is the first step to understanding FizzBuzz. Your inputs: a positive integer, n, greater than or equal to one. n is provided, you have NO CONTROL over its value. Your expected output is an array of positive integers from 1 to n (inclusive). Your job is to write an algorithm that gets you from the input to the output.
["def pre_fizz(n):\n #your code here\n return list(range(1, n+1))", "def pre_fizz(n):\n return [i + 1 for i in range(0, n)]", "def pre_fizz(n):\n \"\"\"Make a list from 1 to n\"\"\"\n return list(range(1, n+1))", "def pre_fizz(n):\n return [x for x in range(1, n+1)]", "pre_fizz=lambda n: list(range(1,n+1))", "def pre_fizz(n): return [i+1 for i in range(n)]", "def pre_fizz(n):\n mas = []\n for i in range(1, n + 1):\n mas.append(i)\n return mas", "def pre_fizz(n):\n ar=[]\n for i in range(1,n+1):\n ar.append(i)\n return ar", "def pre_fizz(n):\n return [ i for i in range(1,n+1)]", "def pre_fizz(n):\n return [*range(1, n+1)]", "from itertools import islice, count\npre_fizz = lambda n: list(islice(count(1), n))", "from typing import List\n\ndef pre_fizz(n: int) -> List[int]:\n \"\"\" Get output with the array of positive integers from 1 to n (inclusive). \"\"\"\n return list(range(1, n + 1))", "def pre_fizz(n):\n lst = list(range(n+1))\n return lst[1:]", "pre_fizz = lambda x:[n+1 for n in range(x)]", "def pre_fizz(n):\n count = 1\n nums = []\n while count <= n:\n nums.append(count)\n count += 1\n return nums", "def pre_fizz(n):\n #your code here\n# integers = []\n# for i in range (1,n+1):\n# integers.append(i)\n \n# return integers\n\n return [i for i in range(1, n+1)]", "def pre_fizz(n):\n i = 1\n list_n = []\n while i != n + 1:\n list_n.append(i)\n i += 1\n return list_n\n", "def pre_fizz(n):\n arr = []\n s = 1\n while s <= n:\n arr.append(s)\n s += 1\n return arr", "def pre_fizz(n):\n out = []\n for i in range(n):\n out.append(i+1) \n return out", "def pre_fizz(n):\n new_list = []\n for i in range(n):\n new_list.append(i+1)\n return new_list", "def pre_fizz(n):\n counter = 0\n result = []\n while counter < n:\n counter += 1\n result.append(counter)\n return result", "def pre_fizz(n):\n return [el for el in range(1, n + 1)]", "def pre_fizz(n):\n return list(range(1,n+1)) \n \n\n # x = range(1, n + 1, 1)\n # for n in x:\n # fizzlist.append( n )\n # return fizzlist\n", "def pre_fizz(n):\n pre_fizz = []\n \n while n !=0:\n pre_fizz.append(n)\n n -= 1\n \n pre_fizz.sort()\n \n return pre_fizz", "def pre_fizz(n):\n #your code here\n arr = []\n for i in range(1, n+1):\n if n >= 1:\n arr.append(i)\n \n return arr", "def pre_fizz(n):\n return [y for y in range(1, n+1)]", "def pre_fizz(n):\n outList = []\n for i in range(n):\n outList.append(i+1)\n return outList", "def pre_fizz(n):\n if n >= 1:\n fizzbuzz = []\n for o in range(1, n + 1):\n fizzbuzz.append(o)\n return fizzbuzz", "def pre_fizz(n):\n ar = []\n number = 0\n for x in range(n):\n number += 1\n ar.append(number)\n return ar\n #your code here\n", "def pre_fizz(n):\n return list(set(range(1, n+1)))", "from typing import List\n\ndef pre_fizz(n: int) -> List[int]:\n return [it for it in range(1,n+1)]", "def pre_fizz(n):\n return [n-i for i in range(n)][::-1]", "def pre_fizz(n):\n new_arr = []\n while n > 0:\n new_arr.append(n)\n n -= 1\n new_arr.sort()\n return new_arr", "def pre_fizz(n):\n n = list(range(n))\n x = n[-1] + 1\n n.append(x)\n del n[0]\n return n\n", "def pre_fizz(n):\n nums = []\n for num in range(n+1):\n if num == 0:\n continue\n else:\n nums.append(num)\n return nums\n \n \n #your code here\n", "def pre_fizz(n):\n #your code here\n mylist = []\n for num in range(n):\n num+=1\n mylist.append(num)\n \n return mylist", "def pre_fizz(n):\n new_arr = list()\n for i in range(1,n + 1):\n new_arr.append(i)\n return new_arr", "def pre_fizz(n):\n x = []\n for i in range(n):\n x.append(i+1)\n return x", "def pre_fizz(n):\n k = [i for i in range(n+1)]\n k.pop(0)\n return k\n", "def pre_fizz(n):\n num = []\n i = 1\n while i <= n:\n #num = num[i]\n num.append(i)\n i +=1\n return num", "def pre_fizz(n):\n resultlist = []\n for i in range(n):\n resultlist.append(i+1)\n return resultlist\n\n", "def pre_fizz(n):\n #your code here\n array = []\n x = 1\n while x <= n:\n array.append(x)\n x += 1\n return array\n", "def pre_fizz(n):\n return [x for x in range(1, n+1)] # returns an array wherein the elements are combined from 1 to n", "def pre_fizz(n):\n z = []\n for x in range(n):\n x += n-n+1\n z.append(x)\n return z", "def pre_fizz(n):\n x = []\n number: int\n for number in range(1, n+1):\n x.append(number)\n return x", "def pre_fizz(n):\n a=[]\n i=1\n for i in range(1,n+1):\n a.append(i)\n i=i+1\n\n return a\n\n #your code here\n", "def pre_fizz(n):\n #your code here\n numbers = []\n for i in range(1,n+1):\n numbers.append(i)\n return numbers\n", "def pre_fizz(n):\n array = [1]\n for i in range(2,n+1):\n array.append(i)\n return array\n #your code here\n", "def pre_fizz(n):\n l_1 = list(range(1,n+1))\n return l_1", "def pre_fizz(n):\n result = []\n i = 1\n while i<= n:\n result.append(i)\n i = i + 1\n return result", "def pre_fizz(n):\n list = []\n i=1\n while i<=n:\n list.append(i)\n i=i+1\n return list", "def pre_fizz(n):\n z = range(1,n+1)\n y = []\n for i in z:\n y.append(i)\n return y", "def pre_fizz(n):\n arr = []\n counter = 1\n for i in range(n):\n arr.append(counter)\n counter += 1\n return arr", "def pre_fizz(n):\n x = 0\n return_list = []\n while x < n:\n x += 1\n return_list.append(x)\n return return_list", "def pre_fizz(n):\n l = [i for i in range(1, n + 1)]\n return l\n\n", "def pre_fizz(n):\n return [1] if n == 1 else list(range(1, (n+1)))", "def pre_fizz(n):\n count = 0\n x = []\n while n > count:\n count +=1\n x.append(count)\n\n\n return x", "def pre_fizz(n):\n i = 1\n a=[]\n while i < n+1:\n a.append(i)\n i += 1\n return a", "def pre_fizz(n):\n \"\"\"\n return list of ints from 1 to n\n \"\"\"\n return [i+1 for i in range(n)]", "def pre_fizz(n):\n #your code here\n res = []\n for number in range (1, n+1):\n res.append (number)\n \n return res", "def pre_fizz(n):\n emptylist = []\n if n >= 1:\n for eachnumber in range(1,n+1):\n emptylist.append(eachnumber)\n return emptylist", "def pre_fizz(n):\n ls=list()\n i=1\n while i<=n:\n ls.append(i)\n i=i+1\n return ls", "def pre_fizz(n):\n i=1\n output=[]\n while i <= n :\n output.append(i)\n i=i+1\n return output ", "def pre_fizz(n):\n li = []\n for k in range(1,n+1):\n li.append(k)\n return li", "def pre_fizz(n):\n return list(map(lambda x: x, list(range(1, n+1))))", "def pre_fizz(n):\n new_list = list()\n if n == 1:\n new_list1 = [n]\n return new_list1\n for numbers in range(1,n+ 1):\n new_list.append(numbers)\n return new_list", "def pre_fizz(n):\n tab = []\n if n == 1:\n tab.append(1)\n return tab\n else:\n for i in range(1, n+1):\n tab.append(i)\n return tab", "def pre_fizz(n):\n a = []\n for i in range(n):\n i += 1\n a.append(i)\n return a", "def pre_fizz(n):\n myList = []\n num = 1\n while len(myList) < n:\n myList.append(num)\n num += 1\n return myList", "def pre_fizz(n):\n lst = range(1, n + 1)\n return list(lst)", "def pre_fizz(n):\n arr = [i for i in range(1, n+1)]\n return(arr)", "def pre_fizz(n):\n new = []\n for num in range(1,n+1):\n new.append(num)\n return new", "def pre_fizz(n):\n \n res = list()\n for i in range(1,n+1):\n res.append(i)\n return res ", "def pre_fizz(n):\n list = []\n for i in range(n+1):\n list.append(i)\n list.pop(0)\n return list", "def pre_fizz(n):\n list = []\n while True:\n if n!= 0:\n list.insert(0, n)\n n-= 1\n elif n == 0:\n break\n return list\n", "def pre_fizz(n):\n a=[]\n for i in range(n):\n a+=[i+1]\n return a", "def pre_fizz(n):\n \n matriz = []\n \n for x in range(1, n + 1):\n matriz.append(x)\n \n return matriz", "def pre_fizz(n):\n list = []\n for i in range(0,n):\n list.append(i + 1)\n \n return list", "def pre_fizz(n:int) -> list:\n answer:list = []\n for i in range(1, n + 1):\n answer.append(i)\n \n return answer\n", "def pre_fizz(n):\n list = []\n account = 1\n \n while account <= n:\n list += [account]\n account += 1\n return list", "def pre_fizz(n):\n return [i for i in range(n+1) if i!= 0]", "def pre_fizz(n):\n list = []\n num = 0\n while num < n:\n num += 1\n list.append(num)\n return list", "def pre_fizz(n):\n numlist = [] \n for shit in range(0, n):\n numlist.append(shit + 1)\n return numlist", "def pre_fizz(n):\n # checking if (n) is an integer\n if type(n) == int:\n # arranging list and finding range of (n)\n a = list(range(1, n + 1))\n #returning list (a)\n return a\n\n\n", "def pre_fizz(n):\n fiz = []\n for i in range(1,n+1):\n fiz.append(i)\n return fiz\n #your code here\n", "def pre_fizz(n):\n vso = []\n for i in range(1,n+1):\n vso.append(i)\n return(vso)", "def pre_fizz(length):\n return [n for n in range(1, length + 1)]", "'''def pre_fizz(n):\n return [i for i in range(1, n + 1)]'''\n \npre_fizz = lambda n: [i for i in range(1, n + 1)] ", "def pre_fizz(n):\n n = n + 1\n n = list(range(1,n))\n return n", "def pre_fizz(n):\n a=[]\n i=1\n while i<n+1:\n a.append(i)\n i=i+1\n return a\n #your code here\n", "def pre_fizz(n):\n output = []\n for i in range(0,n):\n output.append(i+1)\n return output", "def pre_fizz(n):\n fizzbuzz = []\n for i in range(1, n+1):\n fizzbuzz.append(i)\n return(fizzbuzz)\n", "def pre_fizz(n):\n i = n\n x = 1\n list = []\n while x <= i:\n list.append(x)\n x = x+1\n return list\n", "def pre_fizz(n):\n cunt = range(1, n + 1)\n return list(cunt)", "def pre_fizz(n):\n rez = list()\n for it in range(1,n+1):\n rez.append(it)\n return rez", "def pre_fizz(n):\n #your code here\n a = []\n if n == 1:\n return [1]\n for i in range(1,n+1):\n a.append(i)\n \n return a", "from typing import List\n\n\ndef pre_fizz(n: int) -> List[int]:\n return list(range(1, n + 1))\n", "def pre_fizz(n):\n fizz = []\n while n >= 1:\n if n != 0:\n fizz.append(n)\n n = n - 1\n sort_fizz = sorted(fizz)\n return sort_fizz"]
{"fn_name": "pre_fizz", "inputs": [[1], [2], [3], [4], [5]], "outputs": [[[1]], [[1, 2]], [[1, 2, 3]], [[1, 2, 3, 4]], [[1, 2, 3, 4, 5]]]}
INTRODUCTORY
PYTHON3
CODEWARS
11,390
def pre_fizz(n):
924546685fe55209ee4b54b27ec5028e
UNKNOWN
Given a string of characters, I want the function `findMiddle()`/`find_middle()` to return the middle number in the product of each digit in the string. Example: 's7d8jd9' -> 7, 8, 9 -> 7\*8\*9=504, thus 0 should be returned as an integer. Not all strings will contain digits. In this case and the case for any non-strings, return -1. If the product has an even number of digits, return the middle two digits Example: 1563 -> 56 NOTE: Remove leading zeros if product is even and the first digit of the two is a zero. Example 2016 -> 1
["from operator import mul\nfrom functools import reduce\n\ndef find_middle(s):\n if not s or not isinstance(s,str): return -1\n \n lstDig = [int(c) for c in s if c.isnumeric()]\n if not lstDig: return -1\n \n prod = str( reduce(mul,lstDig) )\n i = (len(prod) - 1) // 2\n return int(prod[i:-i or len(prod)])", "def find_middle(string):\n # \u0415\u0441\u043b\u0438 \u0432 String \u043f\u043e\u0434\u0430\u0451\u0442\u0441\u044f None, \u0432\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u043c -1\n if string is None:\n return -1\n # \u0415\u0441\u043b\u0438 \u0432 String \u043f\u043e\u0434\u0430\u0451\u0442\u0441\u044f \u0447\u0438\u0441\u043b\u043e, \u0432\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u043c -1 \n if type(string) is int:\n return -1\n\n # \u0415\u0441\u043b\u0438 \u0432 String \u043f\u0435\u0440\u0435\u0434\u0430\u0451\u0442\u0441\u044f \u043c\u0430\u0441\u0441\u0438\u0432, \u0432\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u043c -1\n if type(string) is list:\n return -1\n\n # \u0421\u043e\u0437\u0434\u0430\u0451\u043c \u043c\u0430\u0441\u0441\u0438\u0432 \u0438 \u0432\u043d\u043e\u0441\u0438\u043c \u0442\u0443\u0434\u0430 \u0442\u043e\u043b\u044c\u043a\u043e \u0447\u0438\u0441\u043b\u0430 \u0438\u0437 String\n spisok = []\n for i in string:\n if i.isdigit():\n spisok.append(i)\n\n # \u0415\u0441\u043b\u0438 \u0432 String \u043d\u0435 \u0431\u044b\u043b\u043e \u0447\u0438\u0441\u0435\u043b, \u0437\u043d\u0430\u0447\u0438\u0442 \u0432\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u043c -1\n if len(spisok) == 0:\n return -1\n\n # \u0421\u043e\u0437\u0434\u0430\u0451\u043c \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u0443\u044e, \u0432 \u043a\u043e\u0442\u043e\u0440\u043e\u0439 \u0431\u0443\u0434\u0435\u0442 \u0445\u0440\u0430\u043d\u0438\u0442\u0441\u044f \u0447\u0438\u0441\u043b\u043e \u043f\u043e\u0441\u043b\u0435 \u043f\u0435\u0440\u0435\u043c\u043d\u043e\u0436\u0435\u043d\u0438\u044f \u0432\u0441\u0435\u0445 \u0447\u0438\u0441\u0435\u043b\n spisok_ans = 1\n\n # \u041f\u0435\u0440\u0435\u043c\u043d\u043e\u0436\u0430\u0435\u043c \u0432\u0441\u0435 \u0447\u0438\u0441\u043b\u0430\n for i in spisok:\n spisok_ans *= int(i)\n\n # \u041f\u0435\u0440\u0435\u0432\u043e\u0434\u0438\u043c \u0438\u0442\u043e\u0433\u043e\u0432\u043e\u0435 \u0447\u0438\u0441\u043b\u043e \u0432 \u0442\u0435\u043a\u0441\u0442, \u0434\u043b\u044f \u0441\u043e\u0431\u043b\u044e\u0434\u0435\u043d\u0438\u044f \u0443\u0441\u043b\u043e\u0432\u0438\u044f \u0437\u0430\u0434\u0430\u0447\u0438\n spisok = str(spisok_ans)\n\n # \u0415\u0441\u043b\u0438 \u0441\u043f\u0438\n if len(spisok) % 2 == 0:\n if len(spisok) >= 2:\n spisok[:1].replace(\"0\", \"\")\n test = int(len(spisok) / 2)\n answer = spisok[test-1:test+1]\n else:\n test = int(len(spisok) / 2)\n answer = spisok[test:test+1]\n\n answer = \"\".join(answer)\n return int(answer)", "from functools import reduce\nfrom operator import mul\n\ndef find_middle(string):\n try:\n s = str(reduce(mul, map(int, filter(str.isdigit, string))))\n q, r = divmod(len(s), 2)\n return int(s[q+r-1:q+1])\n except TypeError:\n return -1", "from functools import reduce\nimport re\n\ndef find_middle(string):\n try:\n nums = re.findall(r'\\d', string)\n result = str(reduce(lambda x, y: x*y, (int(x) for x in nums)))\n return int(result[(len(result)-1)//2:len(result)//2+1])\n except:\n return -1", "from functools import reduce\n\n\ndef find_middle(stg):\n if not isinstance(stg, str):\n return -1\n dig = [int(c) for c in stg if c.isdecimal()]\n if not dig:\n return -1\n prod = str(reduce(int.__mul__, dig))\n l = len(prod)\n i, j = (l - 1) // 2, l // 2 + 1\n return int(prod[i:j])", "def find_middle(string):\n try:\n lst = []\n for i in string:\n if i.isdigit():\n lst.append(i)\n x = str(eval('*'.join(lst)))\n return int(str(x)[len(x)//2]) if len(x) % 2 == 1 else int(str(x)[len(x)//2-1]+str(x)[len(x)//2])\n except:\n return -1\n", "from functools import reduce\nfrom math import ceil\nfrom operator import mul\n\n\ndef find_middle(string):\n try:\n n = str(reduce(mul, list(map(int, list(filter(str.isdigit, string))))))\n size = len(n)\n return int(n[ceil(size / 2 - 1):size // 2 + 1])\n except TypeError:\n return -1\n", "def find_middle(string):\n if not type(string) == str:\n return -1\n numbers = [int(i) for i in string if i.isdigit()]\n if not numbers:\n return -1\n prod = 1\n for i in numbers:\n prod *= i\n prod_str = str(prod)\n return int(prod_str[(len(prod_str) // 2) - 1:(len(prod_str) // 2) + 1]) if len(prod_str) % 2 == 0 else int(prod_str[len(prod_str)//2])", "def find_middle(string):\n if type(string) != str:\n return -1\n result = 1\n count = 0\n for c in string:\n if c.isdigit():\n count += 1\n result *= int(c)\n if count:\n if len(str(result)) % 2 == 0:\n final = str(result)[(len(str(result)) // 2) - 1: (len(str(result)) // 2) + 1]\n if final[0] == '0':\n return int(final[1])\n else:\n return int(final)\n else:\n return int(str(result)[len(str(result)) // 2])\n else:\n return -1", "from numpy import prod \ndef find_middle(string):\n return int(findMiddle(str(prod(list(map(int, filter(type(string).isdigit, string))))))) if type(string) is str and any(char.isdigit() for char in string) else -1\ndef findMiddle(s):\n return s[int(len(s)/2)-1:int(len(s)/2)+1] if not len(s) % 2 else s[int(len(s)/2):int(len(s)/2)+1]"]
{"fn_name": "find_middle", "inputs": [["s7d8jd9"], ["58jd9fgh/fgh6s.,sdf"], ["s7d8jd9dfg4d"], ["s7d8j"], ["asd.fasd.gasdfgsdfgh-sdfghsdfg/asdfga=sdfg"], ["44555"], [null], [[1, 2, 3, 4, 5, 6]], [["a", "b", "c"]], ["5d8jd9fgh/fgh6s.,sdf8sdf9sdf98 3 0"], [" "], ["e^6*9=#asdfd7-4"], ["s7d8jd9qwertqwrt v654ed1frg651"], ["58"], ["s7d1548jd9dfg4d"], ["s7d54sd6f48j"], ["asd.fasd.gasdfgsdf1gh-sdfghsdfg/asdfga=sdfg"], ["44145s555"], ["sdf496as4df6"], [4554], ["asdf544684868"], ["5d8jd9fgh/fgh64f4f4f00s.,sdf8sdf9sdf98"], [" s2 "], ["e^6*9=#as5ddfd7-4"], ["s7d8j987d9"], ["58jd9636fgh/fgh6s.,sdf"], ["s7d8j546sdfd9dfg4d"], ["s7d8sdfs165d41fj"], ["asd.fasd.ga654sdfgsdfgh-sdfghsdfg/asdfga=sdfg"], ["4456846955"], [56465462165484], [["a", 1, 2, 3, 4, 5, 6]], [["a", "b", "c", "sfd"]], ["5d8jd9fgh/fgh6s.,6574ssdf8sdf9sdf98 3"], [" 99 "], ["e^6*9984=#asdfd7-4"], ["s7d8js599d9"], ["58jd9fgh654d/fgh6s.,sdf"], ["s7d8jd654sdf9dfg4d"], ["s7asdf68545fd8j"], ["asd.f855dasd.gasdfgsdfgh-sdfghsdfg/asdfga=sdfg"], ["445 2 2 55"], ["nu11"], ["[1,2,3,4,5,6]"], ["[a, b, c, 4, 3]"], ["5d8jd9fgh/fgh6s.,sdf8s5sdf9sdf98 3 "], [" /./\\ "], ["e^6*9=52d#asdfd7-4"], ["s7564d56d56d8jd9"], ["58jd9fgh/fg97987d9fgh6s.,sdf"]], "outputs": [[0], [16], [1], [56], [-1], [0], [-1], [-1], [-1], [0], [-1], [51], [4], [40], [3], [8], [1], [0], [18], [-1], [8], [0], [2], [56], [40], [32], [19], [72], [2], [36], [-1], [-1], [-1], [5], [81], [54], [41], [92], [19], [88], [0], [0], [1], [2], [12], [6], [-1], [1], [32], [5]]}
INTRODUCTORY
PYTHON3
CODEWARS
5,920
def find_middle(string):
06104ec8efb6dac06f89b416f1bb8d79
UNKNOWN
The most basic encryption method is to map a char to another char by a certain math rule. Because every char has an ASCII value, we can manipulate this value with a simple math expression. For example 'a' + 1 would give us 'b', because 'a' value is 97 and 'b' value is 98. You will need to write a method which does exactly that - get a string as text and an int as the rule of manipulation, and should return encrypted text. for example: encrypt("a",1) = "b" *Full ascii table is used on our question (256 chars) - so 0-255 are the valid values.* Good luck.
["def encrypt(text, rule):\n return \"\".join(chr((ord(i)+rule)%256) for i in text)", "def encrypt(text, rule):\n return \"\".join(chr((ord(c) + rule) % 256) for c in text)", "def encrypt(text, key):\n return \"\".join(chr((ord(ch) + key) & 255) for ch in text)", "def encrypt(text, rule):\n return ''.join(chr((ord(c) + rule) & 255) for c in text)", "def encrypt(text, rule):\n return ''.join([chr((ord(a) + rule) % 256) for a in text])", "def encrypt(text, rule):\n return \"\".join(chr((ord(x) + rule)%256) for x in text)\n", "def encrypt(text, rule):\n return ''.join([chr((ord(s) + rule) % 256) for s in text])", "def encrypt(text, rule):\n return ''.join(map(lambda x: chr((ord(x)+rule)%256), text))", "def encrypt(text, rule):\n encrypted_text = list(text)\n for i in range(len(encrypted_text)):\n encrypted_text[i] = chr((ord(encrypted_text[i]) + rule) % 256 )\n return \"\".join(encrypted_text)", "def encrypt(text, rule):\n retval = ''\n for sss in text:\n retval += chr((ord(sss) + rule) % 256)\n return retval"]
{"fn_name": "encrypt", "inputs": [["", 1], ["a", 1], ["please encrypt me", 2]], "outputs": [[""], ["b"], ["rngcug\"gpet{rv\"og"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,079
def encrypt(text, rule):
ecffe57a6bfaa93863167f1929f14b3a
UNKNOWN
The objective is to disambiguate two given names: the original with another Let's start simple, and just work with plain ascii strings. The function ```could_be``` is given the original name and another one to test against. ```python # should return True if the other name could be the same person > could_be("Chuck Norris", "Chuck") True # should False otherwise (whatever you may personnaly think) > could_be("Chuck Norris", "superman") False ``` Let's say your name is *Carlos Ray Norris*, your objective is to return True if the other given name matches any combinaison of the original fullname: ```python could_be("Carlos Ray Norris", "Carlos Ray Norris") : True could_be("Carlos Ray Norris", "Carlos Ray") : True could_be("Carlos Ray Norris", "Norris") : True could_be("Carlos Ray Norris", "Norris Carlos") : True ``` For the sake of simplicity: * the function is case sensitive and accent sensitive for now * it is also punctuation sensitive * an empty other name should not match any original * an empty orginal name should not be matchable * the function is not symmetrical The following matches should therefore fail: ```python could_be("Carlos Ray Norris", " ") : False could_be("Carlos Ray Norris", "carlos") : False could_be("Carlos Ray Norris", "Norris!") : False could_be("Carlos Ray Norris", "Carlos-Ray Norris") : False could_be("Ray Norris", "Carlos Ray Norris") : False could_be("Carlos", "Carlos Ray Norris") : False ``` Too easy ? Try the next steps: * [Author Disambiguation: a name is a Name!](https://www.codewars.com/kata/author-disambiguation-a-name-is-a-name) * or even harder: [Author Disambiguation: Signatures worth it](https://www.codewars.com/kata/author-disambiguation-signatures-worth-it)
["def could_be(original, another):\n if not another.strip(): return False\n return all(name in original.split() for name in another.split())", "def could_be(original, another):\n original, another = (set(s.split()) for s in (original, another))\n return bool(another) and another <= original", "def could_be(original, another):\n\n s1, s2 = set(another.split()), set(original.split())\n \n return len(s1) > 0 and len(s2) > 0 and s1 <= s2", "def could_be(original, another):\n o, a = set(original.split()), set(another.split())\n return a.issubset(o) if a and o else False", "def could_be(original, another):\n original_words = original.split()\n another_words = another.split()\n if not original_words or not another_words:\n return False\n return all(w in original_words for w in another_words) ", "def could_be(original, another):\n a, b = original.split(), another.split()\n return bool(a and b and set(a) >= set(b))", "def could_be(original, another): \n if not original.strip() or not another.strip():\n return False\n return set(another.split()).issubset(original.split())", "could_be=lambda a,b,s=set:s()<s(b.split())<=s(a.split())>s()", "def could_be(original, another):\n return bool(original and another and (set(original.split(' ')) >= set(another.split(' '))))\n", "def could_be(o, a):\n return all([x in o.split() for x in a.split()]) if a.strip() and o.strip() else False"]
{"fn_name": "could_be", "inputs": [["Carlos Ray Norris", "Carlos Ray Norris"], ["Carlos Ray Norris", "Carlos Ray"], ["Carlos Ray Norris", "Ray Norris"], ["Carlos Ray Norris", "Carlos Norris"], ["Carlos Ray Norris", "Norris"], ["Carlos Ray Norris", "Carlos"], ["Carlos Ray Norris", "Norris Carlos"], ["Carlos Ray Norris", "Carlos Ray Norr"], ["Carlos Ray Norris", "Ra Norris"], ["", "C"], ["", ""], ["Carlos Ray Norris", " "], ["Carlos Ray Norris", "carlos Ray Norris"], ["Carlos", "carlos"], ["Carlos Ray Norris", "Norris!"], ["Carlos Ray Norris", "Carlos-Ray Norris"], ["Carlos Ray", "Carlos Ray Norris"], ["Carlos", "Carlos Ray Norris"]], "outputs": [[true], [true], [true], [true], [true], [true], [true], [false], [false], [false], [false], [false], [false], [false], [false], [false], [false], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,452
def could_be(original, another):
f132372fe3d54ec7c34baa68ab260cb6
UNKNOWN
The Padovan sequence is the sequence of integers `P(n)` defined by the initial values `P(0)=P(1)=P(2)=1` and the recurrence relation `P(n)=P(n-2)+P(n-3)` The first few values of `P(n)` are `1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12, 16, 21, 28, 37, 49, 65, 86, 114, 151, 200, 265, ...` ### Task The task is to write a method that returns i-th Padovan number ```python > padovan(0) == 1 > padovan(1) == 1 > padovan(2) == 1 > padovan(n) = padovan(n-2) + padovan(n-3) ```
["def padovan(n):\n p0 = p1 = p2 = 1\n for i in range(n):\n p0, p1, p2 = p1, p2, p0 + p1\n return p0", "from functools import lru_cache\n\n@lru_cache(maxsize=None)\ndef padovan(n):\n return n<3 or padovan(n-2) + padovan(n-3)", "from functools import lru_cache\n\n@lru_cache()\ndef padovan(n):\n return 1 if n < 3 else padovan(n-2) + padovan(n-3)", "def padovan(n):\n p0 = p1 = p2 = 1\n for i in range(3, n+1):\n p0, p1, p2 = p1, p2, p0+p1\n return p2", "from collections import deque\n\ndef padovan(n):\n q = deque([1,1,1], maxlen=3)\n for i in range(n-2):\n q.append(q[0] + q[1])\n return q[-1]", "def padovan(n):\n a = b = c = 1\n while n:\n a, b, c = b, c, a + b\n n -= 1\n return a", "def padovan(n, a=1, b=1, c=1):\n return a if n==0 else padovan(n-1, b, c, a+b)", "def padovan(n):\n a = b = c = 1\n for i in range(n // 3):\n a += b\n b += c\n c += a\n return (a, b, c)[n % 3]", "import sys\nsys.setrecursionlimit(1500) \n\ndef padovan(n, memo = {0:1, 1:1, 2:1}):\n if n in memo: return memo[n]\n else:\n result = padovan(n-2,memo) + padovan(n-3, memo)\n memo[n] = result\n return result", "def memoize(f):\n memo = {}\n def helper(x):\n if x not in memo: \n memo[x] = f(x)\n return memo[x]\n return helper\n\ndef padovan(n):\n if n==0 or n==1 or n==2:\n return 1\n else:\n return padovan(n-2)+padovan(n-3)\n \npadovan=memoize(padovan)"]
{"fn_name": "padovan", "inputs": [[100]], "outputs": [[1177482265857]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,541
def padovan(n):
265f88a102e99104546c4ee982ec9589
UNKNOWN
## Problem Determine whether a positive integer number is **colorful** or not. `263` is a colorful number because `[2, 6, 3, 2*6, 6*3, 2*6*3]` are all different; whereas `236` is not colorful, because `[2, 3, 6, 2*3, 3*6, 2*3*6]` have `6` twice. So take all consecutive subsets of digits, take their product and ensure all the products are different. ## Examples ```pyhton 263 --> true 236 --> false ```
["def colorful(number):\n base_result = []\n for x in str(number):\n base_result.append(int(x))\n for y in range(len(base_result) - 1):\n temp = base_result[y] * base_result[y + 1]\n base_result.append(temp)\n # Should you really eval the last value ? :shrug: If so, would use eval\n return len(set(base_result)) == len(base_result)", "from functools import reduce\nfrom collections import Counter\n\ndef colorful(n):\n s = list(map(int,str(n)))\n cnt = Counter( reduce(int.__mul__, s[i:i+x]) for x in range(1,len(s)+1) for i in range(len(s)-x+1))\n return cnt.most_common(1)[0][1] == 1", "from functools import reduce\n\n\ndef colorful(n):\n ld = [int(d) for d in str(n)]\n l = len(ld)\n p = [reduce(int.__mul__, ld[i:i+k]) for k in range(1, l+1) for i in range(l-k+1)]\n return len(p) == len(set(p))\n", "REGEX = __import__(\"re\").compile(\n r\"(.).*\\1\" # Duplicate digit\n r\"|[01].+|.+[01]\" # 0 or 1 and another digit\n r\"|(23|32).*6|6.*(23|32)\" # 2*3 and a 6 before or after\n r\"|(24|42).*8|8.*(24|42)\" # 2*4 and a 8 before or after\n r\"|(26|62).*(34|43)|(34|43).*(26|62)\" # 2*6 and 3*4 before or after\n r\"|(29|92).*(36|63)|(36|63).*(29|92)\" # 2*9 and 3*6 before or after\n r\"|(38|83).*(46|64)|(46|64).*(38|83)\" # 3*8 and 4*6 before or after\n r\"|(49|94).*(236|263|326|362|623|632)|(236|263|326|362|623|632).*(49|94)\" # 4*9 and 2*3*6 before or after\n r\"|(89|98).*(346|364|436|463|634|643)|(346|364|436|463|634|643).*(89|98)\" # 8*9 and 3*4*6 before or after\n).search\n\ndef colorful(number):\n return not REGEX(str(number))", "def colorful(number):\n lst = [int(d) for d in str(number)]\n \n if number > 9:\n # no need to compute : if 1 ==> previous * 1 == previous, if 0 ==> previous * 0 == 0\n if 0 in lst or 1 in lst:\n return False\n \n all, previous = lst, -1\n for digit in str(number):\n # not the first time\n if previous != -1:\n lst.append(int(digit) * previous)\n previous = int(digit)\n \n # if 1 or 2 digits : multiplication of all numbers is already added to the list\n if number > 99:\n total = 1\n for d in all:\n total *= d\n lst.append(total)\n \n return len(lst) == len(set(lst))", "def colorful(number):\n if len(str(number)) == 1: \n return True\n else:\n output = list(str(number))\n for n,x in enumerate(list(str(number))):\n if n + 1 < len(str(number)):\n tmp = list(str(number))[n+1]\n \n #tmp = int()\n output.append(str(int(x) * int(tmp)))\n \n if len(output) == len(set(output)):\n return True\n else:\n return False \n \n \n", "from functools import reduce\nfrom operator import mul\n\ndef colorful(number):\n digits = [int(d) for d in str(number)]\n prods = []\n \n for size in range(1, len(digits) +1):\n for start in range(len(digits)-size +1):\n prods.append(reduce(mul, digits[start : start+size]))\n \n return len(prods) == len(set(prods))", "from functools import reduce\n\ndef colorful(n):\n s = list(map(int,str(n)))\n return len(s)*(len(s)+1)//2 == len({ reduce(int.__mul__, s[i:i+x]) for x in range(1,len(s)+1) for i in range(len(s)-x+1)})", "from functools import reduce\n\n\ndef colorful(n):\n p = list(get_sub_mul(n))\n return len(p) == len(set(p))\n\n\ndef get_sub_mul(n):\n s = [int(d) for d in str(n)]\n l = len(s)\n for k in range(1, l+1):\n for i in range(l-k+1):\n yield reduce(int.__mul__, s[i:i+k])\n", "from functools import reduce\nfrom math import ceil\ndef colorful(n): \n li=[reduce(lambda x,y: x*y, map(int, str(n)[i:i+j]))for j in range(1,ceil(len(str(n)) / 2)+2)for i in range(0,len(str(n))-j+1)]\n return all(li.count(i)==1 for i in li)"]
{"fn_name": "colorful", "inputs": [[5], [23], [263], [235789], [50], [13], [236], [2357893]], "outputs": [[true], [true], [true], [true], [false], [false], [false], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,036
def colorful(number):
ec6fce2e85ab454da835d33983b47d6a
UNKNOWN
You are given a length of string and two thumbtacks. On thumbtack goes into the focus point *F₀* with coordinates *x₀* and *y₀*, and the other does into point *F₁* with points *x₁* and *y₁*. The string is then tied at the ends to the thumbtacks and has length *l* excluding the knots at the ends. If you pull the string taught with a pencil and draw around the plane you'll have an ellipse with focuses at *F₀* and *F₁*. Given a new point *P*, determine if it falls inside of the ellipse. You must write a function that takes arguments `f0`, `f1`, `l`, and `p` and returns `true` or `false` depending on whether or not `p` falls inside the ellipse. Each of `f0`, `f1`, and `p` has has properties `x` and `y` for its coordinates. You will never be given the case where the string is too short to reach between the points.
["dist = lambda p1, p2: ((p1['x']-p2['x'])**2+(p1['y']-p2['y'])**2)**0.5\nellipse_contains_point = lambda f0, f1, l, p : dist(p, f0)+dist(p, f1)<=l", "from math import hypot\n\ndef ellipse_contains_point(f0, f1, l, p): \n d0 = hypot(f0[\"x\"] - p[\"x\"], f0[\"y\"] - p[\"y\"])\n d1 = hypot(f1[\"x\"] - p[\"x\"], f1[\"y\"] - p[\"y\"])\n return d0 + d1 <= l", "import math\n\ndef ellipse_contains_point(f0, f1, l, p): \n calc_len = lambda f: math.hypot(*(f[a] - p[a] for a in 'xy'))\n return calc_len(f0) + calc_len(f1) <= l", "from math import sqrt\n\n\ndef ellipse_contains_point(f0, f1, l, p):\n return distance(f0, p) + distance(f1, p) <= l\n\n\ndef distance(p0, p1):\n return sqrt(pow(p0['x'] - p1['x'], 2) + pow(p0['y'] - p1['y'], 2))", "from math import sqrt\n\ndef ellipse_contains_point(f0, f1, l, p): \n # S = {'x' : (f0['x'] + f1['x']) / 2, 'y' : (f0['y'] + f1['y']) / 2}\n d1 = sqrt((f0['x'] - p['x'])**2 + (f0['y'] - p['y'])**2)\n d2 = sqrt((f1['x'] - p['x'])**2 + (f1['y'] - p['y'])**2)\n\n #dy = sqrt(f1['x']**2 + p['x']**2) + sqrt(f1['y']**2 + p['y']**2)\n return d1 + d2 <= l", "import math\ndef ellipse_contains_point(f0, f1, l, p): \n return (math.hypot(p['x'] - f0['x'],p['y'] - f0['y']) + math.hypot(p['x'] - f1['x'],p['y'] - f1['y'])) <= l", "import math\ndef ellipse_contains_point(f0, f1, l, p): \n def dist2d(p1, p2):\n return math.sqrt((p2['x'] - p1['x']) ** 2 + (p2['y'] - p1['y']) ** 2)\n return dist2d(p,f0) + dist2d(p,f1) <= l", "def ellipse_contains_point(f0, f1, l, p): \n return ((p['x']-f0['x'])**2+(p['y']-f0['y'])**2)**.5 + ((p['x']-f1['x'])**2+(p['y']-f1['y'])**2)**.5 <= l", "def ellipse_contains_point(f0, f1, l, p): \n x1, x2, y1, y2 = f0[\"x\"] - p[\"x\"], f1[\"x\"] - p[\"x\"], f0[\"y\"] - p[\"y\"], f1[\"y\"] - p[\"y\"]\n d1 = (x1**2+y1**2)**.5\n d2 = (x2**2+y2**2)**.5\n return d2 + d1 <= l", "def ellipse_contains_point(f0, f1, l, p): \n x1, x2, y1, y2 = f0['x'], f1['x'], f0['y'], f1['y']\n c = (((x1-x2)**2 + (y1-y2)**2)**.5)/2\n h, k = (x1 + x2)/2, (y1 + y2)/2\n a = c + (l-2*c)/2\n b = ((l/2)**2 - c)**.5\n return ((p['x'] - h)**2)/ a**2 + ((p['y'] - k)**2)/ b**2 <=1 and c<l/2.\n"]
{"fn_name": "ellipse_contains_point", "inputs": [[{"x": 0, "y": 0}, {"x": 0, "y": 0}, 2, {"x": 0, "y": 0}], [{"x": 0, "y": 0}, {"x": 0, "y": 0}, 2, {"x": 1, "y": 1}]], "outputs": [[true], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,213
def ellipse_contains_point(f0, f1, l, p):
ad961a88eb654871db7cfae070c1bbf5
UNKNOWN
Speedcubing is the hobby involving solving a variety of twisty puzzles, the most famous being the 3x3x3 puzzle or Rubik's Cube, as quickly as possible. In the majority of Speedcubing competitions, a Cuber solves a scrambled cube 5 times, and their result is found by taking the average of the middle 3 solves (ie. the slowest and fastest times are disregarded, and an average is taken of the remaining times). In some competitions, the unlikely event of a tie situation is resolved by comparing Cuber's fastest times. Write a function ```cube_times(times)``` that, given an array of floats ```times``` returns an array / tuple with the Cuber's result (to 2 decimal places) AND their fastest solve. For example: ```python cube_times([9.5, 7.6, 11.4, 10.5, 8.1]) = (9.37, 7.6) # Because (9.5 + 10.5 + 8.1) / 3 = 9.37 and 7.6 was the fastest solve. ``` Note: ```times``` will always be a valid array of 5 positive floats (representing seconds)
["def cube_times(times):\n return (round((sum(times) - (min(times) + max(times)))/3 , 2), min(times))", "def cube_times(times):\n times = sorted(times)\n return (round(sum(times[1:-1])/3,2), times[0])", "from statistics import mean\n\ndef cube_times(times):\n return (round(mean(sorted(times)[1:4]), 2), min(times))", "def cube_times(times):\n return (round(sum(sorted(times)[1:4]) / 3, 2), min(times))", "def cube_times(times):\n record_time = min(times)\n slowest_time = max(times)\n average = 0\n for time in times:\n if time == record_time or time == slowest_time:\n pass\n else:\n average += time\n rounded_time = round(average / 3, 2)\n return (rounded_time, record_time)", "def cube_times(arr):\n return (round(sum(sorted(arr)[1: 4]) / 3, 2), min(arr))", "def cube_times(times):\n times.sort()\n a= [0,0]\n a[0] = round((float(times[1]) + float(times[2]) + float(times[3]))/3,2)\n a[1] = times[0]\n return tuple(a)\n \n", "def cube_times(times):\n times.sort()\n mid = times[1:4]\n return ( round(sum(mid) / len(mid), 2), times[0])", "def cube_times(times):\n return (round(sum(sorted(times)[1:-1])/3, 2), sorted(times)[0])", "def cube_times(times):\n return (round(sum(sorted(times)[1:-1])/3,2), min(times))"]
{"fn_name": "cube_times", "inputs": [[[9.5, 7.6, 11.4, 10.5, 8.1]], [[13.4, 12.3, 9.5, 11.9, 20.8]], [[28.3, 14.5, 17.3, 8.9, 10.1]]], "outputs": [[[9.37, 7.6]], [[12.53, 9.5]], [[13.97, 8.9]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,322
def cube_times(times):
95acb7f10cd37d99050ed6dff96c92da
UNKNOWN
Have a look at the following numbers. ``` n | score ---+------- 1 | 50 2 | 150 3 | 300 4 | 500 5 | 750 ``` Can you find a pattern in it? If so, then write a function `getScore(n)`/`get_score(n)`/`GetScore(n)` which returns the score for any positive number `n`: ```c++ int getScore(1) = return 50; int getScore(2) = return 150; int getScore(3) = return 300; int getScore(4) = return 500; int getScore(5) = return 750; ```
["def get_score(n):\n return n * (n + 1) * 25", "def get_score(n):\n return 50*(n*(n+1))/2\n \n \n \n", "get_score = lambda n: 25 * n * (n + 1)", "get_score = lambda n, a=0: sum(a+i*50 for i in range(n+1))", "def get_score(n):\n return sum([x*50 for x in range(n+1)])", "def get_score(n):\n return 25 * n * (n + 1)", "def get_score(n):\n return (1+(1<<1<<1))**(1<<1)*n*(n+1)", "get_score=lambda n:25*n*-~n", "get_score=lambda n: n*(n+1)*25"]
{"fn_name": "get_score", "inputs": [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [20], [30], [100], [123], [1000], [1234], [10000], [12345]], "outputs": [[50], [150], [300], [500], [750], [1050], [1400], [1800], [2250], [2750], [10500], [23250], [252500], [381300], [25025000], [38099750], [2500250000], [3810284250]]}
INTRODUCTORY
PYTHON3
CODEWARS
465
def get_score(n):
cc7b90ca0fca6360e250f1133060548b
UNKNOWN
There are some perfect squares with a particular property. For example the number ```n = 256``` is a perfect square, its square root is ```16```. If we change the position of the digits of n, we may obtain another perfect square``` 625``` (square root = 25). With these three digits ```2```,```5``` and ```6``` we can get two perfect squares: ```[256,625]``` The number ```1354896``` may generate another ```4``` perfect squares, having with the number itself, a total of five perfect squares: ```[1354896, 3594816, 3481956, 5391684, 6395841]```, being the last one in the list, ```6395841```, the highest value of the set. Your task is to find the first perfect square above the given lower_limit, that can generate the given k number of perfect squares, and it doesn't contain the digit 0. Then return the maximum perfect square that can be obtained from its digits. Example with the cases seen above: ``` lower_limit = 200 k = 2 (amount of perfect squares) result = 625 lower_limit = 3550000 k = 5 (amount of perfect squares) result = 6395841 ``` Features of the random tests: ``` 100 <= lower_limit <= 1e6 2 <= k <= 5 number of tests = 45 ``` Have a good time!
["from itertools import count, permutations\n\ndef next_perfectsq_perm(limit_below, k):\n for n in count(int(limit_below**.5)+1):\n s = str(n**2)\n if '0' not in s:\n sq_set = {x for x in (int(''.join(p)) for p in permutations(s)) if (x**.5).is_integer()}\n if len(sq_set) == k:\n return max(sq_set)", "from itertools import permutations\nfrom math import sqrt\n\ndef is_per(n):\n return str(sqrt(int(n)))[-1] == '0'\ndef next_perfectsq_perm(lower_limit, k): \n perfect = [i**2 for i in range(2000) if '0' not in str(i**2) if i**2 > lower_limit]\n for i in perfect: \n if i > lower_limit:\n num = set()\n per = set(permutations(str(i)))\n tem = [int(''.join(j)) for j in per if is_per(''.join(j))]\n if len(tem) == k:\n num.add(i)\n ma = max(tem)\n break\n return max(tem)", "from itertools import permutations\ndef next_perfectsq_perm(lower_limit, k): \n while 1:\n lower_limit += 1\n if '0' not in str(lower_limit) and int(lower_limit ** 0.5 + 0.5) ** 2 == lower_limit:\n perms = list([''.join(x) for x in set(permutations(str(lower_limit)))])\n perms = list(map(int, perms))\n perfects = 0\n perfect_list = []\n for i in perms:\n if int(i ** 0.5 + 0.5) ** 2 == i:\n perfects += 1\n perfect_list.append(i)\n if perfects == k:\n return max(perfect_list) \n", "candidates = ((sq, str(sq)) for sq in (i*i for i in range(12, 3000)))\ncandidates = ((sq, s) for sq, s in candidates if '0' not in s)\n\nd = {} # 144: [144, 441], 256: [256, 625], ...\nsqs = {} # 144: [144, 441], 256: [256, 625], 441: [144, 441], 625: [256, 625], ...\nfor sq, s in candidates:\n sqs[sq] = d.setdefault(int(''.join(sorted(s))), [])\n sqs[sq].append(sq)\n\ndef next_perfectsq_perm(lower_limit, k): \n return sqs[min(x for x in sqs if x > lower_limit and len(sqs[x]) == k)][-1]", "from itertools import permutations\n\ndef is_perfect(square):\n return round(square**0.5)**2 == square\n\ndef permuted(n):\n return (int(\"\".join(p)) for p in set(permutations(str(n))))\n\ndef perfect_permutations(n):\n return tuple(p for p in permuted(n) if is_perfect(p))\n \ndef next_perfectsq_perm(lower_limit, k): \n root = int(lower_limit**0.5) + 1\n while True:\n square = root**2\n if not \"0\" in str(square):\n p = perfect_permutations(square)\n if len(p) == k:\n return max(p)\n root += 1\n", "from collections import *\n\nNUM_DIG = 8\npalindromes = OrderedDict()\nfor n in range(int(10 ** (NUM_DIG / 2)) + 1):\n key = Counter(str(n ** 2))\n if '0' not in key:\n palindromes.setdefault(\n frozenset(key.most_common()), []).append(n ** 2)\n\nlasts, lengths = {}, defaultdict(list)\nfor seq in palindromes.values():\n for n in seq:\n lengths[len(seq)].append(n)\n lasts[n] = seq[-1]\nfor k in lengths: lengths[k].sort()\n\nfrom bisect import bisect\ndef next_perfectsq_perm(lower_limit, k):\n return lasts[lengths[k][bisect(lengths[k], lower_limit)]]", "K_PERMS = {\n 2: [144, 256, 441, 625, 1369, 1764, 1936, 4761, 11236, 12769, 14884, 21316, 24649, 24964,\n 27556, 29584, 34596, 36864, 43264, 45369, 46656, 48841, 51984, 54289, 66564, 74529,\n 75625, 79524, 86436, 95481, 96721, 99856, 112225, 113569, 118336, 133956, 139876,\n 142884, 147456, 148225, 148996, 154449, 155236, 166464, 167281, 169744, 173889, 174724,\n 175561, 194481, 198916, 212521, 216225, 224676, 225625, 227529, 233289, 237169, 238144,\n 264196, 265225, 267289, 272484, 287296, 293764, 314721, 316969, 323761, 328329, 329476,\n 344569, 345744, 355216, 368449, 369664, 374544, 383161, 391876, 398161, 427716, 432964,\n 434281, 447561, 456976, 459684, 463761, 467856, 474721, 498436, 521284, 522729, 546121,\n 591361, 594441, 611524, 619369, 622521, 627264, 646416, 649636, 654481, 659344, 667489,\n 669124, 675684, 678976, 712336, 729316, 736164, 741321, 748225, 755161, 758641, 769129,\n 772641, 779689, 781456, 786769, 793881, 795664, 799236, 817216, 835396, 842724, 844561,\n 848241, 874225, 877969, 891136, 894916, 919681, 927369, 933156, 948676, 956484, 964324,\n 972196, 976144, 9114361],\n 3: [961, 9216, 11664, 12544, 16641, 18225, 23716, 25281, 32761, 41616, 42849, 44521, 49284,\n 52441, 72361, 81225, 82944, 131769, 141376, 149769, 164836, 165649, 197136, 319225,\n 349281, 364816, 378225, 381924, 417316, 471969, 481636, 541696, 837225, 931225, 974169,\n 7112889],\n 4: [81796, 112896, 132496, 168921, 195364, 214369, 269361, 298116, 346921, 395641, 436921,\n 543169, 962361, 4511376],\n 5: [43681, 6395841],\n 6: [7241481],\n 7: [4532641] }\n\n\ndef next_perfectsq_perm(lower_limit, k, answer = 0):\n \n for number in K_PERMS[k]:\n if not answer and number > lower_limit:\n answer = number\n elif answer and sorted(str(number)) == sorted(str(answer)):\n answer = number\n \n return answer", "from itertools import permutations, count\n\ndef next_perfectsq_perm(lower_limit, k):\n for i in count(int(lower_limit ** 0.5) + 1):\n j = i ** 2\n if '0' in str(j):\n continue\n k_count = 0\n matches = [j]\n perms = set(permutations(str(j))) - set(matches)\n for p in perms:\n num = int(''.join(p))\n if int(num ** 0.5) ** 2 == num:\n matches.append(num)\n k_count += 1\n if k_count == k:\n return sorted(matches)[-1]", "M,U = {},[]\ndef H(Q) :\n R = 0\n while Q :\n if Q % 10 < 1 : return 0\n R += 1 << (Q % 10 * 3)\n Q //= 10\n return R\nfor F in range(1,10000) :\n F = F * F\n R = H(F)\n if R :\n U.append(F)\n M.setdefault(R,[]).append(F)\ndef next_perfectsq_perm(Q,S) :\n for V in U :\n if Q < V :\n T = M.get(H(V))\n if T and S == len(T) : return T[-1]", "import itertools\ndef next_perfectsq_perm(l, k):\n perf = lambda n: n**0.5%1 == 0\n while True:\n l += 1\n if perf(l) and '0' not in str(l):\n r = [x for x in set([int(''.join(x)) for x in list(itertools.permutations(str(l)))]) if perf(x)]\n if len(r) == k: return max(r)"]
{"fn_name": "next_perfectsq_perm", "inputs": [[100, 2], [100, 3], [100, 4], [500, 2], [1000, 3], [100000, 4], [144, 2], [145, 2], [440, 2], [441, 2], [257, 2]], "outputs": [[441], [961], [81796], [625], [9216], [298116], [625], [625], [441], [625], [441]]}
INTRODUCTORY
PYTHON3
CODEWARS
6,555
def next_perfectsq_perm(lower_limit, k):
f62484600046d0013a4400779e03a925
UNKNOWN
A little weird green frog speaks in a very strange variation of English: it reverses sentence, omitting all puntuation marks `, ; ( ) - ` except the final exclamation, question or period. We urgently need help with building a proper translator. To simplify the task, we always use lower-case letters. Apostrophes are forbidden as well. Translator should be able to process multiple sentences in one go. Sentences are separated by arbitrary amount of spaces. **Examples** `you should use python.` -> `python use should you.` `look, a fly!` -> `fly a look!` `multisentence is good. is not it?` -> `good is multisentence. it not is?`
["import re\n\ndef frogify(s):\n return ' '.join( ' '.join(re.findall(r'[a-z]+', sentence)[::-1]) + punct for sentence,punct in re.findall(r'(.*?)([.!?])', s) )", "import re\n\ndef frogify(s):\n delimiters = set([\".\", \"!\", \"?\"])\n sentences = re.split(\"([\\!\\.\\?])\", re.sub(\"[,\\;\\)\\(-]\", \"\", s))\n res = []\n sentence = \"\"\n \n for item in sentences:\n if item in delimiters:\n res.append(\" \".join(sentence.split(\" \")[::-1]) + item)\n sentence = \"\"\n elif item:\n sentence += re.sub(\"\\s+\", \" \", item).strip()\n\n return \" \".join(res)", "import re\n\ndef rev(s):\n s, punc = s[:-1], s[-1]\n return ' '.join(word for word in s.split()[::-1]) + punc\n\ndef frogify(s):\n return ' '.join(rev(sentence).strip() for sentence in re.findall(r'.+?[.?!]', re.sub('[^ a-z.!?]', '', s)))", "import re\n\ndef reverse_sentence(m):\n words = m.group(1).split()\n rev = ' '.join(reversed(words))\n return m.expand(r' {}\\2'.format(rev))\n\ndef frogify(s):\n s = re.sub(r'[,;{}\\-\\(\\)]', '', s)\n return re.sub(r'(.*?)([.!?])', reverse_sentence, s).strip()", "frogify=lambda s,r=__import__('re').sub:r(\"\\w.*?(?=[.?!])\",lambda m:' '.join(m.group().split()[::-1]),' '.join(r(\"[(),;'-]\",'',s).split()))", "def frogify(s):\n for c in '.!?':\n if c in s:\n return f'{c} '.join(map(frogify, s.split(c))).strip()\n words = ''.join(c for c in s.lower() if c == ' ' or 'a' <= c <= 'z').split()\n return ' '.join(words[::-1])", "import re\ndef frogify(s): \n print(s)\n s =re.sub(\"\\s?[(),\\[\\];{}-]+\",r\"\",s)\n print(s)\n match =re.findall(\"\\w[\\w, -]+\",s)\n for i in match:\n print(i)\n rev = \" \".join(reversed(i.split()))\n s = re.sub(i,rev,s)\n return s.lstrip()\n \n", "import re\n\ndef frogify(s):\n a = re.split(r\"([!?.])\", s.translate(str.maketrans(\"\", \"\", \",;()-\")).strip())\n if not a[-1]:\n a.pop()\n return \"\".join(f(x) for x in a)\n\ndef f(s):\n return s if s in \"!?.\" else \" \" * (s[0] == \" \") + \" \".join(s.strip().split()[::-1])", "import re\ndef frogify(s):\n what = s.replace('.','.&').replace('!','!&').replace('?','?&').replace(',','').replace('-','').replace('(','').replace(')','').replace(';','')\n reason = re.sub(' +', ' ', what)\n reason = reason.split(\"&\")\n hi = reason[:-1]\n arr = []\n for i in hi:\n end = i[-1:]\n result = i[:-1].split(\" \")\n final = result[::-1]\n final2 = (\" \").join(final)\n if final2[len(final2)-1] == \" \":\n final2 = final2[:-1]\n if len(final2) > 0 and final2[0] == \" \":\n final2 = final2.lstrip()\n arr.append(final2 + end)\n sun = (\" \").join(arr)\n return sun", "import re\ndef frogify(s):\n t = re.split(r'(\\W+)', s)[:-1]\n if len(t) == 0: return ''\n t = [re.sub(r'[ ]*[,;:()-]','', s) for s in t]\n t = [(s, ' ')[s == ''] for s in t]\n while t[0] == ' ':\n t.pop(0)\n matches = [j for j, x in enumerate(t) if x[0] in '.?!']\n oldi = 0\n for i in matches:\n t[oldi:i] = t[oldi:i][::-1]\n oldi = i+1\n return ''.join(t)\n"]
{"fn_name": "frogify", "inputs": [["i am a frog."], ["can you do it?"], ["seems like you understand!"], ["multisentence is good. is not it?"], ["green, red or orange - we all just frogs, do not you think so?"]], "outputs": [["frog a am i."], ["it do you can?"], ["understand you like seems!"], ["good is multisentence. it not is?"], ["so think you not do frogs just all we orange or red green?"]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,257
def frogify(s):
37086e3998f52304fbff1c0fca95bc39
UNKNOWN
Take a sentence (string) and reverse each word in the sentence. Do not reverse the order of the words, just the letters in each word. If there is punctuation, it should be interpreted as a regular character; no special rules. If there is spacing before/after the input string, leave them there. String will not be empty. ## Examples ``` "Hi mom" => "iH mom" " A fun little challenge! " => " A nuf elttil !egnellahc " ```
["def reverser(sentence):\n return ' '.join(i[::-1] for i in sentence.split(' '))", "def reverser(s):\n return \" \".join(w[::-1] for w in s.split(\" \"))", "import re\ndef reverser(sentence):\n return ''.join(w[::-1] if ' ' not in w else w for w in re.findall(r'(?:\\w+)|(?:\\s+)', sentence)) ", "from re import compile\n\nr = compile(r\"(\\W)\")\n\n\ndef reverser(sentence: str) -> str:\n return ''.join(w[::-1] for w in r.split(sentence))\n", "def reverser(sentence):\n emt = \" \"\n split_it = sentence.split(\" \")\n for word in split_it:\n emt += word[::-1] + \" \"\n return emt[1:-1]", "import re\ndef reverser(sentence):\n return ''.join(i[::-1] for i in re.split(r'(\\s+)', sentence))\n", "def reverser(sentence):\n newsent = sentence.split(\" \")\n rnsent = [i[::-1] for i in newsent]\n s = \" \"\n s = s.join(rnsent)\n return s", "def reverser(sentence):\n text =sentence.split(' ')\n ans =[]\n for i in text:\n ans.append(i[::-1])\n return ' '.join(ans)\n", "def reverser(sentence):\n ans = ''\n word = ''\n for letter in sentence:\n if letter == ' ':\n ans = ans + word[::-1] + letter\n word = ''\n else:\n word = word + letter\n return ans + word[::-1]", "reverser = lambda x: ' '.join([i[::-1] for i in x.split(' ')])"]
{"fn_name": "reverser", "inputs": [["How now brown cow"], ["racecar"], ["Hi mom"], [" "], [" "], ["go away"], ["I like noodles"], ["The red pen wrote on the wall"], ["Green trucks drive fast"], ["Pink trucks drive slow"]], "outputs": [["woH won nworb woc"], ["racecar"], ["iH mom"], [" "], [" "], ["og yawa"], ["I ekil seldoon"], ["ehT der nep etorw no eht llaw"], ["neerG skcurt evird tsaf"], ["kniP skcurt evird wols"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,362
def reverser(sentence):
f34480b44a9a9c30e5e61c7fa8bcd9ba
UNKNOWN
# Task: Given a list of numbers, determine whether the sum of its elements is odd or even. Give your answer as a string matching `"odd"` or `"even"`. If the input array is empty consider it as: `[0]` (array with a zero). ## Example: ``` odd_or_even([0]) == "even" odd_or_even([0, 1, 4]) == "odd" odd_or_even([0, -1, -5]) == "even" ``` Have fun!
["def odd_or_even(arr):\n return 'even' if sum(arr) % 2 == 0 else 'odd'", "def odd_or_even(arr):\n if sum(arr)%2==0:\n return 'even'\n else:\n return 'odd'", "def odd_or_even(arr):\n return ('even', 'odd')[sum(arr) % 2]", "def odd_or_even(arr):\n return ['even','odd'][sum(arr)%2]", "def odd_or_even(arr):\n return 'odd' if sum(arr) % 2 else 'even'", "def odd_or_even(arr):\n sum = 0\n answer = \"\"\n \n for el in arr:\n sum += el\n \n if sum % 2 == 0:\n answer = \"even\"\n else:\n answer = \"odd\"\n \n return answer", "def odd_or_even(arr):\n if(len(arr) == 0):\n return \"even\"\n else:\n total = 0\n for item in arr:\n total += item\n if(total % 2):\n return \"odd\"\n else:\n return \"even\"", "def odd_or_even(arr):\n counter = 0\n for i in arr:\n counter += int(i)\n if counter % 2 == 0: return \"even\"\n else: return \"odd\"", "def odd_or_even(arr):\n #calculate if sum is odd or even using modulus\n test = sum(arr[-(len(arr)):]) % 2\n #return value as string\n if test == 0:\n return \"even\"\n else:\n return \"odd\"\n", "def odd_or_even(arr):\n zum = 0\n for i in arr:\n zum += i\n if(zum%2== 0):\n return \"even\"\n else:\n return \"odd\"", "def odd_or_even(arr):\n if sum(arr)%2==0: return 'even'\n else: return 'odd'\n return ", "_ = {True:'odd',False:'even'}\ndef odd_or_even(arr):\n return _.get(sum(arr)%2)", "import math\n\ndef odd_or_even(arr):\n i = sum(arr)\n if (i % 2) == 0:\n return \"even\"\n else:\n return \"odd\"", "def odd_or_even(arr):\n a = 0\n for i in range(len(arr)):\n a += arr[i]\n if a % 2 == 0:\n return \"even\"\n else:\n return \"odd\"", "def odd_or_even(arr):\n if sum(arr) % 2 == 0:\n return 'even'\n elif not sum(arr) % 2 == 0:\n return 'odd'", "def odd_or_even(arr):\n return \"even\" if len(arr) == 0 or sum(arr) % 2 == 0 else \"odd\"", "def odd_or_even(arr):\n sum = 0\n for x in arr:\n sum += x\n return \"even\" * int(1 - sum % 2) + \"odd\" * (sum % 2)", "def odd_or_even(arr):\n array = []\n for n in arr:\n total = sum(arr)\n if (total % 2 == 0):\n return \"even\"\n else:\n return \"odd\"", "odd_or_even = lambda a: 'odd' if sum(a)%2!=0 else 'even'", "def odd_or_even(arr):\n if arr: return 'odd' if sum(arr) % 2 else 'even'\n else: return 'even'\n", "def odd_or_even(arr):\n if arr == []:\n return [0]\n elif sum(arr) > 0:\n if sum(arr)%2 == 0:\n return \"even\"\n else:\n return \"odd\"\n \n elif sum(arr) < 0:\n if (-1*sum(arr))%2 == 0:\n return \"even\"\n else:\n return \"odd\"", "def odd_or_even(arr):\n result = 0\n for item in arr:\n result += item\n if result % 2 == 0:\n return \"even\"\n else:\n return \"odd\"", "def odd_or_even(arr):\n no=sum(arr)\n if no%2==0:\n return \"even\"\n else:\n return \"odd\"", "def odd_or_even(arr):\n sum = 0\n for i in arr:\n sum += i\n if sum % 2 == 0:\n return 'even'\n elif sum % 2 != 0:\n return 'odd'\n elif sum == 0:\n return [0]\nodd_or_even([0, 1, 2]) \n \n", "def odd_or_even(a):\n if sum(a)%2==0: return 'even'\n else: return 'odd'", "def odd_or_even(arr):\n if sum(arr[:]) % 2 == 1:\n result = \"odd\"\n else:\n result = \"even\"\n return result", "def odd_or_even(arr):\n sum = 0\n for x in arr:\n sum = sum + x \n if(sum%2 == 0):\n return 'even'\n else:\n return 'odd'\n", "def odd_or_even(arr):\n sum = 0\n for X in arr:\n sum = sum + X\n remainder = sum % 2\n if remainder == 0:\n return \"even\"\n \n else:\n return \"odd\"\n", "def odd_or_even(arr):\n sum=0\n for char in arr:\n sum = sum + int(char)\n return \"even\" if sum % 2 == 0 else \"odd\"\n", "def odd_or_even(arr):\n i = 0\n for x in arr:\n i += x\n if i%2 == 0:\n return f\"{'even'}\"\n else:\n return f\"{'odd'}\"", "def odd_or_even(arr):\n result = sum(arr)\n if result % 2 == 0:\n return ('even')\n elif result % 2 == 1:\n return ('odd')\n else:\n return ([0])", "def odd_or_even(arr):\n if len(arr) == 0:\n return [0]\n \n val = sum(arr)\n \n if val % 2 == 0:\n return\"even\"\n else:\n return \"odd\"", "def odd_or_even(arr):\n sum = 0\n for i in arr:\n sum += i\n if abs(sum)%2==0:\n return \"even\"\n else: return \"odd\"", "odd_or_even = lambda a: ['even','odd'][sum(a)%2]", "def odd_or_even(arr):\n arr = sum(arr)\n return ['even','odd'][arr%2]", "def odd_or_even(arr):\n list = [i for i in arr]\n su = sum(list)\n if su == 0:\n return 'even'\n elif su % 2 == 0:\n return 'even'\n else:\n return 'odd'", "def odd_or_even(arr):\n result = 0\n for number in arr:\n result = result + number\n \n if(result % 2 == 0):\n return \"even\"\n \n return \"odd\"", "def odd_or_even(arr):\n sum = 0\n for i in arr:\n sum += i\n if sum % 2 == 0:\n res = \"even\"\n else:\n res = \"odd\"\n return res", "import functools\ndef odd_or_even(arr):\n return 'even' if functools.reduce(lambda x, y: x + y, arr) % 2 == 0 else 'odd'", "def odd_or_even(arr):\n res = 0\n for i in arr:\n res +=i\n if res%2 == 0:\n return 'even'\n return \"odd\"", "def odd_or_even(arr):\n thesum = 0\n for i in arr:\n thesum +=i\n if thesum %2==0:\n return 'even'\n else:\n return 'odd'", "def odd_or_even(arr):\n a = 0\n for i in arr:\n a = a + i\n if a %2 == True:\n return 'odd'\n else:\n return 'even'", "def odd_or_even(arr):\n add = 0\n for num in arr:\n add += num\n if len(arr) == 0:\n return [0]\n if add % 2 == 0:\n return \"even\"\n return \"odd\"\n\n", "def odd_or_even(arr):\n suma = 0\n result = ''\n if len(arr) == 0:\n result = 'even'\n for x in arr:\n suma = suma +x\n if suma%2 == 0:\n result = 'even'\n else: \n result = 'odd'\n return result\n \n", "def odd_or_even(arr):\n sum=0;\n for i in arr:\n sum+=i\n return \"odd\" if sum%2==1 else \"even\"", "def odd_or_even(arr):\n \n if arr == []:\n arr = [0]\n \n total = sum(arr)\n \n if total % 2 == 0 or total == 0:\n return \"even\"\n else:\n return \"odd\"", "def odd_or_even(arr):\n return \"even\" if sum([n % 2 != 0 for n in arr]) % 2 == 0 else \"odd\"", "def odd_or_even(arr):\n return {1:'odd', 0:'even'}[sum(arr) % 2]", "def odd_or_even(arr):\n g = sum(arr)\n if g %2 ==0:\n return (\"even\")\n else:\n return (\"odd\")", "def odd_or_even(arr):\n sum = 0\n for i in range(0, len(arr)):\n sum = sum + arr[i]\n i += 1\n if sum % 2 == 0:\n return \"even\"\n else:\n return \"odd\"\n pass", "def odd_or_even(liste):\n somme = sum(i for i in liste)\n if somme % 2 ==0:\n return 'even'\n else:\n return 'odd'", "def odd_or_even(arr):\n arr_num = 0\n for i in arr:\n arr_num = arr_num + i\n return \"odd\" if arr_num % 2 != 0 else \"even\"\n", "def odd_or_even(arr):\n add = sum(arr)\n return \"even\" if add % 2 == 0 else \"odd\"", "def odd_or_even(arr):\n if len(arr) == 0:\n arr = 0\n som = sum(arr)\n if som %2 == 0:\n return \"even\"\n else:\n return \"odd\"", "def odd_or_even(arr):\n if len(arr) ==1 and sum(arr) == 0:\n return 'even'\n #\n\n if sum(arr)%2 == 0:\n return 'even'\n else:\n return 'odd'", "def odd_or_even(arr):\n s=sum(arr)\n o=\"odd\"\n e=\"even\"\n if len(arr)>0:\n if s%2==1:\n return o\n else:\n return e\n else:\n return o\n", "def odd_or_even(arr):\n added = sum(arr)\n if str(added)[-1] in \"13579\":\n return \"odd\"\n else:\n return \"even\"\n pass", "def odd_or_even(arr):\n total = sum(arr)\n print(total)\n return 'even' if total % 2 == 0 else 'odd'", "def odd_or_even(arr):\n total_sum = 0\n for i in arr:\n total_sum += i\n if total_sum %2 == 0:\n return \"even\"\n else:\n return \"odd\"", "def odd_or_even(arr):\n n = sum(arr)\n odd = [1,3,5,7,9]\n even = [2,4,6,8,0]\n if (n % 10) in odd:\n return \"odd\"\n else:\n return \"even\"", "def odd_or_even(arr):\n val = 0\n for i in range(len(arr)):\n val += arr[i]\n if val % 2 == 0:\n return \"even\"\n else:\n return \"odd\"", "def odd_or_even(arr):\n return 'odd' if int(sum(arr))%2!=0 else 'even'", "def odd_or_even(arr):\n if not arr:\n arr = [0]\n return \"odd\" if sum(arr)%2 else \"even\"", "def odd_or_even(array): return (\"even\", \"odd\")[sum(array) % 2]", "def odd_or_even(n:list):\n if len(n) == 0:\n return [0]\n elif sum(n) % 2 == 0:\n return \"even\"\n else:\n return \"odd\"", "def odd_or_even(arr):\n summary = 0\n for item in range(len(arr)):\n summary = summary + arr[item]\n if summary % 2 == 0:\n return 'even'\n else:\n return 'odd'", "def odd_or_even(arr):\n var = 0\n for i in arr:\n var = i + var\n \n if var % 2 == 0:\n return(\"even\")\n else:\n return(\"odd\")", "def odd_or_even(arr):\n one = 0\n for num in arr:\n one += num\n if one % 2 == 0:\n return 'even'\n elif one % 2 != 0:\n return 'odd'", "def odd_or_even(arr):\n sum_val = sum(arr)\n if sum_val % 2 == 0:\n return 'even'\n else:\n return 'odd'", "def odd_or_even(arr):\n y = int()\n for x in range(0, len(arr)):\n y += arr[x]\n if y % 2 == 0:\n return \"even\"\n else:\n return \"odd\"", "def odd_or_even(arr):\n return \"even\" if sum(arr) % 2 == 0 else \"odd\"\n\ns = [1,2,3,4,5,6,7,8,9]\nprint(odd_or_even(s))", "def odd_or_even(arr):\n res = sum(map(int,arr))\n return \"even\" if res % 2 == 0 else \"odd\"\n\ns = [0, 1, 3]\nprint(odd_or_even(s))", "def odd_or_even(arr):\n t = 0\n for i in arr:\n t += i\n return \"even\" if t%2==0 else \"odd\"", "def odd_or_even(arr = [0]):\n return \"odd\" if sum(arr) % 2 == 1 else \"even\"", "def odd_or_even(arr):\n arraytot = 0\n for e in arr:\n arraytot += e\n\n if arraytot % 2 == 0:\n return \"even\"\n else:\n return \"odd\"", "def odd_or_even(arr):\n return [0] if not arr else \"odd\" if sum(arr) % 2 else \"even\"\n", "def odd_or_even(arr):\n sumOfNums = sum(arr)\n \n if sumOfNums % 2 == 0:\n return 'even'\n else:\n return 'odd'"]
{"fn_name": "odd_or_even", "inputs": [[[0, 1, 2]], [[0, 1, 3]], [[1023, 1, 2]]], "outputs": [["odd"], ["even"], ["even"]]}
INTRODUCTORY
PYTHON3
CODEWARS
11,286
def odd_or_even(arr):
4890d2305270c9219abf72953b969f4c
UNKNOWN
An isogram is a word that has no repeating letters, consecutive or non-consecutive. Implement a function that determines whether a string that contains only letters is an isogram. Assume the empty string is an isogram. Ignore letter case. ```python is_isogram("Dermatoglyphics" ) == true is_isogram("aba" ) == false is_isogram("moOse" ) == false # -- ignore letter case ``` ```C is_isogram("Dermatoglyphics" ) == true; is_isogram("aba" ) == false; is_isogram("moOse" ) == false; // -- ignore letter case ```
["def is_isogram(string):\n return len(string) == len(set(string.lower()))", "def is_isogram(string):\n string = string.lower()\n for letter in string:\n if string.count(letter) > 1: return False\n return True", "def is_isogram(string): \n return len(set(string.lower())) == len(string)", "def is_isogram(string):\n #your code here\n char_dict = {}\n string = string.lower()\n \n for char in string:\n if char in char_dict:\n # increment count of this character\n char_dict[char] = char_dict[char] + 1\n else:\n char_dict[char] = 1\n \n # loop over the characters in dictionary, if any have\n # more than 1 found, this string is not an isogram, so break\n # the loop and function and return False.\n for key in char_dict:\n if char_dict[key] > 1:\n return False\n \n # If no duplicates were found in the loop directly above,\n # this must be an isogram, so return true!\n return True", "is_isogram = lambda s: len(set(s.lower())) == len(s)", "def is_isogram(string):\n s = set(string.lower()) \n if len(s) == len(string): \n return True\n return False", "def is_isogram(string):\n string = string.lower()\n return len(string) == len(set(string))", "def is_isogram(string):\n return len(set(list(string.lower()))) == len(string)", "from collections import Counter\n\ndef is_isogram(string):\n for x in Counter(string.lower()).values():\n if x > 1:\n return False\n return True", "def is_isogram(string):\n result = {char: string.lower().count(char) for char in string.lower()}\n if 2 in result.values():\n return False\n else:\n return True"]
{"fn_name": "is_isogram", "inputs": [["Dermatoglyphics"], ["isogram"], ["moose"], ["isIsogram"], ["aba"], ["moOse"], ["thumbscrewjapingly"], ["abcdefghijklmnopqrstuvwxyz"], ["abcdefghijklmnopqrstuwwxyz"], [""]], "outputs": [[true], [true], [false], [false], [false], [false], [true], [true], [false], [true]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,750
def is_isogram(string):
95f31392cadeb1cd808480743fc39a7d
UNKNOWN
#It's show time! Archers have gathered from all around the world to participate in the Arrow Function Faire. But the faire will only start if there are archers signed and if they all have enough arrows in their quivers - at least 5 is the requirement! Are all the archers ready? #Reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions #Argument `archers` is an array of integers, in which each element corresponds to the number of arrows each archer has. #Return Your function must return `true` if the requirements are met or `false` otherwise. #Examples `archersReady([1, 2, 3, 4, 5, 6, 7, 8])` returns `false` because there are archers with not enough arrows. `archersReady([5, 6, 7, 8])` returns `true`.
["def archers_ready(archers):\n return all(i >= 5 for i in archers) if archers else False", "def archers_ready(archers):\n return len(archers) > 0 and all(a > 4 for a in archers)", "def archers_ready(archers):\n try:\n return min(archers)>=5\n except:\n return False", "def archers_ready(archers):\n return min(archers, default=0) > 4", "def archers_ready(archers):\n return bool(archers) and all(map((5).__le__, archers))", "def archers_ready(archers):\n return all(n >= 5 for n in archers) if archers else False", "def archers_ready(archers):\n return bool(archers) and all(x >= 5 for x in archers)", "def archers_ready(archers):\n return archers != [] and all(x > 4 for x in archers)", "def archers_ready(archers):\n if not archers:\n return False\n for arrows in archers:\n if arrows < 5:\n return False\n return True"]
{"fn_name": "archers_ready", "inputs": [[[]], [[1, 2, 3, 4]], [[5, 6, 7, 8]], [[5, 6, 7, 4]], [[1, 2, 3, 4, 5, 6, 7, 8]]], "outputs": [[false], [false], [true], [false], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
898
def archers_ready(archers):
3b310e44bc30c8753d625e3333d7ac32
UNKNOWN
You are given the `length` and `width` of a 4-sided polygon. The polygon can either be a rectangle or a square. If it is a square, return its area. If it is a rectangle, return its perimeter. ``` area_or_perimeter(6, 10) --> 32 area_or_perimeter(4, 4) --> 16 ``` > Note: for the purposes of this kata you will assume that it is a square if its `length` and `width` are equal, otherwise it is a rectangle.
["def area_or_perimeter(l, w):\n return l * w if l == w else (l + w) * 2", "area_or_perimeter = lambda a, b : a * b if a == b else 2 * (a + b)", "def area_or_perimeter(l , w):\n return l * w if l == w else 2 * (l + w)", "def area_or_perimeter(l , w):\n return l*w if l==w else l+l+w+w", "def area_or_perimeter(l , w):\n return [(l+w)*2, l*w][(l == w)]", "def area_or_perimeter(l , w):\n return l * l if l == w else 2 * (l + w)", "def area_or_perimeter(l , w):\n if l == w:\n tot = l * w\n else:\n tot = l * 2 + w * 2\n return tot\n", "def area_or_perimeter(l , w):\n return [l*w , 2*(l + w)][l != w]", "area_or_perimeter=lambda l,w:(l==w)*l**2or(l+w)*2", "def area_or_perimeter(l , w):\n resu = 0\n if l == w:\n resu = l*w\n return resu\n else:\n resu = 2*(l+w)\n return resu\n \n", "def area_or_perimeter(l: int, w: int) -> int:\n \"\"\" Get the area of a square or the perimeter of a rectangle. \"\"\"\n return l * w if l == w else l * 2 + w * 2", "def area_or_perimeter(l , w):\n return l * l if l == w else l + l + w + w", "area_or_perimeter = lambda l, w: (l*2)+(w*2) if l != w else l*w", "def area_or_perimeter(l , w):\n # return your answer\n if l == w:\n return l*w\n else:\n return 2 *l + 2 * w", "area_or_perimeter=lambda l,w:[2*(l+w),l*w][l==w]", "def area_or_perimeter(l , w):\n return (2*l+2*w, l**2)[l==w]", "def area_or_perimeter(l , w):\n return 2 * l + 2 * w if l!= w else l * w", "def area_or_perimeter(l , w):\n if l == w :\n return l * w \n else:\n l != w\n return (l * 2) + (w * 2)", "def area_or_perimeter(l , w):\n if l != w:\n return (l + w) * 2\n if l == w:\n return l * w", "def area_or_perimeter(l , w):\n if l != w : \n return 2 * (l + w)\n if l == w :\n return l * w ", "def area_or_perimeter(l , w):\n if l == w:\n return w * l\n else:\n return 2 * (w + l)", "def area_or_perimeter(l , w):\n \n return l ** 2 if l == w else l + l + w + w ", "def area_or_perimeter(l , w):\n if l == w:\n res = l * w\n else:\n res = l + l + w + w\n return res", "def area_or_perimeter(l , w):\n return 2*(l+w) if l != w else w**2 ", "def area_or_perimeter(l , w):\n if l==w:\n return l*w\n else:\n return (w+l)*2", "area_or_perimeter = lambda l, w: l*w if (l==w) else l*2+w*2\n", "def area_or_perimeter(l , w):\n return 2*l + 2*w if l != w else l**2", "def area_or_perimeter(l , w):\n \n# =============================================================================\n# This function is given the length and width of a 4-sided polygon. \n# The polygon can either be a rectangle or a square. \n# Note: \n# for the purposes of this kata you will assume that it is a square \n# if its length and width are equal, otherwise it is a rectangle.\n# \n# If it is a square, the function returns its area. If it is a rectangle, \n# the function returns its perimeter.\n# \n# Examples:\n# area_or_perimeter(6, 10) --> 32\n# area_or_perimeter(4, 4) --> 16\n# =============================================================================\n \n if l == w: # test for a square\n return (l*w)\n else: \n return ((2*l)+(2*w))", "area_or_perimeter = lambda l , w: l*w if l == w else 2*(l+w)", "area_or_perimeter=lambda l,w:l*w if l==w else l+l+w+w", "area_or_perimeter=lambda l,w:[l+w<<1,l*w][l==w]", "def area_or_perimeter(l , w):\n if l == w:\n return l*w\n else:\n return (l+w)*2\n\nprint((area_or_perimeter(6,10)))\nprint((area_or_perimeter(4,4)))\n", "def area_or_perimeter(l , w):\n if l == w: #check square or rectangle\n result = l**2 \n return int(result)\n else:\n result = 2 * ( l + w )\n return int(result)\n", "def area_or_perimeter(l , w):\n if l == w:\n polygon = \"square\"\n return l**2\n else:\n polygon = \"rectangle\"\n return l*2 + w*2", "def area_or_perimeter(length: int, width: int) -> int:\n \"\"\" This function returns area for a square or perimeter for a rectangle. \"\"\"\n if length == width:\n return length * width\n return (2 * length) + (2 * width)", "def area_or_perimeter(l , w):\n if l != w:\n return 2 * (l + w)\n return l**2", "def area_or_perimeter(l , w):\n if l!=w:\n return l*2+w*2\n if l==w:\n return l*w", "def area_or_perimeter(l , w):\n return w**2 if w == l else 2*(l+w)", "def area_or_perimeter(length, width):\n if length == width:\n return length * width\n else:\n return 2 * (length + width)\n", "def area_or_perimeter(l,w):\n if l == w:\n area = l * w\n return (area)\n elif l!=w:\n perimeter = 2 * (l + w)\n return (perimeter)\n else:\n return 0", "def area_or_perimeter(l , w):\n val = l*w if l == w else (2*l+2*w)\n return val", "def area_or_perimeter(l , w):\n if l == w:\n return l * w\n else:\n x = l*2\n y = w*2\n z = x + y\n return z", "def area_or_perimeter(l , w):\n if l != w:\n return 2*w+2*l\n return w*l", "def area_or_perimeter(l , w):\n if w == l:\n return l * w\n else:\n return 2 * (w + l)\n", "def area_or_perimeter(l , w):\n if l == w:\n return l * w # Area of a square\n else:\n return 2 * (l+w) # Perimeter of a rectangle", "def area_or_perimeter(l , w):\n area_rectangle = l * w\n area_square = l * l\n perimeter_rectangle = 2 * (l + w)\n perimeter_square = 4 * l\n if l == w:\n return area_square\n else:\n return perimeter_rectangle", "def area_or_perimeter(I , W):\n if I!=W: \n return 2*I+2*W\n else: \n return I*W\n", "def area_or_perimeter(l , w):\n if l == w:\n return l**2\n else:\n perimetr = (l*2)+(w*2)\n return perimetr", "def area_or_perimeter(l , w):\n if l == w:\n return l*w\n if l != w:\n x=2*l\n y=2*w\n return x+y", "def area_or_perimeter(l , w):\n a = lambda l,w: l*w if(l==w) else 2*l+2*w\n return a(l, w)", "def area_or_perimeter(l , w):\n if l == w:\n k = l**2\n else:\n k = l*2 + w*2\n return(k)", "def area_or_perimeter(l , w):\n square = l == w\n \n if square == True:\n return l * w\n else:\n return 2 * (l + w)\n \n \n # return your answer\n", "def area_or_perimeter(l , w):\n import math\n return math.pow(l, 2) if l == w else int(2 * l + 2 * w)", "import unittest\n\n\ndef area_or_perimeter(length, width):\n return length * width if length == width else 2 * length + 2 * width\n \n \nclass TestAreaOrPerimeter(unittest.TestCase):\n def test_area(self):\n self.assertEqual(area_or_perimeter(length=4, width=4), 16)\n\n def test_perimeter(self):\n self.assertEqual(area_or_perimeter(length=10, width=4), 28)\n", "def area_or_perimeter(l , w):\n if l * w == l * l:\n return l * w\n else:\n return (l*2) + (w*2)", "def area_or_perimeter(l , w):\n return w**2 if w == l else w*2 + l*2", "def area_or_perimeter(l=0, w=0):\n if l == w:\n return l * w\n else:\n return 2 * l + 2 * w\n", "def area_or_perimeter(l , w):\n print(l,w)\n if l == w:\n return 0.5*((l*4) * (w/2))\n else:\n return (l + w) * 2", "def area_or_perimeter(l , w):\n square = (l*w)\n rectangle = 2*(l+w)\n if l == w:\n return square\n else:\n return rectangle", "area_or_perimeter = lambda l,w: [2*l+2*w,l*w][l==w]", "def area_or_perimeter(l , w):\n mo = l+w\n if l == w:\n return l*w\n else:\n return mo * 2", "def area_or_perimeter(l , w):\n if l == w:\n return l * w\n elif l < w or l > w:\n return l * 2 + w * 2", "def area_or_perimeter(le , wi):\n if le == wi:\n return le * wi\n else:\n return 2 * le + 2 * wi", "def area_or_perimeter(l , w):\n '''determine if a shape is a square or a rectangle'''\n square = l * w\n if l == w:\n return square\n else:\n return l + l + w + w\n", "def area_or_perimeter(l , w):\n if l != w:\n return (l * 2) + (w * 2)\n \n if l == w:\n return l ** 2\n \n # return your answer\n", "def area_or_perimeter(l , w):\n if l == w :\n return w * w\n else :\n return w + w + l + l", "def area_or_perimeter(l , w):\n rectangle_perimeter=2*(l+w)\n square_area=l*l\n if l==w:\n return square_area \n else:\n return rectangle_perimeter \n", "def area_or_perimeter(l , w):\n if l == w:\n return l**2\n else:\n l2 = l*2\n r2 = w*2\n return l2+r2", "def area_or_perimeter(l , w):\n if l == w:\n return l*w\n else:\n return 2*(l+w)\n#pogchamp\n", "area_or_perimeter = lambda l , w: (l + w) * 2 if l != w else l**2", "from math import *\n\ndef area_or_perimeter(l , w):\n if l == w:\n area = l * w\n return area\n else:\n p = l+w+l+w\n return p", "def area_or_perimeter(l , w):\n if l == w:\n result = l * w\n else:\n result = (l+w) * 2\n return result", "def area_or_perimeter(length, width):\n return length * width if length == width else (length + width) * 2", "def area_or_perimeter(l,w):\n\n s = l * w\n p = (l + w) * 2\n if l == w:\n return (s)\n else:\n return (p)\n\n\n", "def area_or_perimeter(length, width):\n if length == width:\n return length * width\n else:\n return length * 2 + width * 2", "def area_or_perimeter(l , w):\n l = int(l) #need to specify it as a integer otherwise it concatanets it and treats it as a string\n w = int(w)\n \n if l == w:\n return l*w \n else:\n return l+l+w+w", "def area_or_perimeter(l,w):\n if l==w:\n a=l*w\n return a\n else:\n b=l+w\n p=2*b\n return p\n", "def area_or_perimeter(l, w):\n return l*l if l==w else (l+w)*2\nprint((area_or_perimeter(4, 4)))\nprint((area_or_perimeter(6, 10)))\n \n", "def area_or_perimeter(l , w):\n if l == w:\n return pow(l,2)\n else:\n return (l+w) *2", "def area_or_perimeter(l, w):\n area = (l * w)\n perimeter = 2 * (l + w)\n if (l == w):\n return area\n else:\n return perimeter\n \n#BDD\n#Given length and width of a4-sided polygon\n#Find the area or perimeter\n#The polygon is a square or rectangle\n#If it is a square then return its area\n#If it is a rectangle then return its perimeter\n\n#pseudocode \n#Funtion that takes in a parameter of l and w\n#If square return Area\n#If rectangle return Perimeter\n", "def area_or_perimeter(l , w):\n if l==w:\n res=l*w\n else:\n res=2*l+2*w\n return res\n # return your answer\n", "def area_or_perimeter(l , w):\n return l==w and l**2 or 2*(l+w)", "def area_or_perimeter(l , w):\n if w == l:\n return l * w\n else:\n return (l * 2) + (w * 2)\n \n", "def area_or_perimeter(l , w):\n # return your answer\n if l == w:\n return(l*w)\n else:\n return(l+w+l+w)\nl=4\nw=4\nprint(l+w)", "def area_or_perimeter(l , w):\n if l == w:\n return l*w\n else:\n c = l*2\n b = w*2\n return c+b\n \n", "def area_or_perimeter(l , w):\n if w == l:\n return l * w\n else:\n return (l+w)*2", "def area_or_perimeter(l,\n w):\n\n if (l == w):\n\n return l * w\n\n return 2 * (l + w)\n", "def area_or_perimeter(l, w):\n if(l == w):\n print((w * l))\n return l * w\n else:\n print((2*l + 2*w))\n return 2*l + 2*w\n", "def area_or_perimeter(l , w):\n if l == w :\n return(l * w)\n else:\n return((l+w)*2)\n \narea_or_perimeter(4,4)", "def area_or_perimeter(l , w):\n if l==w:\n answer=l*w\n elif l!=w:\n answer=l+l+w+w\n return answer", "def area_or_perimeter(l , w):\n if l == w:\n res = l*w\n else:\n res = (l*2) + (w*2)\n return res", "def area_or_perimeter(l, w):\n # return your answer\n if l==w:\n return (l*w)\n else:\n return (2*(l+w))\n \n def area_or_perimeter(l , w):\n # return your answer\n if l==w:\n return (l*w)\n else:\n return (2*(l+w))\n \n \n", "def area_or_perimeter(l , w):\n length = l\n width = w\n if length == width:\n return length * width\n return (length + width) * 2", "def area_or_perimeter(l , w):\n # return your answer\n perimeter = 2*l + 2*w\n area = l * w\n if l == w:\n return area\n else:\n return perimeter\n \n \n", "def area_or_perimeter(l , w):\n # return your answer\n if l == w:\n area = l * w\n return area\n else:\n perimeter = l + l + w + w\n return perimeter\n \n return area_or_perimeter", "def area_or_perimeter(l , w):\n ans = (2*l) + (2*w)\n if l == w:\n ans = l*w\n return ans", "def area_or_perimeter(l, w):\n if l != w:\n return l*2 + w*2\n elif l == w:\n return l*w", "def area_or_perimeter(l , w):\n if l == w:\n square = l*w\n return square\n else:\n rectangle = (l*2) + (w*2)\n return rectangle", "def area_or_perimeter(l , w):\n if l==w:\n Square = l*w\n return Square\n else:\n Rectangle = (l+w)*2\n return Rectangle\n", "def area_or_perimeter(l , w):\n if l == w:\n answer = l*w\n else:\n answer = 2*(l+w)\n return answer"]
{"fn_name": "area_or_perimeter", "inputs": [[4, 4], [6, 10]], "outputs": [[16], [32]]}
INTRODUCTORY
PYTHON3
CODEWARS
13,883
def area_or_perimeter(l , w):
87dc46832b6174fabe5c7423a7316bed
UNKNOWN
Fast & Furious Driving School's (F&F) charges for lessons are as below: Time Cost Up to 1st hour $30 Every subsequent half hour** $10 ** Subsequent charges are calculated by rounding up to nearest half hour. For example, if student X has a lesson for 1hr 20 minutes, he will be charged $40 (30+10) for 1 hr 30 mins and if he has a lesson for 5 minutes, he will be charged $30 for the full hour. Out of the kindness of its heart, F&F also provides a 5 minutes grace period. So, if student X were to have a lesson for 65 minutes or 1 hr 35 mins, he will only have to pay for an hour or 1hr 30 minutes respectively. For a given lesson time in minutes (min) , write a function price to calculate how much the lesson costs.
["import math\n\ndef cost(mins):\n return 30 + 10 * math.ceil(max(0, mins - 60 - 5) / 30)", "from math import ceil\n\ndef cost(n):\n n -= 5\n \n if n<60 : return 30\n \n n -= 60\n \n return 30 + ceil(n/30) * 10", "def cost(mins):\n price = 0\n print (mins)\n while mins > 0:\n if mins <= 65:\n price += 30\n mins -= 65\n elif mins - 65 > 0:\n price += 10\n mins -= 30\n return price", "from math import ceil\n\ndef cost(mins):\n periods = ceil((mins - 5) / 30)\n return 30 if periods <= 2 else 30 + (periods - 2) * 10", "def cost(mins):\n return max(0, -(-(mins - 65)//30)) * 10 + 30", "import math\ndef cost(mins):\n return 30 if mins<60 else math.ceil(((mins-60)-5)/30)*10+30\n", "from math import ceil\n\ndef cost(minutes):\n return ceil(max(minutes + 25, 90) / 30) * 10\n", "import math\ndef cost(mins):\n \n if mins <= 60:\n return 30\n \n if mins > 60:\n if (mins % 30) <= 5:\n leftover = mins - 60\n multiple = round(leftover / 30)\n return 30 + (10 * (multiple))\n \n if (mins % 30) > 5:\n leftover = mins - 60\n multiple = math.ceil(leftover/30)\n return 30 + (10 * multiple)\n", "def cost(mins):\n price =30\n while mins > 60:\n mins-=30\n if mins>35:\n price+=10\n else:\n return price\n else:\n return price", "from math import ceil\ndef cost(n):\n return 30 + [ceil((n-65)/30)*10, 0][n<60]"]
{"fn_name": "cost", "inputs": [[45], [63], [84], [102], [273]], "outputs": [[30], [30], [40], [50], [100]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,581
def cost(mins):
9a830acbbc21f3619c86e385117e3dba
UNKNOWN
There exist two zeroes: +0 (or just 0) and -0. Write a function that returns `true` if the input number is -0 and `false` otherwise (`True` and `False` for Python). In JavaScript / TypeScript / Coffeescript the input will be a number. In Python / Java / C / NASM / Haskell / the input will be a float.
["def is_negative_zero(n):\n return str(n) == '-0.0'", "import math\ndef is_negative_zero(n):\n return n == 0 and math.copysign(1, n) == -1", "import math\n\ndef is_negative_zero(n):\n return math.atan2(-0.0, -0.0) == math.atan2(n, n)\n", "def is_negative_zero(n):\n return str(n) == str(-0.0)", "def is_negative_zero(n):\n return True if n == 0 and str(n).startswith('-') else False", "is_negative_zero=lambda n: n == 0 and str(n).startswith('-')", "def is_negative_zero(n):\n return str(n).startswith(\"-\") and n == 0", "def is_negative_zero(n):\n if str(n) == '-0.0':\n return 1\n else:\n return 0", "import struct\n\ndef is_negative_zero(n):\n return struct.pack('>d', n) == b'\\x80\\x00\\x00\\x00\\x00\\x00\\x00\\x00'", "is_negative_zero=lambda n:(str(n)[0]=='-')and not n"]
{"fn_name": "is_negative_zero", "inputs": [[-0.0], [-Infinity], [-5.0], [-4.0], [-3.0], [-2.0], [-1.0], [1.0], [2.0], [3.0], [4.0], [5.0], [Infinity]], "outputs": [[true], [false], [false], [false], [false], [false], [false], [false], [false], [false], [false], [false], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
821
def is_negative_zero(n):
3782715656887c098a8fcae83197d7ba
UNKNOWN
A generalization of Bézier surfaces, called the S-patch, uses an interesting scheme for indexing its control points. In the case of an n-sided surface of degree d, each index has n non-negative integers that sum to d, and all possible configurations are used. For example, for a 3-sided quadratic (degree 2) surface the control points are: > indices 3 2 => [[0,0,2],[0,1,1],[0,2,0],[1,0,1],[1,1,0],[2,0,0]] Given the degree and the number of sides, generate all control point indices. The order of the indices in the list can be arbitrary, so for the above example > [[1,1,0],[2,0,0],[0,0,2],[0,2,0],[0,1,1],[1,0,1]] is also a good solution.
["def gen(n, d):\n if d == 0 or n == 1:\n yield [d]*n\n else:\n for x in range(d+1):\n for y in gen(n-1, d-x):\n yield [x] + y\n\ndef indices(n, d):\n return list(gen(n, d))", "import itertools\ndef indices(n, d):\n return list(recurse(n,d, []))\n\ndef recurse(n, d, prefix):\n if n == 0:\n return prefix\n if n == 1:\n return [prefix + [d]]\n res = []\n for i in range(d+1):\n res += recurse(n-1, d-i, prefix + [i])\n return res\n\n", "def indices(n, d):\n return [[r] + point for r in range(d + 1)\n for point in indices(n-1, d-r)] if n > 1 else [[d]]\n", "import itertools \n\ndic={1:[[1]],2:[[2],[1,1]],3:[[3],[2,1],[1,1,1]],\n 4:[[4],[3,1],[2,1,1],[2,2],[1,1,1,1]],\n 5:[[5],[4,1],[3,1,1],[3,2],[2,1,1,1],[2,2,1],[1,1,1,1,1]],\n 6:[[6],[5,1],[4,1,1],[4,2],[3,1,1,1],[3,2,1],[3,3],[2,1,1,1,1],[2,2,1,1],[2,2,2],[1,1,1,1,1,1]],\n 7:[[7],[6,1],[5,1,1],[5,2],[4,1,1,1],[4,2,1],[4,3],[3,1,1,1,1],[3,2,1,1],[3,2,2],[3,3,1],[2,1,1,1,1,1],[2,2,1,1,1],[2,2,2,1],[1,1,1,1,1,1,1]],\n 8:[[8],[7,1],[6,1,1],[6,2],[5,1,1,1],[5,2,1],[5,3],[4,1,1,1,1],[4,2,1,1],[4,2,2],[4,3,1],[4,4],[3,1,1,1,1,1],[3,2,1,1,1],[3,2,2,1],[3,3,1,1],[2, 3, 3],[2,1,1,1,1,1,1],[2,2,1,1,1,1],[2,2,2,1,1],[2,2,2,2],[1,1,1,1,1,1,1,1]],\n 9:[[9],[8,1],[7,1,1],[7,2],[6,1,1,1],[6,2,1],[6,3],[5,1,1,1,1],[5,2,1,1],[5,2,2],[5,3,1],[5,4],[4,3,1, 1],[4,1,1,1,1,1],[4,2,1,1,1],[4,2,2,1],[4,2,3],[3,3,3],[3,3,1,1,1],[3,3,2,1],[3,1,1,1,1,1,1],[3,2,1,1,1,1],[3,2,2,1,1],[3,2,2,2],[4,4,1],[2,1,1,1,1,1,1,1],[2,2,1,1,1,1,1],[2,2,2,1,1,1],[2,2,2,2,1],[1,1,1,1,1,1,1,1,1]],\n \n }\n\n\ndef indices(n, d):\n print (n,d)\n l=[]\n original=[0]*n\n if not d:\n return [original]\n\n for i in dic[d]:\n if len(i)>n:\n continue\n t=i+[0]*(n-len(i))\n l.extend(list(set(list(itertools.permutations(t) ) )))\n print(\"c->\",sorted(l) )\n \n \n \n\n return map(list,l)", "def indices(n, d):\n result=[]\n temp=[]\n def tt (n, d,temp):\n if d==1:\n result.extend([temp+[n]])\n return 0\n for i in range(0,n+1):\n aa=temp+[i]\n tt(n-i, d-1,aa)\n tt(d, n,temp)\n return result", "def indices(n, d):\n if n == 1: return [[d]]\n if d == 0: return [[0 for i in range(n)]]\n sols = []\n for i in range(d+1):\n sols += [subsol + [i] for subsol in indices(n-1,d-i)]\n \n return sols\n raise NotImplementedError('todo')", "def indices(n, d):\n\n result = ([i] for i in range(d + 1)) # start with all possible lists of length 1 with sum within limit\n\n # until have lists of len n: add every possible num to each list in result that doesn't put over limit d\n for iteration in range(n - 1):\n result = (i + [j] for i in result for j in range(d + 1) if sum(i) + j <= d)\n\n return list(filter(lambda r: sum(r) == d, result)) # return combinations with sum d", "def indices(n, d):\n if n == 1:\n return [[d]]\n result = []\n for i in range(d+1):\n for x in indices(n-1, d-i):\n result.append([i] + x)\n return result\n", "def indices(n, d):\n if d<0:\n return []\n elif n==1:\n return [[d]]\n elif n==2:\n return [[i,d-i] for i in range(d+1)]\n else:\n return [[i]+p for i in range(d+1) for p in indices(n-1,d-i)]", "def indices(n, d):\n from itertools import combinations_with_replacement\n \n lst = []\n for c in combinations_with_replacement(range(n), d):\n base = [0]*n\n for i in c:\n base[i] += 1\n lst.append(base)\n return lst"]
{"fn_name": "indices", "inputs": [[1, 0], [3, 0]], "outputs": [[[[0]]], [[[0, 0, 0]]]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,726
def indices(n, d):
6ea108ebd683fe3e01801f3b6a9aa2a2
UNKNOWN
Given a long number, return all the possible sum of two digits of it. For example, `12345`: all possible sum of two digits from that number are: [ 1 + 2, 1 + 3, 1 + 4, 1 + 5, 2 + 3, 2 + 4, 2 + 5, 3 + 4, 3 + 5, 4 + 5 ] Therefore the result must be: [ 3, 4, 5, 6, 5, 6, 7, 7, 8, 9 ]
["from itertools import combinations\n\ndef digits(num):\n return list(map(sum, combinations(map(int,str(num)),2)))", "# Solution 1\ndef digits(num):\n return [int(a)+int(b) for i,a in enumerate(str(num)) for b in str(num)[(i+1):]]\n \n \n# Solution 2\ndef digits(num):\n from itertools import combinations\n return [int(a)+int(b) for a,b in combinations(str(num), 2)]", "from itertools import combinations\n\ndef digits(num):\n return [int(a) + int(b) for a, b in combinations(str(num), 2)]", "from itertools import combinations\n\ndef digits(num):\n return [sum(pair) for pair in combinations([int(d) for d in str(num)], 2)]\n", "from itertools import combinations\n\ndef digits(num):\n ns = list(map(int, str(num)))\n return [a+b for a, b in combinations(ns, 2)]", "def digits(num):\n num = str(num)\n return [int(x)+int(y) for n, x in enumerate(num,1) for y in num[n:]]\n", "def digits(num):\n return [int(x)+int(y) for i, x in enumerate(str(num)) for j, y in enumerate(str(num)) if j > i]", "def digits(num):\n ints = [int(i) for i in str(num)]\n sums = []\n for i in range(len(ints)-1):\n for j in ints[i+1:]:\n sums.append(ints[i] + j)\n return sums", "from itertools import combinations\n\ndef digits(num):\n lst = list(map(int, str(num)))\n return [a + b for a, b in combinations(lst, 2)]", "def digits(num):\n parse = lambda s: [int(s[0]) + int(x) for x in s[1:]] + (digits(s[1:]) if len(s) > 2 else [])\n return parse(str(num))\n"]
{"fn_name": "digits", "inputs": [[156], [81596], [3852], [3264128], [999999]], "outputs": [[[6, 7, 11]], [[9, 13, 17, 14, 6, 10, 7, 14, 11, 15]], [[11, 8, 5, 13, 10, 7]], [[5, 9, 7, 4, 5, 11, 8, 6, 3, 4, 10, 10, 7, 8, 14, 5, 6, 12, 3, 9, 10]], [[18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,521
def digits(num):
5035054290efa75f3ce9427d8141ac0c
UNKNOWN
Every Friday and Saturday night, farmer counts amount of sheep returned back to his farm (sheep returned on Friday stay and don't leave for a weekend). Sheep return in groups each of the days -> you will be given two arrays with these numbers (one for Friday and one for Saturday night). Entries are always positive ints, higher than zero. Farmer knows the total amount of sheep, this is a third parameter. You need to return the amount of sheep lost (not returned to the farm) after final sheep counting on Saturday. Example 1: Input: {1, 2}, {3, 4}, 15 --> Output: 5 Example 2: Input: {3, 1, 2}, {4, 5}, 21 --> Output: 6 Good luck! :-)
["def lostSheep(friday,saturday,total):\n return total - sum(friday+saturday)", "def lostSheep(friday,saturday,total):\n return total - sum(friday) - sum(saturday)", "def lostSheep(friday,saturday,total):\n sheeps = friday + saturday\n return total - sum(sheeps)", "def lostSheep(friday, saturday, total):\n return total - sum(saturday) - sum(friday)", "def lostSheep(friday,saturday,total):\n return total - (sum(friday) + sum(saturday))", "def lostSheep(friday,saturday,total):\n fritag = 0\n for number in friday:\n fritag = fritag + number\n samstag = 0\n for number in saturday:\n samstag = samstag + number\n return int(str(total)) - (fritag + samstag)\n\n", "def lostSheep(friday,saturday,total):\n sheep = 0\n for num in friday:\n sheep += num\n for num in saturday:\n sheep += num\n return total-sheep", "def lostSheep(friday,saturday,total):\n sheeps =0\n for i in range(len(friday)):\n sheeps+=friday[i]\n for i in range(len(saturday)):\n sheeps+=saturday[i]\n return total-sheeps", "def lostSheep(friday,saturday,total):\n s = total - (sum(friday) + sum(saturday))\n return s", "def lostSheep(friday,saturday,total):\n weekend_total = sum(friday) + sum(saturday)\n difference = total - weekend_total\n return difference"]
{"fn_name": "lostSheep", "inputs": [[[1, 2], [3, 4], 15], [[3, 1, 2], [4, 5], 21], [[5, 1, 4], [5, 4], 29], [[11, 23, 3, 4, 15], [7, 14, 9, 21, 15], 300], [[2, 7, 13, 17], [23, 56, 44, 12, 1, 2, 1], 255], [[2, 5, 8], [11, 23, 3, 4, 15, 112, 12, 4], 355], [[1, 1, 1, 2, 1, 2], [2, 1, 2, 1, 2, 1], 30], [[5, 10, 15], [11, 23, 3, 4, 15], 89], [[3, 6, 9, 12], [3, 2, 1, 2, 3, 1], 44]], "outputs": [[5], [6], [10], [178], [77], [156], [13], [3], [2]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,347
def lostSheep(friday,saturday,total):
6a27c8e0bc0da29f0f2f40819d7e2bc2
UNKNOWN
Given an array (arr) as an argument complete the function `countSmileys` that should return the total number of smiling faces. Rules for a smiling face: - Each smiley face must contain a valid pair of eyes. Eyes can be marked as `:` or `;` - A smiley face can have a nose but it does not have to. Valid characters for a nose are `-` or `~` - Every smiling face must have a smiling mouth that should be marked with either `)` or `D` No additional characters are allowed except for those mentioned. **Valid smiley face examples:** `:) :D ;-D :~)` **Invalid smiley faces:** `;( :> :} :]` ## Example ``` countSmileys([':)', ';(', ';}', ':-D']); // should return 2; countSmileys([';D', ':-(', ':-)', ';~)']); // should return 3; countSmileys([';]', ':[', ';*', ':$', ';-D']); // should return 1; ``` ## Note In case of an empty array return 0. You will not be tested with invalid input (input will always be an array). Order of the face (eyes, nose, mouth) elements will always be the same.
["from re import findall\ndef count_smileys(arr):\n return len(list(findall(r\"[:;][-~]?[)D]\", \" \".join(arr))))", "def count_smileys(arr):\n eyes = [\":\", \";\"]\n noses = [\"\", \"-\", \"~\"]\n mouths = [\")\", \"D\"]\n count = 0\n for eye in eyes:\n for nose in noses:\n for mouth in mouths:\n face = eye + nose + mouth\n count += arr.count(face)\n return count", "import re\n\ndef count_smileys(arr):\n return sum(1 for s in arr if re.match(r'\\A[:;][-~]?[)D]\\Z',s))", "def count_smileys(arr):\n import re\n smiley = re.compile(r\"[:;][-~]?[)D]\")\n return sum(bool(re.match(smiley, el)) for el in arr)", "def count_smileys(arr):\n count = 0\n if not arr:\n return 0\n smileys = [\":)\", \";)\", \":~)\", \";~)\", \":-)\", \";-)\", \":D\", \";D\", \":~D\", \";~D\", \":-D\", \";-D\"]\n for i in arr:\n if i in smileys:\n count += 1\n return count", "def count_smileys(arr):\n total = 0\n eyes = ':;'\n nose = '-~'\n mouth = ')D'\n for char in arr:\n\n if len(char) == 3:\n if char[0] in eyes and char[1] in nose and char[2] in mouth:\n total += 1\n\n elif len(char) == 2:\n if char[0] in eyes and char[1] in mouth:\n total += 1\n return total", "def count_smileys(arr):\n smiles = set([a+b+c for a in \":;\" for b in ['','-', '~'] for c in \")D\"])\n return len([1 for s in arr if s in smiles])", "valid = \":) :D :-) :-D :~) :~D ;) ;D ;-) ;-D ;~) ;~D\".split()\n\ndef count_smileys(arr):\n return sum(face in valid for face in arr)", "import re\ndef count_smileys(arr):\n count = 0\n for i in arr:\n p = re.compile(\"^[:;][-~]*[)D]\")\n if p.match(i):\n count += 1\n return count", "def count_smileys(arr):\n return len(list(filter(lambda x: x in [':D',':~D',':-D',';D',';~D',';-D',':)',':~)',':-)',';)',';~)',';-)'],arr)))"]
{"fn_name": "count_smileys", "inputs": [[[]], [[":D", ":~)", ";~D", ":)"]], [[":)", ":(", ":D", ":O", ":;"]], [[";]", ":[", ";*", ":$", ";-D"]]], "outputs": [[0], [4], [2], [1]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,977
def count_smileys(arr):
58303f89213020c6d1aca91d7d266ee9
UNKNOWN
It's the fourth quater of the Super Bowl and your team is down by 4 points. You're 10 yards away from the endzone, if your team doesn't score a touchdown in the next four plays you lose. On a previous play, you were injured and rushed to the hospital. Your hospital room has no internet, tv, or radio and you don't know the results of the game. You look at your phone and see that on your way to the hospital a text message came in from one of your teamates. It contains an array of the last 4 plays in chronological order. In each play element of the array you will receive the yardage of the play and the type of the play. Have your function let you know if you won or not. # What you know: * Gaining greater than 10 yds from where you started is a touchdown and you win. * Yardage of each play will always be a positive number greater than 0. * There are only four types of plays: "run", "pass", "sack", "turnover". * Type of plays that will gain yardage are: "run", "pass". * Type of plays that will lose yardage are: "sack". * Type of plays that will automatically lose the game are: "turnover". * When a game ending play occurs the remaining (plays) arrays will be empty. * If you win return true, if you lose return false. # Examples: [[8, "pass"],[5, "sack"],[3, "sack"],[5, "run"]] `false` [[12, "pass"],[],[],[]]) `true` [[2, "run"],[5, "pass"],[3, "sack"],[8, "pass"]] `true` [[5, "pass"],[6, "turnover"],[],[]] `false` Good Luck!
["def did_we_win(plays):\n plays = [p for p in plays if p]\n return all(p != 'turnover' for y,p in plays) and sum(-y if p == 'sack' else y for y,p in plays) > 10 ", "def did_we_win(plays):\n s = 0\n for i in range(4):\n if not plays[i]: break\n if plays[i][1] == \"turnover\": return False\n s += plays[i][0] * (-1)**(plays[i][1] == \"sack\")\n return s > 10", "def did_we_win(plays):\n dist = 10\n plays = [t for t in plays if t]\n for play_dist, play in plays:\n if play in ['run', 'pass']:\n dist -= play_dist\n if dist < 0:\n return True\n elif play == 'sack':\n dist += play_dist\n else:\n # Turnover\n break\n return False", "def did_we_win(plays):\n return sum(-100 if p[1][0] == \"t\" else -p[0] if p[1][0] == \"s\" else p[0] for p in plays if p) > 10\n", "def did_we_win(plays):\n if any(play[1] == \"turnover\" or not play for play in plays if play):\n return False\n if not all(plays):\n return True\n return sum(-yards if action == \"sack\" else yards for yards, action in plays) > 10\n", "def did_we_win(plays):\n r = 0\n for p in plays:\n if not p:\n continue\n yd, t = p\n if t in ('run', 'pass'):\n r += yd\n elif t == 'sack':\n r -= yd\n elif t == 'turnover':\n return False\n if r > 10:\n return True\n return False\n", "def did_we_win(plays):\n yard = 0\n for number, type_play in plays:\n if type_play == \"pass\": win=number\n elif type_play == \"run\": win=number\n elif type_play == \"sack\": win=-number\n elif type_play == \"turnover\": return False; break\n yard = yard + win\n if yard>10: return True; break\n if yard>10: return True\n else: return False", "def did_we_win(plays):\n position = 0\n for play in plays:\n if play[1] == 'run' or play[1] == 'pass':\n position += play[0]\n elif play[1] == 'sack':\n position -= play[0]\n else:\n return False\n if position > 10:\n return True\n return False", "def did_we_win(plays):\n yds = 10\n for play in plays:\n if play[1] == \"turnover\":\n return False\n if play[1] == \"sack\":\n yds += play[0]\n else:\n yds -= play[0]\n if yds < 0:\n return True\n return False", "def did_we_win(plays):\n #print(plays)\n increment = [\"pass\",\"run\"]\n decrement = [\"sack\"]\n gameOver = [\"turnover\"]\n score = plays[0][0]\n for x in plays:\n if(x):\n if x[1] in increment:\n score += x[0]\n elif x[1] in decrement:\n score -= x[0]\n else:\n return False\n if (score - plays[0][0]) > 10:\n return True\n else:\n return False\n"]
{"fn_name": "did_we_win", "inputs": [[[[8, "pass"], [5, "sack"], [3, "sack"], [5, "run"]]], [[[12, "pass"], [], [], []]], [[[2, "run"], [5, "pass"], [3, "sack"], [8, "pass"]]], [[[5, "pass"], [6, "turnover"], [], []]], [[[5, "pass"], [5, "pass"], [10, "sack"], [10, "run"]]], [[[5, "pass"], [5, "run"], [1, "run"], []]], [[[6, "run"], [7, "sack"], [10, "sack"], [23, "pass"]]], [[[10, "turnover"], [], [], []]], [[[8, "sack"], [5, "sack"], [6, "sack"], [30, "run"]]], [[[3, "run"], [3, "run"], [3, "run"], [10, "turnover"]]], [[[20, "sack"], [10, "run"], [10, "sack"], [35, "run"]]], [[[10, "run"], [10, "sack"], [10, "pass"], [1, "sack"]]], [[[8, "pass"], [3, "pass"], [], []]], [[[3, "pass"], [5, "pass"], [8, "turnover"], []]], [[[2, "run"], [2, "pass"], [2, "run"], [2, "pass"]]], [[[1, "pass"], [6, "pass"], [8, "pass"], []]], [[[9, "run"], [1, "run"], [3, "turnover"], []]]], "outputs": [[false], [true], [true], [false], [false], [true], [true], [false], [true], [false], [true], [false], [true], [false], [false], [true], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,020
def did_we_win(plays):
29196cc3ad8b56375e518f8bb0864d9c
UNKNOWN
A friend of mine told me privately: "I don't like palindromes". "why not?" - I replied. "Because when I want to do some programming challenges, I encounter 2 or 3 ones first related with palindromes. I'm fed up" - he confess me with anger. I said to myself:"Thankfully, that doesn't happen in Codewars". Talking seriously, we have to count the palindrome integers. Doing that, perhaps, it will help us to make all the flood of palindrome programming challenges more understandable. For example all the integers of 1 digit (not including 0) are palindromes, 9 cases. We have nine of them with two digits, so the total amount of palidromes below ```100``` (10^(2)) is ```18```. At least, will we be able to calculate the amount of them for a certain number of digits? Let's say for ```2000``` digits? Prepare a code that given the number of digits ```n```, may output the amount of palindromes of length equals to n and the total amount of palindromes below 10^(n). You will see more examples in the box. Happy coding!! (You don't know what palindromes are? Investigate, :))
["def count_pal(n):\n # No recursion; direct calculation:\n return [9 * 10**((n-1) // 2), 10**(n // 2) * (13 - 9 * (-1)**n) // 2 - 2]", "def count_pal(n):\n x = lambda y: 9 * int(10 ** ((y - 1)//2))\n return [x(n), sum(x(i) for i in range(n+1))]", "from itertools import accumulate\n\nN_PALS = [0] + [9 * 10**((n-1)//2) for n in range(1,2001)]\nS_PALS = list(accumulate(N_PALS))\n\ndef count_pal(n):\n return [N_PALS[n], S_PALS[n]]", "def count_pal(n):\n pal = lambda n: 9 * 10**((n-1)//2)\n return [pal(n), sum(pal(i) for i in range(1, n+1))]", "from functools import lru_cache\n\n@lru_cache(maxsize=None)\ndef count_pal(n):\n if n == 0: return [0, 0]\n current = 9 * 10**(n-1>>1)\n previous = count_pal(n-1)[1]\n return [current, current+previous]", "count_pal=lambda n:[int('9'+'0'*(n//2-int(not n&1))),int([['1','10'][n&1]+'9'*(n//2-1)+'8','9'][n==1])]", "def count_pal(n): # amount of digits\n res = '1' + ('0' * n)\n temp = '9'\n l = []\n for x in range(1, len(res[1:])+1, 2):\n q = res[x:x+2]\n for _ in q:\n l.append(temp)\n temp += '0'\n return [int(l[-1]), sum(int(x) for x in l)]", "def count_pal(n):\n total = 0\n \n for i in range(n):\n n_digit = 9 * 10**(i//2)\n total += n_digit\n \n return [n_digit, total]", "count_pal=lambda n:[10**(n-1>>1)*9,10**(n-1>>1)*(20-n%2*9)-2]"]
{"fn_name": "count_pal", "inputs": [[1], [2], [3], [4], [5], [10], [30], [50], [70]], "outputs": [[[9, 9]], [[9, 18]], [[90, 108]], [[90, 198]], [[900, 1098]], [[90000, 199998]], [[900000000000000, 1999999999999998]], [[9000000000000000000000000, 19999999999999999999999998]], [[90000000000000000000000000000000000, 199999999999999999999999999999999998]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,399
def count_pal(n):
0adeef4e36c0b50f1cd6f3d5dac43be7
UNKNOWN
Alice and Bob have participated to a Rock Off with their bands. A jury of true metalheads rates the two challenges, awarding points to the bands on a scale from 1 to 50 for three categories: Song Heaviness, Originality, and Members' outfits. For each one of these 3 categories they are going to be awarded one point, should they get a better judgement from the jury. No point is awarded in case of an equal vote. You are going to receive two arrays, containing first the score of Alice's band and then those of Bob's. Your task is to find their total score by comparing them in a single line. Example: Alice's band plays a Nirvana inspired grunge and has been rated ``20`` for Heaviness, ``32`` for Originality and only ``18`` for Outfits. Bob listens to Slayer and has gotten a good ``48`` for Heaviness, ``25`` for Originality and a rather honest ``40`` for Outfits. The total score should be followed by a colon ```:``` and by one of the following quotes: if Alice's band wins: ```Alice made "Kurt" proud!``` if Bob's band wins: ```Bob made "Jeff" proud!``` if they end up with a draw: ```that looks like a "draw"! Rock on!``` The solution to the example above should therefore appear like ``'1, 2: Bob made "Jeff" proud!'``.
["def solve(a, b):\n alice = sum(i > j for i, j in zip(a, b))\n bob = sum(j > i for i, j in zip(a, b))\n \n if alice == bob:\n words = 'that looks like a \"draw\"! Rock on!'\n elif alice > bob:\n words = 'Alice made \"Kurt\" proud!'\n else:\n words = 'Bob made \"Jeff\" proud!'\n \n return '{}, {}: {}'.format(alice, bob, words) ", "def solve(a, b):\n s, n = 0, 0\n for x,y in zip(a, b):\n if x>y: n+=1\n elif x<y: s+=1\n if s!=n:\n return f'{n}, {s}: {\"Alice\" if s<n else \"Bob\"} made \"{\"Kurt\" if s<n else \"Jeff\"}\" proud!'\n return f'{n}, {s}: that looks like a \"draw\"! Rock on!'", "def solve(a, b):\n sa = sum(1 for x, y in zip(a,b) if x > y)\n sb = sum(1 for x, y in zip(a,b) if y > x)\n return '{}, {}: {}'.format(sa, sb, 'that looks like a \"draw\"! Rock on!' if sa == sb else ['Bob made \"Jeff\" proud!', 'Alice made \"Kurt\" proud!'][sa > sb] )", "from operator import gt\nfrom numpy import sign\nresult = {\n -1:'Bob made \"Jeff\" proud!',\n 0:'that looks like a \"draw\"! Rock on!',\n 1:'Alice made \"Kurt\" proud!'}\n\ndef solve(a, b):\n alice = sum(map(gt, a, b))\n bob = sum(map(gt, b, a))\n return f'{alice}, {bob}: {result[sign(alice - bob)]}'", "def solve(a, b):\n x=sum([ 1 for i in range(3) if a[i]>b[i] ])\n y=sum([ 1 for i in range(3) if a[i]<b[i] ])\n if x>y:\n return f'{x}, {y}: Alice made \"Kurt\" proud!'\n elif x<y:\n return f'{x}, {y}: Bob made \"Jeff\" proud!'\n else: return f'{x}, {y}: that looks like a \"draw\"! Rock on!'", "def solve(a, b):\n A = sum (x > y for x,y in zip(a,b))\n B = sum (x < y for x,y in zip(a,b))\n winner,name = ('Alice','Kurt') if A > B else ('Bob','Jeff')\n return '{}, {}: that looks like a \"draw\"! Rock on!'.format(A,B) if A == B \\\n else '{}, {}: {} made \"{}\" proud!'.format(str(A),str(B),winner,name)", "def solve(a, b):\n alis = 0\n bob = 0\n for i in range(3):\n if(a[i]>b[i]):\n alis+=1\n elif(a[i]<b[i]):\n bob+=1\n if(alis==bob):\n return str(bob)+\", \"+str(alis)+\":\"+' that looks like a \"draw\"! Rock on!'\n elif(max(alis,bob)==alis):\n return str(alis)+\", \"+str(bob)+\":\"+' Alice made \"Kurt\" proud!'\n else:\n return str(alis)+\", \"+str(bob)+\":\"+' Bob made \"Jeff\" proud!'\n", "def solve(a, b):\n alice = sum(x > y for x, y in zip(a, b))\n bob = sum(x < y for x, y in zip(a, b))\n return (\n '{}, {}: Alice made \"Kurt\" proud!' if alice > bob else\n '{}, {}: Bob made \"Jeff\" proud!' if alice < bob else\n '{}, {}: that looks like a \"draw\"! Rock on!'\n ).format(alice, bob)", "def solve(a, b):\n count_A = 0\n count_B = 0\n for i in range(len(a)):\n if a[i] > b[i]:\n count_A += 1\n elif a[i] < b[i]:\n count_B += 1\n return f'{count_A}, {count_B}: that looks like a \"draw\"! Rock on!'if count_A == count_B else f'{count_A}, {count_B}: Alice made \"Kurt\" proud!'if count_A > count_B else f'{count_A}, {count_B}: Bob made \"Jeff\" proud!'", "def solve(a, b):\n countA = 0\n countB = 0\n for i in range(len(a)):\n if a[i] > b[i]:\n countA += 1\n elif a[i] < b[i]:\n countB += 1\n return f'{countA}, {countB}: that looks like a \"draw\"! Rock on!'if countA == countB else f'{countA}, {countB}: Alice made \"Kurt\" proud!' if countA > countB else f'{countA}, {countB}: Bob made \"Jeff\" proud!'", "def solve(a, b):\n table_score = {'Player1': 0,\n 'Player2': 0}\n\n for i, s in enumerate(a):\n if s > b[i]:\n table_score['Player1'] += 1\n if s < b[i]:\n table_score['Player2'] += 1\n\n if table_score['Player1'] == table_score ['Player2']:\n return \"\"\"{0}, {1}: that looks like a \"draw\"! Rock on!\"\"\".format(table_score['Player1'], table_score['Player2'])\n\n if table_score['Player1'] > table_score['Player2']:\n return \"\"\"{0}, {1}: Alice made \"Kurt\" proud!\"\"\".format(table_score['Player1'], table_score['Player2'])\n\n if table_score['Player1'] < table_score['Player2']:\n return \"\"\"{0}, {1}: Bob made \"Jeff\" proud!\"\"\".format(table_score['Player1'], table_score['Player2'])", "def solve(a, b):\n A = sum (x > y for x,y in zip(a,b))\n B = sum (x < y for x,y in zip(a,b))\n return '{}, {}: '.format(str(A),str(B)) + \\\n ('that looks like a \"draw\"! Rock on!' if A == B else \\\n ['Alice made \"Kurt\" proud!','Bob made \"Jeff\" proud!'][ A < B]) \n # copied this last bit from daddepledge's solution. Neat!\n", "def solve(a, b):\n c1=0\n c2=0\n for i in range(len(a)):\n if (a[i]>b[i]):\n c1+=1\n elif (a[i]==b[i]):\n pass\n else:\n c2+=1\n if(c1==c2):\n return(\"{}, {}: that looks like a \\\"draw\\\"! Rock on!\".format(c1,c2))\n elif(c1>c2):\n return(\"{}, {}: Alice made \\\"Kurt\\\" proud!\".format(c1,c2))\n else:\n return(\"{}, {}: Bob made \\\"Jeff\\\" proud!\".format(c1,c2))\n \n", "def solve(a, b):\n alice = sum (x > y for x,y in zip(a,b))\n bob = sum (x < y for x,y in zip(a,b))\n if alice > bob:\n return '%s, %s: Alice made \"Kurt\" proud!' % (alice, bob)\n elif bob > alice:\n return '%s, %s: Bob made \"Jeff\" proud!' % (alice, bob)\n else:\n return '%s, %s: that looks like a \"draw\"! Rock on!' % (alice, bob)\n", "def solve(a, b):\n alic = 0\n bob = 0\n for i in range(3):\n if(a[i] > b[i]):\n alic+=1\n elif(a[i]<b[i]):\n bob+=1\n if (alic == bob):\n return str(bob)+\", \"+str(alic)+\":\"+' that looks like a \"draw\"! Rock on!'\n elif (max(alic,bob) == alic):\n return str(alic)+\", \"+str(bob)+\":\"+' Alice made \"Kurt\" proud!'\n else:\n return str(alic)+\", \"+str(bob)+\":\"+' Bob made \"Jeff\" proud!'\n", "def solve(a, b):\n a_count = 0\n b_count = 0\n for i in range(len(a)):\n if a[i] > b[i]:\n a_count += 1\n elif a[i] < b[i]:\n b_count += 1\n if a_count > b_count:\n return \"{a_count}, {b_count}: Alice made \\\"Kurt\\\" proud!\".format(a_count=a_count, b_count=b_count)\n elif b_count > a_count:\n return \"{a_count}, {b_count}: Bob made \\\"Jeff\\\" proud!\".format(a_count=a_count, b_count=b_count)\n else:\n return \"{a_count}, {b_count}: that looks like a \\\"draw\\\"! Rock on!\".format(a_count = a_count, b_count = b_count)", "def solve(a, b):\n Alice=0\n Bob=0\n for i in range(0, len(a)):\n if(a[i]>b[i]):\n Alice+=1\n elif(a[i]<b[i]):\n Bob+=1\n if(Alice>Bob):\n return('{0}, {1}: Alice made \"Kurt\" proud!'.format(Alice,Bob))\n elif(Alice<Bob):\n return('{0}, {1}: Bob made \"Jeff\" proud!'.format(Alice,Bob))\n else:\n return('{0}, {1}: that looks like a \"draw\"! Rock on!'.format(Alice,Bob))\n", "def solve(a, b):\n al= 0\n bo= 0\n for i in range(0,len(a)):\n if a[i]>b[i]:\n al+=1\n elif a[i]<b[i]:\n bo+=1\n if(al>bo):\n return('{0}, {1}: Alice made \"Kurt\" proud!'.format(al,bo))\n elif(al<bo):\n return('{0}, {1}: Bob made \"Jeff\" proud!'.format(al,bo))\n else:\n return('{0}, {1}: that looks like a \"draw\"! Rock on!'.format(al,bo))", "def solve(a, b):\n x=0\n y=0\n for i in range(0,len(a)):\n if a[i]==b[i]:\n pass\n elif a[i]>b[i]:\n x+=1\n else:\n y+=1\n if x==y:\n return '{}, {}: that looks like a \"draw\"! Rock on!'.format(x,y)\n elif x>y:\n return '{}, {}: Alice made \"Kurt\" proud!'.format(x,y)\n else:\n return '{}, {}: Bob made \"Jeff\" proud!'.format(x,y)", "def solve(a, b):\n count_a = 0\n count_b = 0\n for i in range(len(a)):\n if a[i] > b[i]:\n count_a +=1\n elif a[i] < b[i]:\n count_b +=1\n return f'{count_a}, {count_b}: that looks like a \"draw\"! Rock on!' if count_a == count_b else f'{count_a}, {count_b}: Alice made \"Kurt\" proud!' if count_a > count_b else f'{count_a}, {count_b}: Bob made \"Jeff\" proud!'"]
{"fn_name": "solve", "inputs": [[[47, 7, 2], [47, 7, 2]], [[47, 50, 22], [26, 47, 12]], [[25, 50, 22], [34, 49, 50]], [[8, 8, 11], [3, 8, 10]], [[20, 32, 18], [48, 25, 40]], [[5, 6, 7], [3, 6, 10]], [[21, 39, 15], [50, 1, 12]], [[0, 1, 2], [1, 2, 0]]], "outputs": [["0, 0: that looks like a \"draw\"! Rock on!"], ["3, 0: Alice made \"Kurt\" proud!"], ["1, 2: Bob made \"Jeff\" proud!"], ["2, 0: Alice made \"Kurt\" proud!"], ["1, 2: Bob made \"Jeff\" proud!"], ["1, 1: that looks like a \"draw\"! Rock on!"], ["2, 1: Alice made \"Kurt\" proud!"], ["1, 2: Bob made \"Jeff\" proud!"]]}
INTRODUCTORY
PYTHON3
CODEWARS
8,381
def solve(a, b):
f3b1d8f67ec2d5522f64535cb13adb53
UNKNOWN
Late last night in the Tanner household, ALF was repairing his spaceship so he might get back to Melmac. Unfortunately for him, he forgot to put on the parking brake, and the spaceship took off during repair. Now it's hovering in space. ALF has the technology to bring the spaceship home if he can lock on to its location. Given a map: ```` .......... .......... .......... .......X.. .......... .......... ```` The map will be given in the form of a string with \n separating new lines. The bottom left of the map is [0, 0]. X is ALF's spaceship. In this example: If you cannot find the spaceship, the result should be ``` "Spaceship lost forever." ``` Can you help ALF? Check out my other 80's Kids Katas: 80's Kids #1: How Many Licks Does It Take 80's Kids #2: Help Alf Find His Spaceship 80's Kids #3: Punky Brewster's Socks 80's Kids #4: Legends of the Hidden Temple 80's Kids #5: You Can't Do That on Television 80's Kids #6: Rock 'Em, Sock 'Em Robots 80's Kids #7: She's a Small Wonder 80's Kids #8: The Secret World of Alex Mack 80's Kids #9: Down in Fraggle Rock 80's Kids #10: Captain Planet
["def find_spaceship(astromap):\n lines = astromap.splitlines()\n for y, line in enumerate(lines):\n x = line.find('X')\n if x != -1:\n return [x, len(lines) - 1 - y]\n return 'Spaceship lost forever.'\n", "def find_spaceship(astromap):\n for a, row in enumerate(reversed(astromap.split('\\n'))):\n for b, col in enumerate(row):\n if col == 'X':\n return [b, a]\n return 'Spaceship lost forever.'\n", "def find_spaceship(astromap):\n astromap = astromap.split('\\n')\n astromap.reverse()\n for i in range(len(astromap)):\n if 'X' in astromap[i]:\n return [astromap[i].index('X'), i]\n return 'Spaceship lost forever.'", "def find_spaceship(amap):\n a=amap.split('\\n')[::-1]\n for i in a:\n if 'X' in i:\n return[ i.index('X') , a.index(i) ]\n return \"Spaceship lost forever.\"", "def find_spaceship(astromap):\n arr = astromap.split('\\n')[::-1]\n for i in range(len(arr)):\n print(arr[i])\n for j in range(len(arr[i])):\n if arr[i][j] == 'X': return [j, i]\n return \"Spaceship lost forever.\"", "def find_spaceship(astromap):\n try: return next([j, i] for i,row in enumerate(reversed(astromap.split('\\n'))) for j,c in enumerate(row) if c == 'X')\n except: return \"Spaceship lost forever.\"", "find_spaceship=lambda m:\"Spaceship lost forever.\"*('X'not in m)or(lambda x=m.find('X'):[x-1-m[:x].rfind('\\n'),m[x:].count('\\n')])()", "def find_spaceship(astromap):\n return next(([j, i]\n for i, row in enumerate(astromap.splitlines()[::-1])\n for j, x in enumerate(row)\n if x == 'X'\n ), 'Spaceship lost forever.')", "from typing import List, Union\n\n\ndef find_spaceship(astromap: str) -> Union[List[int], str]:\n return next(([x, y] for y, r in enumerate(reversed(astromap.splitlines())) for x, c in enumerate(r) if c == 'X'),\n \"Spaceship lost forever.\")\n"]
{"fn_name": "find_spaceship", "inputs": [["X"], ["X\n."], [".X\n.."], ["..\n.X"], ["..\nX."], [".......\nX......."], ["..........\n..........\n.......X..\n..........\n.........."], ["..........\n..........\n..........\n........X.\n.........."], ["........................"], ["\n\n\n\n"]], "outputs": [[[0, 0]], [[0, 1]], [[1, 1]], [[1, 0]], [[0, 0]], [[0, 0]], [[7, 2]], [[8, 1]], ["Spaceship lost forever."], ["Spaceship lost forever."]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,984
def find_spaceship(astromap):
7704ecb40b7457083c07e9db82305d81
UNKNOWN
### Combine strings function ```if:coffeescript,haskell,javascript Create a function named `combineNames` that accepts two parameters (first and last name). The function should return the full name. ``` ```if:python,ruby Create a function named (`combine_names`) that accepts two parameters (first and last name). The function should return the full name. ``` ```if:csharp Create a function named (`Combine_names`) that accepts two parameters (first and last name). The function should return the full name. ``` Example: ```python combine_names('James', 'Stevens') ``` returns: ```python 'James Stevens' ```
["def combine_names(first, last):\n return first + \" \" + last", "def combine_names(*args):\n return ' '.join(args)\n", "def combine_names(first, second):\n return '{} {}'.format(first, second)", "def combine_names(a,b):\n return '%s %s' %(a,b)", "def combine_names(*ns): return ' '.join(ns)", "# Create the combine_names function here\ndef combine_names(first_name: str, last_name: str) -> str:\n return f'{first_name} {last_name}'", "def combine_names(first, last):\n return '{:s} {:s}'.format(first, last)", "def combine_names(one, two):\n assert isinstance(one, str)\n assert isinstance(two, str)\n return one+' '+two", "def combine_names(first, last):\n return ' '.join([first, last])", "def combine_names(n1, n2):\n return n1+' '+n2", "# Create the combine_names function here\ndef combine_names(a,b):\n return a+' '+b\n", "# Create the combine_names function here\ndef combine_names(first, last):\n return '''%s %s''' % (first, last)", "combine_names = lambda *x: \" \".join(x)", "def combine_names(*string):\n return ' '.join(string)", "combine_names = lambda x,y: \" \".join([x,y])", "def combine_names(*names):\n return ' '.join(names)", "combine_names=lambda*n:' '.join(n)", "def combine_names(first_name, last_name):\n return \"{0} {1}\".format(first_name, last_name)", "# Create the combine_names function here\ndef combine_names(f,l):\n return ' '.join([f,l])", "def combine_names(wa,wb):\n return wa + ' ' + wb", "combine_names = lambda *args: \" \".join(args)", "combine_names = '{} {}'.format", "combine_names = lambda *a: \" \".join(a)", "from typing import Tuple\n\ndef combine_names(*args: Tuple[str]) -> str:\n \"\"\" Get a full name containing two parameters (first and last name). \"\"\"\n return \" \".join(args)", "def combine_names(n,n2):\n return n + \" \" + n2 ", "def combine_names(name,f_name):\n return name +\" \"+ f_name", "def combine_names(n1,n2):\n return str(n1) + \" \" + str(n2)", "def combine_names(f1,f2):# Create the combine_names function here\n return f1 + ' ' + f2", "def combine_names(first, last):\n first = first\n last = last\n answer = first + ' ' + last \n return answer ", "def combine_names(name:str,nik:str)->str:\n result:str = name + \" \" + nik\n return result ", "combine_names = lambda name,surname:f\"{name} {surname}\"", "def combine_names(names,names2):\n return names + ' '+names2", "def combine_names(s1,s2):\n return (str(s1)+ \" \" + str(s2))\n# Create the combine_names function here\n", "def combine_names(fist, last_name):\n return fist + ' ' + last_name", "def combine_names(f,l):\n return f\"{f} {l}\"", "def combine_names(name, name2):\n return str(name)+\" \"+str(name2)", "def combine_names(*args: str) -> str:\n return \" \".join(args)", "def combine_names(*arr):\n return ' '.join(arr)", "def combine_names(first, second):\n return f\"{first} {second}\"", "def combine_names(x,x1):\n name = x + \" \" + x1\n return name", "combine_names = lambda first_name, last_name: first_name + \" \" + last_name", "# Create the combine_names function here\ndef combine_names(name, nickname):\n return name + \" \"+ nickname", "def combine_names(x, a):\n return x + ' '+ a", "# Create the combine_names function here\ndef combine_names(z,x):\n l = z + \" \" + x\n return l", "# Create the combine_names function here\ndef combine_names(j,k):\n return j+' '+ k", "def combine_names(*names):\n # the * takes in all the input\n return \" \".join(names)\n # .join joins the two strings\n", "def combine_names(F,L):\n return F +\" \" + L", "def combine_names(fname: str, lname: str) -> str:\n return fname + \" \" + lname", "def combine_names(first_name:str, last_name:str):\n return f'{first_name} {last_name}'", "def combine_names(name, lastname):\n return \"{} {}\".format(name, lastname)", "def combine_names(name,last):\n return name+\" \"+last", "def combine_names(first, last):\n '''Combines first and last names into a single properly formatted name.'''\n return ' '.join([first, last])", "def combine_names(*parts):\n return ' '.join(parts)", "def combine_names(*a):\n return '{0} {1}'.format(*a)", "def combine_names(n,p):\n return n + \" \" + p", "def combine_names(p1, p2):\n return p1 + ' ' + p2", "def combine_names(f,l):\n return \" \".join((f,l))", "combine_names = lambda *n : ' '.join(list(n))", "# Create the combine_names function here\ndef combine_names(name, surname):\n comb_names = name + ' ' + surname\n return comb_names", "def combine_names(fname, lname):\n res = \"{} {}\".format(fname, lname)\n return res", "combine_names = lambda x, y: f'{x} {y}'", "combine_names = lambda f,l : f'{f} {l}'", "# Create the combine_names function here\ndef combine_names(firstname, lastname ):\n return f'{firstname} {lastname}'", "def combine_names(x, y):\n return \"{0} {1}\".format(x, y)", "def combine_names(first, second):\n return \" \".join([first, second])", "def combine_names(*args):\n return \" \".join([*args]) ", "combine_names = lambda n, m: f\"{n} {m}\"", "def combine_names(fore, sur):\n return '{} {}'.format(fore, sur)", "# Create the combine_names function here\ndef combine_names(name1, name2):\n whole = name1 + ' ' + name2\n return whole", "def combine_names(surname, name):\n return '{} {}'.format(surname, name)", "def combine_names(x,y):\n return f'{x} {y}'", "def combine_names(fn, ls):\n return fn + \" \"+ ls", "def combine_names(name1,name2):\n return str(name1 + ' ' + name2)\n\n\n", "def combine_names(fn, ln):\n return f\"{fn} {ln}\"", "# Create the combine_names function here\ndef combine_names(first, last):\n j = first + ' ' + last\n return j\n\ncombine_names('James', 'Stevens')", "def combine_names (first_name, last_name):\n first_name = first_name + \" \"\n return first_name + last_name", "def combine_names(fname, lname):\n return f\"{fname} {lname}\"", "def combine_names(name1,name2):\n \n full_name = \"{} {}\".format(name1, name2)\n \n return full_name", "# Combines 'first' and 'last'\ndef combine_names(first, last):\n return f\"{first} {last}\" # Returns a full-ish name\n", "def combine_names(name, surname):\n a = name + \" \" + surname \n return a"]
{"fn_name": "combine_names", "inputs": [["James", "Stevens"], ["Davy", "Back"], ["Arthur", "Dent"]], "outputs": [["James Stevens"], ["Davy Back"], ["Arthur Dent"]]}
INTRODUCTORY
PYTHON3
CODEWARS
6,326
def combine_names(first, last):
c56824adc3a28fa869b4c3ea78d95b06
UNKNOWN
Let's assume we need "clean" strings. Clean means a string should only contain letters `a-z`, `A-Z` and spaces. We assume that there are no double spaces or line breaks. Write a function that takes a string and returns a string without the unnecessary characters. ### Examples ```python remove_chars('.tree1') ==> 'tree' remove_chars("that's a pie$ce o_f p#ie!") ==> 'thats a piece of pie' remove_chars('[email protected]') ==> 'johndopedopingtoncom' remove_chars('my_list = ["a","b","c"]') ==> 'mylist abc' remove_chars('1 + 1 = 2') ==> ' ' (string with 4 spaces) remove_chars("0123456789(.)+,|[]{}=@/~;^$'<>?-!*&:#%_") ==> '' (empty string) ```
["import re\n\ndef remove_chars(s):\n return re.sub(r'[^a-zA-Z ]', '', s)", "def remove_chars(s):\n return \"\".join( c for c in s if c.isalpha() or c==\" \" )", "import re\ndef remove_chars(s):\n return re.sub(r'[^A-Za-z\\s]','',s)", "def remove_chars(s):\n return \"\".join(list(i for i in s if i.isalpha() or i.isspace()))", "import re\n\ndef remove_chars(s):\n return re.sub(r\"[^a-zA-Z\\s]\", \"\", s)", "def remove_chars(s):\n return ''.join(c for c in s if c.isalpha() or c.isspace())", "import re\n\ndef remove_chars(s):\n return re.sub('(?i)[^a-z ]', '', s)", "import re\ndef remove_chars(s):\n return re.sub(r'(?i)[^a-z ]', \"\", s)", "def remove_chars(s):\n return ''.join(c for c in s if c.isspace() or c.isalpha())", "import re\nremove_chars = lambda s: re.sub('[^a-z A-Z]','',s)\n", "import re\nremove_chars = lambda s: re.sub('[^a-zA-Z\\ ]', '', s)\n", "def remove_chars(s):\n w = \"\"\n for c in s:\n if c.isalpha() or c == \" \":\n w += c\n return w", "def remove_chars(s):\n letters = \"abcdefghijklmnopqrstuvwxyz \"\n return \"\".join([i for i in s if i in letters or i in letters.upper()])", "import re\n\ndef remove_chars(s):\n s = re.sub('\\W+', ' ', re.sub('[^A-Za-z]+', '', re.sub('[\\s]', 'SSSSSSSSSS', s)))\n return re.sub('[S]{10}', ' ', s)", "def remove_chars(s):\n for x in s:\n if x != ' ':\n if not x.isalpha():\n s = s.replace(x,'')\n return s", "import re\ndef remove_chars(string):\n '''Pattern is anything BUT a-zA-Z and whitespace '''\n pattern = r'[^a-zA-Z\\s]'\n newstr = re.sub(pattern, \"\", string)\n return newstr\n \n", "def remove_chars(s):\n import string\n return ''.join(c for c in s if c == ' ' or c in string.ascii_letters)", "import re\n\ndef remove_chars(s):\n return re.sub(r\"[^a-zA-Z\\ ]\",\"\",s)", "def remove_chars(s):\n import re\n return re.sub('[^a-zA-Z\\s]', '', s)", "def remove_chars(s):\n # without importing string or re and using a quick logic loop\n ret = ''\n for c in s:\n if c.isalpha() or c is ' ':\n ret += c\n return ret"]
{"fn_name": "remove_chars", "inputs": [["co_ol f0un%(c)t-io\"n"], ["test for error!"], [".tree1"], ["that's a pie&ce o_f p#ie!"]], "outputs": [["cool function"], ["test for error"], ["tree"], ["thats a piece of pie"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,184
def remove_chars(s):
26bb2422c5621cbb73547400ec6a5b86
UNKNOWN
We define the "unfairness" of a list/array as the *minimal* difference between max(x1,x2,...xk) and min(x1,x2,...xk), for all possible combinations of k elements you can take from the list/array; both minimum and maximum of an empty list/array are considered to be 0. **More info and constraints:** * lists/arrays can contain values repeated more than once, plus there are usually more combinations that generate the required minimum; * the list/array's length can be any value from 0 to 10^(6); * the value of k will range from 0 to the length of the list/array, * the minimum unfairness of an array/list with less than 2 elements is 0. For example: ```python min_unfairness([30,100,1000,150,60,250,10,120,20],3)==20 #from max(30,10,20)-min(30,10,20)==20, minimum unfairness in this sample min_unfairness([30,100,1000,150,60,250,10,120,20],5)==90 #from max(30,100,60,10,20)-min(30,100,60,10,20)==90, minimum unfairness in this sample min_unfairness([1,1,1,1,1,1,1,1,1,2,2,2,2,2,2],10)==1 #from max(1,1,1,1,1,1,1,1,1,2)-min(1,1,1,1,1,1,1,1,1,2)==1, minimum unfairness in this sample min_unfairness([1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],10)==0 #from max(1,1,1,1,1,1,1,1,1,1)-min(1,1,1,1,1,1,1,1,1,1)==0, minimum unfairness in this sample min_unfairness([1,1,-1],2)==0 #from max(1,1)-min(1,1)==0, minimum unfairness in this sample ``` **Note:** shamelessly taken from [here](https://www.hackerrank.com/challenges/angry-children), where it was created and debatably categorized and ranked.
["def min_unfairness(arr,k):\n arr = sorted(arr)\n return min(b - a for a, b in zip(arr, arr[k-1:])) if arr and k else 0", "def min_unfairness(arr,k):\n if len(arr) < 2 or k < 2:\n return 0\n t = sorted(arr)\n diff = float('inf')\n for i in range(len(t)-k+1):\n x= t[i+k-1]-t[i]\n if x < diff:\n diff = x\n return diff", "def min_unfairness (arr, k): \n if k < 2 or len(arr) < 2:\n return 0\n \n arr = sorted(arr)\n return min(arr[i+k-1] - arr[i] for i in range(0, len(arr)-k+1))", "def min_unfairness(arr,k):\n #your code here\n if k<2 or len(arr)<2:\n return 0\n \n arr.sort()\n\n\n# return min([(arr[k+i-1]-arr[i]) for i in range(len(arr)-k+1)])\n mindist = float('inf')\n \n for i in range(len(arr)-k+1):\n dist = arr[k+i-1] - arr[i]\n \n if dist<mindist:\n mindist = dist\n \n return mindist", "def min_unfairness (arr,k): \n if k == 0 or len(arr) < 2:\n return 0\n \n arr.sort()\n return min( (arr[i+k-1] - arr[i]) for i in range(0, len(arr) - k + 1) )\n", "import numpy as np\ndef min_unfairness(arr,k):\n arr=np.sort(np.array(arr))\n if arr.size<2 or k in (0,1):\n return 0\n return np.min(arr[k-1:]-arr[:-k+1])", "min_unfairness=lambda a,k:a.sort()or k>0<len(a)and min(b-a for a,b in zip(a,a[k-1:]))", "def min_unfairness(arr,k):\n \n if not arr or k ==0: return 0\n arr.sort()\n \n min_unf = float('inf')\n \n for i in range(len(arr)-k+1):\n \n subarr_min = arr[i]\n subarr_max = arr[i+k-1]\n \n min_unf = min(min_unf, subarr_max-subarr_min)\n \n return min_unf\n", "def min_unfairness(arr,k):\n #your code here\n if k < 2: return 0\n arr.sort()\n ans = float(\"inf\")\n i = k - 1\n while i < len(arr):\n if abs(arr[i] - arr[i - k + 1]) < ans:\n ans = abs(arr[i] - arr[i - k + 1])\n i += 1\n return ans"]
{"fn_name": "min_unfairness", "inputs": [[[30, 100, 1000, 150, 60, 250, 10, 120, 20], 3], [[30, 100, 1000, 150, 60, 250, 10, 120, 20], 5], [[1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2], 10], [[1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2], 9], [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 10], [[1, 1, -1], 2], [[1, 1], 2], [[30, 100, 1000, 150, 60, 250, 10, 120, 20], 1], [[30, 100, 1000, 150, 60, 250, 10, 120, 20], 0], [[], 0]], "outputs": [[20], [90], [1], [0], [0], [0], [0], [0], [0], [0]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,970
def min_unfairness(arr,k):
a1feb8c5d4a9ec24319a87561c0cd6c5
UNKNOWN
## Task In this kata you'll be given a string of English digits "collapsed" together, like this: `zeronineoneoneeighttwoseventhreesixfourtwofive` Your task is to split the string back to digits: `zero nine one one eight two seven three six four two five` ## Examples ``` three -> three eightsix -> eight six fivefourseven -> five four seven ninethreesixthree -> nine three six three fivethreefivesixthreenineonesevenoneeight -> five three five six three nine one seven one eight ```
["import re\n\ndef uncollapse(digits):\n return ' '.join(re.findall('zero|one|two|three|four|five|six|seven|eight|nine', digits))", "import re\n\ndef uncollapse(digits):\n return ' '.join(m.group() for m in re.finditer(r'zero|one|two|three|four|five|six|seven|eight|nine', digits))", "uncollapse=lambda s:__import__('re').sub('(zero|one|two|three|four|five|six|seven|eight|nine)',r' \\1',s)[1:]", "import re\n\ndef uncollapse(digits):\n return re.sub(r'(zero|one|two|three|four|five|six|seven|eight|nine)',r'\\1 ',digits).strip()", "digits = \"zero one two three four five six seven eight nine\".split()\n\ndef uncollapse(stg):\n for d in digits:\n stg = stg.replace(d, f\"{d} \")\n return stg.strip()", "import re\n\npattern = re.compile(r\"zero|one|two|three|four|five|six|seven|eight|nine\")\n\ndef uncollapse(digits):\n return ' '.join(pattern.findall(digits))", "import re\n\ndef uncollapse(digits):\n return ' '.join(re.findall(r'(zero|one|two|three|four|five|six|seven|eight|nine)',digits))", "import re \ndef uncollapse(s):\n return ' '.join(re.findall(r'zero|nine|one|eight|two|seven|three|six|four|two|five',s)) ", "import re\n\ndef uncollapse(digits):\n pattern = 'zero|one|two|three|four|five|six|seven|eight|nine'\n return ' '.join(re.findall(pattern, digits))", "import re\n\ndef uncollapse(digits):\n return ' '.join(re.findall('one|two|three|four|five|six|seven|eight|nine|zero', digits))"]
{"fn_name": "uncollapse", "inputs": [["three"], ["eightsix"], ["fivefourseven"], ["ninethreesixthree"], ["foursixeighttwofive"], ["fivethreefivesixthreenineonesevenoneeight"], ["threesevensevensixninenineninefiveeighttwofiveeightsixthreeeight"], ["zeroonetwothreefourfivesixseveneightnine"]], "outputs": [["three"], ["eight six"], ["five four seven"], ["nine three six three"], ["four six eight two five"], ["five three five six three nine one seven one eight"], ["three seven seven six nine nine nine five eight two five eight six three eight"], ["zero one two three four five six seven eight nine"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,446
def uncollapse(digits):
14bb3449c59b66c1d54179f99275ef98
UNKNOWN
Little Petya often visits his grandmother in the countryside. The grandmother has a large vertical garden, which can be represented as a set of `n` rectangles of varying height. Due to the newest irrigation system we can create artificial rain above them. Creating artificial rain is an expensive operation. That's why we limit ourselves to creating the artificial rain only above one section. The water will then flow to the neighbouring sections but only if each of their heights does not exceed the height of the previous watered section. ___ ## Example: Let's say there's a garden consisting of 5 rectangular sections of heights `4, 2, 3, 3, 2`. Creating the artificial rain over the left-most section is inefficient as the water **WILL FLOW DOWN** to the section with the height of `2`, but it **WILL NOT FLOW UP** to the section with the height of `3` from there. Only 2 sections will be covered: `4, 2`. The most optimal choice will be either of the sections with the height of `3` because the water will flow to its neighbours covering 4 sections altogether: `2, 3, 3, 2`. You can see this process in the following illustration: ___ As Petya is keen on programming, he decided to find such section that if we create artificial rain above it, the number of watered sections will be maximal. ## Output: The maximal number of watered sections if we create artificial rain above exactly one section. **Note: performance will be tested.**
["def artificial_rain(garden):\n left,area,record = 0,0,1\n for i in range(1,len(garden)):\n if garden[i] < garden[i-1]:\n left = i\n elif garden[i] > garden[i-1]:\n area = max(area,record)\n record = i - left\n record += 1\n return max(area,record)", "def inclist(a):\n o = [1 for i in a]\n for i in range(1,len(a)):\n if a[i] >= a[i-1]:\n o[i] += o[i-1]\n return o\n \ndef artificial_rain(garden):\n inc = inclist(garden)\n dec = inclist(garden[::-1])[::-1]\n return max([x + y for x, y in zip(inc, dec)])-1", "def artificial_rain(li):\n left, m, i = 0, 0, 1\n while i < len(li):\n prev = left\n while i < len(li) and li[i - 1] <= li[i]:\n if li[left] != li[i] : left = i\n i += 1\n while i < len(li) and li[i - 1] >= li[i]:\n if li[left] != li[i] : left = i\n i += 1\n m = max(m,i-prev)\n return m or 1 ", "def artificial_rain(garden):\n output = []\n garden_cropped = []\n \n for i in range(len(garden)-1):\n if garden[i] < garden[i+1]:\n garden_cropped.append(+1)\n elif garden[i] > garden[i+1]:\n garden_cropped.append(-1)\n else:\n garden_cropped.append(0)\n \n var = 0\n last_n = 1\n recent_zeros = 0\n for idx,elem in enumerate(garden_cropped):\n if elem == 1 and last_n == 1:\n last_n = 1\n var += 1\n recent_zeros = 0\n elif elem == 1 and last_n == -1:\n output.append(var+1)\n last_n = 1\n var = 1+recent_zeros\n recent_zeros = 0\n \n if elem == -1:\n last_n = -1\n var += 1\n recent_zeros = 0\n \n if elem == 0:\n var += 1\n recent_zeros += 1\n \n output.append(var+1)\n \n return max(output) if len(garden) > 1 else 1", "def artificial_rain(garden):\n max_sections = 1\n curr_sections = 1\n flat_sections = 1\n previous = garden[0]\n slope = 'downhill'\n for section in garden[1:]:\n if slope == 'downhill' and section > previous:\n if curr_sections > max_sections:\n max_sections = curr_sections\n curr_sections = flat_sections + 1\n flat_sections = 1\n slope = 'uphill' \n elif slope == 'uphill' and section < previous:\n curr_sections += 1\n flat_sections = 1\n slope = 'downhill'\n else:\n curr_sections += 1\n if section == previous:\n flat_sections += 1 \n else:\n flat_sections = 1\n previous = section\n if curr_sections > max_sections:\n max_sections = curr_sections\n return max_sections\n", "def artificial_rain(garden):\n if len(garden) < 20:\n print(garden)\n res = 0\n last = 0\n m = -1\n k = 0\n while garden:\n while garden and garden[0] >= last:\n last = garden.pop(0)\n res += 1\n while garden and garden[0] <= last:\n if garden[0] == last:\n k += 1\n if garden[0] < last:\n k = 0\n res += 1\n last = garden.pop(0)\n m = max(res, m)\n res = k+1\n m = max(res, m)\n return m", "class C():\n def __eq__(self,x):\n return True\ndef artificial_rain(garden):\n return C()", "def is_min(i, lst):\n if i > 0:\n if i+1 < len(lst):\n return lst[i-1]>=lst[i] and lst[i]<lst[i+1]\n return lst[i-1]>lst[i]\n return lst[i] < lst[i+1]\n \n \ndef is_par(i, lst):\n if i+1 < len(lst):\n return lst[i] == lst[i+1]\n return True\n \n \ndef artificial_rain(lst): \n if len(lst) in (0, 1):\n return len(lst)\n \n mn, nx_mn = 0, -1\n i = 0\n grt = 0\n \n while i < len(lst):\n if is_min(i, lst):\n grt = max(grt, 1+i-mn)\n if nx_mn == -1:\n mn = i\n else:\n mn = nx_mn\n nx_mn = -1\n else:\n nx_mn = -1\n if is_par(i, lst):\n j = i\n if i-1>=0:\n j = i\n while j-1>=0 and lst[j-1] <= lst[j]:\n j-=1\n nx_mn = j\n while i<len(lst) and is_par(i, lst):\n i += 1\n i -= 1\n \n i += 1\n \n return max(grt, i-mn)", "def artificial_rain(garden):\n if not garden: return 0\n sect_cnt = len(garden)\n if sect_cnt < 3: return sect_cnt\n\n best_coverage = 1\n coverages = [2, 1] if garden[0] > garden[1] else [1, 2]\n bump_at = 0 if garden[0] > garden[1] else 1\n coverages += [1] * (sect_cnt - 2)\n for i in range(2, sect_cnt):\n left_height, height = garden[i-1], garden[i]\n if height > left_height:\n coverages[i] += coverages[i-1]\n bump_at = i\n elif height == left_height:\n coverages[i-1] += 1\n coverages[i] = coverages[i-1]\n if i - 1 != bump_at:\n coverages[bump_at] += 1\n else:\n bump_at = i\n else: \n coverages[bump_at] += 1\n if coverages[bump_at] > best_coverage:\n best_coverage = coverages[bump_at]\n\n return best_coverage\n", "def artificial_rain(garden):\n with_left_wall_at = 0\n best_coverage = coverage = 1\n for i in range(1,len(garden)):\n height = garden[i]\n left_neighbor_height = garden[i-1]\n if left_neighbor_height > height:\n with_left_wall_at = i\n elif left_neighbor_height < height:\n if coverage > best_coverage:\n best_coverage = coverage\n coverage = i - with_left_wall_at\n coverage += 1\n\n if coverage > best_coverage:\n best_coverage = coverage\n return best_coverage\n"]
{"fn_name": "artificial_rain", "inputs": [[[2]], [[1, 2, 1, 2, 1]], [[4, 2, 3, 3, 2]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]], [[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]], [[1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1]], [[1, 2, 3, 4, 5, 1, 5, 4, 3, 2, 1]], [[1, 1, 1, 2, 1, 2, 10, 2, 3, 3]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 8, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 100, 7, 6, 5, 4, 3, 2, 1]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 1, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 100, 7, 6, 5, 4, 3, 2, 1]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 1, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 4, 88, 89, 90, 2, 92, 100, 7, 6, 5, 4, 3, 2, 1]]], "outputs": [[1], [3], [4], [10], [10], [11], [6], [5], [53], [61], [48]]}
INTRODUCTORY
PYTHON3
CODEWARS
6,146
def artificial_rain(garden):
27b6eb97842aafee7d9988bfe05d41cf
UNKNOWN
# Task Given two integers `a` and `b`, return the sum of the numerator and the denominator of the reduced fraction `a/b`. # Example For `a = 2, b = 4`, the result should be `3` Since `2/4 = 1/2 => 1 + 2 = 3`. For `a = 10, b = 100`, the result should be `11` Since `10/100 = 1/10 => 1 + 10 = 11`. For `a = 5, b = 5`, the result should be `2` Since `5/5 = 1/1 => 1 + 1 = 2`. # Input/Output - `[input]` integer `a` The numerator, `1 ≤ a ≤ 2000`. - `[input]` integer `b` The denominator, `1 ≤ b ≤ 2000`. - `[output]` an integer The sum of the numerator and the denominator of the reduces fraction.
["from fractions import gcd\n\ndef fraction(a,b):\n return (a+b)//gcd(a,b)", "from math import gcd\ndef fraction(a, b):\n return a/gcd(a,b) + b/(gcd(a,b))", "\ndef fraction(a, b):\n from math import gcd\n return (a + b) / gcd(a, b)", "from fractions import gcd\n\ndef fraction(a, b):\n d = gcd(a, b)\n return a//d + b//d", "from fractions import Fraction\ndef fraction(a, b):\n #coding and coding..\n f = Fraction(a,b)\n return f.numerator + f.denominator", "from fractions import Fraction\ndef fraction(a, b):\n return Fraction(a,b).denominator+Fraction(a,b).numerator", "import fractions\ndef fraction(a, b):\n return sum([int(s) for s in str(fractions.Fraction(a,b)).split('/')])", "def fraction(a, b):\n #coding and coding..\n c=a+b\n if b>a:\n a,b=b,a\n while b!=0:\n a,b=b,a%b\n return int(c/a)", "def fraction(a, b):\n # check if one arguments can serve as the denominator\n if max([a, b]) % min([a, b]) == 0:\n return (a + b) // min([a, b])\n # otherwise start from the half of the smallest argument and search it\n else:\n x = min([a, b]) // 2\n while True:\n if a % x == 0 and b % x == 0:\n break\n x -= 1\n return (a + b) // x", "import math\n\ndef fraction(a, b):\n g = math.gcd(a, b)\n return a / g + b / g"]
{"fn_name": "fraction", "inputs": [[90, 120], [2, 4], [100, 1000], [3, 15], [114, 200], [3, 118]], "outputs": [[7], [3], [11], [6], [157], [121]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,346
def fraction(a, b):
7c871f17f31d5a4b669ae262d065f44b
UNKNOWN
Write a function `generatePairs` that accepts an integer argument `n` and generates an array containing the pairs of integers `[a, b]` that satisfy the following conditions: ``` 0 <= a <= b <= n ``` The pairs should be sorted by increasing values of `a` then increasing values of `b`. For example, `generatePairs(2)` should return ``` [ [0, 0], [0, 1], [0, 2], [1, 1], [1, 2], [2, 2] ] ```
["def generate_pairs(n):\n return [[i,j] for i in range(n+1) for j in range(i, n+1)]", "def generate_pairs(n):\n return [[a, b] for a in range(n+1) for b in range (a, n+1)]", "def generate_pairs(n):\n return [ [i,y] for i in range(n+1) for y in range(i,n+1) ]", "from itertools import combinations_with_replacement\n\ndef generate_pairs(n, m=2):\n return list(map(list, combinations_with_replacement(range(n+1), m)))", "from itertools import combinations_with_replacement\n\ndef generate_pairs(n):\n return sorted(map(list, combinations_with_replacement(list(range(n + 1)), 2)))", "from itertools import combinations_with_replacement\n\n\ndef generate_pairs(n):\n return [list(a) for a in combinations_with_replacement(range(n + 1), 2)]\n", "def generate_pairs(n):\n b= [[y,x] for x in range(n+1) for y in range(x+1)]\n b.sort()\n return b", "def generate_pairs(n):\n return [[i, x] for i in range(n+1) for x in range(n+1) if x >= i]", "from itertools import chain\ndef generate_pairs(n):\n return sorted(list(chain.from_iterable([[[a,b] for a in range(b+1)] for b in range(n+1)])))"]
{"fn_name": "generate_pairs", "inputs": [[2], [0]], "outputs": [[[[0, 0], [0, 1], [0, 2], [1, 1], [1, 2], [2, 2]]], [[[0, 0]]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,117
def generate_pairs(n):
94d28c740fab8ea28d4a19cc92b47fb4
UNKNOWN
# Right in the Center _This is inspired by one of Nick Parlante's exercises on the [CodingBat](https://codingbat.com/java) online code practice tool._ Given a sequence of characters, does `"abc"` appear in the CENTER of the sequence? The sequence of characters could contain more than one `"abc"`. To define CENTER, the number of characters in the sequence to the left and right of the "abc" (which is in the middle) must differ by at most one. If it is in the CENTER, return `True`. Otherwise, return `False`. Write a function as the solution for this problem. This kata looks simple, but it might not be easy. ## Example is_in_middle("AAabcBB") -> True is_in_middle("AabcBB") -> True is_in_middle("AabcBBB") -> False
["def is_in_middle(s):\n while len(s)>4:\n s = s[1:-1]\n return 'abc' in s", "def is_in_middle(seq):\n mid, rem = divmod(len(seq), 2)\n start = mid-1\n end = start+3\n \n if not rem: \n start -= 1\n \n return 'abc' in seq[start:end]\n", "def is_in_middle(s):\n return is_in_middle(s[1:-1]) if s[4:] else 'abc' in s", "def is_in_middle(sequence):\n n = len(sequence)\n i = (n - 3) // 2\n return sequence[i:i+3] == 'abc' or (n % 2 == 0 and sequence[i+1:i+4] == 'abc')", "def is_in_middle(sequence):\n while len(sequence) >= 3: \n if sequence == 'abc' or sequence[1:] == 'abc' or sequence[:-1] == 'abc':\n return True\n sequence = sequence[1:-1] \n return False", "def is_in_middle(sequence):\n length = len(sequence)\n if length < 3:\n return False\n if length % 2 != 0:\n index = (length//2)-1\n if sequence[index:index+3] == \"abc\":\n return True\n return False\n elif length % 2 == 0:\n index1 = (length//2) - 2\n index2 = (length//2) - 1\n if sequence[index1:index1+3] == \"abc\" or sequence[index2:index2+3] == \"abc\":\n return True\n return False", "def in_centre(s,i):\n return s[i] == \"a\" and s[i+1] == \"b\" and s[i+2] == \"c\"\n\ndef is_in_middle(s):\n if \"abc\" not in s or len(s) < 3: return False\n l = len(s)\n if l % 2 == 1: i = (l+1)//2-2; return in_centre(s,i) \n else: i1 = l//2 -2; i2 = l//2 -1; return in_centre(s,i1) or in_centre(s,i2) \n", "def is_in_middle(s):\n return 'abc' in s[(len(s)-1)//2-1 : (len(s)+2)//2+1]\n", "def is_in_middle(seq):\n m = len(seq)//2\n if len(seq)%2 != 0 and seq[m-1:m+2] =='abc':\n return True\n elif len(seq)%2 == 0: \n if seq[m-2:m+1] =='abc' or seq[m-1:m+2] =='abc':\n return True\n return False", "def is_in_middle(s):\n return 'abc' in [s[len(s) // 2 - 1: len(s) // 2 + 2] if len(s) % 2 else s[len(s) // 2 - 2: len(s) // 2 + 2]][0]"]
{"fn_name": "is_in_middle", "inputs": [["abc"], ["abcabcabc"], ["AAabcBBB"], ["AAAabcBB"], ["AAAAabcBB"], ["AAabcabcBB"], ["abcabcabcabc"], ["AabcBBB"], [""], ["ABC"], ["abcZ"], ["Yabc"]], "outputs": [[true], [true], [true], [true], [false], [false], [false], [false], [false], [false], [true], [true]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,036
def is_in_middle(s):
f5a33fa4884b5a3e33ede48c3a2d24bc
UNKNOWN
In this kata, you will make a function that converts between `camelCase`, `snake_case`, and `kebab-case`. You must write a function that changes to a given case. It must be able to handle all three case types: ```python py> change_case("snakeCase", "snake") "snake_case" py> change_case("some-lisp-name", "camel") "someLispName" py> change_case("map_to_all", "kebab") "map-to-all" py> change_case("doHTMLRequest", "kebab") "do-h-t-m-l-request" py> change_case("invalid-inPut_bad", "kebab") None py> change_case("valid-input", "huh???") None py> change_case("", "camel") "" ``` Your function must deal with invalid input as shown, though it will only be passed strings. Furthermore, all valid identifiers will be lowercase except when necessary, in other words on word boundaries in `camelCase`. _**(Any translations would be greatly appreciated!)**_
["import re\n\ndef change_case(label, target):\n if ('_' in label) + ('-' in label) + (label != label.lower()) > 1:\n return\n \n if target == 'snake':\n return re.sub('([A-Z])', r'_\\1', label.replace('-', '_')).lower()\n \n if target == 'kebab':\n return re.sub('([A-Z])', r'-\\1', label.replace('_', '-')).lower()\n \n if target == 'camel':\n return re.sub('([_-])([a-z])', lambda m: m.group(2).upper(), label)", "def change_case(label, case):\n if case not in ['snake', 'kebab', 'camel'] or ('_' in label) + ('-' in label) + (label != label.lower()) > 1:\n return\n \n return ''.join( '_' + c.lower() if c.isupper() and case == 'snake' else\n '_' if c == '-' and case == 'snake' else\n \n '-' + c.lower() if c.isupper() and case == 'kebab' else\n '-' if c == '_' and case == 'kebab' else\n \n c.upper() if label[i-1] in '-_' and case == 'camel' else\n '' if c in '-_' and case == 'camel' else\n \n c for i, c in enumerate(label) )", "import re\n\nCHANGES = {'kebab': '-', 'camel': '', 'snake': '_'}\nVALID_CASE = re.compile(r'[A-Z_-]')\nCHANGE_CASE = re.compile(r'[_-][a-z]|[A-Z]')\n\n\ndef change_case(s, targetCase):\n\n def convertCase(m):\n return (str.upper if targetCase=='camel' else str.lower)(CHANGES[targetCase] + m.group()[-1])\n \n if targetCase in CHANGES and len({'A' if c.isalpha() else c for c in VALID_CASE.findall(s)}) <= 1:\n return CHANGE_CASE.sub(convertCase, s)\n", "import re\n\ndef change_case(s, case):\n \n actions = {\n 'snake': lambda s: re.sub(r'([A-Z\\-])', r'_\\1', s).lower().replace('-', ''),\n 'camel': lambda s: re.sub(r'(\\-|_)(.)', lambda x: x[2].upper(), s),\n 'kebab': lambda s: re.sub(r'([A-Z_])', r'-\\1', s).lower().replace('_', '')\n }\n return s if not s else sum((any(x.isupper() for x in s), '_' in s, '-' in s)) < 2 \\\n and actions.get(case, lambda s: None)(s) or None", "def change_case(id, t):\n q = ('_' in id) + ('-' in id) + any(x.isupper() for x in set(id))\n if q > 1: return\n d = {'kebab': '-', 'snake': '_'}\n l, index = [''], 0\n for x in id:\n if not l[index] or not x.isupper() and x.isalpha() and l[index][-1].isalpha():\n l[index] += x\n elif x.isalpha():\n l.append(x)\n index += 1\n else:\n l.append('')\n index += 1\n\n if t in d:\n return f'{d[t]}'.join(x.lower() for x in l)\n if t == 'camel':\n return ''.join(w.capitalize() if i else w for i,w in enumerate(l))", "def change_case(identifier, targetCase):\n# kebab make dashes after all capital, snake underscore after capital\n# camel makes kebab to caps\n#account for \n if isBad(identifier):\n return None\n if targetCase == 'snake':\n return snake(identifier)\n elif targetCase == 'camel':\n return camel(identifier)\n elif targetCase == 'kebab':\n return kebab(identifier)\n return None\n \ndef snake(myString):\n newString = myString\n for i in range (0, len(myString)):\n if ord(myString[i]) >= ord('A') and ord(myString[i]) <= ord('Z'):\n #means it is caps\n pos = newString.index(myString[i:])\n newString = newString[:pos] + '_' + newString[pos].lower() + newString [pos + 1:]\n elif myString[i] == '-':\n pos = newString.index(myString[i:])\n #newSting = \n newString = newString[:pos] + '_' + newString[pos + 1:]\n return newString.lower()\n \ndef kebab(myString):\n newString = myString\n for i in range (0, len(myString)):\n if ord(myString[i]) > ord('A') -1 and ord(myString[i]) < ord('Z') +1:\n #means it is caps\n pos = newString.index(myString[i:])\n newString = newString[:pos] + '-' + newString[pos].lower() + newString [pos + 1:]\n\n if myString[i] == '_':\n pos = newString.index(myString[i:])\n #newSting = \n newString = newString[:pos] + '-' + newString[pos + 1:]\n #means it is underscore\n return newString.lower()\n \ndef camel(myString):\n #why doesnt this work\n if len(myString) ==0:\n return myString\n myString = myString.replace('-', '_')\n newString = myString.split('_')\n for i in range (0, len(newString)):\n if i != 0:\n newString[i] = newString[i][0].upper() + newString[i][1:]\n return \"\".join(newString) \n #\ndef isBad(myString): \n if '_' in myString and '-' in myString:\n return True\n if '--' in myString or '__' in myString:\n return True\n if not myString.lower() == myString and '_' in myString:\n return True\n if not myString.lower() == myString and '-' in myString:\n return True\n return False", "import re\n\n# TODO: need to refactor later :)\nfind_snake = re.compile(\"([_])([A-Za-z])\")\nfind_camel = re.compile(\"([A-Z])\")\nfind_kebab = re.compile(\"([-])([A-Za-z])\")\n\nis_camel = lambda x: x != x.lower()\nis_snake = lambda x: '_' in x\nis_kebab = lambda x: '-' in x\n\ndef to_camel(match):\n return match.group(2).upper()\n\ndef to_snake(match):\n return '_' + match.group(1).lower()\n \ndef to_kebab(match):\n return '-' + match.group(1).lower()\n\ndef change_case(text, target):\n if text == '':\n return ''\n if target not in ['camel','kebab','snake'] \\\n or sum([is_camel(text), is_snake(text), is_kebab(text)]) != 1:\n return None\n if is_camel(text):\n if target == 'snake':\n return re.sub(find_camel, to_snake, text).lower()\n elif target == 'kebab':\n return re.sub(find_camel, to_kebab, text).lower()\n elif is_snake(text):\n if target == 'camel':\n return re.sub(find_snake, to_camel, text)\n elif target == 'kebab':\n return text.replace('_', '-').lower()\n elif is_kebab(text):\n if target == 'snake':\n return text.replace('-', '_').lower()\n elif target == 'camel':\n return re.sub(find_kebab, to_camel, text)\n return text", "def discover_case(identifier):\n if identifier is None:\n return None\n elif identifier == '':\n return ''\n elif is_camel(identifier):\n return 'camel'\n elif is_snake(identifier):\n return 'snake'\n elif is_kebab(identifier):\n return 'kebab'\n return None\n\ndef is_camel(identifier):\n found_uppercase = False\n \n for index, ch in enumerate(identifier):\n if not ch.isalnum():\n return False\n elif index != 0 and ch.isalpha() and ch.isupper():\n found_uppercase = True\n \n return found_uppercase\n\ndef is_snake(identifier):\n for ch in identifier:\n if ch.isupper():\n return False\n \n return '_' in identifier and '-' not in identifier\n\ndef is_kebab(identifier):\n for ch in identifier:\n if ch.isupper():\n return False\n \n return '-' in identifier and '_' not in identifier\n\ndef split_words(identifier, case):\n if case == 'camel':\n words = []\n word = ''\n \n for ch in identifier:\n if ch.isupper():\n words.append(word.lower())\n word = ch\n else:\n word += ch\n \n words.append(word.lower())\n return words\n elif case == 'snake':\n return identifier.split('_')\n elif case == 'kebab':\n return identifier.split('-')\n else:\n return None\n\ndef to_camel(words):\n result = ''\n for index, word in enumerate(words):\n if index == 0:\n result += word\n else:\n result += word.capitalize()\n return result\n\ndef to_snake(words):\n return '_'.join(words)\n\ndef to_kebab(words):\n return '-'.join(words)\n\ndef change_case(identifier, targetCase):\n case = discover_case(identifier)\n if not case:\n return case\n \n words = split_words(identifier, case)\n if not words:\n return None\n \n if targetCase == 'camel':\n return to_camel(words)\n elif targetCase == 'snake':\n return to_snake(words)\n elif targetCase == 'kebab':\n return to_kebab(words)\n else:\n return None\n", "def change_case(identifier, targetCase):\n id = list(str(identifier))\n conv = []\n \n if identifier.islower() == False and (id.count('-') != 0 or id.count('_') != 0) == True: #checks if there are upper case and hyphens or underscores\n return None\n \n if id.count('-') != 0 and id.count('_') != 0:\n return None\n \n if targetCase == 'snake':\n return change_snake(id, conv)\n \n if targetCase == 'camel':\n return change_camel(id, conv)\n \n if targetCase == 'kebab':\n return change_kebab(id, conv)\n \n else:\n return None\n \ndef change_snake(id, conv): #converts Capital to _lower \n for i in id:\n if i.isupper() == True:\n conv.append('_' + i.lower())\n #conv.append(i.lower())\n \n elif i == '-':\n conv.append('_')\n \n else:\n conv.append(i)\n \n return ''.join(conv)\n \ndef change_camel(id, conv): #converts -lower to Capital\n ids = id.copy()\n ids.insert(0, '.')\n n = 0\n \n for i in id: \n n = n+1\n \n if i == '-' or i == '_': \n continue \n \n if ids[n-1] == '-' or ids[n-1] == '_':\n \n conv.append(i.upper())\n \n else:\n conv.append(i)\n \n \n return ''.join(conv)\n \ndef change_kebab(id, conv): #converts \n for i in id:\n if i == '_':\n conv.append('-')\n continue\n \n if i.isupper() == True:\n conv.append('-' + i.lower())\n \n else:\n conv.append(i)\n \n return ''.join(conv)", "import re\n\ndef is_snake_case(identifier):\n return bool( re.fullmatch(r'[a-z_]+', identifier) )\n\ndef is_camel_case(identifier):\n return bool(re.fullmatch(r'([a-z]+[A-Z])+[a-z]*', identifier))\n\ndef is_kebab_case(identifier):\n return bool(re.fullmatch(r'[a-z]*-?', identifier))\n \ndef is_mixed_case(identifier):\n if \"-\" in identifier and \"_\" in identifier:\n return True\n elif \"-\" in identifier and [c for c in identifier if c.isupper()]:\n return True\n elif \"_\" in identifier and [c for c in identifier if c.isupper()]:\n return True\n \ndef change_case(identifier, targetCase):\n # if identifier is empty\n if not identifier:\n return \"\"\n \n # if targetCase is invalid\n elif targetCase not in ['kebab', 'camel', 'snake']:\n return None\n \n # if identifier is mixed case\n elif is_mixed_case(identifier):\n return None\n \n # change case to snake case\n elif targetCase == \"snake\" and not is_snake_case(identifier):\n split = [char for char in re.split(r'([A-Z]|-)', identifier) if char]\n for i, char in enumerate(split):\n if char.isupper():\n split[i] = '_' + char.lower()\n elif char == \"-\":\n split[i] = \"_\"\n return ''.join(split)\n \n # change case to camel case\n elif targetCase == \"camel\" and not is_camel_case(identifier): \n split = re.split(r'[_-]', identifier)\n return split[0] + ''.join(word.title() for word in split[1:])\n \n # change case to kebab case\n elif targetCase == \"kebab\" and not is_kebab_case(identifier):\n split = re.split(r'([A-Z]|_)', identifier)\n kebab = split[0]\n for i, word in enumerate(split[1:]):\n if not word or word == \"_\":\n kebab += \"-\"\n elif word.isupper():\n if kebab[-1] == \"-\": \n kebab += word.lower()\n else:\n kebab += '-' + word.lower()\n else:\n kebab += word.lower()\n return kebab\n \n # identifier and targetCase already match\n else:\n return identifier"]
{"fn_name": "change_case", "inputs": [["snakeCase", "snake"], ["some-lisp-name", "camel"], ["map_to_all", "kebab"], ["doHTMLRequest", "kebab"], ["invalid-inPut_bad", "kebab"], ["valid-input", "huh???"], ["", "camel"], ["snake-kebab_case", "kebab"], ["snakeCamel_case", "snake"], ["kebabCamel-case", "snake"], ["case-Camel", "kebab"]], "outputs": [["snake_case"], ["someLispName"], ["map-to-all"], ["do-h-t-m-l-request"], [null], [null], [""], [null], [null], [null], [null]]}
INTRODUCTORY
PYTHON3
CODEWARS
12,704
def change_case(identifier, targetCase):
9309aeaec067ac9c11bdca9a196918a9
UNKNOWN
## Story John runs a shop, bought some goods, and then sells them. He used a special accounting method, like this: ``` [[60,20],[60,-20]] ``` Each sub array records the commodity price and profit/loss to sell (percentage). Positive mean profit and negative means loss. In the example above, John's first commodity sold at a price of $60, he made a profit of 20%; Second commodities are sold at a price of $60 too, but he lost 20%. Please calculate, whether his account is profit or loss in the end? ## Rules Write a function ```profitLoss```, argument ```records``` is the list of sales. return a number(positive or negative), round to two decimal places. ## Examples
["def profitLoss(records):\n return round(sum(price - price / (1 + profit / 100) for (price, profit) in records), 2)", "def profitLoss(records):\n return round(sum(pr * pe / (100+pe) for pr, pe in records), 2)", "def profitLoss(records):\n \n return round(sum(amount * (1 - 1/(1 + perc/100)) for amount, perc in records), 2)", "def profitLoss(records):\n return round(sum(price * percent / (100 + percent) for price, percent in records), 2)", "def profitLoss(records):\n return round(sum(x * p / (100 + p) for x, p in records), 2)", "profitLoss=lambda a:round(sum(p*l/(l+100)for p,l in a),2)", "def profitLoss(r):\n return round(sum( i[0]-i[0]*100./(100+i[1]) for i in r),2)", "def profitLoss(records):\n return round(sum([r - (r / (1 + p / 100)) for r, p in records]), 2)\n", "def profitLoss(records):\n return round(100 * (sum(c[0] - c[0]/(1+c[1]/100) for c in records)))/100", "def profitLoss(records):\n return round(sum(map(lambda r: r[0] * r[1] / (100 + r[1]), records)), 2)"]
{"fn_name": "profitLoss", "inputs": [[[[60, 20], [60, -20]]], [[[60, 100], [60, -50]]], [[[60, 0], [60, 0]]]], "outputs": [[-5], [-30], [0]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,015
def profitLoss(records):
39e67919fb211dc0c822f0df15185a07
UNKNOWN
## The Story Green Lantern's long hours of study and practice with his ring have really paid off -- his skills, focus, and control have improved so much that now he can even use his ring to update and redesign his web site. Earlier today he was focusing his will and a beam from his ring upon the Justice League web server, while intensely brainstorming and visualizing in minute detail different looks and ideas for his web site, and when he finished and reloaded his home page, he was absolutely thrilled to see that among other things it now displayed ~~~~ In brightest day, in blackest night, There's nothing cooler than my site! ~~~~ in his favorite font in very large blinking green letters. The problem is, Green Lantern's ring has no power over anything yellow, so if he's experimenting with his web site and accidentally changes some text or background color to yellow, he will no longer be able to make any changes to those parts of the content or presentation (because he doesn't actually know any HTML, CSS, programming languages, frameworks, etc.) until he gets a more knowledgable friend to edit the code for him. ## Your Mission You can help Green Lantern by writing a function that will replace any color property values that are too yellow with shades of green or blue-green. Presumably at a later time the two of you will be doing some testing to find out at exactly which RGB values yellow stops being yellow and starts being off-white, orange, brown, etc. as far as his ring is concerned, but here's the plan to get version 1.0 up and running as soon as possible: Your function will receive either an HTML color name or a six-digit hex color code. (You're not going to bother with other types of color codes just now because you don't think they will come up.) If the color is too yellow, your function needs to return a green or blue-green shade instead, but if it is not too yellow, it needs to return the original color name or hex color code unchanged. ### HTML Color Names (If don't know what HTML color names are, take a look at this HTML colors names reference.) For HMTL color names, you are going to start out trying a pretty strict definition of yellow, replacing any of the following colors as specified: ~~~~ Gold => ForestGreen Khaki => LimeGreen LemonChiffon => PaleGreen LightGoldenRodYellow => SpringGreen LightYellow => MintCream PaleGoldenRod => LightGreen Yellow => Lime ~~~~ HTML color names are case-insensitive, so your function will need to be able to identify the above yellow shades regardless of the cases used, but should output the green shades as capitalized above. Some examples: ``` "lemonchiffon" "PaleGreen" "GOLD" "ForestGreen" "pAlEgOlDeNrOd" "LightGreen" "BlueViolet" "BlueViolet" ``` ### Hex Color Codes (If you don't know what six-digit hex color codes are, take a look at this Wikipedia description. Basically the six digits are made up of three two-digit numbers in base 16, known as hexidecimal or hex, from 00 to FF (equivalent to 255 in base 10, also known as decimal), with the first two-digit number specifying the color's red value, the second the green value, and the third blue.) With six-digit color hex codes, you are going to start out going really overboard, interpreting as "yellow" any hex code where the red (R) value and the green (G) value are each greater than the blue (B) value. When you find one of these "yellow" hex codes, your function will take the three hex values and rearrange them that the largest goes to G, the middle goes to B, and the smallest to R. For example, with the six-digit hex color code `#FFD700`, which has an R value of hex FF (decimal 255), a G value of hex D7 (decimal 215), and a B value of hex 00 (decimal 0), as the R and G values are each larger than the B value, you would return it as `#00FFD7` -- the FF reassigned to G, the D7 to B, and the 00 to R. Hex color codes are also case-insensitive, but your function should output them in the same case they were received in, just for consistency with whatever style is being used. Some examples: ``` "#000000" "#000000" "#b8860b" "#0bb886" "#8FBC8F" "#8FBC8F" "#C71585" "#C71585" ```
["def yellow_be_gone(s):\n d = {'gold':'ForestGreen', 'khaki':'LimeGreen', 'lemonchiffon':'PaleGreen', 'lightgoldenrodyellow':'SpringGreen',\n 'lightyellow':'MintCream', 'palegoldenrod':'LightGreen', 'yellow':'Lime'}\n \n if s[0] == '#':\n R, G, B = s[1:3], s[3:5], s[5:]\n if B < G and B < R:\n R, B, G = sorted([R, G, B])\n s = '#' + R + G + B\n \n return d.get(s.lower(), s)", "COLORDICT = {\"gold\" : \"ForestGreen\",\n \"khaki\" : \"LimeGreen\",\n \"lemonchiffon\" : \"PaleGreen\",\n \"lightgoldenrodyellow\" : \"SpringGreen\",\n \"lightyellow\" : \"MintCream\",\n \"palegoldenrod\" : \"LightGreen\",\n \"yellow\" : \"Lime\"}\n\ndef yellow_be_gone(clrIn):\n\n if \"#\"==clrIn[0]:\n R, G, B = clrIn[1:3], clrIn[3:5], clrIn[5:7]\n if R>B and G>B: return \"#\"+B+G+R if R<G else \"#\"+B+R+G\n\n for clr in COLORDICT.keys():\n if clr==clrIn.lower(): return COLORDICT[clr]\n \n return clrIn", "COLORS = {\n 'gold': 'ForestGreen', 'khaki': 'LimeGreen', 'lemonchiffon': 'PaleGreen',\n 'lightgoldenrodyellow': 'SpringGreen', 'lightyellow': 'MintCream',\n 'palegoldenrod': 'LightGreen', 'yellow': 'Lime',\n}\n\ndef yellow_be_gone(color):\n if color.startswith('#'):\n r, g, b = color[1:3], color[3:5], color[5:]\n if r > b < g:\n return '#{}{}{}'.format(b, max(r, g), min(r, g))\n return COLORS.get(color.lower(), color)", "def yellow_be_gone(color):\n color_change = {\"gold\": \"ForestGreen\", \"khaki\": \"LimeGreen\", \"lemonchiffon\": \"PaleGreen\", \"lightgoldenrodyellow\": \"SpringGreen\",\n \"lightyellow\": \"MintCream\", \"palegoldenrod\": \"LightGreen\", \"yellow\": \"Lime\"}\n if color.startswith(\"#\"):\n codes = [(int(rgb, 16), rgb) for rgb in [color[1:3], color[3:5], color[5:]]]\n rgb_string = color if any(c <= codes[2][0] for c in (x for x, _ in codes[:2])) else\\\n \"#\" + \"{0}{2}{1}\".format(*[c for _, c in sorted(codes)])\n return rgb_string\n return color_change.get(color.lower(), color)", "SHADES = {\n \"gold\": \"ForestGreen\",\n \"khaki\": \"LimeGreen\",\n \"lemonchiffon\": \"PaleGreen\",\n \"lightgoldenrodyellow\": \"SpringGreen\",\n \"lightyellow\": \"MintCream\",\n \"palegoldenrod\": \"LightGreen\",\n \"yellow\": \"Lime\"\n}\n\ndef yellow_be_gone(color):\n if color[0] == '#':\n r, g, b = color[1:3], color[3:5], color[5:]\n if r > b and g > b:\n color = '#{0}{2}{1}'.format(*sorted([r, g, b]))\n return SHADES.get(color.lower(), color)\n", "import re\nh={\n'gold':'ForestGreen',\n'khaki':'LimeGreen',\n'lemonchiffon':'PaleGreen',\n'lightgoldenrodyellow':'SpringGreen',\n'lightyellow':'MintCream',\n'palegoldenrod':'LightGreen',\n'yellow':'Lime',\n}\n\ndef yellow_be_gone(c):\n n=c.lower()\n if n in h:return h[n]\n \n m=re.match(r'#([a-zA-Z0-9]{2})([a-zA-Z0-9]{2})([a-zA-Z0-9]{2})',c)\n if m:\n r,g,b=list(m.groups())\n l=sorted([r,g,b])\n if(r>b and g>b):\n return'#%s%s%s'%(l[0],l[2],l[1])\n return c", "def yellow_be_gone(s):\n d = {\n 'gold': 'ForestGreen',\n 'khaki': 'LimeGreen',\n 'lemonchiffon': 'PaleGreen',\n 'lightgoldenrodyellow': 'SpringGreen',\n 'lightyellow': 'MintCream',\n 'palegoldenrod': 'LightGreen',\n 'yellow': 'Lime' \n }\n \n if s[0] == '#':\n R, G, B = s[1:3], s[3:5], s[5:7]\n if B < G and B < R:\n R, B, G = sorted([R,G,B])\n s = '#' + R + G + B\n \n return d.get(s.lower(), s)\n", "def yellow_be_gone(color_name_or_code):\n d = {\n 'gold': 'ForestGreen',\n 'khaki': 'LimeGreen',\n 'lemonchiffon': 'PaleGreen',\n 'lightgoldenrodyellow': 'SpringGreen',\n 'lightyellow': 'MintCream',\n 'palegoldenrod': 'LightGreen',\n 'yellow': 'Lime' \n }\n \n if not '#' in color_name_or_code:\n return d[color_name_or_code.lower()] if color_name_or_code.lower() in d else color_name_or_code \n\n intcodes = [int(color_name_or_code[i:i+2], 16) for i in range(1, len(color_name_or_code), 2)]\n if intcodes[0] <= intcodes[2] or intcodes[1] <= intcodes[2]:\n return color_name_or_code\n \n intcodes = sorted(intcodes)\n intcodes = map (lambda x: hex(x)[2:] if len(hex(x)[2:]) == 2 else '0' + hex(x)[2:] , [intcodes[0], intcodes[2], intcodes[1]])\n intcodes = '#' + ''.join(intcodes)\n \n return intcodes.upper() if any([c.isupper() for c in color_name_or_code]) else intcodes", "def yellow_be_gone(s):\n if s[0] == \"#\":\n x = s[1:]\n r, g, b = x[:2], x[2:4], x[4:]\n if r > b and g > b:\n r, b, g = sorted((r, g, b))\n return f\"#{r}{g}{b}\"\n return s\n d = {\"gold\": \"ForestGreen\", \"khaki\": \"LimeGreen\", \"lemonchiffon\": \"PaleGreen\", \"lightgoldenrodyellow\": \"SpringGreen\", \"lightyellow\": \"MintCream\", \"palegoldenrod\": \"LightGreen\", \"yellow\": \"Lime\"}\n x = s.lower()\n return d[x] if x in d else s", "def yellow_be_gone(s):\n d = {'gold':'ForestGreen','khaki':'LimeGreen','lemonchiffon':'PaleGreen', 'lightgoldenrodyellow':'SpringGreen','lightyellow':'MintCream','palegoldenrod':'LightGreen','yellow':'Lime'}\n if s.lower() in d: return d.get(s.lower())\n if not s.startswith('#'): return s\n flag = any(i.isupper() for i in s)\n r,g,b = map(lambda x: int(x,16), (s[1:3],s[3:5],s[5:8]))\n if r>b and g>b: \n x,y,z = sorted((r,g,b))\n r,g,b = x,z,y\n c = '#' + ''.join(format(i,'02x') for i in (r,g,b))\n return c.upper() if flag else c"]
{"fn_name": "yellow_be_gone", "inputs": [["lemonchiffon"], ["GOLD"], ["pAlEgOlDeNrOd"], ["BlueViolet"], ["#000000"], ["#b8860b"], ["#8FBC8F"], ["#C71585"]], "outputs": [["PaleGreen"], ["ForestGreen"], ["LightGreen"], ["BlueViolet"], ["#000000"], ["#0bb886"], ["#8FBC8F"], ["#C71585"]]}
INTRODUCTORY
PYTHON3
CODEWARS
5,788
def yellow_be_gone(s):
dd9d855229a31130283504eae51d6f79
UNKNOWN
We have two consecutive integers k1 and k2, k2 = k1 + 1 We need to calculate the lowest integer `n`, such that: the values nk1 and nk2 have the same digits but in different order. E.g.# 1: ``` k1 = 100 k2 = 101 n = 8919 #Because 8919 * 100 = 891900 and 8919 * 101 = 900819 ``` E.g.# 2: ``` k1 = 325 k2 = 326 n = 477 #Because 477 * 325 = 155025 and 477 * 326 = 155502 ``` Your task is to prepare a function that will receive the value of `k` and outputs the value of `n`. The examples given above will be: ```python find_lowest_int(100) === 8919 find_lowest_int(325) === 477 ``` Features of the random tests ``` 10 < k < 10.000.000.000.000.000 (For Python, Ruby and Haskell) 10 < k < 1.000.000.000 (For Javascript 1e9) ``` Enjoy it!! Ruby and Javascript versions will be released soon.
["def find_lowest_int(k1):\n k2, n = k1 + 1, 1\n\n def digits(n):\n return sorted(str(n))\n \n while digits(n*k1) != digits(n*k2):\n n += 1\n \n return n", "from itertools import count as c\n\ndef find_lowest_int(k):\n return next((n for n in c(1) if sorted(str(n*k))== sorted(str(n*(k+1)))))\n\n", "def find_lowest_int(k):\n return next(n for n in range(9, 9999999, 9) if sorted(str(n * k)) == sorted(str(n * (k+1))))", "def find_lowest_int(k):\n l, n = k + 1, 9\n while digits(k * n) != digits(l * n):\n n += 9\n return n\n\ndef digits(n):\n return sorted(str(n)) ", "def find_lowest_int(number):\n multiplier = 1\n while sorted(str(number * multiplier)) != sorted(str((number + 1) * multiplier)):\n multiplier += 1\n return multiplier", "from itertools import count\n\ndef find_lowest_int(k):\n return next(n for n in count(1) if sorted(str(n*k)) == sorted(str(n*(k+1))))", "from collections import Counter\n\n# idea: the difference between k*n and (k+1)*n is n\n# for them to have the same digits they must have the same digit sum\n# so n must have a digit sum of 0 (mod 9) - n must be divisible by 9\ndef find_lowest_int(k):\n n = 9\n while True:\n if Counter(str(k*n)) == Counter(str((k+1)*n)):\n return n\n n += 9\n", "def find_lowest_int(k):\n n=2\n while True:\n if sorted(str(n*k))==sorted(str(n*(k+1))):return n\n n+=1"]
{"fn_name": "find_lowest_int", "inputs": [[325], [599], [855], [1], [100], [1000], [10000]], "outputs": [[477], [2394], [999], [125874], [8919], [89919], [899919]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,461
def find_lowest_int(k):
ffdaea9b53a36d6808e00231d4552509
UNKNOWN
Write a function that takes a list comprised of other lists of integers and returns the sum of all numbers that appear in two or more lists in the input list. Now that might have sounded confusing, it isn't: ```python repeat_sum([[1, 2, 3],[2, 8, 9],[7, 123, 8]]) >>> sum of [2, 8] return 10 repeat_sum([[1], [2], [3, 4, 4, 4], [123456789]]) >>> sum of [] return 0 repeat_sum([[1, 8, 8], [8, 8, 8], [8, 8, 8, 1]]) sum of [1,8] return 9 ```
["from collections import defaultdict\n\ndef repeat_sum(l):\n count = defaultdict(int)\n for l1 in l:\n for val in set(l1):\n count[val] += 1\n \n return sum(k for k,v in list(count.items()) if v > 1)\n", "from collections import Counter\n\n\ndef repeat_sum(l):\n counter = sum((Counter(set(el)) for el in l), Counter())\n return sum(num for num in counter if counter[num] > 1)\n", "def repeat_sum(l):\n s, r = set(), set()\n for a in map(set, l):\n r |= a & s\n s |= a\n return sum(r)", "from collections import Counter\nfrom itertools import chain\n\ndef repeat_sum(l):\n return sum(key for key, value in Counter(chain.from_iterable(set(x) for x in l)).items() if value > 1)", "from collections import Counter as Cnt\n\nrepeat_sum = lambda l: sum(k for k,v in Cnt([e for ll in l for e in set(ll)]).items() if v>1)\n", "def repeat_sum(l):\n f = [n for s in l for n in set(s)]\n return sum(n for n in set(f) if f.count(n) > 1)", "from collections import Counter\n\ndef repeat_sum(l):\n commons = Counter()\n for s in l:\n commons.update(set(s))\n return sum(x for x,c in commons.items() if c>1)", "repeat_sum=lambda x:sum(list(set([j for i in x for j in i if sum(1for q in x if j in q)>1])))"]
{"fn_name": "repeat_sum", "inputs": [[[[1, 2, 3], [2, 8, 9], [7, 123, 8]]], [[[1], [2], [3, 4, 4, 4], [123456789]]], [[[1, 8, 8], [8, 8, 8], [8, 8, 8, 1]]], [[[1]]]], "outputs": [[10], [0], [9], [0]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,277
def repeat_sum(l):
415de8424b0be9eab199831c9d5fba73
UNKNOWN
Most football fans love it for the goals and excitement. Well, this Kata doesn't. You are to handle the referee's little notebook and count the players who were sent off for fouls and misbehavior. The rules: Two teams, named "A" and "B" have 11 players each; players on each team are numbered from 1 to 11. Any player may be sent off the field by being given a red card. A player can also receive a yellow warning card, which is fine, but if he receives another yellow card, he is sent off immediately (no need for a red card in that case). If one of the teams has less than 7 players remaining, the game is stopped immediately by the referee, and the team with less than 7 players loses. A `card` is a string with the team's letter ('A' or 'B'), player's number, and card's color ('Y' or 'R') - all concatenated and capitalized. e.g the card `'B7Y'` means player #7 from team B received a yellow card. The task: Given a list of cards (could be empty), return the number of remaining players on each team at the end of the game (as a tuple of 2 integers, team "A" first). If the game was terminated by the referee for insufficient number of players, you are to stop the game immediately, and ignore any further possible cards. Note for the random tests: If a player that has already been sent off receives another card - ignore it.
["def men_still_standing(cards):\n # generate teams\n A = {k: 0 for k in range(1, 12)}\n B = A.copy()\n \n for card in cards:\n # parse card\n team = A if card[0] == \"A\" else B\n player = int(card[1:-1])\n color = card[-1]\n \n if player not in team:\n continue\n \n # record penalty\n team[player] += 1 if color == \"Y\" else 2\n \n if team[player] >= 2:\n del team[player]\n \n if len(team) < 7:\n break\n \n return len(A), len(B)\n", "class Player:\n def __init__ (self):\n self.red_cards = 0\n self.yellow_cards = 0\n @property\n def excluded (self):\n return (self.red_cards or \n self.yellow_cards > 1)\n def receive_red (self):\n self.red_cards += 1\n def receive_yellow (self):\n self.yellow_cards += 1\n\nclass Team:\n def __init__ (self, size):\n self.size = size\n self.players = {number: Player()\n for number in range(1, size+1)}\n @property\n def count (self):\n return sum(not player.excluded for \n player in list(self.players.values()))\n def give_red (self, number):\n self.players[number].receive_red()\n def give_yellow (self, number):\n self.players[number].receive_yellow()\n\ndef men_still_standing (cards):\n teams = { 'A': Team(11), 'B': Team(11) }\n actions = {\n 'R': Team.give_red, 'Y': Team.give_yellow }\n \n import re\n pattern = '(A|B)([0-9]+)(R|Y)'\n for card in cards:\n match = re.match(pattern, card)\n team, player, color = match.group(1, 2, 3)\n actions[color](teams[team], int(player))\n if any(team.count < 7 \n for team in list(teams.values())):\n break\n \n return tuple(team.count for team in list(teams.values()))\n \n \n \n \n", "def men_still_standing(cards):\n teams = {'A': dict.fromkeys(range(1, 12), 2), 'B': dict.fromkeys(range(1, 12), 2)}\n for card in cards:\n t, number, color = card[:1], int(card[1:-1]), card[-1:]\n team = teams[t]\n if number not in team:\n continue\n team[number] -= 2 if color == 'R' else 1\n if team[number] <= 0:\n del team[number]\n if len(team) < 7:\n break\n return len(teams['A']), len(teams['B'])", "def men_still_standing(cards):\n players, Y, R = {\"A\": 11, \"B\": 11}, set(), set()\n for c in cards:\n if c[:-1] not in R:\n players[c[0]] -= c[-1] == \"R\" or c[:-1] in Y\n if 6 in players.values():\n break\n (R if (c[-1] == \"R\" or c[:-1] in Y) else Y).add(c[:-1])\n return players[\"A\"], players[\"B\"]", "'''\n1.\u521b\u5efaA,B\u4e24\u961f\u7684\u5b57\u5178 key=player\u51e0\u53f7\u7403\u5458 value=\u88ab\u7f5a\u6570 \u521d\u59cb\u503c\u90fd\u662f0 \u9ec4\u724c+1 \u7ea2\u724c+2\n2.\u5faa\u73afcards \u5148\u5224\u65ad\u662fA.B\u54ea\u961f\uff1f\u518d\u5224\u65ad\u662f\u51e0\u53f7\u7403\u5458\uff1f \u518d\u770b\u662f\u54ea\u4e2a\u989c\u8272\uff1f\n3.\u5982\u679c\u8fd9\u4e2a\u961f\u5458\u5df2\u7ecf\u4e0d\u518dteam\u4e2d\uff08\u6dd8\u6c70\uff09 \u5219\u7ee7\u7eed\u5faa\u73af\n4.\u82e5\u4e3a\u9ec4\u8272\u5219\u901a\u8fc7key=player\u627e\u5230value+1 \u7ea2\u8272\u5219+2\n5.\u82e5value=2\u5219del\n6.\u5982\u679c\u5220\u9664\u540elen(team)<7 \u8df3\u51fa\u5faa\u73af\n7.\u6700\u540e\u8fd4\u56delen(A) len(B)---\u56e0\u4e3ateam=A \u6d45\u62f7\u8d1d\n\u6ce8\u610f\uff1acopy\u662f\u6df1\u62f7\u8d1d B\u4e0d\u4f1a\u968f\u7740A\u6539\u53d8\u800c\u6539\u53d8\n'''\ndef men_still_standing(cards):\n #\u8d77\u59cb\u7403\u5458\u72b6\u6001\n A={k:0 for k in range(1,12)}\n B=A.copy()\n \n #\u8bb0\u5f55\u7403\u5458\u4fe1\u606f\n for card in cards:\n team=A if card[0]=='A' else B\n player=int(card[1:-1])\n color=card[-1]\n \n if player not in team: #\u7403\u5458\u5df2\u7ecf\u88ab\u6dd8\u6c70\n continue\n \n team[player]+=1 if color=='Y' else 2\n \n if team[player]>=2:\n del team[player]\n \n if len(team)<7:\n break\n return len(A),len(B)\n", "def men_still_standing(cards):\n print(cards)\n playersA = {}\n playersB = {}\n \n countA = 11\n countB = 11\n \n for i in range(1, 12):\n playersA[i] = 2\n playersB[i] = 2\n \n for foul in cards:\n team = foul[0]\n \n countA = 11\n countB = 11\n \n if len(foul) == 4:\n number = int(foul[1:3])\n cardColor = foul[3]\n \n else: # 3 letters\n number = int(foul[1])\n cardColor = foul[2]\n \n if cardColor == 'R':\n cardValue = 2\n else:\n cardValue = 1\n \n if team == 'A':\n playersA[number] -= cardValue\n else:\n playersB[number] -= cardValue\n \n for value in list(playersA.values()):\n if value <= 0:\n countA -= 1\n \n for value in list(playersB.values()):\n if value <= 0:\n countB -= 1\n \n if countA < 7 or countB < 7:\n return (countA, countB)\n \n return (countA, countB)\n", "def men_still_standing(cards):\n a = {'n': 11}\n b = {'n': 11}\n for x in cards:\n jg(a if x[0] == 'A' else b, x)\n if a['n'] < 7 or b['n'] < 7: break\n return a['n'], b['n']\ndef jg(t, x):\n o = t.get(x[1:-1])\n if o == 1:\n t[x[1:-1]] = -1\n t['n'] -= 1\n elif o == None:\n if x[-1] == 'R':\n t[x[1:-1]] = -1\n t['n'] -= 1\n if x[-1] == 'Y':\n t[x[1:-1]] = 1", "def men_still_standing(cards):\n sent_off_A = set()\n sent_off_B = set()\n for i, card in enumerate(cards):\n if card.endswith(\"R\"):\n sent_off_B.add(card[1:-1]) if card[0] == \"B\" else sent_off_A.add(card[1:-1])\n elif card.endswith(\"Y\") and cards[:i].count(card) > 0:\n sent_off_B.add(card[1:-1]) if card[0] == \"B\" else sent_off_A.add(card[1:-1])\n if len(sent_off_A) == 5 or len(sent_off_B) == 5:\n break\n return (11 - len(sent_off_A), 11 - len(sent_off_B))\n", "def men_still_standing(cards):\n res={'A':[11]+[0]*11, 'B':[11]+[0]*11}\n for c in cards:\n team,num,card=c[0],int(c[1:-1]),c[-1]\n if res[team][num]<2:\n res[team][num]+= 1 if card==\"Y\" else 2\n if res[team][num]>1: \n res[team][0]-=1\n if res[team][0]<7:break\n return res['A'][0], res['B'][0]", "def men_still_standing(cards):\n players = [[2] * 11, [2] *11]\n AB = {\"A\":0, \"B\":1}\n penalty = {\"Y\": 1, \"R\": 2}\n for card in cards:\n team, number, color = card[0], int(card[1:-1]), card[-1]\n players[AB[team]][number-1] -= penalty[color]\n if sum(i>0 for i in players[AB[team]]) < 7:\n break\n return tuple((sum(i>0 for i in x) for x in players))\n", "def men_still_standing(cards):\n players = [11,11]\n dic = {}\n for string in cards:\n player = string[:-1]\n if player in dic:\n if dic[player][1] != 'out':\n dic[player][0] = 1\n else:\n if string[len(string) - 1] == 'Y':\n dic[player] = [0,'in']\n else:\n dic[player] = [1,'in']\n if dic[player][0] == 1 and dic[player][1] is 'in':\n if player[0] == 'A':\n players[0] -= 1\n else:\n players[1] -= 1\n dic[player][1] = 'out'\n if players[0] < 7 or players[1] < 7:\n return tuple(players)\n return tuple(players)\n", "def men_still_standing(cards):\n teams = {\n 'A': [ True, True, True, True, True, True, True, True, True, True, True ],\n 'B': [ True, True, True, True, True, True, True, True, True, True, True ], \n }\n for card in cards:\n team = card[0]\n color = card[-1]\n player = int(card[1:-1]) - 1\n if color == 'R' or teams[team][player] == 'Y':\n teams[team][player] = False\n elif color == 'Y' and teams[team][player] != False:\n teams[team][player] = 'Y'\n if len([1 for (_, team) in list(teams.items()) if players_up(team) >= 7]) < 2:\n break\n return (players_up(teams['A']), players_up(teams['B']))\n \ndef players_up(players):\n return len([1 for player in players if player != False])\n", "find=lambda d1,d2:(sum(1for j in d1.values()if len(j)<2and\"R\"not in j),sum(1for j in d2.values()if len(j)<2and\"R\"not in j))\ndef men_still_standing(a):\n d1 = {i: [] for i in range(1, 12)}\n d2 = __import__(\"copy\").deepcopy(d1)\n for i in a:\n [d1,d2][i[0] == \"B\"][int(i[1:-1])].append(i[-1])\n r = find(d1,d2)\n if any(j < 7 for j in r) : return r\n return find(d1,d2)", "from collections import defaultdict\ndef men_still_standing(cards):\n book = [defaultdict(int), defaultdict(int)]\n f = lambda book: sum((-1 for b in book.values() if b > 1), 11)\n cnt = [11, 11]\n for c in cards:\n team, num, card = c[0] == 'B', c[1:-1], c[-1]\n book[team][num] += (1,2)[card == 'R']\n cnt = list(map(f, book))\n if min(cnt) < 7:\n break\n return tuple(cnt)", "def men_still_standing(cards):\n A = {str(i):0 for i in range(1,12)}\n B = A.copy()\n for card in cards:\n if (11-sum(1 for i in A.values() if i >= 2)) <= 6 or (11-sum(1 for i in B.values() if i >= 2)) <= 6: break\n if card[-1] == 'Y': eval(card[0])[card[1:-1]] += 1 \n elif card[-1]==\"R\": eval(card[0])[card[1:-1]] += 2\n return (max(11-sum(1 for i in A.values() if i >= 2), 6), max(11-sum(1 for i in B.values() if i >= 2),6))", "def men_still_standing(cards):\n red = []\n yellow = []\n still_playing = {\"A\": 11, \"B\": 11}\n\n for card in cards:\n if still_playing[\"A\"] < 7 or still_playing[\"B\"] < 7:\n break\n\n if card[-1::] == \"Y\" and card[:-1:] not in red:\n if card[:-1:] not in yellow:\n yellow.append(card[:-1:])\n elif card[:-1:] in yellow:\n red.append(card[:-1:])\n still_playing[card[:1:]] -= 1\n elif card[-1::] == \"R\" and card[:-1:] not in red:\n red.append(card[:-1:])\n still_playing[card[:1:]] -= 1\n\n return still_playing[\"A\"], still_playing[\"B\"]", "def men_still_standing(cards):\n team_a = {i+1:0 for i in range(11)}\n team_b = team_a.copy()\n teams_dict = {'A': team_a, 'B': team_b} \n gone_players = {'A': [], 'B': []}\n for booking in cards:\n team = teams_dict[booking[0]]\n player = int(booking[1:-1])\n if player in gone_players[booking[0]]:\n continue\n if booking[-1]=='R':\n team[player] +=1\n else:\n team[player] +=0.5\n if team[player] >= 1:\n gone_players[booking[0]].append(player)\n if len(gone_players[booking[0]]) > 4:\n break\n return tuple([11 - len(gone_players['A']), 11 - len(gone_players['B'])])\n \n", "def men_still_standing(cards):\n A_sentoff = set()\n B_sentoff = set()\n \n for index, card in enumerate(cards):\n if card[-1] == \"R\":\n A_sentoff.add(card[1:-1]) if card[0] == \"A\" else B_sentoff.add(card[1:-1])\n elif card[-1] == \"Y\" and cards[:index].count(card) > 0:\n A_sentoff.add(card[1:-1]) if card[0] == \"A\" else B_sentoff.add(card[1:-1])\n \n if len(A_sentoff) == 5 or len(B_sentoff) == 5:\n break\n \n a_remaining = 11 - len(A_sentoff)\n b_remaining = 11 - len(B_sentoff)\n \n return (a_remaining, b_remaining)", "def men_still_standing(cards):\n if cards == []: return (11, 11)\n a, b = [1]*11, [1]*11\n dicA, dicB = {}, {}\n for i in cards:\n if i[-1] == 'Y':\n if i[:-1] in dicA:\n a[dicA[i[:-1]]-1] = 0\n elif i[:-1] in dicB:\n b[dicB[i[:-1]]-1] = 0\n else:\n if i[0] == 'A':\n dicA[i[:-1]] = int(i[1:-1])\n else:\n dicB[i[:-1]] = int(i[1:-1])\n elif i[-1] == 'R':\n if i[0] == 'A':\n a[int(i[1:-1])-1] = 0\n elif i[0] == 'B':\n b[int(i[1:-1])-1] = 0\n if sum(a) == 6 or sum(b) == 6:\n return (sum(a), sum(b))\n return (sum(a),sum(b))\n", "def men_still_standing(cards):\n\n print(cards)\n \n Team_A = 11\n Team_B = 11\n \n Yellows = []\n Reds = []\n \n for event in cards:\n \n if Team_A == 6 or Team_B == 6: #Traps too few players and abandons the match\n #print (\"Match abandoned\")\n return (Team_A, Team_B)\n\n else:\n \n print(event)\n\n if event[-1] == \"R\" and event[0:(len(event)-1)] not in Reds:\n \n print(\"Red card event\")\n \n Reds.append(event[0:(len(event)-1)]) # Add player to list of sent off players\n print(\"Red Cards\",Reds) \n \n if event[0] == \"A\":\n Team_A -= 1\n print(\"Team A remaining = \",str(Team_A))\n else:\n Team_B -= 1\n print(\"Team B remaining = \",str(Team_B))\n \n elif event[-1] == \"Y\" and event[0:(len(event)-1)] in Yellows and event[0:(len(event)-1)] not in Reds:\n print(\"2nd Yellow Card event, Player sent off\", Reds)\n Reds.append(event[0:(len(event)-1)]) # Add player to list of sent off players\n \n if event[0] == \"A\":\n Team_A -= 1\n print(\"Team A remaining = \",str(Team_A))\n else:\n Team_B -= 1\n print(\"Team B remaining = \",str(Team_B)) \n \n elif event[-1] == \"Y\":\n \n if event[0:(len(event)-1)] in Reds:\n print(\"Player already sent off\")\n else:\n Yellows.append(event[0:(len(event)-1)]) # Add player to list of players with a Yellow card\n print(\"Yellow card issued to\",Yellows)\n else:\n print(\"player already sent off!\")\n \n print(Team_A, Team_B)\n \n return(Team_A, Team_B)"]
{"fn_name": "men_still_standing", "inputs": [[[]], [["A4Y", "A4Y"]], [["A4Y", "A4R"]], [["A4Y", "A5R", "B5R", "A4Y", "B6Y"]], [["A4R", "A4R", "A4R"]], [["A4R", "A2R", "A3R", "A6R", "A8R", "A10R", "A11R"]]], "outputs": [[[11, 11]], [[10, 11]], [[10, 11]], [[9, 10]], [[10, 11]], [[6, 11]]]}
INTRODUCTORY
PYTHON3
CODEWARS
14,877
def men_still_standing(cards):
464ebcb1ee21fde9a366bed9ced1a470
UNKNOWN
Your task is to ___find the next higher number (int) with same '1'- Bits___. I.e. as much `1` bits as before and output next higher than input. Input is always an int in between 1 and 1<<30 (inclusive). No bad cases or special tricks... ### Some easy examples: ``` Input: 129 => Output: 130 (10000001 => 10000010) Input: 127 => Output: 191 (01111111 => 10111111) Input: 1 => Output: 2 (01 => 10) Input: 323423 => Output: 323439 (1001110111101011111 => 1001110111101101111) ``` First some static tests, later on many random tests too;-)! ### Hope you have fun! :-)
["def next_higher(value):\n s = f'0{value:b}'\n i = s.rfind('01')\n s = s[:i] + '10' + ''.join(sorted(s[i+2:]))\n return int(s, 2)", "from itertools import count\ndef next_higher(value):\n bits = bin(value).count('1')\n return next(i for i in count(value+1) if bin(i).count('1')==bits)", "import re\n\ndef next_higher(v):\n return int(re.sub(r'(0?1)(1*)(0*)$', r'10\\3\\2', f'{v:b}'), 2)", "from math import log2\n\ndef next_higher(v):\n l = v&-v\n u = ~(v|l-1) & -~(v|l-1)\n return (v|u-1)^u-1 | u | (v&u-1) >> int(log2(l))+1", "next_higher = lambda x : x + (x & -x) | (x ^ x + (x & -x)) // (x & -x) >> 2 \n", "from collections import Counter\n\ndef next_higher(prev: int) -> int:\n \"\"\"\n Consider the integer as a binary integer, left-padded with a zero. To find\n the next binary integer with the same number of bits we must swap (to\n preserve the number of set bits) the least significant zero (to ensure the\n increase is not too large) that is more significant than a one (to ensure\n that the swap causes an increase).\n\n This ensures that the number is strictly greater than the input.\n To ensure that it is the next number the remaining (less-significant) bit\n must be sorted (unset bits more significant than set bits) to get the\n smallest possible number.\n \"\"\"\n\n bin_string = f'0{prev:b}'\n i = bin_string.rfind(\"01\")\n counts = Counter(bin_string[i + 2:])\n return int(f'{bin_string[:i]}10{\"0\" * counts[\"0\"]}{\"1\" * counts[\"1\"]}', 2)", "def next_higher(value):\n value = list(bin(value)[2:][-1::-1])\n one = value.count('1')\n while True:\n tale = 1\n for i in range(len(value)):\n bite = str((int(value[i]) + tale) % 2)\n value[i] = bite\n tale = 1 if bite == '0' else 0\n if not tale:\n break\n if tale:\n value.append('1')\n if value.count('1') == one:\n break\n return int(''.join(value[-1::-1]), 2)", "def next_higher(n):\n b = f\"0{n:b}\"\n i = b.rfind(\"01\")\n return int(f\"{b[:i]}10{''.join(sorted(b[i+2:]))}\", 2)\n", "def next_higher(value):\n c=bin(value).count('1')\n output_num=''\n while True:\n value=value+1\n if c==bin(value).count('1'):\n output_num=value\n break\n return output_num", "def next_higher(value):\n value2=value+1\n while (bin(value)).count(\"1\")!=(bin(value2)).count(\"1\"):\n value2+=1\n return value2"]
{"fn_name": "next_higher", "inputs": [[128], [1], [1022], [127], [1253343]], "outputs": [[256], [2], [1279], [191], [1253359]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,544
def next_higher(value):
ce2713f019213f84b0076ec53aa640f7
UNKNOWN
Return an output string that translates an input string `s`/`$s` by replacing each character in `s`/`$s` with a number representing the number of times that character occurs in `s`/`$s` and separating each number with the character(s) `sep`/`$sep`.
["def freq_seq(s, sep):\n return sep.join([str(s.count(i)) for i in s])\n", "from collections import Counter\n\ndef freq_seq(s, sep):\n freq = Counter(s)\n return sep.join(str(freq[c]) for c in s)\n", "from collections import Counter\n\ndef freq_seq(string, separator):\n count = Counter(string)\n return separator.join(str(count[symbol]) for symbol in string)\n", "def freq_seq(s, sep):\n return sep.join(str(s.count(c)) for c in s)\n", "from collections import Counter \n\ndef freq_seq(s, sep):\n dic = Counter(s) \n result = ''\n \n for char in s:\n for key, value in list(dic.items()):\n if char == key:\n result += str(value)+sep\n \n \n return result[:-1]\n", "def freq_seq(s, sep):\n return sep.join([str(s.count(c)) for c in s])\n", "from collections import Counter\n\ndef freq_seq(string, sep):\n counter = Counter(string)\n return sep.join(str(counter[char]) for char in string)", "def freq_seq(s, sep):\n numero = len(s)\n conta = 0\n contatore = 0\n contatore1 = 0\n lista = []\n while conta != numero:\n z = str(s[conta])\n while contatore1 < numero:\n if z == s[contatore1]:\n contatore += 1\n contatore1 += 1\n contatore1 = 0\n lista.append(str(contatore))\n contatore = 0\n conta += 1\n x = sep.join(lista)\n return x\n\n \n", "def freq_seq(s, sep):\n return sep.join([str(s.count(letter)) for letter in s])", "def freq_seq(s, sep):\n freq = {}\n newStr = []\n for i in s:\n if freq.get(i) == None:\n freq[i] = 1\n else:\n freq[i] += 1\n for i in s:\n newStr.append(str(freq[i]))\n return sep.join(newStr)\n"]
{"fn_name": "freq_seq", "inputs": [["hello world", "-"], ["19999999", ":"], ["^^^**$", "x"]], "outputs": [["1-1-3-3-2-1-1-2-1-3-1"], ["1:7:7:7:7:7:7:7"], ["3x3x3x2x2x1"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,776
def freq_seq(s, sep):
904a1587a9b546939f55e1fab77d180d
UNKNOWN
# Task Given a sequence of 0s and 1s, determine if it is a prefix of Thue-Morse sequence. The infinite Thue-Morse sequence is obtained by first taking a sequence containing a single 0 and then repeatedly concatenating the current sequence with its binary complement. A binary complement of a sequence X is a sequence Y of the same length such that the sum of elements X_i and Y_i on the same positions is equal to 1 for each i. Thus the first few iterations to obtain Thue-Morse sequence are: ``` 0 0 1 0 1 1 0 0 1 1 0 1 0 0 1 ... ``` # Examples For `seq=[0, 1, 1, 0, 1]`, the result should be `true`. For `seq=[0, 1, 0, 0]`, the result should be `false`. # Inputs & Output - `[input]` integer array `seq` An non-empty array. Constraints: `1 <= seq.length <= 1000` `seq[i] ∈ [0,1]` - `[output]` a boolean value `true` if it is a prefix of Thue-Morse sequence. `false` otherwise.
["def is_thue_morse(seq):\n init_seq = [0]\n while len(init_seq) < len(seq):\n init_seq += [1 if n == 0 else 0 for n in init_seq]\n return init_seq[:len(seq)] == seq\n", "def is_thue_morse(seq):\n return all(bin(i).count('1')%2==n for i,n in enumerate(seq))", "sequence =\"0110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010010110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100101101001100101101001011001101001100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010010110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010011001011001101001011010011001011010010110011010010110100110010110011010011001011010010110011010010110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010010110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100101101001100101101001011001101001100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100101101001100101101001011001101001100101100110100101101001100101101001011001101001011010011001011001101001100101101001011001101001100101100110100101101001100101100110100110010110100101100110100101101001100101101001011001101001100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010010110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100101101001100101101001011001101001100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010010110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010011001011001101001011010011001011010010110011010010110100110010110011010011001011010010110011010010110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010010110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010011001011001101001011010011001011010010110011010010110100110010110011010011001011010010110011010011001011001101001011010011001011001101001100101101001011001101001011010011001011010010110011010011001011001101001011010011001011010010110011010010110100110010110011010011001011010010110011010010110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010011001011001101001011010011001011010010110011010010110100110010110011010011001011010010110011010010110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010010110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100101101001100101101001011001101001100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010010110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010011001011001101001011010011001011010010110011010010110100110010110011010011001011010010110011010010110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010010110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100101101001100101101001011001101001100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100101101001100101101001011001101001100101100110100101101001100101101001011001101001011010011001011001101001100101101001011001101001100101100110100101101001100101100110100110010110100101100110100101101001100101101001011001101001100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010010110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100101101001100101101001011001101001100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100101101001100101101001011001101001100101100110100101101001100101101001011001101001011010011001011001101001100101101001011001101001100101100110100101101001100101100110100110010110100101100110100101101001100101101001011001101001100101100110100101101001100101101001011001101001011010011001011001101001100101101001011001101001011010011001011010010110011010011001011001101001011010011001011001101001100101101001011001101001100101100110100101101001100101101001011001101001011010011001011001101001100101101001011001101001100101100110100101101001100101100110100110010110100101100110100101101001100101101001011001101001100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100101101001100101101001011001101001100101100110100101101001100101101001011001101001011010011001011001101001100101101001011001101001100101100110100101101001100101100110100110010110100101100110100101101001100101101001011001101001100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010010110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100101101001100101101001011001101001100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010010110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010011001011001101001011010011001011010010110011010010110100110010110011010011001011010010110011010010110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010010110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100101101001100101101001011001101001100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100101101001100101101001011001101001100101100110100101101001100101101001011001101001011010011001011001101001100101101001011001101001100101100110100101101001100101100110100110010110100101100110100101101001100101101001011001101001100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010010110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100101101001100101101001011001101001100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010010110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010011001011001101001011010011001011010010110011010010110100110010110011010011001011010010110011010010110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010010110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010011001011001101001011010011001011010010110011010010110100110010110011010011001011010010110011010011001011001101001011010011001011001101001100101101001011001101001011010011001011010010110011010011001011001101001011010011001011010010110011010010110100110010110011010011001011010010110011010010110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010011001011001101001011010011001011010010110011010010110100110010110011010011001011010010110011010010110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010010110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100101101001100101101001011001101001100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010010110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010011001011001101001011010011001011010010110011010010110100110010110011010011001011010010110011010010110100110010110\"\ndef is_thue_morse(seq): \n ins = \"\".join([str(i) for i in seq])\n return sequence.startswith(ins)", "def is_thue_morse(seq):\n return seq[0] == 0 and all(seq[i // 2] ^ seq[i] == i % 2 for i in range(len(seq)))", "import itertools\n\ndef genThueMorse():\n for n in itertools.count():\n yield (1 if bin(n).count('1') % 2 else 0)\n\ndef is_thue_morse(seq):\n gen = genThueMorse()\n for i in range(len(seq)):\n if seq[i] != next(gen):\n return False\n \n return True", "def is_thue_morse(seq):\n tm, lt, ls = [0], 1, len(seq)\n while lt <= ls:\n if seq[:lt] != tm:\n return False\n tm.extend([not d for d in tm])\n lt *= 2\n return tm[:ls] == seq", "def is_thue_morse(seq):\n s=[0]\n while len(s)<len(seq):\n s+=[1-v for v in s]\n return s[:len(seq)]==seq", "def is_thue_morse(seq):\n return seq == [1 if bin(n).count('1')%2 else 0 for n in range(len(seq))]", "is_thue_morse=lambda s: \"\".join(map(str,s))==\"0110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010010110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100101101001100101101001011001101001100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010010110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010011001011001101001011010011001011010010110011010010110100110010110011010011001011010010110011010010110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010010110100110010110100101100110100110010110011010010110100110010110\"[:len(s)]"]
{"fn_name": "is_thue_morse", "inputs": [[[0, 1, 1, 0, 1]], [[0]], [[1]], [[0, 1, 0, 0]]], "outputs": [[true], [true], [false], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
12,352
def is_thue_morse(seq):
9937ae390eda33785fbdec16fbeddf7c
UNKNOWN
Imagine you start on the 5th floor of a building, then travel down to the 2nd floor, then back up to the 8th floor. You have travelled a total of 3 + 6 = 9 floors of distance. Given an array representing a series of floors you must reach by elevator, return an integer representing the total distance travelled for visiting each floor in the array in order. ``` // simple examples elevatorDistance([5,2,8]) = 9 elevatorDistance([1,2,3]) = 2 elevatorDistance([7,1,7,1]) = 18 // if two consecutive floors are the same, //distance travelled between them is 0 elevatorDistance([3,3]) = 0 ``` Array will always contain at least 2 floors. Random tests will contain 2-20 elements in array, and floor values between 0 and 30.
["def elevator_distance(array):\n return sum(abs(a - b) for a, b in zip(array, array[1:]))", "def elevator_distance(array):\n return sum(abs(array[i+1] - array[i]) for i in range(len(array)-1))", "def elevator_distance(floors):\n return sum(abs(floors[i + 1] - floors[i]) for i in range(len(floors) - 1))", "def elevator_distance(array):\n return sum(abs(a - b) for a, b in zip(array, array[1::]))", "def elevator_distance(floors):\n return sum(abs(floors[i-1] - floors[i]) for i in range(1, len(floors)))", "def elevator_distance(array):\n a=0\n for i in range(0, len(array)-1):\n a+=abs(int(array[i]) - int(array[i+1]))\n return a\n", "def elevator_distance(array):\n return sum(abs(x-y) for x,y in zip(array[:-1],array[1:]))", "def elevator_distance(array):\n\n n = len(array)\n m = 0\n total_dist = 0\n\n while n >= 2:\n distance = abs(array[m] - array[m+1]) \n total_dist += distance\n\n n -= 1\n m += 1\n \n return (total_dist)", "def elevator_distance(ls):\n return sum(abs(x-y) for x,y in zip(ls,ls[1:]))", "from functools import reduce\n\ndef elevator_distance(lst):\n return sum(abs(a - b) for a, b in zip(lst, lst[1:]))"]
{"fn_name": "elevator_distance", "inputs": [[[5, 2, 8]], [[1, 2, 3]], [[7, 1, 7, 1]]], "outputs": [[9], [2], [18]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,226
def elevator_distance(array):
bfcbaabb551773ee2967653956cbb285
UNKNOWN
# Task The function `fold_cube(number_list)` should return a boolean based on a net (given as a number list), if the net can fold into a cube. Your code must be effecient and complete the tests within 500ms. ## Input Imagine a net such as the one below. ``` @ @ @ @ @ @ ``` Then, put it on the table with each `@` being one cell. ``` -------------------------- | 1 | 2 | 3 | 4 | 5 | -------------------------- | 6 | 7 | 8 | 9 | 10 | -------------------------- | 11 | 12 | 13 | 14 | 15 | -------------------------- | 16 | 17 | 18 | 19 | 20 | -------------------------- | 21 | 22 | 23 | 24 | 25 | -------------------------- ``` The number list for a net will be the numbers the net falls on when placed on the table. Note that the numbers in the list won't always be in order. The position of the net can be anywhere on the table, it can also be rotated. For the example above, a possible number list will be `[1, 7, 8, 6, 9, 13]`. ## Output `fold_cube` should return `True` if the net can be folded into a cube. `False` if not. --- # Examples ### Example 1: `number_list` = `[24, 20, 14, 19, 18, 9]` Shape and rotation of net: ``` @ @ @ @ @ @ ``` Displayed on the table: ``` -------------------------- | 1 | 2 | 3 | 4 | 5 | -------------------------- | 6 | 7 | 8 | @ | 10 | -------------------------- | 11 | 12 | 13 | @ | 15 | -------------------------- | 16 | 17 | @ | @ | @ | -------------------------- | 21 | 22 | 23 | @ | 25 | -------------------------- ``` So, `fold_cube([24, 20, 14, 19, 18, 9])` should return `True`. ### Example 2: `number_list` = `[1, 7, 6, 17, 12, 16]` Shape and rotation of net: ``` @ @ @ @ @ @ ``` Displayed on the table: ``` -------------------------- | @ | 2 | 3 | 4 | 5 | -------------------------- | @ | @ | 8 | 9 | 10 | -------------------------- | 11 | @ | 13 | 14 | 15 | -------------------------- | @ | @ | 18 | 19 | 20 | -------------------------- | 21 | 22 | 23 | 24 | 25 | -------------------------- ``` `fold_cube([1, 7, 6, 17, 12, 16])` should return `False`. #### *Translations appreciated!!* --- ### If you liked this kata.... check out these! - [Folding a 4D Cube (Tesseract)](https://www.codewars.com/kata/5f3b561bc4a71f000f191ef7) - [Wraping a net around a cube](https://www.codewars.com/kata/5f4af9c169f1cd0001ae764d)
["def fold_cube(nums):\n return expand(nums.pop(), set(nums), 1, 2, 3) == {1, 2, 3, -1, -2, -3}\n\n\ndef expand(val, nums, x, y, z):\n dirs = {z}\n for num in nums.copy():\n if abs(val - num) not in (1, 5) or {val % 5, num % 5} == {0, 1}:\n continue\n\n nums.discard(num)\n diff = val - num\n sign = diff // abs(diff)\n nx, ny, nz = (x, z * sign, -y * sign) if abs(diff) == 1 else (-z * sign, y, x * sign)\n dirs |= expand(num, nums, nx, ny, nz)\n return dirs", "def fold_cube(nums):\n stack = [nums[0]]\n for _ in range(6):\n for i in range(len(stack)):\n if ((stack[i]-1) % 5 > 0) and ((stack[i] - 1) in nums) and ((stack[i] - 1) not in stack):\n stack.append(stack[i] - 1)\n if ((stack[i]-1) % 5 < 4) and ((stack[i] + 1) in nums) and ((stack[i] + 1) not in stack):\n stack.append(stack[i] + 1)\n if ((stack[i]-1) > 5) and ((stack[i] - 5) in nums) and ((stack[i] - 5) not in stack):\n stack.append(stack[i] - 5)\n if ((stack[i]-1) < 21) and ((stack[i] + 5) in nums) and ((stack[i] + 5) not in stack):\n stack.append(stack[i] + 5)\n print(stack)\n print(nums)\n \n \n if len(stack) != 6:\n return False\n cols = []\n for n in stack:\n if ((n-1) % 5) not in cols:\n cols.append((n-1) % 5)\n rows = []\n for n in stack:\n if (int((n-1) / 5)) not in rows:\n rows.append(int((n-1) / 5))\n# print()\n# print(rows)\n# print()\n# print(cols)\n if len(rows) + len(cols) != 7:\n return False\n if len(rows) == 2:\n if (sum(rows)+1)/2*5+ sum(cols)/5+1 not in stack or (sum(rows)-1)/2*5+ sum(cols)/5+1 not in stack:\n return False\n if len(rows) == 3:\n if sum(rows)/3*5+(sum(cols)+2)/4+1 not in stack or sum(rows)/3*5+(sum(cols)-2)/4+1 not in stack:\n print((3))\n return False\n if len(rows) == 4:\n if (sum(rows)+2)/4*5+sum(cols)/3+1 not in stack or (sum(rows)-2)/4*5+sum(cols)/3+1 not in stack:\n print((4))\n return False\n if len(rows) == 5:\n if sum(rows)+ (sum(cols)+1)/2+1 not in stack or sum(rows)+ (sum(cols)-1)/2+1 not in stack:\n print((5))\n return False\n if len(rows) == 2:\n if sum(stack)%30 != 3:\n return False\n if len(rows) == 5:\n if sum(stack)%6 != 3:\n return False\n print(True)\n return True\n \n \n \n \n", "# Today I shall be mostly using geometry, group theory, and massive overkill to solve a problem... \n\n# These are the archetypes of the nets from a cube\nnets = [\n [\n [1, 0, 0, 0],\n [1, 1, 1, 1],\n [1, 0, 0, 0],\n ],\n [\n [1, 0, 0, 0],\n [1, 1, 1, 1],\n [0, 1, 0, 0],\n ],\n [\n [1, 0, 0, 0],\n [1, 1, 1, 1],\n [0, 0, 1, 0],\n ],\n [\n [1, 0, 0, 0],\n [1, 1, 1, 1],\n [0, 0, 0, 1],\n ],\n [\n [0, 1, 0, 0],\n [1, 1, 1, 1],\n [0, 0, 1, 0],\n ],\n [\n [0, 1, 0, 0],\n [1, 1, 1, 1],\n [0, 1, 0, 0],\n ],\n [\n [1, 1, 0, 0],\n [0, 1, 1, 1],\n [0, 1, 0, 0],\n ],\n [\n [1, 1, 0, 0],\n [0, 1, 1, 1],\n [0, 0, 1, 0],\n ],\n [\n [1, 0, 0, 0],\n [1, 1, 1, 0],\n [0, 0, 1, 1],\n ],\n [\n [1, 1, 0, 0],\n [0, 1, 1, 0],\n [0, 0, 1, 1],\n ],\n [\n [1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1],\n ],\n]\n\n# Various transformations we can apply to the nets...\ndef h_mirror(m):\n # Mirror a matrix horizontally\n return m[::-1]\n\ndef v_mirror(m):\n # Mirror a matrix vertically\n return [r[::-1] for r in m]\n \ndef transpose(m):\n # Transpose a matrix\n return list(map(list, zip(*m)))\n\ndef rotate_cw(m):\n # Rotate a matrix clock-wise\n coords = [(x, y) for y, row in enumerate(m) for x, v in enumerate(row) if v == 1]\n new_coords = normalise([(y, -x) for x, y in coords])\n result = [[0 for _ in range(len(m))] for _ in range(len(m[0]))]\n for x, y in new_coords:\n result[y][x] = 1\n return result\n\ndef rotate_ccw(m):\n # Rotate a matrix counter lock-wise\n coords = [(x, y) for y, row in enumerate(m) for x, v in enumerate(row) if v == 1]\n new_coords = normalise([(-y, x) for x, y in coords])\n result = [[0 for _ in range(len(m))] for _ in range(len(m[0]))]\n for x, y in new_coords:\n result[y][x] = 1\n return result\n\ndef identity(coords):\n # No transformation\n return coords\n\ndef normalise(coords):\n # Translate all coordinates to that all x>=0 and y>=0\n min_x = min(x for x, y in coords)\n min_y = min(y for x, y in coords)\n return tuple([(x - min_x, y - min_y) for x, y in coords])\n\ndef compose(*fns):\n # Compose transformations\n def apply(*args, **kwargs):\n result = fns[0](*args, **kwargs)\n for fn in fns[1:]: \n result = fn(result)\n return result\n return apply\n\n# Transformations needed to generate all the symmetries of the nets\ncompositions = [\n identity,\n h_mirror,\n v_mirror,\n transpose,\n rotate_cw,\n rotate_ccw,\n compose(rotate_cw, rotate_cw),\n compose(rotate_cw, rotate_cw, transpose),\n]\n\n# Build all possible transformations of each net\nsolutions = []\nfor net in nets:\n for composition in compositions:\n net_prime = composition(net)\n if net_prime not in solutions:\n solutions.append(net_prime)\n\ndef to_relative(m):\n # Find the coordinates of the 1s in the supplied matrix\n return tuple(sorted([(x, y) for y, row in enumerate(m) for x, v in enumerate(row) if v == 1]))\n\n# All possible solutions using a relative coordinate system\nrelative_coordinate_solutions = set(to_relative(s) for s in solutions)\n\ndef fold_cube(number_list):\n # Convert from numbered cells to relative coordinates\n relative_coordinates = normalise(sorted([((n - 1) // 5, (n - 1) % 5) for n in number_list]))\n # See if we have a known solution\n return relative_coordinates in relative_coordinate_solutions", "# number the cube faces like a dice 1-6\ndef folding(grid,face,list_on_face,remain_list):\n faces=[face]\n dirs=[1,-1,5,-5]\n if list_on_face % 5==1:\n dirs.remove(-1)\n if list_on_face % 5 ==0:\n dirs.remove(1)\n goto_dirs=[]\n print(remain_list)\n for direction in dirs:\n goto_cell=direction+list_on_face\n print((goto_cell,remain_list))\n if goto_cell in remain_list:\n remain_list.remove(goto_cell)\n goto_dirs.append(direction)\n print((\"face\",face,\"grid\",grid,\"listCELL\",list_on_face,\"to\",goto_dirs))\n for direction in goto_dirs:\n faces.extend(folding(\n grid=new_grid(face,direction,grid),\n face=new_face(grid, direction),\n list_on_face=list_on_face+direction,\n remain_list=remain_list\n ))\n return faces\n\ndef new_face(grid,direction):\n return grid[[1,-1,5,-5].index(direction)]\n\ndef new_grid(face, direction, grid):\n opposite_face={1:6,2:4,6:1,4:2,5:3,3:5}\n dir_index={1:0,-1:1,5:2,-5:3}\n newgrid=grid.copy()\n newgrid[dir_index[-direction]]=face\n newgrid[dir_index[direction]]=opposite_face[face]\n return newgrid\n\ndef fold_cube(number_list):\n faces=folding(grid=[3,5,2,4], #in dir [1,-1,5,-5]\n face=1,\n list_on_face=number_list[0],\n remain_list=number_list[1:])\n return sorted(faces)==list(range(1,7))\n #return True or False\n", "BASE = {' x\\nxxx\\n x \\n x ', ' x\\n x\\nxx\\nx \\nx ', ' x \\n xx\\nxx \\n x ', 'xx \\n xx\\n x \\n x ', ' x \\n xx\\nxx \\nx ', 'xxx\\n x \\n x \\n x ', 'xx \\n x \\n xx\\n x ', 'xx \\n x \\n xx\\n x', 'xx \\n x \\n x \\n xx', ' xx\\n xx \\nxx ', ' x \\nxxx\\n x \\n x '}\n\ndef reflect(s):\n return '\\n'.join(r[::-1] for r in s.split('\\n'))\n\ndef rotate(s):\n return '\\n'.join(''.join(c[::-1]) for c in zip(*s.split('\\n')))\n\ndef fold_cube(arr):\n table = [[' '] * 5 for _ in range(5)]\n x0, y0, x1, y1 = 4, 4, 0, 0\n for p in arr:\n x, y = divmod(p - 1, 5)\n table[x][y] = 'x'\n x0, y0 = min(x, x0), min(y, y0)\n x1, y1 = max(x, x1), max(y, y1)\n net = '\\n'.join(''.join(r[y0:y1 + 1]) for r in table[x0:x1 + 1])\n net2 = reflect(net)\n for i in range(4):\n if net in BASE or net2 in BASE:\n return True\n net, net2 = rotate(net), rotate(net2)\n return False", "db = [{9, 14, 18, 19, 20, 24}, {13, 14, 15, 16, 17, 18}, {2, 3, 8, 9, 10, 13}, {3, 6, 7, 8, 9, 12}, {4, 7, 8, 9, 10, 14}, {4, 6, 7, 8, 9, 13}, {8, 9, 13, 17, 18, 23}, {5, 10, 14, 15, 19, 24}, {3, 8, 12, 13, 18, 19}, {8, 12, 13, 14, 18, 23}, {7, 11, 12, 13, 17, 22}, {8, 13, 17, 18, 23, 24}, {8, 12, 13, 14, 18, 23}, {3, 8, 12, 13, 18, 19}, {13, 16, 17, 18, 19, 23}, {4, 9, 13, 14, 15, 19}, {2, 7, 8, 11, 12, 16}, {1, 6, 7, 8, 13, 14}, {13, 17, 18, 19, 20, 22}, {8, 12, 13, 14, 15, 18}, {15, 17, 18, 19, 20, 23}, {3, 6, 7, 8, 9, 12}, {8, 13, 17, 18, 19, 24}, {3, 4, 8, 13, 17, 18}, {6, 11, 12, 13, 14, 18}, {8, 12, 13, 18, 19, 24}, {2, 7, 8, 9, 10, 14}, {15, 17, 18, 19, 20, 25}, {10, 14, 15, 18, 19, 24}, {15, 17, 18, 19, 20, 24}, {11, 16, 17, 18, 19, 23}, {4, 8, 9, 14, 15, 19}, {5, 8, 9, 10, 14, 19}, {9, 13, 14, 19, 20, 24}, {8, 13, 14, 19, 20, 24}, {11, 16, 17, 18, 19, 22}, {2, 6, 7, 8, 13, 14}, {8, 12, 13, 18, 19, 23}, {8, 9, 14, 15, 19, 24}, {9, 13, 14, 19, 20, 24}, {3, 8, 12, 13, 14, 18}, {7, 12, 13, 17, 21, 22}, {7, 12, 16, 17, 18, 23}, {1, 2, 3, 7, 12, 17}, {9, 14, 18, 19, 24, 25}, {9, 11, 12, 13, 14, 16}, {14, 17, 18, 19, 20, 24}, {4, 9, 13, 14, 19, 20}, {2, 7, 8, 9, 14, 15}, {2, 3, 8, 9, 10, 13}, {6, 11, 12, 13, 17, 22}, {12, 16, 17, 18, 23, 24}, {7, 12, 16, 17, 18, 21}, {13, 14, 17, 18, 21, 22}, {4, 6, 7, 8, 9, 12}, {12, 17, 18, 19, 21, 22}, {8, 13, 18, 19, 22, 23}, {7, 12, 13, 18, 19, 23}, {1, 2, 7, 8, 9, 12}, {9, 14, 19, 20, 23, 24}, {11, 16, 17, 18, 19, 21}, {8, 13, 14, 17, 18, 23}, {9, 14, 15, 19, 23, 24}, {7, 12, 13, 14, 15, 19}, {6, 11, 12, 13, 17, 22}, {2, 6, 7, 8, 12, 17}, {3, 6, 7, 8, 9, 13}, {4, 5, 7, 8, 9, 12}, {3, 8, 9, 12, 13, 17}, {2, 3, 8, 9, 10, 15}, {6, 11, 12, 17, 22, 23}, {13, 17, 18, 19, 20, 24}, {8, 9, 14, 15, 19, 24}, {6, 7, 12, 13, 17, 22}, {9, 13, 14, 15, 17, 18}, {7, 12, 16, 17, 18, 22}, {8, 9, 14, 15, 19, 24}, {4, 9, 10, 14, 18, 19}, {8, 12, 13, 18, 19, 24}, {3, 4, 9, 10, 14, 19}, {8, 13, 14, 19, 24, 25}, {7, 12, 16, 17, 22, 23}, {8, 11, 12, 13, 17, 22}, {7, 12, 16, 17, 18, 22}, {2, 6, 7, 8, 13, 14}, {3, 4, 6, 7, 8, 12}, {3, 8, 9, 10, 14, 19}, {8, 13, 14, 15, 19, 24}, {4, 8, 9, 10, 12, 13}, {8, 13, 17, 18, 19, 23}, {2, 6, 7, 8, 9, 13}, {13, 16, 17, 18, 19, 23}, {3, 8, 12, 13, 14, 17}, {3, 7, 8, 9, 13, 18}, {9, 14, 15, 18, 19, 24}, {3, 6, 7, 8, 9, 12}, {11, 16, 17, 18, 19, 23}, {8, 9, 11, 12, 13, 18}, {7, 12, 13, 14, 15, 19}, {10, 12, 13, 14, 15, 18}, {8, 13, 17, 18, 23, 24}, {4, 9, 13, 14, 15, 19}, {13, 16, 17, 18, 23, 24}, {1, 2, 3, 7, 12, 17}, {9, 12, 13, 14, 15, 17}, {4, 9, 10, 14, 18, 19}, {12, 13, 18, 19, 24, 25}, {2, 7, 11, 12, 17, 18}, {2, 6, 7, 12, 13, 17}, {3, 7, 8, 9, 10, 13}, {1, 6, 7, 8, 9, 14}, {2, 7, 8, 9, 10, 12}, {3, 7, 8, 9, 10, 13}, {3, 7, 8, 13, 14, 19}, {5, 9, 10, 13, 14, 19}, {8, 13, 14, 17, 18, 23}, {4, 8, 9, 14, 15, 19}, {4, 8, 9, 14, 19, 20}, {3, 7, 8, 13, 14, 19}, {1, 2, 7, 8, 9, 12}, {7, 8, 13, 14, 19, 20}, {14, 15, 17, 18, 19, 23}, {8, 11, 12, 13, 17, 22}, {4, 8, 9, 12, 13, 18}, {4, 8, 9, 14, 19, 20}, {4, 9, 13, 14, 15, 18}, {7, 12, 13, 14, 15, 17}, {2, 7, 8, 11, 12, 16}, {1, 6, 7, 8, 9, 13}, {15, 17, 18, 19, 20, 24}, {8, 9, 10, 11, 12, 13}, {12, 16, 17, 18, 19, 21}, {9, 14, 18, 19, 20, 25}, {3, 4, 8, 12, 13, 18}, {9, 12, 13, 14, 15, 17}, {6, 7, 12, 13, 17, 22}, {10, 14, 15, 18, 19, 24}, {2, 3, 6, 7, 12, 17}, {4, 9, 13, 14, 15, 19}, {2, 7, 8, 9, 13, 18}, {3, 8, 13, 14, 17, 18}, {9, 10, 13, 14, 19, 24}, {3, 8, 9, 12, 13, 18}, {8, 12, 13, 14, 15, 18}, {14, 15, 18, 19, 22, 23}, {12, 16, 17, 18, 19, 21}, {7, 11, 12, 17, 18, 22}, {3, 6, 7, 8, 9, 11}, {7, 8, 12, 16, 17, 22}, {9, 13, 14, 15, 17, 18}, {6, 11, 12, 13, 14, 17}, {13, 17, 18, 19, 21, 22}, {12, 16, 17, 18, 19, 24}, {6, 11, 12, 13, 14, 18}, {14, 16, 17, 18, 19, 23}, {3, 7, 8, 9, 10, 13}, {4, 6, 7, 8, 9, 13}, {9, 12, 13, 14, 15, 20}, {2, 3, 6, 7, 12, 17}, {12, 13, 18, 19, 20, 23}, {8, 9, 10, 11, 12, 13}, {8, 13, 14, 17, 18, 23}, {4, 6, 7, 8, 9, 14}, {9, 12, 13, 14, 15, 19}, {3, 7, 8, 9, 11, 12}, {3, 8, 9, 12, 13, 18}, {9, 14, 15, 18, 19, 23}, {8, 12, 13, 14, 15, 18}, {3, 4, 9, 14, 15, 19}, {4, 8, 9, 14, 15, 20}, {7, 11, 12, 13, 14, 18}, {4, 9, 14, 18, 19, 20}, {2, 6, 7, 12, 13, 18}, {13, 16, 17, 18, 19, 23}, {9, 14, 19, 23, 24, 25}, {6, 11, 12, 13, 14, 18}, {7, 12, 16, 17, 18, 23}, {10, 12, 13, 14, 15, 19}, {4, 8, 9, 10, 14, 19}, {13, 16, 17, 18, 19, 22}, {4, 7, 8, 9, 10, 13}, {14, 17, 18, 19, 20, 23}, {12, 17, 18, 19, 20, 23}, {16, 17, 18, 23, 24, 25}, {8, 11, 12, 13, 14, 18}, {3, 8, 12, 13, 14, 18}, {9, 12, 13, 14, 15, 18}, {9, 13, 14, 19, 20, 25}, {7, 12, 13, 14, 15, 20}, {11, 12, 13, 18, 19, 20}, {7, 8, 13, 14, 18, 23}, {3, 6, 7, 8, 9, 12}, {10, 13, 14, 15, 17, 18}, {6, 7, 12, 13, 17, 22}, {4, 7, 8, 9, 10, 15}, {10, 13, 14, 15, 19, 24}, {8, 9, 11, 12, 13, 16}, {8, 12, 13, 14, 15, 20}, {11, 16, 17, 18, 19, 24}, {2, 7, 8, 9, 10, 12}, {13, 16, 17, 18, 19, 23}, {9, 12, 13, 14, 15, 19}, {4, 6, 7, 8, 9, 12}, {12, 16, 17, 18, 19, 22}, {2, 7, 11, 12, 13, 18}, {14, 15, 17, 18, 19, 22}, {3, 7, 8, 13, 18, 19}, {9, 11, 12, 13, 14, 16}, {9, 10, 12, 13, 14, 17}, {8, 12, 13, 14, 15, 18}, {12, 17, 18, 19, 20, 25}, {4, 7, 8, 9, 10, 14}, {8, 13, 18, 19, 22, 23}, {7, 8, 13, 14, 15, 20}, {12, 16, 17, 18, 19, 23}, {4, 7, 8, 9, 10, 15}, {1, 2, 7, 12, 17, 18}, {3, 7, 8, 13, 14, 18}, {4, 8, 9, 14, 15, 20}, {8, 12, 13, 14, 16, 17}, {4, 7, 8, 9, 10, 14}, {6, 7, 12, 13, 14, 19}, {12, 17, 18, 19, 20, 23}, {14, 17, 18, 19, 20, 23}, {8, 12, 13, 18, 19, 24}, {8, 12, 13, 18, 23, 24}, {8, 12, 13, 14, 15, 19}, {4, 5, 8, 9, 12, 13}, {6, 11, 12, 13, 17, 22}, {7, 11, 12, 13, 14, 19}, {8, 13, 17, 18, 19, 24}, {13, 16, 17, 18, 19, 23}, {2, 6, 7, 8, 12, 17}, {7, 12, 16, 17, 18, 22}, {14, 17, 18, 19, 20, 23}, {4, 8, 9, 10, 14, 19}, {6, 11, 12, 13, 14, 18}, {5, 8, 9, 10, 14, 19}, {9, 14, 18, 19, 20, 24}, {9, 13, 14, 15, 17, 18}, {6, 11, 12, 17, 18, 22}, {7, 11, 12, 17, 22, 23}, {7, 11, 12, 13, 14, 18}, {10, 13, 14, 15, 19, 24}, {12, 13, 18, 19, 20, 23}, {13, 16, 17, 18, 23, 24}, {8, 13, 17, 18, 19, 22}, {12, 16, 17, 18, 19, 23}, {11, 16, 17, 18, 19, 22}, {13, 16, 17, 18, 19, 23}, {14, 15, 17, 18, 19, 23}, {14, 17, 18, 19, 20, 24}, {6, 7, 12, 17, 22, 23}, {8, 11, 12, 13, 18, 19}, {8, 9, 11, 12, 13, 18}, {8, 13, 18, 19, 22, 23}, {18, 19, 20, 21, 22, 23}, {7, 12, 13, 14, 16, 17}, {7, 12, 16, 17, 18, 22}, {3, 4, 6, 7, 8, 13}, {2, 7, 8, 9, 10, 14}, {3, 8, 12, 13, 18, 19}, {9, 11, 12, 13, 14, 17}, {9, 13, 14, 17, 18, 23}, {7, 11, 12, 13, 18, 19}, {9, 11, 12, 13, 14, 16}, {10, 12, 13, 14, 15, 20}, {2, 7, 11, 12, 13, 16}, {14, 17, 18, 19, 20, 22}, {8, 12, 13, 14, 15, 18}, {15, 17, 18, 19, 20, 24}, {13, 17, 18, 19, 24, 25}, {12, 17, 18, 19, 20, 22}, {4, 5, 7, 8, 9, 14}, {9, 14, 18, 19, 24, 25}, {2, 7, 8, 11, 12, 17}, {12, 17, 18, 19, 20, 23}, {3, 8, 9, 13, 17, 18}, {6, 7, 12, 13, 14, 19}, {9, 14, 15, 18, 19, 24}, {10, 14, 15, 18, 19, 23}, {7, 12, 16, 17, 18, 22}, {12, 16, 17, 18, 19, 22}, {15, 17, 18, 19, 20, 22}, {3, 8, 13, 14, 17, 18}, {4, 8, 9, 12, 13, 18}, {7, 11, 12, 13, 18, 19}, {8, 11, 12, 13, 14, 17}, {7, 12, 16, 17, 18, 22}, {14, 17, 18, 19, 21, 22}, {1, 2, 7, 8, 13, 14}, {12, 16, 17, 18, 19, 23}, {2, 6, 7, 8, 9, 12}, {7, 11, 12, 13, 14, 19}, {5, 7, 8, 9, 10, 12}, {5, 7, 8, 9, 10, 15}, {4, 7, 8, 9, 14, 15}, {9, 12, 13, 14, 19, 20}, {3, 4, 9, 14, 15, 19}, {8, 13, 14, 17, 18, 23}, {2, 7, 8, 11, 12, 17}, {2, 7, 8, 13, 18, 19}, {8, 12, 13, 14, 18, 23}, {5, 10, 14, 15, 19, 24}, {4, 7, 8, 9, 10, 15}, {14, 15, 17, 18, 19, 23}, {8, 9, 14, 15, 19, 24}, {3, 7, 8, 9, 10, 13}, {9, 14, 15, 18, 19, 24}, {5, 7, 8, 9, 10, 15}, {7, 12, 17, 21, 22, 23}, {3, 8, 9, 14, 15, 20}, {12, 13, 18, 19, 20, 24}, {8, 13, 17, 18, 19, 23}, {7, 12, 13, 14, 16, 17}, {9, 13, 14, 19, 24, 25}, {8, 12, 13, 14, 16, 17}, {4, 9, 13, 14, 15, 18}, {1, 2, 7, 8, 12, 17}, {8, 9, 11, 12, 13, 16}, {9, 14, 18, 19, 20, 23}, {12, 17, 18, 19, 20, 24}, {3, 8, 12, 13, 17, 22}, {9, 14, 19, 20, 23, 24}, {2, 7, 8, 13, 14, 18}, {9, 14, 19, 23, 24, 25}, {8, 9, 11, 12, 13, 18}, {2, 7, 11, 12, 13, 17}, {1, 6, 11, 12, 17, 22}, {1, 6, 7, 12, 13, 17}, {7, 8, 12, 17, 21, 22}, {14, 16, 17, 18, 19, 24}, {12, 16, 17, 18, 19, 22}, {7, 12, 13, 16, 17, 22}, {8, 13, 14, 17, 18, 23}, {9, 13, 14, 19, 20, 24}, {2, 7, 8, 12, 16, 17}, {3, 4, 6, 7, 8, 13}, {4, 5, 7, 8, 9, 14}, {2, 6, 7, 8, 9, 13}, {7, 12, 16, 17, 22, 23}, {2, 6, 7, 8, 12, 17}, {7, 11, 12, 17, 18, 22}, {9, 10, 14, 18, 19, 23}, {8, 9, 13, 17, 18, 23}, {14, 16, 17, 18, 19, 23}, {7, 8, 12, 17, 21, 22}, {14, 16, 17, 18, 19, 23}, {10, 12, 13, 14, 15, 18}, {3, 6, 7, 8, 9, 12}, {6, 11, 12, 13, 17, 22}, {8, 11, 12, 13, 17, 22}, {8, 12, 13, 14, 15, 19}, {8, 9, 11, 12, 13, 16}, {7, 12, 16, 17, 18, 21}, {8, 11, 12, 13, 17, 22}, {8, 13, 14, 19, 24, 25}, {3, 8, 9, 10, 12, 13}, {6, 11, 12, 13, 17, 22}, {7, 12, 13, 14, 15, 17}, {14, 15, 17, 18, 19, 23}, {4, 9, 10, 13, 14, 18}, {8, 9, 10, 11, 12, 13}, {2, 7, 8, 13, 18, 19}, {3, 8, 12, 13, 18, 19}, {9, 13, 14, 19, 20, 24}, {2, 7, 12, 13, 18, 23}, {6, 11, 12, 17, 18, 23}, {4, 9, 14, 18, 19, 20}, {9, 12, 13, 14, 15, 17}, {6, 11, 12, 13, 14, 16}, {9, 13, 14, 15, 19, 24}, {14, 17, 18, 19, 20, 25}, {14, 17, 18, 19, 21, 22}, {7, 12, 13, 18, 19, 23}, {3, 4, 9, 14, 15, 20}, {2, 6, 7, 8, 9, 13}, {3, 4, 6, 7, 8, 13}, {8, 13, 14, 15, 19, 24}, {13, 16, 17, 18, 19, 22}, {8, 9, 11, 12, 13, 17}, {2, 6, 7, 12, 13, 17}, {1, 2, 7, 8, 9, 12}, {3, 8, 9, 12, 13, 17}, {2, 3, 8, 9, 10, 14}, {13, 16, 17, 18, 19, 23}, {8, 11, 12, 13, 14, 17}, {2, 7, 8, 11, 12, 16}, {6, 7, 12, 13, 14, 17}, {13, 18, 19, 20, 22, 23}, {10, 12, 13, 14, 15, 20}, {1, 6, 11, 12, 17, 22}, {2, 7, 8, 11, 12, 17}, {8, 9, 14, 19, 20, 25}, {2, 7, 11, 12, 17, 18}, {2, 6, 7, 12, 17, 18}, {8, 13, 18, 19, 22, 23}, {4, 8, 9, 10, 14, 19}, {9, 14, 18, 19, 20, 23}, {4, 6, 7, 8, 9, 12}, {14, 17, 18, 19, 20, 24}, {4, 8, 9, 10, 14, 19}, {2, 6, 7, 8, 9, 12}, {13, 17, 18, 19, 20, 25}, {7, 11, 12, 17, 22, 23}, {3, 6, 7, 8, 9, 13}, {7, 11, 12, 13, 14, 17}, {7, 11, 12, 13, 14, 19}, {4, 9, 13, 14, 18, 23}, {7, 12, 13, 16, 17, 22}, {4, 8, 9, 12, 13, 17}, {11, 12, 17, 18, 19, 23}, {12, 16, 17, 18, 19, 23}, {3, 8, 12, 13, 14, 19}, {1, 2, 3, 7, 12, 17}, {8, 9, 11, 12, 13, 18}, {7, 12, 13, 16, 17, 21}, {7, 11, 12, 13, 17, 22}, {2, 7, 11, 12, 13, 18}, {12, 16, 17, 18, 19, 23}, {7, 11, 12, 17, 18, 22}, {3, 8, 9, 10, 12, 13}, {7, 8, 9, 13, 18, 23}, {2, 7, 8, 9, 13, 18}, {11, 12, 13, 18, 19, 20}, {7, 12, 13, 14, 15, 20}, {4, 7, 8, 9, 10, 12}, {2, 7, 11, 12, 13, 17}, {9, 11, 12, 13, 14, 18}, {9, 11, 12, 13, 14, 17}, {9, 11, 12, 13, 14, 19}, {3, 8, 12, 13, 18, 19}, {4, 8, 9, 13, 17, 18}, {12, 13, 18, 19, 24, 25}, {7, 11, 12, 13, 17, 22}, {13, 18, 19, 20, 22, 23}, {6, 11, 12, 13, 17, 22}, {4, 5, 7, 8, 9, 13}, {8, 9, 10, 11, 12, 13}, {8, 9, 11, 12, 13, 17}, {8, 9, 10, 14, 19, 24}, {9, 14, 19, 23, 24, 25}, {13, 17, 18, 19, 20, 23}, {9, 14, 18, 19, 20, 24}, {11, 12, 17, 18, 19, 23}, {13, 16, 17, 18, 19, 23}, {7, 12, 16, 17, 18, 21}, {7, 8, 9, 13, 18, 23}, {5, 8, 9, 10, 12, 13}, {5, 7, 8, 9, 10, 12}, {2, 6, 7, 12, 13, 17}, {9, 12, 13, 14, 15, 19}, {14, 16, 17, 18, 19, 23}, {7, 12, 17, 18, 21, 22}, {16, 17, 18, 23, 24, 25}, {8, 12, 13, 14, 15, 17}, {8, 13, 17, 18, 19, 23}, {2, 3, 8, 9, 10, 14}, {4, 9, 14, 15, 18, 19}, {15, 17, 18, 19, 20, 25}, {4, 9, 10, 14, 18, 19}, {13, 16, 17, 18, 19, 23}, {7, 12, 13, 16, 17, 21}, {9, 11, 12, 13, 14, 19}, {3, 7, 8, 9, 10, 14}, {4, 8, 9, 14, 15, 19}, {2, 7, 12, 13, 16, 17}, {6, 7, 8, 13, 14, 15}, {7, 8, 12, 16, 17, 22}, {8, 9, 14, 15, 19, 24}, {3, 8, 13, 14, 17, 18}, {7, 12, 13, 14, 15, 19}, {15, 17, 18, 19, 20, 24}, {3, 6, 7, 8, 9, 11}, {3, 7, 8, 11, 12, 16}, {8, 12, 13, 16, 17, 22}, {6, 7, 8, 12, 17, 22}, {11, 16, 17, 18, 19, 21}, {8, 13, 14, 15, 19, 24}, {2, 6, 7, 12, 17, 18}, {7, 8, 13, 18, 23, 24}, {3, 6, 7, 8, 9, 13}, {4, 7, 8, 9, 13, 18}, {13, 17, 18, 19, 20, 24}, {3, 7, 8, 9, 10, 12}, {1, 6, 7, 12, 13, 17}, {3, 8, 9, 14, 15, 19}, {13, 16, 17, 18, 19, 22}, {12, 16, 17, 18, 19, 22}, {3, 7, 8, 9, 10, 14}, {14, 17, 18, 19, 20, 22}, {7, 11, 12, 17, 18, 22}, {1, 6, 7, 12, 13, 17}, {1, 6, 7, 8, 12, 17}, {2, 6, 7, 12, 17, 18}, {3, 7, 8, 9, 10, 15}, {7, 12, 13, 16, 17, 21}, {4, 6, 7, 8, 9, 13}, {1, 6, 7, 8, 9, 11}, {2, 7, 11, 12, 13, 17}, {13, 17, 18, 19, 20, 24}, {9, 13, 14, 15, 19, 24}, {8, 9, 13, 17, 18, 23}, {4, 9, 10, 13, 14, 19}, {1, 2, 3, 7, 12, 17},{9, 10, 14, 18, 19, 24}, {7, 12, 13, 14, 15, 18}, {4, 5, 9, 14, 18, 19}, {3, 4, 7, 8, 11, 12}, {8, 13, 18, 22, 23, 24}, {1, 6, 7, 12, 17, 18}, {2, 7, 8, 9, 10, 13}, {3, 6, 7, 8, 9, 14}, {8, 9, 14, 19, 20, 24}, {4, 6, 7, 8, 9, 11}, {9, 12, 13, 14, 18, 23}, {1, 2, 7, 8, 9, 13}, {8, 9, 13, 18, 22, 23}, {2, 3, 8, 13, 14, 18}, {1, 2, 7, 12, 13, 18}, {14, 16, 17, 18, 19, 22}, {1, 2, 7, 12, 13, 17}, {6, 7, 12, 13, 14, 18}, {3, 6, 7, 8, 12, 17}, {3, 7, 8, 11, 12, 17}, {1, 6, 7, 12, 13, 18}, {8, 12, 13, 17, 21, 22}, {4, 5, 8, 9, 14, 19}, {1, 6, 7, 8, 9, 12}, {7, 8, 11, 12, 17, 22}, {13, 16, 17, 18, 19, 21}, {6, 7, 12, 17, 18, 23}, {8, 11, 12, 13, 14, 19}, {2, 7, 11, 12, 16, 21}, {5, 9, 10, 14, 18, 19}, {4, 9, 14, 15, 20, 25}, {7, 8, 12, 16, 17, 21}, {9, 10, 12, 13, 14, 18}, {9, 10, 12, 13, 14, 19}, {2, 3, 7, 11, 12, 17}, {9, 13, 14, 17, 18, 22}, {7, 11, 12, 17, 18, 23}, {13, 14, 16, 17, 18, 23}, {14, 17, 18, 19, 24, 25}, {8, 13, 14, 15, 17, 18}, {7, 11, 12, 13, 14, 16}, {3, 8, 13, 14, 19, 24}, {2, 3, 8, 9, 13, 18}, {3, 4, 7, 8, 13, 18}, {4, 5, 9, 13, 14, 18}, {4, 9, 13, 14, 15, 20}, {2, 3, 8, 13, 14, 19}, {2, 7, 12, 16, 17, 18}, {10, 14, 15, 19, 23, 24}, {5, 7, 8, 9, 10, 14}, {3, 4, 6, 7, 8, 11}, {2, 7, 8, 13, 14, 19}, {3, 6, 7, 8, 13, 14}, {7, 12, 13, 14, 18, 23}, {7, 12, 13, 18, 23, 24}, {2, 3, 8, 13, 18, 19}, {14, 16, 17, 18, 19, 21}, {11, 12, 17, 18, 19, 22}, {8, 9, 12, 13, 18, 23}, {3, 4, 5, 6, 7, 8}, {4, 5, 9, 13, 14, 19}, {8, 9, 12, 13, 16, 17}, {8, 11, 12, 13, 14, 16}, {2, 7, 8, 9, 10, 15}, {4, 7, 8, 9, 11, 12}, {5, 9, 10, 13, 14, 18}, {13, 16, 17, 18, 19, 24}, {14, 18, 19, 20, 22, 23}, {8, 12, 13, 14, 19, 20}, {3, 8, 13, 17, 18, 19}, {3, 4, 9, 14, 19, 20}, {14, 15, 17, 18, 19, 24},{7, 8, 13, 18, 19, 23}, {2, 3, 8, 9, 14, 15}, {6, 7, 12, 17, 18, 22}, {3, 4, 8, 12, 13, 17}, {13, 14, 16, 17, 18, 21}, {2, 3, 7, 12, 16, 17}, {2, 6, 7, 8, 9, 14}, {13, 14, 16, 17, 18, 22}, {2, 3, 7, 11, 12, 16}, {2, 7, 8, 9, 11, 12}, {3, 4, 5, 9, 14, 19}, {8, 9, 13, 17, 18, 22}, {10, 12, 13, 14, 15, 17}, {7, 8, 13, 14, 15, 18}, {7, 12, 13, 14, 19, 20}, {2, 6, 7, 8, 9, 11}, {7, 8, 13, 18, 19, 24}, {3, 7, 8, 9, 14, 15}, {11, 16, 17, 18, 23, 24}, {7, 8, 13, 14, 15, 19}, {2, 3, 4, 8, 13, 18}, {8, 13, 14, 17, 18, 22}, {7, 12, 13, 18, 19, 24}, {9, 13, 14, 18, 22, 23}, {9, 10, 13, 14, 17, 18},{9, 10, 14, 19, 23, 24}, {12, 13, 18, 19, 20, 25}, {6, 11, 12, 13, 14, 19}, {8, 13, 14, 18, 22, 23}, {3, 7, 8, 12, 16, 17}, {1, 2, 7, 8, 9, 14}, {8, 12, 13, 16, 17, 21}, {6, 7, 12, 13, 18, 19}, {9, 12, 13, 14, 16, 17}, {15, 18, 19, 20, 22, 23}, {5, 7, 8, 9, 10, 13}, {6, 11, 12, 13, 18, 19}, {8, 13, 14, 19, 20, 25}, {8, 9, 14, 19, 24, 25}, {12, 17, 18, 19, 24, 25}, {1, 2, 3, 8, 9, 10}, {11, 12, 17, 18, 19, 24}, {3, 8, 9, 14, 19, 20}, {11, 12, 17, 18, 23, 24}]\ndef fold_cube(num_list): return set(num_list) in db\n'''\n\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\n\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\n\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff wait - that's illegal \u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\n\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\n\u28ff\u28ff\u28ff\u28ff\u28ff\u284f\u2809\u281b\u28bf\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u287f\u28ff\n\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u2800\u2800\u2800\u2808\u281b\u28bf\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u283f\u281b\u2809\u2801\u2800\u28ff\n\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28e7\u2840\u2800\u2800\u2800\u2800\u2819\u283f\u283f\u283f\u283b\u283f\u283f\u281f\u283f\u281b\u2809\u2800\u2800\u2800\u2800\u2800\u28f8\u28ff\u28ff\n\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28f7\u28c4\u2800\u2840\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u28f4\u28ff\u28ff\u28ff\u28ff\n\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u280f\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2820\u28f4\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\n\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u285f\u2800\u2800\u28b0\u28f9\u2846\u2800\u2800\u2800\u2800\u2800\u2800\u28ed\u28f7\u2800\u2800\u2800\u2838\u28ff\u28ff\u28ff\u28ff\u28ff\n\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u2803\u2800\u2800\u2808\u2809\u2800\u2800\u2824\u2804\u2800\u2800\u2800\u2809\u2801\u2800\u2800\u2800\u2800\u28bf\u28ff\u28ff\u28ff\u28ff\n\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28be\u28ff\u28f7\u2800\u2800\u2800\u2800\u2860\u2824\u2884\u2800\u2800\u2800\u2820\u28ff\u28ff\u28f7\u2800\u28b8\u28ff\u28ff\u28ff\u28ff\n\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u2840\u2809\u2800\u2800\u2800\u2800\u2800\u2884\u2800\u2880\u2800\u2800\u2800\u2800\u2809\u2809\u2801\u2800\u2800\u28ff\u28ff\u28ff\u28ff\n\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28e7\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2808\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28b9\u28ff\u28ff\u28ff\u28ff\n\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u28ff\u2803\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28b8\u28ff\u28ff\u28ff\u28ff\n'''", "U = 1\nF = 2\nR = 3\n\n\ndef fold_cube(num_list):\n print(num_list)\n nums = set(num_list)\n faces = set()\n print(nums)\n try:\n face = Face(nums.pop(), nums, faces)\n except:\n return False\n faces.add(face)\n# print(face.val)\n# print(face.borders())\n# for face in faces:\n# print(face.val, face.z)\n# return sum(f.z for f in faces) == 0\n fs = set(f.z for f in faces)\n return fs == {1, 2, 3, -1, -2, -3}\n\n\nclass Face:\n def __init__(self, val, nums, faces, x=F, y=R, z=U):\n# print(val, nums)\n self.nums = nums\n self.val = val\n self.z = z\n self.x = x\n self.y = y\n\n for num in self.borders():\n self.nums.remove(num)\n z, x, y = self.fold(num)\n# print(z, x, y)\n faces.add(Face(num, self.nums, faces, x=x, y=y, z=z))\n\n def borders(self):\n borders = []\n ds = (self.val - 1) // 5\n ms = (self.val - 1) % 5\n for num in self.nums:\n dn = (num - 1) // 5\n mn = (num - 1) % 5\n# print(ds, ms, dn, mn)\n if ds - dn == 0 and abs(ms - mn) == 1 or ms - mn == 0 and abs(ds - dn) == 1:\n borders.append(num)\n# if abs(self.val - num) in [1, 5]:\n# borders.append(num)\n# print(borders)\n return borders\n\n def fold(self, num):\n relation = self.val - num\n if relation == 5:\n z = self.x\n x = -self.z\n y = self.y\n elif relation == -5:\n z = -self.x\n x = self.z\n y = self.y\n elif relation == 1:\n z = -self.y\n x = self.x\n y = self.z\n elif relation == -1:\n z = self.y\n x = self.x\n y = -self.z\n return z, x, y\n\n def __hash__(self):\n return self.val\n\n def __eq__(self, other):\n return self.val == other.val\n", "def fold_cube(number_list):\n print(number_list)\n connections = 0\n number_list.sort()\n\n for i in range(len(number_list)):\n if ((number_list[i] - 1) in number_list) and (number_list[i] not in [6, 11, 16, 21]): connections += 1\n for j in range(len(number_list)):\n if ((number_list[j] - 5) in number_list): connections += 1\n\n # in cube 6 faces are connected by 5 edges\n if connections != 5: return False\n\n horizontal = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]]\n vertical = [[1, 6, 11, 16, 21], [2, 7, 12, 17, 22], [3, 8, 13, 18, 23], [4, 9, 14, 19, 24], [5, 10, 15, 20, 25]]\n\n lenghts_horizontal = []\n height = 0\n\n for h in horizontal:\n lh = 1\n any_in_row = False\n for i in range(len(number_list)):\n if number_list[i] in h:\n any_in_row = True\n if ((number_list[i] - 1) in number_list) and (number_list[i] in h) and (\n number_list[i] not in [6, 11, 16, 21]):\n lh += 1\n if lh > 1:\n lenghts_horizontal.append(lh)\n elif any_in_row:\n lenghts_horizontal.append(1)\n if any_in_row:\n height += 1\n\n if lenghts_horizontal[0] == 4 or lenghts_horizontal[-1] == 4:\n return False\n\n is_3_horizontal_fist = False\n if lenghts_horizontal[0] == 3 or lenghts_horizontal[-1] == 3:\n is_3_horizontal_fist = True\n\n lenghts_horizontal.sort(reverse=True)\n\n if lenghts_horizontal[0] > 4: return False\n\n width = 0\n lenghts_vertical = []\n\n for v in vertical:\n lv = 1\n any_in_row = False\n for i in range(len(number_list)):\n if number_list[i] in v:\n any_in_row = True\n if ((number_list[i] - 5) in number_list) and (number_list[i] in v):\n lv += 1\n if lv > 1:\n lenghts_vertical.append(lv)\n elif any_in_row:\n lenghts_vertical.append(1)\n if any_in_row:\n width += 1\n\n if height == 3 and width == 3:\n return False\n\n if lenghts_vertical[0] == 4 or lenghts_vertical[-1] == 4:\n return False\n\n is_3_vertical_first = False\n if (lenghts_vertical[0] == 3) or (lenghts_vertical[-1] == 3):\n is_3_vertical_first = True\n\n lenghts_vertical.sort(reverse=True)\n\n if is_3_vertical_first and height == 4:\n return False\n\n if is_3_horizontal_fist and width == 4:\n return False\n\n if lenghts_vertical[0] > 4: return False\n\n if (lenghts_vertical[0] == 3 and lenghts_vertical[1] == 3 and width == 2):\n return True\n\n if (lenghts_horizontal[0] == 3 and lenghts_horizontal[1] == 3 and height == 2):\n return True\n\n upper = False\n upper_list = [1, 2, 3, 4, 5]\n lower = False\n lower_list = [21, 22, 23, 24, 25]\n left = False\n left_list = [1, 6, 11, 16, 21]\n right = False\n right_list = [5, 10, 15, 20, 25]\n\n for n in number_list:\n if n in upper_list:\n upper = True\n if n in lower_list:\n lower = True\n if n in left_list:\n left = True\n if n in right_list:\n right = True\n\n if upper and lower: return False\n if right and left: return False\n\n if lenghts_vertical == [2, 2, 1, 1] and lenghts_horizontal == [3, 2, 1] and width == 3 and height == 4:\n return False\n\n if ((lenghts_vertical[0] == 3 and width == 4 and height != 2) or (\n lenghts_horizontal[0] == 3 and height == 4 and width != 2)) and (lenghts_vertical != [3, 1, 1, 1]):\n return True\n\n if (lenghts_vertical[0] == 4 and width == 3 and height != 2) or (\n lenghts_horizontal[0] == 4 and height == 3 and width != 2):\n return True\n\n if (lenghts_vertical[0] == 3 and height == 4 and width != 2) or (\n lenghts_horizontal[0] == 3 and width == 4 and height != 2):\n return True\n\n if (lenghts_vertical[0] == 4 and height == 3 and width != 2) or (\n lenghts_horizontal[0] == 4 and width == 3 and height != 2):\n return True\n\n if lenghts_vertical == [2, 2, 2] and lenghts_horizontal == [2, 2, 1, 1]:\n return True\n\n if lenghts_horizontal == [2, 2, 2] and lenghts_vertical == [2, 2, 1, 1]:\n return True\n\n return False", "def fold_cube(number_list):\n print(number_list)\n connections = 0\n number_list.sort()\n\n for i in range(len(number_list)):\n if ((number_list[i] - 1) in number_list) and (number_list[i] not in [6, 11, 16, 21]): connections += 1\n for j in range(len(number_list)):\n if ((number_list[j] - 5) in number_list): connections += 1\n\n # in cube 6 faces are connected by 5 edges\n if connections != 5: return False\n\n horizontal = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]]\n vertical = [[1, 6, 11, 16, 21], [2, 7, 12, 17, 22], [3, 8, 13, 18, 23], [4, 9, 14, 19, 24], [5, 10, 15, 20, 25]]\n\n lenghts_horizontal = []\n height = 0\n\n for h in horizontal:\n lh = 1\n any_in_row = False\n for i in range(len(number_list)):\n if number_list[i] in h:\n any_in_row = True\n if ((number_list[i] - 1) in number_list) and (number_list[i] in h) and (\n number_list[i] not in [6, 11, 16, 21]):\n lh += 1\n if lh > 1:\n lenghts_horizontal.append(lh)\n elif any_in_row:\n lenghts_horizontal.append(1)\n if any_in_row:\n height += 1\n\n if lenghts_horizontal[0] == 4 or lenghts_horizontal[-1] == 4:\n return False\n\n # print(lenghts_horizontal)\n is_3_horizontal_fist = False\n if lenghts_horizontal[0] == 3 or lenghts_horizontal[-1] == 3:\n is_3_horizontal_fist = True\n\n lenghts_horizontal.sort(reverse=True)\n\n if lenghts_horizontal[0] > 4: return False\n\n width = 0\n lenghts_vertical = []\n\n for v in vertical:\n lv = 1\n any_in_row = False\n for i in range(len(number_list)):\n if number_list[i] in v:\n any_in_row = True\n if ((number_list[i] - 5) in number_list) and (number_list[i] in v):\n lv += 1\n if lv > 1:\n lenghts_vertical.append(lv)\n elif any_in_row:\n lenghts_vertical.append(1)\n if any_in_row:\n width += 1\n\n # print(lenghts_vertical)\n # print(lenghts_horizontal)\n # print(height,width)\n\n if height == 3 and width == 3:\n return False\n\n if lenghts_vertical[0] == 4 or lenghts_vertical[-1] == 4:\n return False\n\n is_3_vertical_first = False\n if (lenghts_vertical[0] == 3) or (lenghts_vertical[-1] == 3):\n is_3_vertical_first = True\n # print(height)\n\n # print(lenghts_vertical)\n # print(lenghts_vertical[0])\n\n lenghts_vertical.sort(reverse=True)\n\n if is_3_vertical_first and height == 4:\n return False\n\n if is_3_horizontal_fist and width == 4:\n return False\n\n print((height, width))\n print(lenghts_vertical)\n print(lenghts_horizontal)\n\n # print(is_3_vertical_first, is_3_horizontal_fist)\n\n if lenghts_vertical[0] > 4: return False\n\n # if (lenghts_vertical[0] == 3 and width == 3) or (lenghts_horizontal[0] == 3 and height == 3):\n # return True\n\n # if (lenghts_vertical[0] == 3 and height == 3) or (lenghts_horizontal[0] == 3 and width == 3):\n # return True\n\n if (lenghts_vertical[0] == 3 and lenghts_vertical[1] == 3 and width == 2):\n return True\n\n if (lenghts_horizontal[0] == 3 and lenghts_horizontal[1] == 3 and height == 2):\n return True\n\n upper = False\n upper_list = [1, 2, 3, 4, 5]\n lower = False\n lower_list = [21, 22, 23, 24, 25]\n left = False\n left_list = [1, 6, 11, 16, 21]\n right = False\n right_list = [5, 10, 15, 20, 25]\n\n for n in number_list:\n if n in upper_list:\n upper = True\n if n in lower_list:\n lower = True\n if n in left_list:\n left = True\n if n in right_list:\n right = True\n\n if upper and lower: return False\n if right and left: return False\n\n if lenghts_vertical == [2, 2, 1, 1] and lenghts_horizontal == [3, 2, 1] and width == 3 and height == 4:\n return False\n\n if ((lenghts_vertical[0] == 3 and width == 4 and height != 2) or (\n lenghts_horizontal[0] == 3 and height == 4 and width != 2)) and (lenghts_vertical != [3, 1, 1, 1]):\n return True\n\n if (lenghts_vertical[0] == 4 and width == 3 and height != 2) or (\n lenghts_horizontal[0] == 4 and height == 3 and width != 2):\n return True\n\n if (lenghts_vertical[0] == 3 and height == 4 and width != 2) or (\n lenghts_horizontal[0] == 3 and width == 4 and height != 2):\n return True\n\n if (lenghts_vertical[0] == 4 and height == 3 and width != 2) or (\n lenghts_horizontal[0] == 4 and width == 3 and height != 2):\n return True\n\n if lenghts_vertical == [2, 2, 2] and lenghts_horizontal == [2, 2, 1, 1]:\n return True\n\n if lenghts_horizontal == [2, 2, 2] and lenghts_vertical == [2, 2, 1, 1]:\n return True\n\n return False\n\n"]
{"fn_name": "fold_cube", "inputs": [[[24, 20, 14, 19, 18, 9]], [[1, 7, 6, 17, 12, 16]], [[12, 14, 13, 9, 10, 6]], [[18, 16, 17, 15, 13, 14]], [[1, 25, 24, 2, 3, 16]], [[1, 1, 1, 1, 1, 1]], [[2, 3, 8, 9, 10, 13]]], "outputs": [[true], [false], [false], [true], [false], [false], [true]]}
INTRODUCTORY
PYTHON3
CODEWARS
38,106
def fold_cube(nums):
ecdde50bf9b24e28ce10c81073bcf67c
UNKNOWN
In geometry, a cube is a three-dimensional solid object bounded by six square faces, facets or sides, with three meeting at each vertex.The cube is the only regular hexahedron and is one of the five Platonic solids. It has 12 edges, 6 faces and 8 vertices.The cube is also a square parallelepiped, an equilateral cuboid and a right rhombohedron. It is a regular square prism in three orientations, and a trigonal trapezohedron in four orientations. You are given a task of finding a if the provided value is a perfect cube!
["def you_are_a_cube(cube):\n return round(cube ** (1/3)) ** 3 == cube", "def you_are_a_cube(cube):\n return int(cube**0.33334)**3 == cube", "def you_are_a_cube(cube):\n x = round(abs(cube)**(1/3))\n if x**3 == cube:\n return True\n else:\n return False", "def you_are_a_cube(cube):\n return round(cube**(1/3),2) % 1 == 0", "def you_are_a_cube(cube):\n if(round(cube ** (1/3),10) == int(round(cube ** (1/3),10))):\n return True\n else:\n return False", "you_are_a_cube = lambda c: round(c**(1/3.0))**3 == c", "you_are_a_cube=lambda n:-n**(1/3)%1<1e-9", "def you_are_a_cube(cube):\n return int(round(cube**(1./3)))**3==cube", "def you_are_a_cube(cube):\n return (round(cube ** (1. / 3.), 2)).is_integer();", "from math import isclose\ndef you_are_a_cube(cube):\n return isclose(cube**(1.00/3.00)%1,1,rel_tol=0.0001) or isclose(cube**(1.00/3.00)%1,0,rel_tol=0.0001)"]
{"fn_name": "you_are_a_cube", "inputs": [[27], [1], [2], [99], [64]], "outputs": [[true], [true], [false], [false], [true]]}
INTRODUCTORY
PYTHON3
CODEWARS
926
def you_are_a_cube(cube):
a931970146414128c9c3c3a80b1bb3ba
UNKNOWN
In this Kata, we will check if a string contains consecutive letters as they appear in the English alphabet and if each letter occurs only once. ```Haskell Rules are: (1) the letters are adjacent in the English alphabet, and (2) each letter occurs only once. For example: solve("abc") = True, because it contains a,b,c solve("abd") = False, because a, b, d are not consecutive/adjacent in the alphabet, and c is missing. solve("dabc") = True, because it contains a, b, c, d solve("abbc") = False, because b does not occur once. solve("v") = True ``` All inputs will be lowercase letters. More examples in test cases. Good luck!
["import string\n\ndef solve(st):\n return ''.join(sorted(st)) in string.ascii_letters", "def solve(s):\n return \"\".join(sorted(s)) in \"abcdefghijklmnopqrstuvwxyz\"", "def solve(s):\n return len(s) == len(set(s)) == ord(max(s)) - ord(min(s)) + 1", "def solve(s):\n return len(s) == ord(max(s)) - ord(min(s)) + 1", "def solve(stg):\n return \"\".join(sorted(stg)) in \"abcdefghijklmnopqrstuvwxyz\"", "def solve(st):\n b = list(st)\n c = []\n for i in range(len(st)):\n c.append(ord(b[i]))\n for i in c:\n if c.count(i) != 1:\n return False\n for i in range(min(c),max(c)):\n if i+1 not in c:\n return False\n return True\n", "def solve(st):\n a = ''.join(sorted(st))\n if a in 'abcdefghijklmnopqrstuvwxyz':\n return True\n else:\n return False\n", "alph = \"abcdefghijklmnopqrstuvwxyz\"\n\ndef solve(st):\n return ''.join(sorted(st)) in alph", "def solve(st):\n new_st = []\n letters = 'abcdefghijklmnopqrstuvwxyz'\n for i in st:\n new_st.append(letters.index(i))\n new_st = sorted(new_st)\n \n a = [(new_st[i+1] - new_st[i]) for i in range(len(new_st)-1)]\n if a.count(1) == len(st) - 1:\n return True\n return False", "def solve(s):\n return \"\".join(sorted(list(s), key = str.lower)) in \"abcdefghijklmnopqrstuvwxyz\""]
{"fn_name": "solve", "inputs": [["abc"], ["abd"], ["dabc"], ["abbc"]], "outputs": [[true], [false], [true], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,366
def solve(st):
82942651a5ee6d9d805f1754de76edc9
UNKNOWN
In computing, there are two primary byte order formats: big-endian and little-endian. Big-endian is used primarily for networking (e.g., IP addresses are transmitted in big-endian) whereas little-endian is used mainly by computers with microprocessors. Here is an example (using 32-bit integers in hex format): Little-Endian: 00 6D F4 C9 = 7,206,089 Big-Endian: C9 F4 6D 00 = 3,388,239,104 Your job is to write a function that switches the byte order of a given integer. The function should take an integer n for the first argument, and the bit-size of the integer for the second argument. The bit size must be a power of 2 greater than or equal to 8. Your function should return a None value if the integer is negative, if the specified bit size is not a power of 2 that is 8 or larger, or if the integer is larger than the specified bit size can handle. In this kata, assume that all integers are unsigned (non-negative) and that all input arguments are integers (no floats, strings, None/nil values, etc.). Remember that you will need to account for padding of null (00) bytes. Hint: bitwise operators are very helpful! :)
["def switch_endian(n, bits):\n out = 0\n while bits > 7:\n bits -= 8\n out <<= 8\n out |= n & 255\n n >>= 8\n return None if n or bits else out", "# Bitwise operators? What's that? Don't need it\ndef switch_endian(n, bits):\n if not (0 <= n < 2**bits and bits == 2**(bits.bit_length()-1)): return\n x = f\"{n:0{bits}b}\"\n return int(''.join(x[i-8:i] for i in range(bits, 0, -8)), 2)", "def switch_endian(n, bits):\n if not (bits >= 8 and bits & bits - 1 == 0 and bits >= n.bit_length()):\n return None\n return int.from_bytes(n.to_bytes(bits // 8, 'little'), 'big')", "# Python 3 rocks!\nswitch_endian = lambda n, bits: int.from_bytes(n.to_bytes(bits//8, 'big'), 'little') if bits % 8 == 0 and bits >= 8 and n.bit_length() <= bits else None", "def switch_endian(n, bits):\n if 2**bits <= n or bits%8 != 0 or bits < 8:\n return None\n xn = bits//4\n x = format(n, 'x').zfill(xn)\n lst = [x.upper()[i:i+2] for i in range(0,len(x),2)]\n s = ''.join(lst[::-1])\n ans = int(s, 16)\n return ans if len(bin(ans)[2:]) <= bits else None", "lst0 = [2]\nfor i in range(1, 20):\n lst0.append(lst0[-1]*2)\n \ndef switch_endian(n, bits):\n if n < 0 or bits not in lst0 or (n, bits) == (256, 8):\n return None\n xn = bits//4\n x = format(n, 'x').zfill(xn)\n lst = [x.upper()[i:i+2] for i in range(0,len(x),2)]\n s = ''.join(lst[::-1])\n ans = int(s, 16)\n return ans if len(bin(ans)[2:]) <= bits else None", "# Switch the endianness of integer n\n# Assume 64-bit unsigned integers\ndef switch_endian(n, bits):\n if n<0 or bits&(bits-1) or bits<8 or n>=2**bits:\n return None\n result = 0\n for _ in range(bits//8):\n result = (result<<8) | (n&255)\n n >>= 8\n return result", "# Switch the endianness of integer n\n# Assume 64-bit unsigned integers\nimport re\nimport math\ndef switch_endian(n, bits):\n number_in_hex = hex(n)\n length = len(number_in_hex)-2\n result = int(bits/4)\n x = math.log(bits, 2).is_integer()\n if x == False:\n return None\n if length > result:\n return None\n if length <= result:\n diff = result-length\n number_in_hex = number_in_hex.replace('0x','0'*diff)\n res_list = re.findall('[\\da-z]{2}[^\\da-z]*', number_in_hex)\n res_list = res_list[::-1]\n number_in_hex = ''.join(res_list)\n return(int('0x'+number_in_hex, 0))\n", "from math import log2\ndef switch_endian(n, bits):\n if bits<8 or 2**int(log2(bits))!=bits or 2**bits-1<n:\n return None\n s='{:X}'.format(n).zfill(bits//4)\n r=''\n for i in range(0,len(s),2):\n r=s[i:i+2]+r\n return int(r,16)"]
{"fn_name": "switch_endian", "inputs": [[153, 8], [255, 8], [256, 8], [1534, 32], [364334, 32], [2, 64], [164345, 64], [23, 128], [256245645346, 128], [6423, 256], [988847589347589798345, 256], [98, 512], [9827498275894278943758934789347, 512], [111, 1024], [859983475894789589772983457982345896389458937589738945435, 1024], [98345873489734895, 16], [893458278957389257892374587, 32], [3457892758927985892347589273895789, 64], [5315, 9], [9999, 124], [1355, 2], [5425, 4], [1111, 1], [24626, 666]], "outputs": [[153], [255], [null], [4261740544], [781124864], [144115188075855872], [17978653386462986240], [30572243903053065076787562386447925248], [45528303328508850820834438375932952576], [10447366694034586540826038121892877184087912282225534899373057468243260735488], [91242511062515682511683596760355486395666889244852199999154981214322488770560], [5132676473181150452180681444625675470675694728195525589909800865174737792762529702056967504767017718412590320712014191342452658263948296307619131260141568], [11930836310133384514326160681165088053924843877461649523769728440666263776393580347680430230979602503027248413303643954184674561174505233796513849034145792], [77946850769420728811700342256867869309216970571326574052151324251985652400041433233322816339012642571657549377600486963672365876321875957409008065628834483616922797539687769006521665530227798622106610186255607970082166897421927265014079512773561809863796510492144840252477126168637689491549705283548003434496], [109358791181702534675750459978375317655425491983637702648061053285141449541556750052943705607891736023254034131895692863702552970350431938079186312678981100327891943154445619222027830694165819898582344009910545707293292608754474937152496600707613861415524072325452544924390687309129714181920077788312386928640], [null], [null], [null], [null], [null], [null], [null], [null], [null]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,736
def switch_endian(n, bits):
702a1cf0f621fccee5eea6227e49ecf0
UNKNOWN
Section numbers are strings of dot-separated integers. The highest level sections (chapters) are numbered 1, 2, 3, etc. Second level sections are numbered 1.1, 1.2, 1.3, 2.1, 2.2, 2.3, etc. Next level sections are numbered 1.1.1, 1.1.2, 1.1.2, 1.2.1, 1.2.2, erc. There is no bound on the number of sections a document may have, nor is there any bound on the number of levels. A section of a certain level may appear directly inside a section several levels higher without the levels between. For example, section 1.0.1 may appear directly under section 1, without there being any level 2 section. Section 1.1 comes after section 1.0.1. Sections with trailing ".0" are considered to be the same as the section with the trailing ".0" truncated. Thus, section 1.0 is the same as section 1, and section 1.2.0.0 is the same as section 1.2. ```if:python Write a function `compare(section1, section2)` that returns `-1`, `0`, or `1` depending on whether `section1` is before, same as, or after `section2` respectively. ``` ```if:javascript Write a function `cmp(section1, section2)` that returns `-1`, `0`, or `1` depending on whether `section1` is before, same as, or after `section2` respectively. ``` ```if:haskell Write a function `cmp section1 section2` that returns `LT`, `EQ` or `GT` depending on whether `section1` is before, same as, or after `section2` respectively. ```
["def compare(s1, s2):\n v1,v2 = version(s1),version(s2)\n return -1 if v1 < v2 else 1 if v1 > v2 else 0\n\ndef version( s ):\n v = [int(n) for n in s.split(\".\")]\n while( v[-1]==0 ) : v = v[0:-1]\n return v", "def compare(s1, s2):\n s1 , s2 = s1.split('.') , s2.split('.')\n for i in range(abs(len(s1)-len(s2))): min(s1,s2,key = len).append('0')\n for num1 , num2 in zip(s1 , s2):\n num1 , num2 = int(num1) , int(num2)\n if num1 > num2: return 1\n elif num1 < num2: return -1\n return 0", "from itertools import zip_longest as z\ncompare=lambda s1,s2:next(([1,-1][int(i)<int(j)] for i,j in z(s1.split('.'),s2.split('.'),fillvalue='0') if int(i)!=int(j)),0)", "import re\nfrom distutils.version import LooseVersion\n\nTRAILING_ZEROS = re.compile(r'(\\.0+)+$')\n\ndef cmp(a, b):\n return (a > b) - (a < b)\n\ndef compare(s1, s2):\n return cmp(LooseVersion(TRAILING_ZEROS.sub('', s1)), LooseVersion(TRAILING_ZEROS.sub('', s2)))", "def compare(s1, s2):\n s1, s2 = s1.split('.'), s2.split('.')\n if len(s1) < len(s2):\n s1 += ['0'] * (len(s2) - len(s1))\n elif len(s1) > len(s2):\n s2 += ['0'] * (len(s1) - len(s2))\n for i in range(len(s2)):\n if int(s1[i]) > int(s2[i]): return 1\n elif int(s1[i]) < int(s2[i]): return -1\n return 0", "def compare(s1, s2):\n s1 = list(map(int, s1.split('.')))\n s2 = list(map(int, s2.split('.')))\n dif = abs(len(s1) - len(s2))\n s1.extend([0]*dif) if len(s1) < len(s2) else s2.extend([0]*dif) \n for val_1, val_2 in zip(s1, s2):\n if val_1 != val_2:\n return 1 if val_1 > val_2 else -1\n return 0\n\n", "def compare(s1, s2):\n n1, n2 = [int(i) for i in s1.split(\".\")], [int(i) for i in s2.split(\".\")]\n l = min(len(n1), len(n2))\n for i in range(l):\n if n1[i] == n2[i]:\n continue\n return 1 if n1[i] > n2[i] else -1\n if any(n1[l:] + n2[l:]):\n return 1 if len(n1) > len(n2) else -1\n return 0"]
{"fn_name": "compare", "inputs": [["1", "2"], ["1.1", "1.2"], ["1.1", "1"], ["1.2.3.4", "1.2.3.4"], ["3", "3.0"], ["3", "3.0.0.0"], ["1.2.1", "1.2.0"], ["3.0.0", "3.1.1"], ["3.0.1", "3.1"], ["1.2.3", "1.02.003"], ["1.20", "1.5"]], "outputs": [[-1], [-1], [1], [0], [0], [0], [1], [-1], [-1], [0], [1]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,026
def compare(s1, s2):
9034f50837140f5efa4f77ec738e3142
UNKNOWN
# Palindrome strings A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward. This includes capital letters, punctuation, and word dividers. Implement a function that checks if something is a palindrome. ## Examples ``` isPalindrome("anna") ==> true isPalindrome("walter") ==> false isPalindrome(12321) ==> true isPalindrome(123456) ==> false ```
["def is_palindrome(string):\n return str(string)[::-1] == str(string)", "def is_palindrome(string):\n return str(string).lower() == str(string).lower()[::-1]", "def is_palindrome(string):\n return str(string) == str(string)[::-1]", "def is_palindrome(string):\n string=str(string)\n return string==string[::-1]", "def is_palindrome(string):\n a = []\n for i in str(string):\n a.insert(0, i)\n if list(str(string)) != a:\n return False\n else:\n return True\n", "def is_palindrome(string):\n string = str(string)\n return True if string[:len(string)//2] in string[len(string)//2:][::-1] else False", "def is_palindrome(string):\n string = str(string)\n return (string[::-1] == str(string)) ", "def is_palindrome(s):\n s = str(s).lower()\n return s == s[::-1]", "def is_palindrome(string):\n string = str(string)\n return string[::-1] == string", "def is_palindrome(s):\n return str(s) == str(s)[::-1]", "def is_palindrome(val):\n s = str(val)\n half_len = len(s) >> 1\n return s[:half_len] == s[::-1][:half_len]", "def is_palindrome(s):\n # If s is an int, make a list of digits of it\n if isinstance(s, int):\n digits = []\n while s:\n s, r = divmod(s, 10)\n digits.append(r)\n s = digits\n \n # Now check if the left side of s is the reversed of the right side \n return all(s[l] == s[r] for l, r in enumerate(range(len(s) - 1, len(s) // 2 - 1, -1)))\n", "def is_palindrome(string):\n s=str(string)\n if len(s)<1:\n return True\n else:\n if s[0]==s[-1]:\n return is_palindrome(s[1:-1])\n else:\n return False", "import string\ndef is_palindrome(string):\n string = str(string)\n string = string.casefold()\n rev = string[::-1]\n \n if string == rev:\n return True\n else:\n return False", "def is_palindrome(string):\n if type(string) == int: string = str(string)\n if len(string) < 2: return True\n return string[0] == string[-1] and is_palindrome(string[1:-1])", "def is_palindrome(string):\n x = str(string)\n if x[0] != x[-1]:\n return False\n else:\n if len(x) == 1 or len(x) == 2:\n return True\n else:\n return is_palindrome(x[1:-1])", "def is_palindrome(string):\n s = str(string)\n if len(s) < 2:\n return True\n else:\n if s[0] != s[-1]:\n return False\n else:\n return is_palindrome(s[1:-1])", "def is_palindrome(string):\n string=str(string)\n for i in range(0,len(string)//2):\n if string[i]==string[-i-1]:\n pass\n else:\n return False\n return True\n", "def is_palindrome(s):\n if not s:\n return True\n s = str(s)\n return is_palindrome(s[1:-1]) if s[0] == s[-1] else False", "def is_palindrome(string):\n start = 0\n end = -1\n palindrome = True\n for x in range(len(str(string))):\n if str(string)[start] == str(string)[end]:\n start += 1\n end -= 1\n else: palindrome = False\n return True if palindrome is True else False", "def is_palindrome(str):\n str = f\"{str}\"\n x = str[::-1]\n temp = - ((len(str) - 1 ) // 2 + 1 )\n if str[:-temp] == x[:-temp]:\n return True\n return False", "def is_palindrome(string):\n string = str(string)\n return str(string) == str(string[::-1])", "def is_palindrome(string):\n try:\n if string == string[::-1]:\n return True\n except:\n if str(string) == str(string)[::-1]:\n return True\n return False", "def is_palindrome(input):\n str_input = str(input)\n\n for i in range(len(str_input) // 2 - 1):\n if str_input[i] != str_input[-(i+1)]:\n return False\n \n return True\n", "def is_palindrome(string):\n s=str(string)\n if(s[::-1]==s):\n return True\n else:\n return False\n", "def is_palindrome(xs):\n return str(xs)[::-1] == str(xs)", "def is_palindrome(string):\n if type(string) == type(1):\n string = str(string)\n m = len(string)//2\n if len(string) % 2 != 0:\n l,r = string[:m],string[m+1:]\n else:\n l,r = string[:m],string[m:]\n return True if l == r[::-1] else False", "def is_palindrome(string):\n xd = 12321\n if string == xd:\n return True\n string = str(string)\n a = len(string)\n b = a % 2\n nr = -1\n \n if b != 0:\n return False \n else:\n a = a/2\n a = int(a)\n for x in range(a):\n if string[x] == string[nr]:\n nr = nr - 1\n else:\n return False\n return True\n", "def is_palindrome(string):\n a = str(string)\n return str(string) == a[::-1]", "def is_palindrome(string):\n x=len(str(string))//2\n if str(string)[:x] == str(string)[-1:-(x+1):-1]:\n return True\n else:\n return False\n", "def is_palindrome(s):\n if type(s) is str:\n if s == s[::-1]: return True\n else: return False\n elif type(s) is int:\n if str(s) == (str(s))[::-1]: return True\n else: return False\n\n \n \n# Implement a function that checks if something is a palindrome.\n", "def is_palindrome(string):\n if type(string) is int:\n st_res = str(string)\n if st_res == st_res[::-1]:\n return True\n else:\n return False\n if type(string) is str:\n if string == string[::-1]:\n return True\n else:\n return False", "def is_palindrome(string):\n string = str(string)\n string_length = len(string)\n for i in range(string_length // 2):\n if string[i] != string[string_length - 1 - i]:\n return False\n return True\n", "def is_palindrome(string):\n if type(string) == int:\n line = str(string)\n else:\n line = string\n n = len(line) - 1\n chars = []\n \n while (n>=0):\n char = line[n]\n chars.append(char)\n n-=1\n \n new_string = ''.join(chars)\n return line == new_string\n", "def is_palindrome(string):\n\n target = str(string)\n start, end = 0, len(target) - 1\n while (start < end):\n if (target[start] != target[end]):\n\n return False\n\n start += 1\n end -= 1\n\n return True\n", "def is_palindrome(string):\n return str(string)==str(string)[::-1] if str(string).isdigit() else string.lower()==string.lower()[::-1]", "def is_palindrome(st):\n st=str(st)\n if len(st)%2==0:\n if st[:(len(st)//2)][::-1]==st[(len(st)//2):]:\n return True\n return False\n else:\n if st[:(len(st)//2)][::-1]==st[(len(st)//2)+1:]:\n return True\n return False", "def is_palindrome(string):\n return [*str(string)] == list(reversed([*str(string)]))", "def is_palindrome(string: str) -> bool:\n return str(string) == str(string)[::-1]", "def is_palindrome(input):\n input = str(input)\n return input == input[::-1]", "def is_palindrome(string):\n r = str(string)\n z = \"\"\n for v in r:\n z = v + z\n if z == r:\n return(True)\n else:\n return(False)", "def is_palindrome(string):\n string = str(string)\n if string[::-1] == string:\n return True\n if string[::-1] != string: \n return False", "def is_palindrome(string):\n if type(string) == str:\n return string == string[::-1]\n return str(string) == str(string)[::-1]\n", "import math\n\ndef is_palindrome(string):\n new_string = str(string)\n last_element = len(new_string) - 1\n half_arra = math.floor(len(new_string) / 2)\n for item in range(0, half_arra):\n if new_string[item] != new_string[last_element]:\n return False\n last_element = last_element - 1\n return True\n", "def is_palindrome(string):\n TestStr = str(string)\n return TestStr == TestStr[::-1]", "def is_palindrome(v):\n return str(v) == str(v)[::-1]\n", "def is_palindrome(s):\n s = str(s)\n return s[0:] == s[::-1]", "def is_palindrome(s):\n try:\n return s==s[::-1]\n except TypeError:\n c=str(s)\n return c==c[::-1]", "def is_palindrome(string):\n string = f\"{string}\"\n try: \n return string == \"\".join(reversed(string))\n except:\n return string == int(\"\".join(reversed(string)))", "def is_palindrome(string):\n x = str(string)\n for i in range (0, len(x) - 1):\n if x[i] == x[len(x) - 1 - i]:\n return True\n else:\n return False\n pass", "def is_palindrome(s):\n if isinstance(s,str):\n return s==s[::-1]\n return s==int(str(s)[::-1])", "def is_palindrome(input):\n \n if type(input) is int:\n return input == int(''.join([i for i in str(input)[::-1]]))\n else:\n return input == ''.join([i for i in input[::-1]])", "def is_palindrome(s):\n s=str(s)\n return True if s==s[::-1] else False ", "def is_palindrome(string):\n strings = str(string)\n return strings == strings [::-1]", "def is_palindrome(string):\n word = \"\"\n for i in str(string):\n word = i + word\n return str(string) == word\n \n \n# import functools\n# def palindrome(string):\n# rev = functools.reduce(lambda a, b: b + a, str(string))\n# return rev == str(string)\n\n# def palindrome(string):\n# string = str(string)\n# return string == string[::-1]\n# print(palindrome(12321))\n", "def is_palindrome(string):\n s = str(string)\n return all( b==e for b, e in zip(s[:len(s)//2], s[len(s)//2:][::-1]))", "def is_palindrome(string):\n try: return str(string) == str(string)[::-1]\n except: return False", "def is_palindrome(string):\n result = str(string)\n reversed_string = ''.join(reversed(result))\n if result.lower() == reversed_string.lower():\n return True\n else:\n return False", "def is_palindrome(string):\n x = str(string)\n return True if x == x[::-1] else False", "def is_palindrome(string):\n string = str(string) if not isinstance(string, str) else string\n return string == string[::-1]", "def is_palindrome(string):\n string=str(string)\n output=True\n for i in range(0,len(string)//2):\n print(i)\n if string[i]!=string[len(string)-i-1]:\n output=False\n return output\n return output", "def is_palindrome(string):\n string = str(string)\n emptystring = ''\n for eachletter in string:\n emptystring = eachletter + emptystring\n return emptystring == string", "def is_palindrome(string):\n return all([str(string)[i] == str(string)[len(str(string)) - i - 1] for i in range(int(len(str(string))/2))])", "def is_palindrome(string):\n if type(string)==int:\n n=int(string)\n n1=int(string)\n rev = 0\n while(n > 0): \n a = n % 10\n rev = rev * 10 + a \n n = n // 10\n return n1==rev\n else:\n string1=list(string)\n string=list(string)\n string.reverse()\n string2=list(string)\n if string1==string2:\n return True\n return False", "import unittest\n\n\ndef is_palindrome(string):\n string = str(string)\n return string == string[::-1]\n \n \nclass TestPalindromeStrings(unittest.TestCase):\n def test_is_palindrome_with_not_palindrome_string(self):\n string = 'walter'\n actual = is_palindrome(string)\n self.assertEqual(actual, False)\n\n def test_is_palindrome_with_palindrome_string(self):\n string = 'anna'\n actual = is_palindrome(string)\n self.assertEqual(actual, True)\n\n def test_is_palindrome_with_not_palindrome_integer_value(self):\n string = 12345\n actual = is_palindrome(string)\n self.assertEqual(actual, False)\n\n def test_is_palindrome_with_palindrome_integer_value(self):\n string = 12321\n actual = is_palindrome(string)\n self.assertEqual(actual, True)\n", "def is_palindrome(string):\n if str(string)[::]== str(string)[::-1]:\n return True \n else:\n return False", "def is_palindrome(string):\n string = list(str(string))\n \n while len(string) > 1:\n if string[0] != string[-1]:\n return False\n \n string.pop(0)\n string.pop()\n \n return True", "def is_palindrome(string):\n msg = True\n stringised = str(string)\n string_length = len(stringised)\n for x in range(string_length // 2):\n if stringised[x] != stringised[-x-1]:\n msg = False\n break\n return msg", "def is_palindrome(string):\n a = str(string)\n if a[::-1] == a:\n return True\n else:\n return False", "def is_palindrome(string):\n \"\"\"return True if 'string' is palidrome\"\"\"\n return str(string)==str(string)[::-1]", "def is_palindrome(string):\n return str(string)==str(string)[::-1] if True else False", "def is_palindrome(string):\n string = str(string)\n return True if string.lower() == string.lower()[::-1] else False ", "def is_palindrome(string):\n if type(string)==int:\n string = str(string)\n if string[::-1] == string:\n return True\n else:\n return False\n else:\n return string[::-1] == string", "def is_palindrome(string):\n if(list(str(string)) == list(str(string))[::-1]):\n return True\n return False\n", "def is_palindrome(input):\n string = str(input)\n return string.lower() == string.lower()[::-1]", "def is_palindrome(string=''):\n return str(string)[::-1] == str(string)\n\n", "def is_palindrome(string):\n print(string)\n return str(string) == ''.join(list(reversed(str(string))))", "def is_palindrome(a):\n a = str(a)\n i, n = 0, len(a)-1\n while i < n: \n if a[i] != a[n]: return False\n i, n = i+1, n-1\n return True", "def is_palindrome(string):\n #print(string)\n string = str(string)\n return string == string[::-1]", "def is_palindrome(string):\n if isinstance(string, int):\n return list(str(string)) == list(str(string)[::-1])\n elif isinstance(string, str):\n return string[::-1] == string\n else:\n pass", "def is_palindrome(string):\n string2 = str(string)\n return str(string) == string2[::-1]", "def is_palindrome(string):\n \n s = str(string)\n l = len(s)\n l2 = l // 2\n\n\n if l % 2 == 0 and s[0:l2] == s[l2::][::-1]:\n return True\n elif l % 2 == 0 and s[0:l2] != s[l2::][::-1]:\n return False\n elif l % 2 != 0 and s[0:l2] == s[l2+ 1::][::-1]:\n return True\n elif l % 2 != 0 and s[0:l2] != s[l2+ 1::][::-1]:\n return False\n else:\n return None", "def is_palindrome(string):\n if type(string)==str:\n return bool(string==string[::-1])\n elif type(string)==int:\n string=str(string)\n return bool(string==string[::-1])\n \n \n", "def is_palindrome(string):\n new_string = str(string)\n long = len(new_string)\n counter = 0\n while counter < long:\n if new_string[counter] != new_string[-1-counter]:\n return False\n counter += 1\n else:\n return True", "def is_palindrome(string):\n string=str(string)\n result=False\n i=0\n \n for i in range(0,len(string)//2):\n if string[i]==string[len(string)-i-1]:\n result=True\n i+=1\n else:\n result=False\n break\n \n return result", "import string\ndef is_palindrome(string):\n string=str(string)\n stra=string[::-1]\n if stra==string:\n return True\n return False", "def is_palindrome(string):\n gnirts=(str(string))[::-1]\n return gnirts==str(string)", "def is_palindrome(string):\n \n string = str(string)\n \n if str(string)[::-1] == string:\n return True\n \n else:\n return False", "def is_palindrome(string):\n l = list(str(string))\n return l[:] == l[::-1]", "def is_palindrome(e):\n return str(e) == str(e)[::-1]", "def is_palindrome(string):\n m = list(str(string))\n return m == m[::-1]", "def is_palindrome(string):\n string = str(string)\n for i in string:\n nonstring = string[::-1]\n if nonstring == string:\n return True\n else:\n return False", "def is_palindrome(string):\n #se for um numero, converte para string\n if isinstance(string, int):\n string = str(string)\n \n result = False\n \n strcmp = string[::-1]\n \n if strcmp == string:\n result = True\n else:\n result = False\n \n return result\n", "def is_palindrome(x):\n return str(x) == str(x)[::-1]", "def is_palindrome(string):\n if string:\n return str(string) == str(string)[::-1]\n elif string.isalpha():\n return string == string[::-1]", "def is_palindrome(string):\n string = str(string)\n for i in range(len(string)//2): # Go up to middle of the string and read both sides\n if len(string)%2 == 0:\n if string[len(string)//2-i-1] != string[i+len(string)//2]:\n return False\n elif len(string)%2 == 1:\n if string[len(string)//2-i-1] != string[i+len(string)//2+1]:\n return False\n return True", "def is_palindrome(string):\n if type(string)==int:\n string=str(string)\n return True if string==string[::-1] else False", "def is_palindrome(string):\n word = str(string)[::-1]\n return word == str(string)", "def is_palindrome(string):\n subString = str(string)\n control = True\n for i in range(0, int(len(subString)/2)):\n if subString[i:i+1] != subString[len(subString)-i-1:len(subString)-i]:\n control = False\n break\n return control", "def is_palindrome(string):\n arr = []\n count = -1\n for i in str(string):\n arr.append(i)\n if arr[0] == arr[count]:\n count -= 1\n return True\n else:\n return False", "def is_palindrome(string):\n yazi = str(string)\n \n if yazi == yazi[::-1]:\n return True\n return False", "def reverse(s): \n return s[::-1] \ndef is_palindrome(s):\n s = str(s)\n rev = reverse(s) \n if (s == rev): \n return True\n return False", "def is_palindrome(string):\n s = str(string) \n return s[:]==s[::-1]", "def is_palindrome(string):\n if type(string) == 'str':\n return string == string[::-1]\n else:\n str1 = str(string)\n return str1 == str1[::-1]", "def is_palindrome(string):\n string = str(string)\n if string[::-1] == string:\n return True\n else:\n return False\n pass", "def is_palindrome(string):\n a = len(str(string))\n for i in range(0, a):\n if str(string)[i] != str(string)[a - i - 1]:\n return False\n \n return True", "def is_palindrome(string):\n return \"\".join(\"{}\".format(string)[::-1])==\"{}\".format(string)", "def is_palindrome(string):\n string = str(string)\n string = list(string.lower())\n return string == string[::-1]"]
{"fn_name": "is_palindrome", "inputs": [["anna"], ["walter"], [12321], [123456]], "outputs": [[true], [false], [true], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
19,458
def is_palindrome(string):
97ce8696317690a35ef96af96c5d78d2
UNKNOWN
Linear Kingdom has exactly one tram line. It has `n` stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. ## Your task Calculate the tram's minimum capacity such that the number of people inside the tram never exceeds this capacity at any time. Note that at each stop all exiting passengers exit before any entering passenger enters the tram. ## Example ```c++ tram(4, {0, 2, 4, 4}, {3, 5, 2, 0}) ==> 6 ``` Explaination: * The number of passengers inside the tram before arriving is 0. * At the first stop 3 passengers enter the tram, and the number of passengers inside the tram becomes 3. * At the second stop 2 passengers exit the tram (1 passenger remains inside). Then 5 passengers enter the tram. There are 6 passengers inside the tram now. * At the third stop 4 passengers exit the tram (2 passengers remain inside). Then 2 passengers enter the tram. There are 4 passengers inside the tram now. * Finally, all the remaining passengers inside the tram exit the tram at the last stop. There are no passenger inside the tram now, which is in line with the constraints. Since the number of passengers inside the tram never exceeds 6, a capacity of 6 is sufficient. Furthermore it is not possible for the tram to have a capacity less than 6. Hence, 6 is the correct answer.
["from itertools import accumulate\n\ndef tram(stops, descending, onboarding):\n return max(accumulate(o - d for d, o in zip(descending[:stops], onboarding)))", "def tram(stops, descending, onboarding):\n return max(sum(onboarding[:i])-sum(descending[:i]) for i in range(stops+1))\n", "def tram(stops, descending, onboarding):\n n, m = 0, 0\n for d,u in zip(descending[:stops], onboarding):\n n += u-d\n m = max(m, n)\n return m", "def tram(stops, descending, onboarding):\n min_capacity, passengers = 0, 0\n for (off, on) in zip(descending[:stops], onboarding[:stops]):\n passengers += on - off\n min_capacity = max(min_capacity, passengers)\n return min_capacity", "from itertools import accumulate as acc\n\ndef tram(stops, down, up):\n return max(acc(u - d for d, u in zip(down[:stops], up)))", "def tram(stops, off, on):\n total = 0\n passengers = []\n for i in range(stops):\n total += on[i] - off[i]\n passengers.append(total)\n \n return max(passengers)", "tram=lambda s,d,o,c=0,m=0: (lambda c: tram(s-1,d[1:],o[1:],c,m=max(c,m)))(c+o[0]-d[0]) if s else max(c,m)", "tram = lambda s, d, o,a=__import__(\"itertools\").accumulate: max(a(map(int.__sub__, o[:s], d[:s])))", "from itertools import accumulate\ndef tram(stops, descending, onboarding):\n return max(accumulate(b - a for _, a, b in zip(range(stops), descending, onboarding)))", "from itertools import accumulate\nfrom operator import add\ndef tram(stops,off,on):\n return max(accumulate((b-a for a,b in zip(off,on[:stops])),add))"]
{"fn_name": "tram", "inputs": [[4, [0, 2, 4, 4], [3, 5, 2, 0]], [2, [0, 2, 4, 4], [3, 5, 2, 0]], [1, [0, 2, 4, 4], [3, 5, 2, 0]], [10, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]], [5, [0, 2, 4, 14, 2], [3, 5, 14, 0, 0]]], "outputs": [[6], [6], [3], [25], [16]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,587
def tram(stops, descending, onboarding):
e2e5c9537ccb7cd6685ef3303fcf1f0f
UNKNOWN
Write a function that accepts two parameters (a and b) and says whether a is smaller than, bigger than, or equal to b. Here is an example code: var noIfsNoButs = function (a,b) { if(a > b) return a + " is greater than " + b else if(a < b) return a + " is smaller than " + b else if(a == b) return a + " is equal to " + b } There's only one problem... You can't use if statements, and you can't use shorthands like (a < b)?true:false; in fact the word "if" and the character "?" are not allowed in the code. Inputs are guarenteed to be numbers You are always welcome to check out some of my other katas: Very Easy (Kyu 8) Add Numbers Easy (Kyu 7-6) Convert Color image to greyscale Array Transformations Basic Compression Find Primes in Range No Ifs No Buts Medium (Kyu 5-4) Identify Frames In An Image Photoshop Like - Magic Wand Scientific Notation Vending Machine - FSA Find Matching Parenthesis Hard (Kyu 3-2) Ascii Art Generator
["def no_ifs_no_buts(a, b):\n return {\n a == b: str(a) + \" is equal to \" + str(b),\n a < b: str(a) + \" is smaller than \" + str(b),\n a > b: str(a) + \" is greater than \" + str(b),\n }[True]", "def no_ifs_no_buts(a, b):\n return ([\n '%d is smaller than %d',\n '%d is equal to %d',\n '%d is greater than %d'\n ][int(a >= b) + int(a > b)] % (a, b))", "def no_ifs_no_buts(a, b):\n d = {a<b:'smaller than', a==b:'equal to', a>b: 'greater than'}\n return f'{a} is {d[True]} {b}'", "def no_ifs_no_buts(a, b):\n while a<b:\n return str(a) + \" is smaller than \" + str(b)\n while a>b:\n return str(a) + \" is greater than \" + str(b)\n while a==b:\n return str(a) + \" is equal to \" + str(b)", "def no_ifs_no_buts(a, b):\n result = {\n a == b: \"equal to\",\n a < b: \"smaller than\",\n a > b: \"greater than\",\n }[True]\n return f\"{a} is {result} {b}\"", "def no_ifs_no_buts(a, b):\n compare = {\n -1: \" is smaller than \",\n 0 : \" is equal to \",\n 1 : \" is greater than \"\n }\n return str(a) + compare[(a > b) - (a < b)] + str(b)", "def no_ifs_no_buts(a, b):\n return \"{} is {} {}\".format(a, [\"{}er than\".format([\"great\", \"small\"][a < b]), \"equal to\"][a == b], b)", "def no_ifs_no_buts(a, b):\n return [[str(a) + \" is smaller than \" + str(b), str(a) + \" is greater than \" + str(b)][a > b], str(a) + \" is equal to \" + str(b)][a == b]\n"]
{"fn_name": "no_ifs_no_buts", "inputs": [[45, 51], [1, 2], [-3, 2], [1, 1], [100, 100], [100, 80], [20, 19]], "outputs": [["45 is smaller than 51"], ["1 is smaller than 2"], ["-3 is smaller than 2"], ["1 is equal to 1"], ["100 is equal to 100"], ["100 is greater than 80"], ["20 is greater than 19"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,519
def no_ifs_no_buts(a, b):
e7888786810c259944beae2e3288dec2
UNKNOWN
Description Lets imagine a yoga classroom as a Square 2D Array of Integers ```classroom```, with each integer representing a person, and the value representing their skill level. ``` classroom = [ [3,2,1,3], [1,3,2,1], [1,1,1,2], ] poses = [1,7,5,9,10,21,4,3] ``` During a yoga class the instructor gives a list of integers ```poses``` representing a yoga pose that each person in the class will attempt to complete. A person can complete a yoga pose if the sum of their row and their skill level is greater than or equal to the value of the pose. Task Your task is to return the total amount poses completed for the entire ```classroom```. Example ``` classroom = [ [1,1,0,1], #sum = 3 [2,0,6,0], #sum = 8 [0,2,2,0], #sum = 4 ] poses = [4, 0, 20, 10] 3 people in row 1 can complete the first pose Everybody in row 1 can complete the second pose Nobody in row 1 can complete the third pose Nobody in row 1 can complete the fourth pose The total poses completed for row 1 is 7 You'll need to return the total for all rows and all poses. ``` Translations are welcomed!
["def yoga(classroom, poses):\n total_poses = 0\n for pose in poses:\n for row in classroom:\n for person in row:\n if person + sum(row) >= pose:\n total_poses += 1\n return total_poses", "def yoga(classroom, poses):\n return sum(1 for r in classroom for v in r for p in poses if p<=v+sum(r))", "def yoga(room, poses):\n return sum(sum(v<=p+s for v in poses for p in r) for r,s in ((r,sum(r)) for r in room) )", "def yoga(classroom, poses):\n result = 0\n for row in classroom:\n s = sum(row)\n result += sum(s+x >= p for x in row for p in poses)\n return result", "from bisect import bisect_left\n\ndef yoga(a, b):\n c = []\n for x in a:\n y = sum(x)\n c.append([z + y for z in sorted(x)])\n return sum(sum(len(x) - bisect_left(x, y) for y in b) for x in c)", "def yoga(classroom, poses):\n return sum(1 for row in classroom for o in row for p in poses if o + sum(row) >= p)\n", "yoga = lambda classroom, poses: sum(sum(len([1 for p in poses if p<=c+sum(r)]) for c in r) for r in classroom)\n", "def yoga(classroom, poses):\n if not classroom or not poses:\n return 0\n res = 0\n for row in classroom:\n row_sum = sum(row)\n for pose in poses:\n for person in row:\n if person + row_sum >= pose:\n res += 1\n return res", "def yoga(classroom, poses):\n return len([z for i in poses for k in classroom for z in k if sum(k) + z >= i])\n", "def yoga(classroom, poses):\n new_classroom = []\n for row in classroom:\n row_sum = sum(row)\n new_row = []\n for person in row:\n new_row.append(person + row_sum)\n new_classroom.append(new_row)\n people = [person for row in new_classroom for person in row]\n\n result = 0\n for pose in poses:\n for person in people:\n if person >= pose:\n result += 1\n return result"]
{"fn_name": "yoga", "inputs": [[[[0, 0], [0, 0]], [1, 1, 0, 1, 2, 3, 0, 1, 5]], [[], [1, 3, 4]], [[[0, 0], [0, 0]], []], [[], []]], "outputs": [[8], [0], [0], [0]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,998
def yoga(classroom, poses):
f4003e70ae03a6a590cd5b5cb69e1861
UNKNOWN
.task { background: #fff; color: #333; padding: 25px; box-sizing: border-box; font-family: Comfortaa, sans-serif !important; position: relative; } .task code, .task_code { display: inline-block; padding: 0; border-radius: 2px; margin: 0; position: relative; top: 6px; background: bisque; border: 1px solid #f9d2a4; padding: 3px; line-height: 1em; } .task_code { top: -1px; } .task_header { color: #333 !important; margin-top: 0; font-size: 30px !important; } .task_inner { box-shadow: 0 2px 11px -3px rgba(0,0,0,.6); padding: 20px; border-radius: 3px; } .task_devil { float: right; margin-left: 15px; shape-outside: circle(150px); } .task_devil img { max-width: 150px; } .task_part-header { font-size: 20px !important; font-weight: 800; color: #333; padding: 20px 0 10px; } .task_part-header:first-of-type { padding-top: 0; } .task_list { padding: 0; margin: 10px 0; padding-left: 30px; } .task_list ul { padding: 0; margin: 0; } .font-effect-canvas-print { color: black; } Devil's Sequence Problem Robodevil likes to do some mathematics between rehearsals of his orchestra. Today he invented devilish sequence No. 1729: x0 = 0, x1 = 1, xn = (xn - 1 + xn - 2) / 2. For example, x10 = 0.666015625. Robodevil became interested at once how many `sixes` there were at the beginning of an arbitrary xn. In 6 nanoseconds, he had a formula. Can you do the same? Input You are given an integer n; `2 ≤ n ≤ 100000`. Output Output the number of sixes at the beginning of xn in decimal notation. Example Input Output 10 3
["from math import floor, log\ndef count_sixes(n):\n return floor((n - n % 2) * log(2, 10))", "count_sixes=lambda n:len(str(1<<n-n%2))-1", "from math import log10, floor, log\n\ndef count_sixes(n):\n k = floor(log10(3) + (n - 1)*log10(2))\n return k - (k*log(10) > (n - (n & 1))*log(2))\n\n# x[n] = 2/3 + d if n is odd\n# x[n] = 2/3 - d otherwise\n# d = 1/(3*2**(n-1))\n# k = log10(1/d)\n# adjust k depending on carry/borrow from adding/subtracting d\n# if n is odd:\n# k-1 if 1/(3*10**k) <= d\n# k otherwise\n# else:\n# k-1 if 2/(3*10**k) <= d\n# k otherwise\n", "import math\ncount_sixes = lambda n: int((n-n%2)*math.log10(2))", "def count_sixes(n):\n res = str(10**n//15-(-5)**n//15)\n return len(res)-len(res.lstrip('6')) \n\n\"\"\" For my poor memory :\n\n with some paper and a pen, 2->10:\n 2 : 0.5\n 3 : 0.75\n 4 : 0.625\n 5 : 0.6875\n 6 : 0.65625\n 7 : 0.671875\n 8 : 0.6640625\n 9 : 0.66796875\n 10 : 0.666015625 ==> that's the example !\n \n I'm lazy : check OEIS with only the decimals (5, 75, 625, 6875...) ==> https://oeis.org/A091903\n Formula : a(n)=10^n/15-(-5)^n/15\n \n Adapt formula to python :)\n\"\"\"", "\"\"\"\nWhen you're bad at maths.... x)\nThe complete story in the comments.\n\"\"\"\n\n\ndef definer(left, nL, right, nR, name):\n (inpL, outL), (inpR, outR) = left[:2], right[:2]\n return (inpL*nL + inpR*nR, outL*nL + outR*nR, left, nL, right, nR, name)\n\nINF = 10**6\n\n\"\"\"\nTREE DATA: length as... left nL right nR name (debugging)\n inp out \n\"\"\"\nC00 = (4, 0, None, None, None, None, \"C00\")\nC2 = (2, 1, None, None, None, None, \"C2\")\nC4 = (4, 1, None, None, None, None, \"C4\")\n\nC6 = definer( C2, 1, C4, 1, \"C6\" )\nC10 = definer( C4, 1, C6, 1, \"C10\")\nC19_6 = definer( C10, 19, C6, 1, \"C19_6\")\nC18_6 = definer( C10, 18, C6, 1, \"C18_6\")\nC19x5_18x1 = definer( C19_6, 5, C18_6, 1, \"C19x5_18x1\")\nC19x4_18x1 = definer( C19_6, 4, C18_6, 1, \"C19x4_18x1\")\nC_x5andx4 = definer( C19x5_18x1, 1, C19x4_18x1, 1, \"C_x5andx4\")\nC_x13andx4 = definer( C_x5andx4, 13, C19x4_18x1, 1, \"C_x13andx4\")\nC_TOP = definer( C_x13andx4, INF, C2, 0, \"C_TOP\") # C2 is dummy, here\n\nSTART = definer( C00, 1, C_TOP, 1, \"START\" )\n\n\ndef count_sixes(n, c=START):\n\n _, out, left, nL, right, _, name = c\n \n if left: inpL, outL = left[:2]\n \n if not left: return out\n \n elif n < inpL * nL:\n complete, r = divmod(n, inpL)\n return outL * complete + (left and count_sixes(r, left))\n\n else:\n return outL * nL + (right and n and count_sixes(n - inpL*nL, right)) \n", "import math\n\ndef count_sixes(n):\n n0 = int((math.log10(2) * (n - 1)))\n n1 = int((math.log10(2) * n))\n n2 = int((math.log10(2) * (n + 1)))\n len = n1\n if n1 == n2 and n1 == (n0 + 1) and (n % 2) != 0:\n len = n0\n return len", "from fractions import Fraction \nfrom decimal import *\n\ndef count_sixes(n):\n a = 6 << (n - 2)\n b = Fraction(2,3)\n c = Fraction(1,a) \n d = 0 \n if n % 2 == 0:\n d = b - c \n else:\n d = b + c \n getcontext().prec = 100000\n e = str(Decimal(d.numerator)/Decimal(d.denominator))\n f = 0 \n for i in range(2,len(e)):\n if e[i] == '6': \n f += 1\n else: break \n return f\n", "def count_sixes(n):\n num = 3*2**(n-1)\n c=0\n if n%2 ==0 and int(str(num)[:2]) < 15:\n c = 1\n elif n%2 == 1 and int(str(num)[0]) < 3:\n c=1\n return len(str(num))-1 -c"]
{"fn_name": "count_sixes", "inputs": [[10]], "outputs": [[3]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,066
def count_sixes(n):
83a7840b6385a4a9fa1584f08beb573d
UNKNOWN
# Background: You're working in a number zoo, and it seems that one of the numbers has gone missing! Zoo workers have no idea what number is missing, and are too incompetent to figure it out, so they're hiring you to do it for them. In case the zoo loses another number, they want your program to work regardless of how many numbers there are in total. ___ ## Task: Write a function that takes a shuffled list of unique numbers from `1` to `n` with one element missing (which can be any number including `n`). Return this missing number. **Note**: huge lists will be tested. ## Examples: ``` [1, 3, 4] => 2 [1, 2, 3] => 4 [4, 2, 3] => 1 ```
["def find_missing_number(a):\n n = len(a) + 1\n return n * (n + 1) // 2 - sum(a)", "def find_missing_number(numbers):\n if numbers == []:return 1\n diff = list(set(range(1, len(numbers)+1))- set(numbers))\n if diff == []:return max(numbers)+1\n return diff[0]", "def find_missing_number(nums):\n return sum(range(1,len(nums)+2))-sum(nums)", "def find_missing_number(numbers):\n return sum(list(range(1, len(numbers)+2))) - sum(numbers) ", "def find_missing_number(n):\n return sum(list(range(1,len(n)+2))) - sum(n)", "def find_missing_number(numbers):\n x = len(numbers)\n total = sum(numbers)\n rest = ((x+1)*(x+2))\n rest = rest/2\n missing = rest - total\n \n return missing", "def find_missing_number(numbers):\n a = [False for i in range(len(numbers) +1)]\n for i in numbers:\n a[i-1] = True\n return a.index(False) +1 ", "def find_missing_number(numbers):\n s = set(numbers)\n m = max(s, default=0)\n try:\n return (set(range(1, m)) - s).pop()\n except KeyError:\n return m + 1", "def find_missing_number(numbers):\n t1 = sum(numbers)\n t2 = sum(range(1, len(numbers)+2))\n return (t2 - t1)", "def find_missing_number(numbers):\n n = len(numbers) + 1\n expected = (n * (n + 1))/2\n return expected - sum(numbers)"]
{"fn_name": "find_missing_number", "inputs": [[[2, 3, 4]], [[1, 3, 4]], [[1, 2, 4]], [[1, 2, 3]], [[]], [[1]], [[2]]], "outputs": [[1], [2], [3], [4], [1], [2], [1]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,336
def find_missing_number(numbers):
99026f79befdf0c53ffa78194edad4ad
UNKNOWN
We have the integer `9457`. We distribute its digits in two buckets having the following possible distributions (we put the generated numbers as strings and we add the corresponding formed integers for each partition): ``` - one bucket with one digit and the other with three digits [['9'], ['4','5','7']] --> ['9','457'] --> 9 + 457 = 466 [['9','5','7'], ['4']] --> ['957','4'] --> 957 + 4 = 961 [['9','4','7'], ['5']] --> ['947','5'] --> 947 + 5 = 952 [['9','4','5'], ['7']] --> ['945','7'] --> 945 + 7 = 952 - two buckets with 2 digits each: [['9','4'], ['5','7']] --> ['94','57'] --> 94 + 57 = 151 [['9','5'], ['4','7']] --> ['95','47'] --> 95 + 47 = 142 [['9','7'], ['4','5']] --> ['97','45'] --> 97 + 45 = 142 ``` Now we distribute the digits of that integer in three buckets, and we do the same presentation as above: ``` one bucket of two digits and two buckets with one digit each: [['9'], ['4'], ['5','7']] --> ['9','4','57'] --> 9 + 4 + 57 = 70 [['9','4'], ['5'], ['7']] --> ['94','5','7'] --> 94 + 5 + 7 = 106 [['9'], ['4', '5'], ['7']] --> ['9','45','7'] --> 9 + 45 + 7 = 61 [['9'], ['5'], ['4','7']] --> ['9','5','47'] --> 9 + 5 + 47 = 61 [['9','5'], ['4'], ['7']] --> ['95','4','7'] --> 95 + 4 + 7 = 106 [['9','7'], ['4'], ['5']] --> ['97','4','5'] --> 97 + 4 + 5 = 106 ``` Finally we distribute the digits in the maximum possible amount of buckets for this integer, four buckets, with an unique distribution: ``` One digit in each bucket. [['9'], ['4'], ['5'], ['7']] --> ['9','4','5','7'] --> 9 + 4 + 5 + 7 = 25 ``` In the distribution we can observe the following aspects: - the order of the buckets does not matter - the order of the digits in each bucket matters; the available digits have the same order than in the original number. - the amount of buckets varies from two up to the amount of digits The function, `f =` `bucket_digit_distributions_total_sum`, gives for each integer, the result of the big sum of the total addition of generated numbers for each distribution of digits. ```python bucket_digit_distributions_total_sum(9457) === 4301 # 466 + 961 + 952 + 952 + 151 + 142 + 142 + 70 + 106 + 61 + 61 + 106 + 106 + 25 = 4301 ``` It is interesting to see the value of this function for a number that has one or more zeroes as digits, for example: ```python bucket_digit_distributions_total_sum(10001) === 5466 ``` Given an integer `n`, with its corresponding value of the above function, `f(n)`, and another integer `z`, find the closest and higher integer to n, `nf`, such `f(nf) > f(n) + z`. Example: ```python find(10001,100) === 10003 find(30000, 1000) === 30046 ``` Features of the random tests: ``` 100 <= n <= 1500000 50 <= z <= 6000 ```
["def subsets(collection):\n if len(collection) == 1:\n yield [collection]\n return\n\n first = collection[0]\n for smaller in subsets(collection[1:]):\n yield [first] + smaller\n for n, subset in enumerate(smaller):\n yield smaller[:n] + [first + subset] + smaller[n+1:]\n\ndef bucket_digit_distributions_total_sum(n):\n return sum(sum(map(int, sub)) for sub in subsets(str(n))) - n\n\ndef find(n, z):\n f_nf = bucket_digit_distributions_total_sum(n) + z\n while 1:\n n += 1\n if bucket_digit_distributions_total_sum(n) > f_nf:\n return n", "from functools import reduce\nfrom itertools import count\ncoefs = [\n [22, 13, 4],\n [365, 167, 50, 14],\n [5415, 2130, 627, 177, 51],\n [75802, 27067, 7897, 2254, 661, 202],\n [1025823, 343605, 100002, 28929, 8643, 2694, 876]\n]\ndef f(n): return sum(c*int(d) for c,d in zip(coefs[len(str(n))-3], str(n)))\n\ndef find(n,z):\n t = f(n)+z\n for nf in count(n):\n if f(nf) > t: return nf", "from itertools import count\n\ndef rec(n):\n if not n: yield 0; return\n for i in range(1 << (len(n) - 1)):\n tmp = [[], []]\n for t in n:\n i, r = divmod(i, 2)\n tmp[r].append(t)\n x, y = int(''.join(tmp[0])), tmp[1]\n for k in rec(y): yield x + k\nval = lambda n: sum(rec(str(n))) - n\n\ndef find(n, z):\n z += val(n)\n return next(i for i in count(n+1) if val(i) > z)", "def find(n,z):\n r=n+1\n sumn=sumof(n)\n while True:\n if sumof(r)>sumn+z: return r\n r+=1\n return \"Perhaps this is a different way to solve the kata, but it works ;-)(not cheat)\"\ndef sumof(n):\n fm=[[],[],[],[22,13,4],[365,167,50,14],[5415,2130,627,177,51],[75802,27067,7897,2254,661,202],[123456,123456,123456,123456,123456,123456,123456]]\n l=1 if n<10 else(2 if n<100 else(3 if n<1000 else(4 if n<10000 else (5 if n<100000 else (6 if n<1000000 else 7)))))\n a,i,r=fm[l],l-1,0\n while n>0:\n t=n%10\n n//=10\n r+=t*a[i]\n i-=1\n return r", "# Partition generator taken from \n# https://stackoverflow.com/questions/19368375/set-partitions-in-python\ndef partition(collection):\n if len(collection) == 1:\n yield [ collection ]\n return\n\n first = collection[0]\n for smaller in partition(collection[1:]):\n # insert `first` in each of the subpartition's subsets\n for n, subset in enumerate(smaller):\n yield smaller[:n] + [[ first ] + subset] + smaller[n+1:]\n # put `first` in its own subset \n yield [ [ first ] ] + smaller\n \ndef part_sum(part_list):\n tot_sum = 0\n for elem in part_list:\n tot_sum += sum(int(''.join(x)) for x in elem)\n return tot_sum\n\ndef find(n,z):\n min_sum = part_sum([x for x in partition(list(str(n)))][1:]) + z\n i = 1\n nf_sum = part_sum([x for x in partition(list(str(n+i)))][1:])\n while nf_sum <= min_sum:\n i += 1\n nf_sum = part_sum([x for x in partition(list(str(n+i)))][1:])\n return n+i", "def find(n, z):\n lim = bucket_digit_distributions_total_sum(n) + z\n num = n\n \n while True: \n num += 1\n res = bucket_digit_distributions_total_sum(num)\n if lim < res: \n return num\n \n return num\n\ndef bucket_digit_distributions_total_sum(n): \n parts = get_partitions(list(str(n)), len(str(n)))\n buckets_sum = 0\n \n for p in parts: \n if len(p) > 1:\n b = [int(''.join(l)) for l in p]\n buckets_sum += sum(b)\n \n return buckets_sum\n \n\ndef get_partitions(lst, n):\n if n <= 0: \n yield []\n return\n else: \n curr = lst[n - 1]\n for part in get_partitions(lst, n - 1): \n for l in list(part): \n l.append(curr)\n yield part\n l.pop()\n yield part + [[curr]]", "def find(n, z):\n \n \n lim = bucket_digit_distributions_total_sum(n) + z\n num = n\n \n while True: \n num += 1\n res = bucket_digit_distributions_total_sum(num)\n if lim < res: \n return num\n \n return num\n\ndef bucket_digit_distributions_total_sum(n): \n parts = get_partitions(list(str(n)), len(str(n)))\n buckets_sum = 0\n \n for p in parts: \n if len(p) > 1:\n b = [int(''.join(l)) for l in p]\n buckets_sum += sum(b)\n \n return buckets_sum\n \n\ndef get_partitions(lst, n):\n if n <= 0: \n yield []\n return\n else: \n curr = lst[n - 1]\n for part in get_partitions(lst, n - 1): \n for l in list(part): \n l.append(curr)\n yield part\n l.pop()\n yield part + [[curr]]\n \nprint(find(9457, 4))", "#def find(n,z):\n\n# s = [i for i in str(n)]\n# print (s)\n# k = []\n# for i in range(len(s)):\n# s_n = s[:i]+s[i+1:]\n# b = [s[i]]\n# k = [s[i]] + [s_n]\n# print (k)\n# for i in range(len(s_n)):\ndef subsets(collection):\n if len(collection) == 1:\n yield [collection]\n return\n\n first = collection[0]\n\n for smaller in subsets(collection[1:]):\n yield [first] + smaller\n for n, subset in enumerate(smaller):\n yield smaller[:n] + [first + subset] + smaller[n+1:]\n\ndef bucket_digit_distributions_total_sum(n):\n return sum(sum(map(int, sub)) for sub in subsets(str(n))) - n\n\ndef find(n, z):\n f_nf = bucket_digit_distributions_total_sum(n) + z\n while 1:\n n += 1\n if bucket_digit_distributions_total_sum(n) > f_nf:\n return n ", "def get_partitionr(ss):\n out = []\n if len(ss) <= 1:\n return [ss]\n for i in range(2**len(ss)//2):\n parts = [[], []]\n for item in ss:\n parts[i&1].append(item)\n i >>= 1\n bb = get_partitionr(parts[1])\n for b in bb:\n out.append([parts[0]]+ b)\n return out\n\ndef add(parts):\n total = 0\n for part in parts:\n total += sum(int(''.join(p)) if isinstance(p, list) else int(p) for p in part)\n return total\n\ndef find(n, z):\n parts = get_partitionr(list(str(n)))[1:]\n add_parts = add(parts)\n target = add_parts + z\n while add_parts <= target:\n n += 1\n parts = get_partitionr(list(str(n)))[1:]\n add_parts = add(parts)\n return n", "import itertools\ndef find(n,z):\n find.combination_dict = {0:((),), \n 1:( ((0,),), ), }\n # 2:(((0,), (1,)), ((0, 1),), ), }\n # 3: (((0,), (1,), (2,)), ((0,), (1,2)), ((1,), (0,2)), ((2,), (0,1)), ((0,1,2),),)}\n def get_combination(length):\n if length not in find.combination_dict:\n for i in range(length):\n get_combination(i)\n template = list(range(length))\n result = [{tuple(i for i in template)}]\n for init_tuple_length in range(1, length):\n for c in itertools.combinations(template, init_tuple_length):\n remain = [i for i in template if i not in c]\n for combinations in find.combination_dict[length - init_tuple_length]:\n new_combination = [tuple(c)]\n for combination in combinations:\n new_combination.append(tuple(remain[index] for index in combination))\n if set(new_combination) not in result:\n result.append(set(new_combination))\n find.combination_dict[length] = tuple(tuple(i) for i in result)\n return find.combination_dict[length]\n\n def f(num):\n num = str(num)\n value = []\n for combinations in get_combination(len(num)): \n if len(combinations) != 1:\n for combination in combinations:\n value.append(''.join(num[i] for i in combination))\n return sum(map(int, value))\n \n# print('running', n, f(n), z)\n limit = f(n) + z\n for nf in itertools.count(n):\n if f(nf) > limit: \n return nf\n"]
{"fn_name": "find", "inputs": [[500, 200], [1000, 2000], [3000, 1000], [5200, 500], [10001, 100], [30000, 1000]], "outputs": [[888], [1987], [3388], [5288], [10003], [30046]]}
INTRODUCTORY
PYTHON3
CODEWARS
8,278
def find(n,z):
04d1e218ef5dcf41318eea5c9bbda610
UNKNOWN
## Task Complete function `splitOddAndEven`, accept a number `n`(n>0), return an array that contains the continuous parts of odd or even digits. Please don't worry about digit `0`, it won't appear ;-) ## Examples
["def split_odd_and_even(n):\n \n import re\n \n return [int(i) for i in re.findall(r\"[2468]+|[13579]+\", str(n))]", "from itertools import groupby\n\ndef split_odd_and_even(n):\n return [int(\"\".join(g))\n for i, g in groupby(str(n), key=lambda x: int(x) % 2)]", "import re\ndef split_odd_and_even(n):\n return [int(x) for x in re.findall(r\"([2468]+|[13579]+)\",str(n))]", "def split_odd_and_even(n):\n new_n = ''\n for c in str(n):\n if not new_n or not (int(new_n[-1]) - int(c)) % 2:\n new_n += c\n else :\n new_n += '.'+c\n return [int(i) for i in new_n.split('.')]", "def is_even(n):\n return int(n)%2==0\n\ndef split_odd_and_even(n):\n index, s = 0, str(n)\n l = [[s[0]]]\n for x in s[1:]:\n if is_even(x) and is_even(l[index][-1]):\n l[index].append(x)\n elif not is_even(x) and not is_even(l[index][-1]):\n l[index].append(x)\n else:\n l.append([x])\n index += 1\n return [int(''.join(x)) for x in l]", "from itertools import groupby\n\ndef split_odd_and_even(n):\n return [int(''.join(list(gp))) for _, gp in groupby(str(n), key = lambda x: int(x) % 2)]", "from itertools import groupby\n\ndef split_odd_and_even(n):\n return [int(''.join(grp)) for _, grp in groupby(str(n), key=lambda x: int(x) % 2)]", "import re\n\ndef split_odd_and_even(n):\n return [int(group[0] or group[1]) for group in re.findall(r'([13579]+)|([2468]+)', str(n))]", "from itertools import groupby\n\n\ndef split_odd_and_even(n):\n return [int(''.join(str(b) for b in g)) for k, g in\n groupby((int(a) for a in str(n)), key=lambda b: b % 2)]"]
{"fn_name": "split_odd_and_even", "inputs": [[123], [223], [111], [13579], [2468642], [135246], [123456], [8123456], [82123456], [88123456]], "outputs": [[[1, 2, 3]], [[22, 3]], [[111]], [[13579]], [[2468642]], [[135, 246]], [[1, 2, 3, 4, 5, 6]], [[8, 1, 2, 3, 4, 5, 6]], [[82, 1, 2, 3, 4, 5, 6]], [[88, 1, 2, 3, 4, 5, 6]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,698
def split_odd_and_even(n):
e36d8db97880d313acf65a1b8d30db9f
UNKNOWN
Karan's company makes software that provides different features based on the version of operating system of the user. For finding which version is more recent, Karan uses the following method: While this function worked for OS versions 10.6, 10.7, 10.8 and 10.9, the Operating system company just released OS version 10.10. Karan's function fails for the new version: ```python compare_versions ("10.9", "10.10"); # returns True, while it should return False ``` Karan now wants to spend some time to right a more robust version comparison function that works for any future version/sub-version updates. Help Karan write this function. Here are a few sample cases: ```python compare_versions("11", "10"); # returns True compare_versions("11", "11"); # returns True compare_versions("10.4.6", "10.4"); # returns True compare_versions("10.4", "11"); # returns False compare_versions("10.4", "10.10"); # returns False compare_versions("10.4.9", "10.5"); # returns False ``` ```haskell compareVersions "11" "10" `shouldBe` GT compareVersions "10.4.6" "10.4" `shouldBe` GT compareVersions "10.10" "10.9" `shouldBe` GT compareVersions xs xs `shouldBe` EQ -- xs is an arbitrary version compareVersions "10" "11" `shouldBe` LT compareVersions "10.4" "10.4.6" `shouldBe` LT compareVersions "10.99" "10.100" `shouldBe` LT ``` It can be assumed that version strings are non empty and only contain numeric literals and the character `'.'`.
["def compare_versions(ver1,ver2):\n return [int(i) for i in ver1.split(\".\")] >= [int(i) for i in ver2.split(\".\")]\n", "def compare_versions(version1,version2):\n from distutils.version import LooseVersion, StrictVersion\n return LooseVersion(version1) >= LooseVersion(version2)\n", "from distutils.version import LooseVersion\n\ndef compare_versions(version1,version2):\n return LooseVersion(version1) >= LooseVersion(version2)", "from distutils.version import LooseVersion, StrictVersion\ndef compare_versions(v1,v2):\n return LooseVersion(v1) >= LooseVersion(v2)", "import itertools\n\ndef compare_versions(v1,v2):\n p = list(map(int, v1.split('.')))\n q = list(map(int, v2.split('.')))\n for i, v in itertools.zip_longest(p, q, fillvalue=0):\n if i < v:\n return False\n return True", "def compare_versions(v1, v2):\n return [int(n) for n in v1.split(\".\")] >= [int(n) for n in v2.split(\".\")]", "from distutils.version import LooseVersion\n\n\ndef compare_versions(version1, version2):\n v1 = LooseVersion(version1)\n v2 = LooseVersion(version2)\n return v1 >= v2", "def compare_versions(version1, version2):\n v1 = version1.split('.')\n v2 = version2.split('.')\n a = max(len(v1), len(v2))\n v1.append('0'*abs(len(v1) - a))\n v2.append('0'*abs(len(v2) - a))\n if v1[-1] == '':\n v1.pop(-1)\n if v2[-1] == '':\n v2.pop(-1)\n k = 0\n for i in v1:\n if int(i) < int(v2[k]):\n return False\n elif int(i) >= int(v2[k]):\n k += 1\n return True", "def compare_versions(version1, version2):\n v1 = map(int, version1.split('.'))\n v2 = map(int, version2.split('.'))\n return list(v1) >= list(v2)"]
{"fn_name": "compare_versions", "inputs": [["11", "10"], ["11", "11"], ["10.4.6", "10.4"], ["10.4", "10.4.8"], ["10.4", "11"], ["10.4.9", "10.5"], ["4.3.3", "4.3.3.1"], ["10.4.9", "104.9"], ["10.15", "10.12"]], "outputs": [[true], [true], [true], [false], [false], [false], [false], [false], [true]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,746
def compare_versions(version1, version2):
ecf63640df9a662b48b648db467fc861
UNKNOWN
We have an array with string digits that occurrs more than once, for example, ```arr = ['1', '2', '2', '2', '3', '3']```. How many different string numbers can be generated taking the 6 elements at a time? We present the list of them below in an unsorted way: ``` ['223213', '312322', '223312', '222133', '312223', '223321', '223231', '132223', '132322', '223132', '322321', '322312', '231322', '222313', '221233', '213322', '122323', '321322', '221332', '133222', '123232', '323221', '222331', '132232', '321232', '212323', '232213', '232132', '331222', '232312', '332212', '213223', '123322', '322231', '321223', '231232', '233221', '231223', '213232', '312232', '233122', '322132', '223123', '322123', '232231', '323122', '323212', '122233', '212233', '123223', '332221', '122332', '221323', '332122', '232123', '212332', '232321', '322213', '233212', '313222'] ``` There are ```60``` different numbers and ```122233``` is the lowest one and ```332221``` the highest of all of them. Given an array, ```arr```, with string digits (from '0' to '9'), you should give the exact amount of different numbers that may be generated with the lowest and highest value but both converted into integer values, using all the digits given in the array for each generated string number. The function will be called as ```proc_arr()```. ```python proc_arr(['1', '2', '2', '3', '2', '3']) == [60, 122233, 332221] ``` If the digit '0' is present in the given array will produce string numbers with leading zeroes, that will not be not taken in account when they are converted to integers. ```python proc_arr(['1','2','3','0','5','1','1','3']) == [3360, 1112335, 53321110] ``` You will never receive an array with only one digit repeated n times. Features of the random tests: ``` Low performance tests: Number of tests: 100 Arrays of length between 6 and 10 Higher performance tests: Number of tests: 100 Arrays of length between 30 and 100 ```
["from operator import mul\nfrom math import factorial\nfrom functools import reduce\nfrom collections import Counter\n\ndef proc_arr(arr):\n s = ''.join(sorted(arr))\n return [factorial(len(arr)) // reduce(mul, list(map(factorial, list(Counter(arr).values())))), int(s), int(s[::-1])]\n", "from math import factorial\n\ndef proc_arr(arr):\n arr = ''.join(sorted(arr))\n comb = factorial(len(arr))\n same = eval('*'.join(map(str, [factorial(arr.count(n)) for n in '0123456879'])))\n \n return [ comb/same, int(arr), int(arr[::-1]) ]", "from collections import Counter\nfrom operator import floordiv\nfrom functools import reduce\nfrom math import factorial\n\ndef proc_arr(arr):\n count = reduce(floordiv, map(factorial, Counter(arr).values()), factorial(len(arr)))\n mini = int(''.join(sorted(arr)))\n maxi = int(''.join(sorted(arr, reverse=True)))\n return [count, mini, maxi]", "from functools import reduce\nfrom math import factorial as fac\nfrom operator import mul\n\ndef proc_arr(lst):\n stg = \"\".join(sorted(lst))\n p = fac(len(stg)) // reduce(mul, (fac(stg.count(d)) for d in set(stg)))\n return [p, int(stg), int(stg[::-1])]", "from math import factorial as f \nfrom functools import reduce as r\nfrom operator import mul as m\nfrom collections import Counter as C\nproc_arr=lambda a:[f(len(a))//r(m,map(f,C(a).values())),int(''.join(sorted(a,key=int))),int(''.join(sorted(a,key=int))[::-1])]", "from collections import Counter\nfrom math import factorial\nfrom operator import mul\nfrom functools import reduce\n\ndef proc_arr(arr):\n c = Counter(arr)\n xs = sorted(arr)\n n = factorial(len(arr)) // reduce(mul, list(map(factorial, list(c.values()))))\n return [n, int(''.join(xs)), int(''.join(xs[::-1]))]\n", "from collections import Counter\nfrom math import factorial\n\ndef proc_arr(arr):\n perm, strng = factorial(len(arr)), []\n for k, v in sorted(Counter(arr).items()):\n perm //= factorial(v)\n strng.append(k * v)\n return [perm, int(''.join(strng)), int(''.join(strng[::-1]))]\n", "import math\nfrom collections import Counter\nfrom functools import reduce\n\ndef proc_arr(arr): #, k):\n arrstr = \"\".join(sorted(arr, key=int))\n dupes = reduce((lambda x, y: x * y), [math.factorial(x[1]) for x in Counter(arr).most_common() if x[1] > 1] or [1])\n return [math.factorial(len(arr)) / dupes, int(arrstr), int(arrstr[::-1])]\n", "from math import factorial\n\nimport re\n\ndef proc_arr(arr):\n s = ''.join(sorted(arr))\n r = ''.join(reversed(s))\n low, high = int(s), int(r)\n digits = len(s)\n denominator = mul([factorial(end - start) for start, end in \n [m.span() for m in re.finditer('(?P<D>\\d)(?P=D)*', s)]])\n return [(factorial(digits) // denominator), low, high]\n \ndef mul(coll):\n return 1 if not coll else coll[0] * mul(coll[1:])\n"]
{"fn_name": "proc_arr", "inputs": [[["1", "2", "2", "3", "2", "3"]]], "outputs": [[[60, 122233, 332221]]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,902
def proc_arr(arr):
4efb92bcaf9224516b087bfadb085bcb
UNKNOWN
Welcome young Jedi! In this Kata you must create a function that takes an amount of US currency in `cents`, and returns a dictionary/hash which shows the least amount of coins used to make up that amount. The only coin denominations considered in this exercise are: `Pennies (1¢), Nickels (5¢), Dimes (10¢) and Quarters (25¢)`. Therefor the dictionary returned should contain exactly 4 key/value pairs. Notes: * If the function is passed either 0 or a negative number, the function should return the dictionary with all values equal to 0. * If a float is passed into the function, its value should be be rounded down, and the resulting dictionary should never contain fractions of a coin. ## Examples ``` loose_change(56) ==> {'Nickels': 1, 'Pennies': 1, 'Dimes': 0, 'Quarters': 2} loose_change(-435) ==> {'Nickels': 0, 'Pennies': 0, 'Dimes': 0, 'Quarters': 0} loose_change(4.935) ==> {'Nickels': 0, 'Pennies': 4, 'Dimes': 0, 'Quarters': 0} ```
["import math\n\ndef loose_change(cents):\n if cents < 0:\n cents = 0\n cents = int(cents)\n \n change = {}\n\n change['Quarters'] = cents // 25\n cents = cents % 25\n\n change['Dimes'] = cents // 10\n cents = cents % 10\n\n change['Nickels'] = cents // 5\n cents = cents % 5\n \n change['Pennies'] = cents\n \n return change", "CHANGES = (('Quarters', 25),\n ('Dimes', 10),\n ('Nickels', 5),\n ('Pennies', 1))\n\ndef loose_change(cents):\n cents, changed = max(0, int(cents)), {}\n for what,value in CHANGES:\n n,cents = divmod(cents,value)\n changed[what] = n\n return changed", "def loose_change(cents):\n coins = {'Nickels': 0, 'Pennies': 0, 'Dimes': 0, 'Quarters': 0}\n if cents <= 0:\n return coins\n coins['Quarters'] = cents // 25\n coins['Dimes'] = cents % 25 // 10\n coins['Nickels'] = cents % 25 % 10 // 5\n coins['Pennies'] = cents % 25 % 10 % 5 // 1\n \n return coins", "def loose_change(cents):\n res = {}\n res['Quarters'], cents = divmod(cents, 25) if cents > 0 else (0, 0)\n res['Dimes'], cents = divmod(cents, 10)\n res['Nickels'], cents = divmod(cents, 5)\n res['Pennies'], cents = divmod(cents, 1)\n return res", "def loose_change(cents):\n\n total_cents = 0\n \n denomination_list = [ [\"Quarters\", 25],\n [\"Dimes\", 10],\n [\"Nickels\", 5],\n [\"Pennies\", 1] ]\n \n change_dict = {}\n \n for denomination in denomination_list:\n \n coin_count = 0\n \n while total_cents + denomination[1] <= cents:\n \n total_cents += denomination[1]\n coin_count += 1\n \n change_dict [denomination [0]] = coin_count\n\n return change_dict", "def loose_change(cents):\n cents = max(cents, 0)\n d = {}\n for coin, n in ('Quarters', 25), ('Dimes', 10), ('Nickels', 5), ('Pennies', 1):\n d[coin], cents = divmod(cents, n)\n return d", "def loose_change(cents):\n if cents <=0: cents = 0\n return {'Nickels':int(cents)%25%10//5, 'Pennies':int(cents)%5, 'Dimes':int(cents)%25//10, 'Quarters':int(cents)//25}", "from math import floor\ndef loose_change(cents):\n change_dict = {}\n cents = 0 if cents < 0 else floor(cents)\n change_dict[\"Quarters\"] = cents // 25\n cents %= 25\n change_dict[\"Dimes\"] = cents // 10\n cents %= 10\n change_dict[\"Nickels\"] = cents // 5\n cents %= 5\n change_dict[\"Pennies\"] = cents\n return change_dict", "def loose_change(cents):\n cents = max(int(cents), 0)\n changes = {}\n \n for i, n in enumerate((25, 10, 5, 1)):\n units = ['Quarters', 'Dimes', 'Nickels', 'Pennies']\n changes[ units[i] ] = cents // n\n cents = cents % n\n \n return changes"]
{"fn_name": "loose_change", "inputs": [[56], [0], [100], [-3], [7.9]], "outputs": [[{"Nickels": 1, "Pennies": 1, "Dimes": 0, "Quarters": 2}], [{"Nickels": 0, "Pennies": 0, "Dimes": 0, "Quarters": 0}], [{"Nickels": 0, "Pennies": 0, "Dimes": 0, "Quarters": 4}], [{"Nickels": 0, "Pennies": 0, "Dimes": 0, "Quarters": 0}], [{"Nickels": 1, "Pennies": 2, "Dimes": 0, "Quarters": 0}]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,916
def loose_change(cents):
a9770a0aa986cb7b15fb01aae034c222
UNKNOWN
Consider the prime number `23`. If we sum the square of its digits we get: `2^2 + 3^2 = 13`, then for `13: 1^2 + 3^2 = 10`, and finally for `10: 1^2 + 0^2 = 1`. Similarly, if we start with prime number `7`, the sequence is: `7->49->97->130->10->1`. Given a range, how many primes within that range will eventually end up being `1`? The upperbound for the range is `50,000`. A range of `(2,25)` means that: `2 <= n < 25`. Good luck! If you like this Kata, please try: [Prime reversion](https://www.codewars.com/kata/59b46276afcda204ed000094) [Domainant primes](https://www.codewars.com/kata/59ce11ea9f0cbc8a390000ed)
["def is_prime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n sqrtn = int(n**0.5) + 1\n for i in range(5, sqrtn, 6):\n if n % i == 0 or n % (i + 2) == 0:\n return False\n return True\n\ndef end_one(n):\n while n > 6:\n n = sum(map(lambda x: int(x)*int(x) ,f\"{n}\"))\n if n == 1:\n return True\n \ndef solve(a,b):\n return sum(1 for n in range(a, b) if is_prime(n) and end_one(n))", "def solve(a,b):\n return len([x for x in [7, 13, 19, 23, 31, 79, 97, 103, 109, 139, 167, 193, 239, 263, 293, 313, 331, 367, 379, 383, 397, 409, 487, 563, 617, 653, 673, 683, 709, 739, 761, 863, 881, 907, 937, 1009, 1033, 1039, 1093, 1151, 1277, 1303, 1373, 1427, 1447, 1481, 1487, 1511, 1607, 1663, 1697, 1733, 1847, 1933, 2003, 2039, 2063, 2111, 2221, 2309, 2333, 2339, 2383, 2393, 2417, 2557, 2693, 2741, 2833, 2851, 2903, 2963, 3001, 3019, 3067, 3079, 3083, 3109, 3137, 3209, 3301, 3313, 3319, 3323, 3329, 3331, 3371, 3391, 3463, 3607, 3637, 3643, 3673, 3709, 3779, 3797, 3803, 3823, 3833, 3907, 3923, 3931, 4111, 4127, 4157, 4217, 4271, 4363, 4441, 4447, 4481, 4517, 4663, 4721, 4751, 4817, 4871, 5147, 5227, 5281, 5417, 5471, 5477, 5527, 5569, 5659, 5741, 5821, 5879, 5897, 5987, 6037, 6053, 6073, 6163, 6197, 6203, 6329, 6337, 6343, 6353, 6361, 6367, 6373, 6389, 6637, 6661, 6673, 6701, 6703, 6719, 6733, 6763, 6791, 6803, 6899, 6917, 6971, 6983, 7039, 7127, 7309, 7331, 7451, 7457, 7481, 7541, 7547, 7589, 7603, 7691, 7793, 7841, 7937, 8081, 8147, 8233, 8369, 8521, 8597, 8693, 8699, 8741, 8821, 8929, 8963, 8969, 9001, 9007, 9013, 9103, 9133, 9203, 9323, 9377, 9587, 9623, 9689, 9829, 9857, 10009, 10039, 10067, 10093, 10141, 10151, 10177, 10211, 10247, 10303, 10333, 10337, 10427, 10457, 10487, 10607, 10663, 10733, 10771, 10847, 10903, 11113, 11131, 11149, 11159, 11197, 11243, 11251, 11311, 11423, 11467, 11471, 11483, 11491, 11519, 11681, 11719, 11941, 11971, 12011, 12101, 12143, 12149, 12347, 12413, 12437, 12473, 12491, 12511, 12583, 12671, 12743, 12823, 12841, 12853, 12941, 12959, 13003, 13009, 13033, 13037, 13093, 13177, 13241, 13309, 13339, 13411, 13421, 13457, 13487, 13499, 13577, 13679, 13697, 13757, 13841, 13903, 13933, 13967, 14011, 14057, 14081, 14087, 14207, 14281, 14321, 14327, 14347, 14387, 14407, 14437, 14449, 14461, 14537, 14549, 14551, 14561, 14723, 14753, 14783, 14813, 14821, 14831, 14939, 15101, 15121, 15299, 15377, 15451, 15461, 15473, 15541, 15641, 15679, 15737, 15773, 15787, 15823, 15877, 15887, 16007, 16063, 16097, 16127, 16217, 16363, 16417, 16451, 16603, 16633, 16741, 16759, 16811, 16937, 16993, 17027, 17033, 17107, 17137, 17191, 17207, 17317, 17443, 17483, 17569, 17573, 17609, 17627, 17659, 17669, 17713, 17827, 17911, 18041, 18047, 18143, 18223, 18253, 18341, 18401, 18413, 18523, 18587, 18743, 18757, 18839, 18899, 19141, 19259, 19333, 19421, 19699, 19763, 19889, 19963, 19979, 19997, 20063, 20147, 20177, 20333, 20369, 20393, 20639, 20693, 20717, 20771, 20899, 20903, 20963, 21011, 21101, 21143, 21149, 21283, 21341, 21347, 21407, 21419, 21481, 21491, 21599, 21617, 21767, 21787, 21841, 22129, 22229, 22273, 22291, 22381, 22483, 22549, 22573, 22621, 22651, 22783, 22861, 22921, 23039, 23227, 23369, 23417, 23447, 23581, 23609, 23663, 23741, 23827, 23887, 23893, 23899, 23977, 24071, 24107, 24113, 24137, 24181, 24229, 24317, 24371, 24473, 24683, 24859, 25057, 25111, 25183, 25237, 25261, 25453, 25561, 25621, 25657, 25801, 25849, 25919, 26003, 26171, 26177, 26227, 26251, 26267, 26309, 26339, 26393, 26557, 26627, 26633, 26669, 26711, 26717, 26821, 26903, 27017, 27107, 27143, 27253, 27283, 27299, 27397, 27431, 27611, 27617, 27697, 27701, 27739, 27793, 27817, 27823, 27883, 27967, 28051, 28081, 28099, 28123, 28351, 28387, 28393, 28411, 28463, 28513, 28549, 28621, 28643, 28723, 28771, 28789, 28837, 28879, 28909, 28933, 29033, 29063, 29221, 29297, 29303, 29363, 29383, 29389, 29411, 29633, 29833, 29927, 29983, 30013, 30029, 30091, 30097, 30103, 30109, 30133, 30137, 30139, 30269, 30293, 30313, 30319, 30323, 30367, 30391, 30553, 30637, 30643, 30661, 30689, 30713, 30763, 30803, 30869, 30931, 30977, 31033, 31039, 31177, 31247, 31307, 31393, 31481, 31547, 31663, 31699, 31769, 31771, 31847, 32009, 32069, 32083, 32141, 32257, 32303, 32309, 32369, 32411, 32609, 32693, 32779, 32797, 32803, 32839, 32887, 32983, 33013, 33023, 33029, 33071, 33083, 33091, 33107, 33203, 33289, 33301, 33359, 33391, 33413, 33589, 33629, 33829, 33931, 34127, 34147, 34157, 34211, 34217, 34313, 34471, 34499, 34603, 34721, 34747, 34781, 34871, 34897, 34919, 34949, 35053, 35227, 35281, 35339, 35393, 35569, 35603, 35771, 35839, 35933, 35983, 36007, 36037, 36061, 36067, 36073, 36209, 36263, 36293, 36307, 36343, 36433, 36559, 36607, 36637, 36791, 36809, 36919, 36923, 37013, 37097, 37117, 37171, 37441, 37447, 37489, 37517, 37571, 37619, 37663, 37691, 37907, 38069, 38189, 38239, 38287, 38299, 38303, 38329, 38333, 38593, 38609, 38669, 38749, 38891, 38923, 38953, 39023, 39103, 39133, 39301, 39313, 39419, 39619, 39623, 39671, 39727, 39749, 39761, 39799, 39829, 39847, 39979, 40009, 40087, 40111, 40127, 40471, 40577, 40609, 40751, 40841, 41011, 41047, 41057, 41081, 41113, 41117, 41131, 41183, 41213, 41231, 41281, 41333, 41357, 41381, 41387, 41399, 41507, 41549, 41617, 41641, 41651, 41761, 41801, 41813, 41911, 42017, 42071, 42131, 42181, 42283, 42437, 42473, 42589, 42683, 42701, 42743, 42859, 42863, 43063, 43133, 43271, 43313, 43331, 43427, 43499, 43517, 43633, 43721, 43781, 43789, 43987, 43991, 43997, 44017, 44041, 44071, 44159, 44249, 44273, 44371, 44453, 44491, 44519, 44543, 44633, 44647, 44651, 44699, 44701, 44773, 44789, 44879, 44939, 44959, 44987, 45077, 45137, 45161, 45289, 45317, 45491, 45523, 45553, 45641, 45707, 45853, 45949, 46141, 46171, 46411, 46447, 46451, 46499, 46511, 46663, 46997, 47041, 47051, 47057, 47111, 47123, 47143, 47161, 47351, 47381, 47389, 47407, 47431, 47501, 47507, 47513, 47699, 47743, 47857, 47939, 47969, 48017, 48121, 48131, 48259, 48311, 48371, 48397, 48449, 48479, 48497, 48623, 48731, 48757, 48799, 48947, 48973, 49121, 49139, 49193, 49211, 49391, 49451, 49459, 49549, 49697, 49739, 49783, 49789, 49937, 49943] if x in range(a,b)])\n", "import math as m\ndef IsPrime(a):\n if a==1:\n return False\n for i in range(2,int(m.sqrt(a)+1)):\n if a%i==0:\n return False\n return True\ndef algorithm(a):\n while a!=4:\n sum=0\n for j in str(a):\n sum+=int(j)**2\n a=sum\n if a==1:\n return True\n return False \ndef solve(a,b):\n counter=0\n for i in range(a,b):\n if IsPrime(i):\n if algorithm(i):\n counter+=1\n return counter", "\ndef build_solver(limit):\n # Initial list of known values\n reducers = [(2, 0), (3, 0), (5, 0)]\n # Intermediate values known to end in a non-terminating sequence\n known_failures = {2, 3, 5}\n \n def reduces_to_1(p):\n # Determine if successive summation of digit squares reduces to 1\n seq = set()\n n = p\n while n not in seq and n not in known_failures and n != 1:\n seq.add(n)\n m = n\n t = 0\n while m > 0:\n m, d = divmod(m, 10)\n t += d * d\n n = t\n if n != 1:\n # Add to the set of known failing intermeduiate states\n known_failures.update(seq)\n return n == 1\n \n # Build primes up to limit\n prime_candidate = reducers[-1][0]\n root = int(prime_candidate ** 0.5) + 1\n while prime_candidate < limit:\n prime_candidate += 2\n if root * root < prime_candidate:\n root += 1\n for p, _ in reducers:\n if prime_candidate % p == 0:\n break\n if p > root:\n reducers.append((prime_candidate, reduces_to_1(prime_candidate)))\n break\n \n # Keep only those primes that reduce to 1\n reducers = [p for p, r in reducers if r]\n\n def solve(a, b):\n result = 0\n for p in reducers:\n if p < a:\n continue\n if p >= b:\n break\n result += 1\n return result\n \n return solve\n \nsolve = build_solver(50_000)", "import numpy as np\n\ndef ssloop(n):\n seen = set()\n while n != 1 and n not in seen:\n seen.add(n)\n n = sum(x*x for x in map(int, str(n)))\n return n == 1\n\ns = np.ones(50001)\ns[:2] = s[4::2] = 0\nfor i in range(3, int(len(s) ** 0.5) + 1, 2):\n if s[i]:\n s[i*i::i] = 0\nxs = [i for i, x in enumerate(s) if x and ssloop(i)]\n\ndef solve(a,b):\n return np.searchsorted(xs, b) - np.searchsorted(xs, a)", "N = 10 ** 5\n\ndef sum_square_digits(n):\n return sum((ord(d) - 48) ** 2 for d in str(n))\n\ndef reductible(n):\n suite = set()\n while n not in suite:\n suite.add(n)\n n = sum_square_digits(n)\n return n == 1\n\nmax_digit_sum = 81 * len(str(N))\nsum_reduc = set(filter(reductible, range(max_digit_sum + 1)))\n\ndef primes(n):\n sieve = n // 2 * [True]\n for i in range(3, int(n**.5) + 1, 2):\n if sieve[i // 2]:\n sieve[i*i // 2::i] = [False] * ((n - i*i - 1) // (2*i) + 1)\n return [2] + [2*i + 1 for i in range(1, n // 2) if sieve[i]]\n\nprime_reduc = [n for n in primes(N) if sum_square_digits(n) in sum_reduc]\n\nfrom bisect import bisect_left\ndef solve(a, b):\n return bisect_left(prime_reduc, b) - bisect_left(prime_reduc, a)", "def isprime(n):\n if n<2: return False\n for i in range(2,int(n**0.5)+1):\n if n%i==0:\n return False\n return True\n \ndef solve(a,b):\n count = 0\n for i in range(a,b):\n if isprime(i):\n c = 0\n while i!=1 and c!= 10:\n i = sum(int(j)**2 for j in list(str(i)))\n c += 1\n if i==1:\n count += 1\n return count", "N = 50000\nsieve, reduceable = [False, False] + [True] * (N - 1), set()\nfor i, is_prime in enumerate(sieve):\n if is_prime:\n seen, n = set(), i\n while n not in seen:\n seen.add(n)\n n = sum(int(c)**2 for c in str(n))\n if n == 1: reduceable.add(i) \n\n for j in range(i*i, N+1, i): sieve[j] = False\n\ndef solve(a,b):\n return sum(1 for e in reduceable if a <= e < b)"]
{"fn_name": "solve", "inputs": [[1, 25], [100, 1000], [100, 2000], [100, 3000], [100, 4000]], "outputs": [[4], [28], [47], [65], [95]]}
INTRODUCTORY
PYTHON3
CODEWARS
10,504
def solve(a,b):
c758f07bbc2eec918344da1eebaec089
UNKNOWN
Every number may be factored in prime factors. For example, the number 18 may be factored by its prime factors ``` 2 ``` and ```3``` ``` 18 = 2 . 3 . 3 = 2 . 3² ``` The sum of the prime factors of 18 is ```2 + 3 + 3 = 8``` But some numbers like 70 are divisible by the sum of its prime factors: ``` 70 = 2 . 5 . 7 # sum of prime factors = 2 + 5 + 7 = 14 and 70 is a multiple of 14 ``` Of course that primes would fulfill this property, but is obvious, because the prime decomposition of a number, is the number itself and every number is divisible by iself. That is why we will discard every prime number in the results We are interested in collect the integer positive numbers (non primes) that have this property in a certain range ```[a, b]``` (inclusive). Make the function ```mult_primefactor_sum()```, that receives the values ```a```, ```b``` as limits of the range ```[a, b]``` and ```a < b``` and outputs the sorted list of these numbers. Let's see some cases: ```python mult_primefactor_sum(10, 100) == [16, 27, 30, 60, 70, 72, 84] mult_primefactor_sum(1, 60) == [1, 4, 16, 27, 30, 60] ```
["def mult_primefactor_sum(a, b): \n s=[]\n for i in range(a,b+1):\n r=factorize_add(i)\n if r!=i and i%r==0: s.append(i)\n return s\n \ndef factorize_add(num):\n if num<4: return num\n d=2; p=0\n while d<num**.5+1:\n while not num%d: p+=d; num/=d\n d+=1 if d==2 else 2\n return p if num==1 else p+num", "def mult_primefactor_sum(a, b):\n ret = []\n for m in range(a, b + 1):\n p, s, n = 2, 0, m\n while n > 1 and p <= n ** .5:\n while n % p == 0:\n s += p\n n //= p\n p += 1\n s += n > 1 and n\n if s < m and m % s == 0:\n ret.append(m)\n return ret", "from bisect import bisect_left, bisect_right\n\ndef spf(n):\n result = 0\n nd = 0\n while n % 2 == 0:\n result += 2\n nd += 1\n n //= 2\n d = 3\n while n > 1:\n while n % d == 0:\n result += d\n n //= d\n nd += 1\n d += 2\n return n+1 if nd == 1 else (result or n+1) # nd == 1 -> prime\n\nxs = [x for x in range(1, 20001) if x % spf(x) == 0]\n\ndef mult_primefactor_sum(a, b):\n i = bisect_left(xs, a)\n j = bisect_right(xs, b)\n return xs[i:j]", "def mult_primefactor_sum(a, b):\n prime_factors = [factorize(n) for n in range(a, b+1)]\n return [n for n, pf in enumerate(prime_factors, a) if len(pf) > 1 and n % sum(pf) == 0]\n\n\n# Memoization and this factorization algorithm are overkill here,\n# one of them is enough (I didn't try none of them).\n# More simple than memoize is to precompute prime_factors, if you\n# know the max number to factorize (seems to be 20000 here).\n\ndef memoize(func):\n cache = {}\n def wrapper(*args):\n if args not in cache:\n cache[args] = func(*args)\n return cache[args]\n return wrapper\n\n@memoize\ndef factorize(n):\n if n < 2:\n return []\n factors = []\n for k in (2, 3):\n while n % k == 0:\n n //= k\n factors.append(k)\n k = 5\n step = 2\n while k * k <= n:\n if n % k:\n k += step\n step = 6 - step\n else:\n n //= k\n factors.append(k)\n if n > 1:\n factors.append(n)\n return factors", "''' keep track of numbers checked '''\nNUMS = [0, 0]\n\ndef mult_primefactor_sum(a, b):\n \n ''' only check numbers greater than before '''\n for n in range(len(NUMS), b+1):\n x, div, factors = n, 2, []\n \n ''' generate prime factors '''\n while x > 1:\n if x % div == 0:\n factors.append(div)\n x //= div\n else:\n div += 1 if div == 2 else 2\n \n ''' store number if it fulfills the conditions, otherwise put 0 '''\n if len(factors) == 1 or n % sum(factors) != 0:\n NUMS.append(0)\n else:\n NUMS.append(n)\n \n ''' return the results '''\n return [ x for x in NUMS[a:b+1] if x ]", "def primes(n):\n primfac = []\n d = 2\n while d*d <= n:\n while (n % d) == 0:\n primfac.append(d)\n n //= d\n d += 1\n if n > 1:\n primfac.append(n)\n return primfac\ndef mult_primefactor_sum(a, b): \n l = []\n for i in range(a, b+1):\n factors = primes(i) \n if i>sum(factors) and not i%sum(factors):\n l.append(i)\n return l", "def prime_factorizations(n):\n sieve = [0 for x in range(n)]\n for i in range(2, n):\n if not sieve[i]:\n sieve[i] = i\n for r in range(i, n, i):\n sieve[r] = sieve[r] or i\n return sieve\n\ndef factor_sum(sieve, n):\n results = 0\n while n > 1:\n p = sieve[n]\n results += p\n if p == n:\n break\n n //= p\n return results\n\ndef mult_primefactor_sum(a, b):\n sieve = prime_factorizations(b+1)\n return [n for n in range(a, b+1) if sieve[n]!=n and n%factor_sum(sieve, n)==0]", "def prime_factors(n):\n if n%2==0 and n>0:return [2]+prime_factors(n//2)\n \n for a in range(3,int(n**.5)+1,2): \n if n%a==0:return sorted(prime_factors(n//a)+prime_factors(a)) \n return [n] if n>1 else []\n\ndef mult_primefactor_sum(a, b): # [a, b] range of numbers included a and b\n return [c for c in range(a,b+1) if len(prime_factors(c))>1 and c%sum(prime_factors(c))==0]"]
{"fn_name": "mult_primefactor_sum", "inputs": [[10, 100], [80, 150], [90, 200]], "outputs": [[[16, 27, 30, 60, 70, 72, 84]], [[84, 105, 150]], [[105, 150, 180]]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,478
def mult_primefactor_sum(a, b):
6232c6857073116053bc7d8e05e70d77
UNKNOWN
Implement a class/function, which should parse time expressed as `HH:MM:SS`, or `null/nil/None` otherwise. Any extra characters, or minutes/seconds higher than 59 make the input invalid, and so should return `null/nil/None`.
["def to_seconds(time):\n try:\n s, m, h = int(time[-2:]), int(time[3:5]), int(time[:2])\n return s + m*60 + h*3600 if m < 60 and s < 60 and len(time) == 8 else None\n except:\n return None", "import re\n\n\ndef to_seconds(time):\n if bool(re.match('[0-9][0-9]:[0-5][0-9]:[0-5][0-9]\\Z', time)):\n return int(time[:2]) * 3600 + int(time[3:5]) * 60 + int(time[6:8])\n else:\n return None", "from re import compile, match\n\nREGEX = compile(r'^(?P<h>\\d{2}):(?P<m>[0-5]\\d):(?P<s>[0-5]\\d)$')\n\n\ndef to_seconds(time):\n m = match(REGEX, time)\n if m and time[slice(*m.span())] == time:\n hms = m.groupdict()\n return int(hms['h']) * 3600 + int(hms['m']) * 60 + int(hms['s'])\n", "import re\nfrom functools import reduce\n\nHH_MM_SS_PATTERN = re.compile(r'\\A(\\d\\d):([0-5]\\d):([0-5]\\d)\\Z')\n\n\ndef to_seconds(time):\n m = HH_MM_SS_PATTERN.search(time)\n if m:\n return reduce(lambda x, y: x * 60 + int(y), m.groups(), 0)\n return None\n", "import re\ndef to_seconds(time): \n match=re.fullmatch(r'(\\d{2}):([0-5][0-9]):([0-5][0-9])',time)\n return int(match.group(1))*3600+int(match.group(2))*60+int(match.group(3)) if match else None\n \n", "import re\n\n\ndef to_seconds(time):\n match = re.match(r\"(\\d\\d):([0-5]\\d):([0-5]\\d)\\Z\", time)\n return match and sum(int(n) * 60**i for i, n in enumerate(match.groups()[::-1]))\n", "import re;to_seconds=lambda t:sum(int(j)*i for i,j in zip([3600,60,1],t.split(':')))if re.sub(r'^\\d{2}:[0-5][0-9]:[0-5][0-9]$','',t)==''else None", "def to_seconds(time):\n try:\n h, m, s = map(int, time.split(':'))\n if not (len(time) == 8 and 0 <= m < 60 > s >= 0):\n return None\n except ValueError:\n return None\n return h * 3600 + m * 60 + s"]
{"fn_name": "to_seconds", "inputs": [["00:00:00"], ["01:02:03"], ["01:02:60"], ["01:60:03"], ["99:59:59"], ["0:00:00"], ["00:0:00"], ["00:00:0"], ["00:00:00\n"], ["\n00:00:00"], ["100:59:59"], ["09:059:59"], ["09:159:59"], ["09:59:059"], ["09:59:159"]], "outputs": [[0], [3723], [null], [null], [359999], [null], [null], [null], [null], [null], [null], [null], [null], [null], [null]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,829
def to_seconds(time):
caac478416858a334396a6bfdbedc05f
UNKNOWN
Welcome This kata is inspired by This Kata We have a string s We have a number n Here is a function that takes your string, concatenates the even-indexed chars to the front, odd-indexed chars to the back. Examples s = "Wow Example!" result = "WwEapeo xml!" s = "I'm JomoPipi" result = "ImJm ii' ooPp" The Task: return the result of the string after applying the function to it n times. example where s = "qwertyuio" and n = 2: after 1 iteration s = "qetuowryi" after 2 iterations s = "qtorieuwy" return "qtorieuwy" Note there's a lot of tests, big strings, and n is greater than a billion so be ready to optimize. after doing this: do it's best friend! # Check out my other kata! Matrix Diagonal Sort OMG String -> N iterations -> String String -> X iterations -> String ANTISTRING Array - squareUp b! Matrix - squareUp b! Infinitely Nested Radical Expressions pipi Numbers!
["def jumbled_string(s, n):\n iterations = [s]\n \n while True:\n s = s[::2] + s[1::2]\n if s == iterations[0]: break\n iterations.append(s)\n \n return iterations[n % len(iterations)]", "#Kata: String -> N iterations -> String Rating 5kyu\n\n\n#To optimize this problem, we must look at the circular (modular) nature of the iterations\n#of the even/odd rule. Given any string, under the even/odd rule, the number of permutations\n#will be no longer than the length of the original message. \n# e.g. 'abcdefghijklmnop' has only four unique permutations under the even/odd rule:\n# ['abcdefghijklmnop', 'acegikmobdfhjlnp', 'aeimbfjncgkodhlp', 'aibjckdlemfngohp']\n# So, if we want to apply the even/odd rule N times for string 'abcdefghijklmnop', we need but\n# access the 'N modulo n' element in the permutation list (where m is the length of permutation list)\n\n\ndef buildPermList(originalMsg):\n \n listPerms = []\n listPerms.append(originalMsg) #index 0 is original message\n curMsg = originalMsg\n \n while True:\n even = curMsg[0::2]\n odd = curMsg[1::2]\n curMsg = even+odd\n if curMsg != originalMsg: #Scenario: Back to the original message\n listPerms.append(curMsg)\n else:\n break\n\n #listPerms is <= the length of the origianl message; ith element is the ith permutation under\n # the even/odd rules\n return listPerms \n#-----end function\n\n\ndef jumbled_string(msg, n):\n\n permList = buildPermList(msg)\n numUniquePerms = len(permList)\n desiredRotIndex = n % numUniquePerms\n\n return permList[desiredRotIndex]\n\n#-----end function\n\n\n#Demonstrative test code\n# msg = 'abcdefghijklmnop'\n# n=18\n# myList = buildPermList(msg)\n# print(\"---Length of list: \", len(myList))\n# print(\"---List: \", myList)\n# lenList = len(myList)\n# desiredIndex = n % lenList\n# print( \"The location: \", str(desiredIndex) )\n# print( \"Desired String\", rotationsByN(msg, n) )\n", "def jumbled_string(s, n):\n seen = []\n while s not in seen:\n seen.append(s)\n s = f\"{s[::2]}{s[1::2]}\"\n return seen[n % len(seen)]", "def jumbled_string(s, n):\n ml = ['bullshit']\n new_str = s\n\n while s != ml[-1]:\n new_str = new_str[::2] + new_str[1::2]\n ml.append(new_str)\n return ml[n% (len(ml)-1)]", "def jumbled_string(s, n):\n mixer = lambda s: s[::2] + s[1::2]\n \n if n == 1: return mixer(s) \n \n # Count max possible iterations\n cnt = 1\n x = s\n while s != mixer(x):\n cnt += 1\n x = mixer(x)\n \n # Calculate needed amount of iterations \n max = n % cnt\n while max != 0:\n s = mixer(s)\n max -= 1\n return s", "def jumbled_string(s, n):\n results = [s]\n while n:\n s = s[::2] + s[1::2]\n n -= 1\n if s == results[0]:\n return results[n % len(results)]\n else:\n results.append(s)\n return s", "def jumbled_string(s, n):\n a = s\n i = 0\n while i < n: # Find the period of string after which it's the same\n s = s[::2] + s[1::2]\n i += 1\n if s == a:\n break\n n = n % i\n for i in range(n):\n s = s[::2] + s[1::2]\n return s", "def jumbled_string(s, n):\n idx = list(range(0,len(s),2)) + list(range(1,len(s),2))\n lst = []\n while not lst or s != lst[0]:\n lst.append(s)\n s = ''.join(s[i] for i in idx)\n if len(lst) == n: return s\n return lst[ n%len(lst) ]", "def jumbled_string(s, n):\n combine = lambda s : s[0::2] + s[1::2]\n for _ in range(n%multiplicativeOrder(2, len(s))):\n s = combine(s)\n return s\n\ndef GCD (a, b ) : \n if (b == 0 ) : \n return a \n return GCD( b, a % b ) \n\ndef multiplicativeOrder(A, N) : \n if (GCD(A, N ) != 1) : \n return multiplicativeOrder(A, N-1)\n result = 1\n\n K = 1\n while (K < N) : \n result = (result * A) % N \n if (result == 1) : \n return K \n K = K + 1\n return -1\n\n", "\"\"\"\nl = length of string\nm = l (if l is odd) or l - 1 (if l is even)\nk = length of a cycle to get back to original string\nthen (2^k) mod m = 1\n\"\"\"\n# find minimum k where (b ^ k) % m = 1 and k > 0\ndef multiplicativeOrder(b, m):\n k, r = 1, 1\n while True:\n r = (r * b) % m\n if r == 1:\n return k\n k += 1\n\ndef jumbled_string(s, n):\n l = len(s)\n m = l if l & 1 else l - 1\n k = multiplicativeOrder(2, m)\n answer = s\n for i in range(n % k):\n answer = answer[::2] + answer[1::2]\n return answer"]
{"fn_name": "jumbled_string", "inputs": [["Such Wow!", 1], ["better example", 2], ["qwertyuio", 2], ["Greetings", 8], ["I like it!", 1234], ["codingisfornerdsyounerd", 10101010], ["this_test_will_hurt_you", 12345678987654321]], "outputs": [["Sc o!uhWw"], ["bexltept merae"], ["qtorieuwy"], ["Gtsegenri"], ["Iiei t kl!"], ["criyinodedsgufrnodnoser"], ["ti_etwl_utyuhsts_ilhr_o"]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,723
def jumbled_string(s, n):
3dbe5dd66df0dd25a030377334a924f7
UNKNOWN
In the previous Kata we discussed the OR case. We will now discuss the AND case, where rather than calculating the probablility for either of two (or more) possible results, we will calculate the probability of receiving all of the viewed outcomes. For example, if we want to know the probability of receiving head OR tails in two tosses of a coin, as in the last Kata we add the two probabilities together. However if we want to know the probability of receiving head AND tails, in that order, we have to work differently. The probability of an AND event is calculated by the following rule: `P(A ∩ B) = P(A | B) * P(B)` or `P(B ∩ A) = P(B | A) * P(A)` That is, the probability of A and B both occuring is equal to the probability of A given B occuring times the probability of B occuring or vice versa. If the events are mutually exclusive like in the case of tossing a coin, the probability of A occuring if B has occured is equal to the probability of A occuring by itself. In this case, the probability can be written as the below: `P(A ∩ B) = P(A) * P(B)` or `P(B ∩ A) = P(B) * P(A)` Applying to the heads and tails case: `P(H ∩ T) = P(0.5) * P(0.5)` or `P(H ∩ T) = P(0.5) * P(0.5)` The task: You are given a random bag of 10 balls containing 4 colours. `Red`, `Green`, `Yellow` and `Blue`. You will also be given a sequence of 2 balls of any colour e.g. `Green` and `Red` or `Yellow` and `Yellow`. You have to return the probability of pulling a ball at random out of the bag and it matching the first colour and then pulling a ball at random out of the bag and it matching the second colour. You will be given a boolean value of `true` or `false` which indicates whether the balls that is taken out in the first draw is replaced in to the bag for the second draw. Hint: this will determine whether the events are mutually exclusive or not. You will receive two arrays and a boolean value. The first array contains the colours of the balls in the bag and the second contains the colour of the two balls you have to receive. As per above the final boolean value will indicate whether the bals arel being replaced `true` or not `false`. Return the probability to 3 decimal places. e.g. `[["y","r","g","b","b","y","r","g","r","r"],["r","b"],false]` Other Kata in this series: Statistics in Kata 1: OR case - Unfair dice
["from collections import Counter as C\ndef ball_probability(b):\n d, n, p = C(b[0]), len(b[0]), 1\n for i in b[1]:\n p *= d.get(i,0)/n\n n -= b[2]^1\n d[i] -= b[2]^1\n return round(p,3)", "def ball_probability(balls):\n colors, (first, second), replaced = balls\n first_choice = colors.count(first) / len(colors)\n second_choice = colors.count(second) / len(colors) if replaced else (colors.count(second) - 1 * (first == second)) / (len(colors) - 1)\n return round(first_choice * second_choice, 3)", "def ball_probability(balls):\n size = len(balls[0])\n if not balls[2]:\n p1 = balls[0].count(balls[1][0])\n p2 = p1 - 1 if balls[1][0] == balls[1][1] else balls[0].count(balls[1][1])\n return round((p1 * p2) / (size * (size - 1)), 3)\n return round((balls[0].count(balls[1][0]) * balls[0].count(balls[1][1])) / size**2, 3)", "def ball_probability(balls):\n l, selection, replaced = balls\n a, b = selection\n prob = (l.count(a) * (l.count(b) + (0 if replaced or (a != b) else -1))) / (len(l) * (len(l) + (0 if replaced else -1)))\n \n return round(prob, 3)", "def ball_probability(balls):\n bag, draws, replaced = balls\n return round(bag.count(draws[0]) / len(bag) * \\\n (bag.count(draws[1]) - (not replaced) * (draws[0] == draws[1])) / \\\n (len(bag) - (not replaced)), 3)", "def ball_probability(balls):\n bag,t,r=balls\n a,b=(bag.count(i) for i in t)\n m=len(bag)\n return round(1.0*a*(b if r or t[0]!=t[1] else b-1)/m/(m if r else m-1),3)", "from collections import Counter\ndef ball_probability(balls):\n c = Counter(balls[0])\n b1, b2 = balls[1]\n if balls[2]:\n return round(c[b1]/len(balls[0]) * c[b2]/len(balls[0]), 3)\n else:\n return round(c[b1]/len(balls[0]) * (c[b2]-1 if b1==b2 else c[b2])/(len(balls[0]) - 1), 3)", "def ball_probability(balls):\n balls, draw, repl = balls\n b1, l1 = balls.count(draw[0]), len(balls)\n if b1 == 0: return 0\n b2 = balls.count(draw[1]) if draw[0] != draw[1] else b1 + repl - 1\n l2 = l1 + repl - 1\n return round(b1 / l1 * b2 / l2, 3)", "from collections import Counter\n\ndef ball_probability(balls):\n bag, (call1, call2), replaced = balls\n bag, total = Counter(bag), len(bag)\n\n A = bag[call1] / total\n\n if not replaced:\n bag[call1] -= 1\n total -= 1\n\n B = bag[call2] / total\n return round(A * B, 3)", "from collections import Counter\n\ndef ball_probability(balls):\n bag, (call1, call2), replaced = balls\n bag = Counter(bag)\n total = sum(bag.values())\n\n A = bag[call1] / total\n \n if not replaced:\n bag[call1] -= 1\n total -= 1\n\n B = bag[call2] / total\n \n return round(A * B, 3)"]
{"fn_name": "ball_probability", "inputs": [[[["red", "blue", "yellow", "green", "red", "blue", "yellow", "green", "red", "blue"], ["red", "blue"], true]], [[["red", "blue", "yellow", "green", "red", "blue", "yellow", "green", "red", "blue"], ["red", "red"], true]], [[["red", "red", "yellow", "green", "red", "red", "yellow", "green", "red", "red"], ["blue", "blue"], true]], [[["red", "blue", "yellow", "green", "red", "blue", "yellow", "green", "red", "blue"], ["red", "blue"], false]], [[["red", "blue", "yellow", "green", "red", "blue", "yellow", "green", "red", "blue"], ["red", "red"], false]]], "outputs": [[0.09], [0.09], [0], [0.1], [0.067]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,796
def ball_probability(balls):
cde28f8856cf8162d05022fae9a4f95f
UNKNOWN
There's a **"3 for 2"** (or **"2+1"** if you like) offer on mangoes. For a given quantity and price (per mango), calculate the total cost of the mangoes. ### Examples ```python mango(3, 3) ==> 6 # 2 mangoes for 3 = 6; +1 mango for free mango(9, 5) ==> 30 # 6 mangoes for 5 = 30; +3 mangoes for free ```
["def mango(quantity, price):\n return (quantity - quantity // 3) * price", "def mango(quantity, price):\n return ((quantity - int(quantity/3)) * price)", "def mango(quantity, price):\n batch = quantity//3 \n total = (batch * 2 + quantity%3 ) * price \n return total", "def mango(quantity, price):\n return price * (quantity - (quantity // 3))", "def mango(quantity, price):\n print(quantity)\n return (quantity-quantity//3)*price", "def mango(quantity, price):\n return ((quantity/ 3) * (2 * price)) + (quantity % 3 * price)", "def mango(quantity, price):\n a, b = divmod(quantity, 3)\n return price * (a * 2 + b)", "mango = lambda q,p: p*(q-q//3)", "mango = lambda count, price: (count - count // 3) * price", "def mango(quantity: int, price: int) -> int:\n \"\"\"\n Calculate the total cost of the mangoes for a given quantity and price.\n Rule: \"3 for 2\" (or \"2+1\" if you like) offer on mangoes.\n \"\"\"\n return (quantity - (quantity // 3)) * price", "from math import ceil; mango=lambda q, p: ceil(q/3*2)*p", "mango = lambda q, p: (q // 3 * 2 + q % 3) * p;", "def mango(quantity, price):\n free = 0\n for i in range(1, quantity +1):\n if i%3 == 0:\n free += 1\n return price * (quantity - free)", "def mango(quantity, price):\n q,r = divmod(quantity,3)\n return price*(2*q+r)", "mango=lambda q,p:(q-q/3)*p", "mango=lambda q,p:q//3*2*p+q%3*p", "def mango(quantity, price):\n quantity = quantity - quantity // 3\n return quantity * price", "def mango(quantity, price):\n groups_of_three = quantity // 3\n remainding = quantity % 3\n \n return groups_of_three * 2 * price + remainding * price", "def mango(quantity, price):\n return (quantity * price) - (price * (quantity // 3)) ", "def mango(quantity, price):\n if quantity % 3 == 0:\n return (quantity * 2 * price // 3)\n else:\n return (quantity // 3 * 2 * price + quantity % 3 * price)", "def mango(quantity, price):\n a = quantity - quantity//3\n return a*price", "def mango(quantity, price):\n if quantity == 2 or quantity ==3:\n return 2 * quantity\n else:\n free = quantity // 3\n return (quantity - free) * price\n", "import numpy as np\ndef mango(quantity, price):\n return (quantity-(np.floor(quantity/3)))*price", "def mango(quant, price):\n return (quant - (quant // 3)) * price", "def mango(q, p):\n return sum(map(lambda x,y: x*y, [q//3, q%3],[2*p, p]))", "def mango(quantity, price):\n remaining = quantity%3\n quantity = (quantity - remaining) *2/3\n return quantity*price + remaining*price", "def mango(quantity, price):\n non_discounted_mangos = quantity % 3\n discounted_mangos = quantity - non_discounted_mangos\n return (((discounted_mangos / 3) * 2) * price) + (non_discounted_mangos * price)", "def mango(quantity, price):\n s, e = divmod(quantity, 3) # set of three + extra\n return price*((2*s)+e) # 3 for 2 + extra\n", "def mango(quantity, price):\n special_price_lots = quantity // 3\n full_price_mangoes = quantity - special_price_lots * 3\n return (special_price_lots * 2 + full_price_mangoes) * price", "def mango(quantity, price):\n if quantity / 3 == 1:\n return (quantity - 1) * price \n else:\n actual_quantity = quantity // 3\n return (quantity - actual_quantity) * price", "def mango(q, price):\n\n return price*(q-q//3)", "def mango(quantity, price):\n return 2 * price if quantity == 3 else (quantity - (quantity // 3)) * price\n", "import math\ndef mango(quantity, price):\n n=math.ceil(quantity*(2/3))\n return price*n", "def mango(quantity, price):\n a = int(quantity / 3)\n quantity -= a\n return price * quantity", "def mango(quantity, price):\n if quantity % 3 == 0:\n return quantity * 2 / 3 * price\n else:\n return (quantity - quantity // 3) * price", "def mango(quantity, price):\n\n free = quantity//3\n res = (quantity - free) * price\n return res", "from math import ceil\ndef mango(quantity, price):\n x = quantity // 3\n return (quantity-x) * price", "def mango(q,p):\n \"\"\"mangos are three for two\n \"\"\"\n return (2 * (q // 3) + (q % 3))*p\n", "import math\ndef mango(quantity, price):\n actual=math.floor(quantity/3)\n return (quantity-actual)*price", "def mango(quantity, price):\n total_cost = price * (quantity - quantity // 3)\n return total_cost", "def mango(quantity, price):\n return (quantity - quantity//3)*price if quantity > 3 else 6", "def mango(quantity, price):\n return price * (quantity // 3) * 2 + price * (quantity % 3)", "def mango(quantity, price):\n grupos = quantity//3\n residuo = quantity%3\n precio = (grupos*2 * price)\n\n if residuo == 0:\n return precio\n elif residuo == 1:\n return precio+price\n elif residuo == 2:\n return precio+(price*2)", "def mango(quantity, price):\n discount = quantity // 3\n return ((quantity - discount) * price)", "def mango(quantity, price):\n return price * round((quantity * 2)/3 + 0.5)\n", "import math\n\ndef mango(quantity, price):\n free_mangos = math.floor(quantity / 3)\n return (quantity - free_mangos) * price\n", "def mango(quantity, price):\n free = quantity - (quantity // 3)\n return free * price", "def mango(quantity, price):\n pass\n \n c = (quantity-quantity//3)*price\n \n return c", "import math\ndef mango(quantity, price):\n return ((quantity // 3) + (quantity - ((quantity // 3) * 2))) * price\n", "def mango(quantity, price):\n \n q = quantity\n p = price\n \n return (q - (q // 3)) * p", "mango = lambda quantity, price: (quantity - quantity//3) * price", "def mango(quantity, price):\n print(quantity, price)\n if not quantity%3==2:\n return price*(quantity*2//3)+price*(quantity%3) \n else:\n return price*(quantity*2//3)+price*(quantity%3)/2", "def mango(quantity, price):\n if quantity % 3 == 0:\n return quantity*2/3 * price\n elif quantity % 3 == 1:\n return (quantity-1) * 2/3 * price + price\n elif quantity % 3 == 2:\n return (quantity-2) * 2/3 * price + 2 * price", "import math\ndef mango(quantity, price):\n return (quantity - (quantity // 3)) * price", "def mango(quantity, price):\n buy = 0\n bill = 0\n while buy<quantity:\n buy+=3\n bill+=price*2\n \n if buy==quantity:\n return bill\n elif buy-quantity==1:\n return bill\n elif buy-quantity==2:\n return bill-price", "def mango(quantity, price):\n n = 0\n all_price = 0\n if quantity <= 2:\n return quantity * price\n elif quantity > 2:\n while n < quantity:\n n += 1\n all_price += price\n if n % 3 == 0:\n all_price -= price\n return all_price\n \n \n \n \n pass", "def mango(quantity, price):\n deal = int(quantity/3) \n no_deal = quantity - deal*3\n return deal*2*price + no_deal*price", "def mango(quantity, price):\n real_quant = quantity - (quantity //3)\n return real_quant * price", "def mango(quantity, price):\n if quantity % 3 == 0:\n a = (quantity / 3) * 2\n return a * price\n elif quantity % 3 != 0:\n b = quantity % 3\n c = ((quantity - b) / 3) * 2\n d = (c + b) \n return d * price\n", "def mango(quantity, price):\n total = 0\n for each in range(1,quantity +1):\n if each % 3 != 0:\n total += price\n return total\n", "def mango(quantity, price):\n pass\n x=quantity//3\n y=quantity%3\n return (2*x+y)*price", "# def mango(quantity, price):\n# # if quantity % 3 == 0:\n# # return (quantity//3)*2*price\n# # # if quantity % 3 == 1:\n# # else:\n# # return ((quantity//3)*2 + 1)*price\ndef mango(quantity, price):\n return (quantity - quantity // 3) * price", "import math\ndef mango(quantity, price):\n return quantity * price - math.floor(quantity/3) * price", "from math import floor\ndef mango(q,p): return (q-floor(q/3))*p", "def mango(q,p):\n price = 0\n while q % 3 != 0:\n price += p\n q -= 1\n return price+q*(2/3)*p", "def mango(quantity, price):\n return (int(quantity * 2 / 3) + (1 if quantity % 3 else 0)) * price", "import math\ndef mango(quantity, price):\n print(quantity, price)\n \n return math.ceil(quantity / 3 * 2) * price", "def mango(q, p):\n return (q -(q // 3)) * p\n # Flez \n", "def mango(q, p):\n print((q, p))\n return (q * p) - ((q // 3) * p)\n # Flez\n", "def mango(quantity, price):\n groups_three = quantity // 3\n extra = quantity % 3\n cost = 0\n cost = cost + groups_three * (price * 2)\n cost = cost + extra * price\n return cost", "def mango(quantity, price):\n groupsOfThree = quantity // 3\n remainder = quantity - groupsOfThree * 3\n return groupsOfThree * price * 2 + remainder * price", "from math import ceil\ndef mango(quantity, price):\n return ceil(quantity / 3 * 2) * price", "def mango(q, p):\n Q = q/3*2\n Q = int(Q) if Q%1==0 else int(Q)+1\n return Q*p", "def mango(quantity, price):\n total = 0\n for i in range(1, quantity + 1):\n if i % 3 != 0:\n total += price\n else:\n pass\n return total", "def mango(quantity, price):\n return int((quantity - int(quantity / 3)) * price)", "def mango(quantity, price):\n q = quantity // 3 * 2\n q += quantity - (q * 1.5)\n return q * price", "def mango(quantity, price):\n return round((quantity//3)*2 * price + quantity%3 * price) \n", "def mango(quantity, price):\n return (quantity % 3 * price) + (int(quantity - (quantity % 3))) / 3 * 2 * price", "def mango(q, pr):\n return ((q // 3) * 2 * pr) + ((q-q//3*3) * pr)", "from operator import mod\n\n\ndef mango(quantity, price):\n x = int((quantity / 3)) * 2\n r = mod(quantity, 3)\n return x * price + (r * price)", "def mango(q, price):\n return (2 * (q // 3) + q % 3) * price", "def mango(quantity, price):\n total = 0\n\n for count in range(1, quantity + 1):\n if count % 3 == 0:\n continue\n total += price\n\n return total", "def mango(quantity, price):\n priceOfTwo = quantity // 3 \n remaining = quantity-priceOfTwo*3\n return (priceOfTwo * price * 2) + (remaining * price)", "def mango(quantity, price):\n p2 = price * 2\n calc = divmod(quantity,3)\n \n calc2 = calc[0] * p2\n return calc2 + (calc[1] * price)\n\n", "def mango(quantity, price):\n ost = quantity % 3\n return ((quantity-ost) * 2 / 3 + ost) * price", "def mango(quantity, price):\n return (int(quantity/3)*price*2) + (quantity - (int(quantity/3)*3))*price", "def mango(q, p):\n return q//3*2*p if q % 3 == 0 else q//3*2*p + (q%3)*p\n", "def mango(q, p):\n return (q-q//3)*p\n#Solved on 30th Sept, 2019 at 01:08 AM.\n", "import math\ndef mango(quantity, price):\n a = math.floor(quantity/3)\n return math.floor((quantity-a)*price)", "def mango(a,b):\n return(((a//3)*2)*b+(a%3)*b)", "def mango(quantity, price):\n return (2/3*(quantity - quantity%3)+quantity%3)*price", "from math import floor\n\ndef mango(quantity, price):\n return (quantity-floor(quantity/3))*price", "def mango(quantity, price):\n paid_mangos = ((quantity - quantity % 3) // 3 * 2) + quantity % 3\n return paid_mangos * price\n", "def mango(total_quantity, price_per_mango):\n\n quantity_of_set_3 = int(total_quantity/3)\n remaining_mangoes = total_quantity%3\n \n price_per_two_mangoes = price_per_mango*2\n cost_of_set3 = quantity_of_set_3*price_per_two_mangoes\n \n cost_remaining_mangoes = remaining_mangoes*price_per_mango\n total_cost = cost_of_set3 + cost_remaining_mangoes\n \n return total_cost\n\n \n", "def mango(quantity, price):\n return (quantity-quantity//3)*price #I solved this Kata on 8/30/2019 01:07 AM...#Hussam'sCodingDiary\n", "def mango(quantity, price):\n x = quantity // 3\n return (quantity - x) * price", "def mango(quantity, price):\n sum = 0\n \n while quantity > 2:\n quantity = quantity - 3\n sum = sum + price * 2\n \n return sum + price * quantity", "def mango(quantity, price):\n result = divmod(quantity,3)\n return result[0]*2*price + result[1] * price", "def mango(quantity, price):\n a = quantity%3\n b = quantity - a\n c = 2*b/3\n d = c*price + a*price\n return d", "def mango(quantity, price):\n print(\"==>> \",quantity, price)\n num_3 = int(quantity / 3)\n print(\"Num_3: \",num_3)\n output = (quantity-num_3)*price\n return output"]
{"fn_name": "mango", "inputs": [[3, 3], [9, 5]], "outputs": [[6], [30]]}
INTRODUCTORY
PYTHON3
CODEWARS
12,803
def mango(quantity, price):
442a1a6a8926907695575c81cddc887f
UNKNOWN
Your task it to return ```true``` if the fractional part (rounded to 1 digit) of the result (```a``` / ```b```) exists, more than ```0``` and is multiple of ```n```. Otherwise return ```false```. (For Python return True or False) All arguments are positive digital numbers. Rounding works like toFixed() method. (if more than...5 rounds up) Find exapmles below: ``` isMultiple(5, 2, 3) -> false // 2.5 -> 5 is not multiple of 3 isMultiple(5, 3, 4) -> false // 1.7 -> 7 is not multiple of 4 isMultiple(5, 4, 3) -> true // 1.3 -> 3 is multiple of 3 isMultiple(666, 665, 2) -> false // 1.0 -> return false ```
["def isMultiple(a, b, n):\n remainder = int((a / b + 0.05) * 10) % 10\n return remainder > 0 and remainder % n == 0", "def isMultiple(a, b, n):\n frac_part = int(10.0 * (a / b - a // b) + 0.5) % 10\n return frac_part != 0 and frac_part % n == 0", "isMultiple=lambda a,b,n:(lambda d:d>0==d%n)((20*a/b+1)//2%10)", "def isMultiple(a, b, n):\n x = round(float('.'+str(a/b+.00001).split('.')[-1]),1)\n x = x*10 if x<1 else x\n return x!=0 and x%n==0", "def isMultiple(a,b,n):\n c=(round(a/b+0.0001,1)*10)%10\n return c%n==0 and bool(c)", "from math import floor\n\ndef isMultiple(a, b, n):\n fractional_part = floor(10 * (a/b - a//b) + 0.5)\n if fractional_part == 10:\n fractional_part //= 10 \n return fractional_part and fractional_part % n == 0", "def isMultiple(a, b, n):\n x=int((a/b-a//b)*10+0.5)\n return 0<x<10 and x%n==0", "import math\ndef normal_round(n):\n if n - math.floor(n) < 0.5:\n return math.floor(n)\n return math.ceil(n)\n\ndef isMultiple(a, b, n):\n to_test = normal_round((a/b - int(a/b)) * 10)\n if to_test >= 10:\n return False\n else:\n return to_test > 0 and to_test % n == 0", "def isMultiple(a, b, n):\n def rond(x):\n return int(x) if x % 1 < 0.5 else int(x + 1)\n \n res = a/b\n res = rond(res*10) / 10\n #Extra round here to deal with floating-point nonsense\n remainder = round(res % 1,1)\n return remainder and not (10*remainder) % n", "def isMultiple(a, b, n):\n print((a/b))\n print(n)\n quot = a/b*10\n digit = int(quot)%10\n if quot%1>=0.5: digit = (int(quot)+1)%10\n return digit > 0 and digit % n == 0\n"]
{"fn_name": "isMultiple", "inputs": [[5, 2, 3], [5, 3, 4], [5, 4, 3], [666, 665, 2], [3691401, 1892272, 5]], "outputs": [[false], [false], [true], [false], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,673
def isMultiple(a, b, n):