instruction
stringlengths 115
1.36k
| input
stringclasses 2
values | output
stringlengths 16
864
|
---|---|---|
def get_odd_collatz(n):
"""
Given a positive integer n, return a sorted list that has the odd numbers in collatz sequence.
The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
as follows: start with any positive integer n. Then each term is obtained from the
previous term as follows: if the previous term is even, the next term is one half of
the previous term. If the previous term is odd, the next term is 3 times the previous
term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
Note:
1. Collatz(1) is [1].
2. returned list sorted in increasing order.
For example:
get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | if n%2==0:
odd_collatz = []
else:
odd_collatz = [n]
while n > 1:
if n % 2 == 0:
n = n/2
else:
n = n*3 + 1
if n%2 == 1:
odd_collatz.append(int(n))
return sorted(odd_collatz)
|
def median(l: list):
"""Return median of elements in the list l.
>>> median([3, 1, 2, 4, 5])
3
>>> median([-10, 4, 6, 1000, 10, 20])
15.0
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | l = sorted(l)
if len(l) % 2 == 1:
return l[len(l) // 2]
else:
return (l[len(l) // 2 - 1] + l[len(l) // 2]) / 2.0
|
def compare_one(a, b):
"""
Create a function that takes integers, floats, or strings representing
real numbers, and returns the larger variable in its given variable type.
Return None if the values are equal.
Note: If a real number is represented as a string, the floating point might be . or ,
compare_one(1, 2.5) β 2.5
compare_one(1, "2,3") β "2,3"
compare_one("5,1", "6") β "6"
compare_one("1", 1) β None
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | temp_a, temp_b = a, b
if isinstance(temp_a, str): temp_a = temp_a.replace(',','.')
if isinstance(temp_b, str): temp_b = temp_b.replace(',','.')
if float(temp_a) == float(temp_b): return None
return a if float(temp_a) > float(temp_b) else b
|
def strlen(string: str) -> int:
""" Return length of given string
>>> strlen('')
0
>>> strlen('abc')
3
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | return len(string)
|
def Strongest_Extension(class_name, extensions):
"""You will be given the name of a class (a string) and a list of extensions.
The extensions are to be used to load additional classes to the class. The
strength of the extension is as follows: Let CAP be the number of the uppercase
letters in the extension's name, and let SM be the number of lowercase letters
in the extension's name, the strength is given by the fraction CAP - SM.
You should find the strongest extension and return a string in this
format: ClassName.StrongestExtensionName.
If there are two or more extensions with the same strength, you should
choose the one that comes first in the list.
For example, if you are given "Slices" as the class and a list of the
extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
(its strength is -1).
Example:
for Strongest_Extension('my_class', ['AA', 'Be', 'CC']) == 'my_class.AA'
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | strong = extensions[0]
my_val = len([x for x in extensions[0] if x.isalpha() and x.isupper()]) - len([x for x in extensions[0] if x.isalpha() and x.islower()])
for s in extensions:
val = len([x for x in s if x.isalpha() and x.isupper()]) - len([x for x in s if x.isalpha() and x.islower()])
if val > my_val:
strong = s
my_val = val
ans = class_name + "." + strong
return ans
|
from typing import List
def intersperse(numbers: List[int], delimeter: int) -> List[int]:
""" Insert a number 'delimeter' between every two consecutive elements of input list `numbers'
>>> intersperse([], 4)
[]
>>> intersperse([1, 2, 3], 4)
[1, 4, 2, 4, 3]
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | if not numbers:
return []
result = []
for n in numbers[:-1]:
result.append(n)
result.append(delimeter)
result.append(numbers[-1])
return result
|
def encode_shift(s: str):
"""
returns encoded string by shifting every character by 5 in the alphabet.
"""
return "".join([chr(((ord(ch) + 5 - ord("a")) % 26) + ord("a")) for ch in s])
def decode_shift(s: str):
"""
takes as input string encoded with encode_shift function. Returns decoded string.
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | return "".join([chr(((ord(ch) - 5 - ord("a")) % 26) + ord("a")) for ch in s])
|
def is_palindrome(text: str):
"""
Checks if given string is a palindrome
>>> is_palindrome('')
True
>>> is_palindrome('aba')
True
>>> is_palindrome('aaaaa')
True
>>> is_palindrome('zbcd')
False
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | for i in range(len(text)):
if text[i] != text[len(text) - 1 - i]:
return False
return True
|
def starts_one_ends(n):
"""
Given a positive integer n, return the count of the numbers of n-digit
positive integers that start or end with 1.
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | if n == 1: return 1
return 18 * (10 ** (n - 2))
|
from typing import List
def parse_music(music_string: str) -> List[int]:
""" Input to this function is a string representing musical notes in a special ASCII format.
Your task is to parse this string and return list of integers corresponding to how many beats does each
not last.
Here is a legend:
'o' - whole note, lasts four beats
'o|' - half note, lasts two beats
'.|' - quater note, lasts one beat
>>> parse_music('o o| .| o| o| .| .| .| .| o o')
[4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | note_map = {'o': 4, 'o|': 2, '.|': 1}
return [note_map[x] for x in music_string.split(' ') if x]
|
def words_in_sentence(sentence):
"""
You are given a string representing a sentence,
the sentence contains some words separated by a space,
and you have to return a string that contains the words from the original sentence,
whose lengths are prime numbers,
the order of the words in the new string should be the same as the original one.
Example 1:
Input: sentence = "This is a test"
Output: "is"
Example 2:
Input: sentence = "lets go for swimming"
Output: "go for"
Constraints:
* 1 <= len(sentence) <= 100
* sentence contains only letters
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | new_lst = []
for word in sentence.split():
flg = 0
if len(word) == 1:
flg = 1
for i in range(2, len(word)):
if len(word)%i == 0:
flg = 1
if flg == 0 or len(word) == 2:
new_lst.append(word)
return " ".join(new_lst)
|
def f(n):
""" Implement the function f that takes n as a parameter,
and returns a list of size n, such that the value of the element at index i is the factorial of i if i is even
or the sum of numbers from 1 to i otherwise.
i starts from 1.
the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
Example:
f(5) == [1, 2, 6, 24, 15]
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | ret = []
for i in range(1,n+1):
if i%2 == 0:
x = 1
for j in range(1,i+1): x *= j
ret += [x]
else:
x = 0
for j in range(1,i+1): x += j
ret += [x]
return ret
|
from typing import List, Tuple
def rolling_max(numbers: List[int]) -> List[int]:
""" From a given list of integers, generate a list of rolling maximum element found until given moment
in the sequence.
>>> rolling_max([1, 2, 3, 2, 3, 4, 2])
[1, 2, 3, 3, 3, 4, 4]
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | running_max = None
result = []
for n in numbers:
if running_max is None:
running_max = n
else:
running_max = max(running_max, n)
result.append(running_max)
return result
|
def hex_key(num):
"""You have been tasked to write a function that receives
a hexadecimal number as a string and counts the number of hexadecimal
digits that are primes (prime number, or a prime, is a natural number
greater than 1 that is not a product of two smaller natural numbers).
Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
So you have to determine a number of the following digits: 2, 3, 5, 7,
B (=decimal 11), D (=decimal 13).
Note: you may assume the input is always correct or empty string,
and symbols A,B,C,D,E,F are always uppercase.
Examples:
For num = "AB" the output should be 1.
For num = "1077E" the output should be 2.
For num = "ABED1A33" the output should be 4.
For num = "123456789ABCDEF0" the output should be 6.
For num = "2020" the output should be 2.
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | primes = ('2', '3', '5', '7', 'B', 'D')
total = 0
for i in range(0, len(num)):
if num[i] in primes:
total += 1
return total
|
def smallest_change(arr):
"""
Given an array arr of integers, find the minimum number of elements that
need to be changed to make the array palindromic. A palindromic array is an array that
is read the same backwards and forwards. In one change, you can change one element to any other element.
For example:
smallest_change([1,2,3,5,4,7,9,6]) == 4
smallest_change([1, 2, 3, 4, 3, 2, 2]) == 1
smallest_change([1, 2, 3, 2, 1]) == 0
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | ans = 0
for i in range(len(arr) // 2):
if arr[i] != arr[len(arr) - i - 1]:
ans += 1
return ans
|
def sort_even(l: list):
"""This function takes a list l and returns a list l' such that
l' is identical to l in the odd indicies, while its values at the even indicies are equal
to the values of the even indicies of l, but sorted.
>>> sort_even([1, 2, 3])
[1, 2, 3]
>>> sort_even([5, 6, 3, 4])
[3, 6, 5, 4]
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | evens = l[::2]
odds = l[1::2]
evens.sort()
ans = []
for e, o in zip(evens, odds):
ans.extend([e, o])
if len(evens) > len(odds):
ans.append(evens[-1])
return ans
|
def get_closest_vowel(word):
"""You are given a word. Your task is to find the closest vowel that stands between
two consonants from the right side of the word (case sensitive).
Vowels in the beginning and ending doesn't count. Return empty string if you didn't
find any vowel met the above condition.
You may assume that the given string contains English letter only.
Example:
get_closest_vowel("yogurt") ==> "u"
get_closest_vowel("FULL") ==> "U"
get_closest_vowel("quick") ==> ""
get_closest_vowel("ab") ==> ""
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | if len(word) < 3:
return ""
vowels = {"a", "e", "i", "o", "u", "A", "E", 'O', 'U', 'I'}
for i in range(len(word)-2, 0, -1):
if word[i] in vowels:
if (word[i+1] not in vowels) and (word[i-1] not in vowels):
return word[i]
return ""
|
def rounded_avg(n, m):
"""You are given two positive integers n and m, and your task is to compute the
average of the integers from n through m (including n and m).
Round the answer to the nearest integer and convert that to binary.
If n is greater than m, return -1.
Example:
rounded_avg(1, 5) => "0b11"
rounded_avg(7, 5) => -1
rounded_avg(10, 20) => "0b1111"
rounded_avg(20, 33) => "0b11010"
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | if m < n:
return -1
summation = 0
for i in range(n, m+1):
summation += i
return bin(round(summation/(m - n + 1)))
|
def order_by_points(nums):
"""
Write a function which sorts the given list of integers
in ascending order according to the sum of their digits.
Note: if there are several items with similar sum of their digits,
order them based on their index in original list.
For example:
>>> order_by_points([1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
>>> order_by_points([]) == []
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | def digits_sum(n):
neg = 1
if n < 0: n, neg = -1 * n, -1
n = [int(i) for i in str(n)]
n[0] = n[0] * neg
return sum(n)
return sorted(nums, key=digits_sum)
|
def right_angle_triangle(a, b, c):
'''
Given the lengths of the three sides of a triangle. Return True if the three
sides form a right-angled triangle, False otherwise.
A right-angled triangle is a triangle in which one angle is right angle or
90 degree.
Example:
right_angle_triangle(3, 4, 5) == True
right_angle_triangle(1, 2, 3) == False
'''
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | return a*a == b*b + c*c or b*b == a*a + c*c or c*c == a*a + b*b
|
def add_elements(arr, k):
"""
Given a non-empty array of integers arr and an integer k, return
the sum of the elements with at most two digits from the first k elements of arr.
Example:
Input: arr = [111,21,3,4000,5,6,7,8,9], k = 4
Output: 24 # sum of 21 + 3
Constraints:
1. 1 <= len(arr) <= 100
2. 1 <= k <= len(arr)
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | return sum(elem for elem in arr[:k] if len(str(elem)) <= 2)
|
def prime_length(string):
"""Write a function that takes a string and returns True if the string
length is a prime number or False otherwise
Examples
prime_length('Hello') == True
prime_length('abcdcba') == True
prime_length('kittens') == True
prime_length('orange') == False
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | l = len(string)
if l == 0 or l == 1:
return False
for i in range(2, l):
if l % i == 0:
return False
return True
|
def string_sequence(n: int) -> str:
""" Return a string containing space-delimited numbers starting from 0 upto n inclusive.
>>> string_sequence(0)
'0'
>>> string_sequence(5)
'0 1 2 3 4 5'
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | return ' '.join([str(x) for x in range(n + 1)])
|
from typing import List, Tuple
def sum_product(numbers: List[int]) -> Tuple[int, int]:
""" For a given list of integers, return a tuple consisting of a sum and a product of all the integers in a list.
Empty sum should be equal to 0 and empty product should be equal to 1.
>>> sum_product([])
(0, 1)
>>> sum_product([1, 2, 3, 4])
(10, 24)
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | sum_value = 0
prod_value = 1
for n in numbers:
sum_value += n
prod_value *= n
return sum_value, prod_value
|
def get_row(lst, x):
"""
You are given a 2 dimensional data, as a nested lists,
which is similar to matrix, however, unlike matrices,
each row may contain a different number of columns.
Given lst, and integer x, find integers x in the list,
and return list of tuples, [(x1, y1), (x2, y2) ...] such that
each tuple is a coordinate - (row, columns), starting with 0.
Sort coordinates initially by rows in ascending order.
Also, sort coordinates of the row by columns in descending order.
Examples:
get_row([
[1,2,3,4,5,6],
[1,2,3,4,1,6],
[1,2,3,4,5,1]
], 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
get_row([], 1) == []
get_row([[], [1], [1, 2, 3]], 3) == [(2, 2)]
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | coords = [(i, j) for i in range(len(lst)) for j in range(len(lst[i])) if lst[i][j] == x]
return sorted(sorted(coords, key=lambda x: x[1], reverse=True), key=lambda x: x[0])
|
def skjkasdkd(lst):
"""You are given a list of integers.
You need to find the largest prime value and return the sum of its digits.
Examples:
For lst = [0,3,2,1,3,5,7,4,5,5,5,2,181,32,4,32,3,2,32,324,4,3] the output should be 10
For lst = [1,0,1,8,2,4597,2,1,3,40,1,2,1,2,4,2,5,1] the output should be 25
For lst = [1,3,1,32,5107,34,83278,109,163,23,2323,32,30,1,9,3] the output should be 13
For lst = [0,724,32,71,99,32,6,0,5,91,83,0,5,6] the output should be 11
For lst = [0,81,12,3,1,21] the output should be 3
For lst = [0,8,1,2,1,7] the output should be 7
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | def isPrime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
maxx = 0
i = 0
while i < len(lst):
if(lst[i] > maxx and isPrime(lst[i])):
maxx = lst[i]
i+=1
result = sum(int(digit) for digit in str(maxx))
return result
|
def simplify(x, n):
"""Your task is to implement a function that will simplify the expression
x * n. The function returns True if x * n evaluates to a whole number and False
otherwise. Both x and n, are string representation of a fraction, and have the following format,
<numerator>/<denominator> where both numerator and denominator are positive whole numbers.
You can assume that x, and n are valid fractions, and do not have zero as denominator.
simplify("1/5", "5/1") = True
simplify("1/6", "2/1") = False
simplify("7/10", "10/2") = False
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | a, b = x.split("/")
c, d = n.split("/")
numerator = int(a) * int(c)
denom = int(b) * int(d)
if (numerator/denom == int(numerator/denom)):
return True
return False
|
def is_multiply_prime(a):
"""Write a function that returns true if the given number is the multiplication of 3 prime numbers
and false otherwise.
Knowing that (a) is less then 100.
Example:
is_multiply_prime(30) == True
30 = 2 * 3 * 5
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | def is_prime(n):
for j in range(2,n):
if n%j == 0:
return False
return True
for i in range(2,101):
if not is_prime(i): continue
for j in range(2,101):
if not is_prime(j): continue
for k in range(2,101):
if not is_prime(k): continue
if i*j*k == a: return True
return False
|
def sort_array(array):
"""
Given an array of non-negative integers, return a copy of the given array after sorting,
you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
or sort it in descending order if the sum( first index value, last index value) is even.
Note:
* don't change the given array.
Examples:
* sort_array([]) => []
* sort_array([5]) => [5]
* sort_array([2, 4, 3, 0, 1, 5]) => [0, 1, 2, 3, 4, 5]
* sort_array([2, 4, 3, 0, 1, 5, 6]) => [6, 5, 4, 3, 2, 1, 0]
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | return [] if len(array) == 0 else sorted(array, reverse= (array[0]+array[-1]) % 2 == 0)
|
def how_many_times(string: str, substring: str) -> int:
""" Find how many times a given substring can be found in the original string. Count overlaping cases.
>>> how_many_times('', 'a')
0
>>> how_many_times('aaa', 'a')
3
>>> how_many_times('aaaa', 'aa')
3
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | times = 0
for i in range(len(string) - len(substring) + 1):
if string[i:i+len(substring)] == substring:
times += 1
return times
|
def compare(game,guess):
"""I think we all remember that feeling when the result of some long-awaited
event is finally known. The feelings and thoughts you have at that moment are
definitely worth noting down and comparing.
Your task is to determine if a person correctly guessed the results of a number of matches.
You are given two arrays of scores and guesses of equal length, where each index shows a match.
Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
the value is 0, and if not, the value is the absolute difference between the guess and the score.
example:
compare([1,2,3,4,5,1],[1,2,3,4,2,-2]) -> [0,0,0,0,3,3]
compare([0,5,0,0,0,4],[4,1,1,0,0,-2]) -> [4,4,1,0,0,6]
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | return [abs(x-y) for x,y in zip(game,guess)]
|
def exchange(lst1, lst2):
"""In this problem, you will implement a function that takes two lists of numbers,
and determines whether it is possible to perform an exchange of elements
between them to make lst1 a list of only even numbers.
There is no limit on the number of exchanged elements between lst1 and lst2.
If it is possible to exchange elements between the lst1 and lst2 to make
all the elements of lst1 to be even, return "YES".
Otherwise, return "NO".
For example:
exchange([1, 2, 3, 4], [1, 2, 3, 4]) => "YES"
exchange([1, 2, 3, 4], [1, 5, 3, 4]) => "NO"
It is assumed that the input lists will be non-empty.
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | odd = 0
even = 0
for i in lst1:
if i%2 == 1:
odd += 1
for i in lst2:
if i%2 == 0:
even += 1
if even >= odd:
return "YES"
return "NO"
|
from typing import List, Optional
def longest(strings: List[str]) -> Optional[str]:
""" Out of list of strings, return the longest one. Return the first one in case of multiple
strings of the same length. Return None in case the input list is empty.
>>> longest([])
>>> longest(['a', 'b', 'c'])
'a'
>>> longest(['a', 'bb', 'ccc'])
'ccc'
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | if not strings:
return None
maxlen = max(len(x) for x in strings)
for s in strings:
if len(s) == maxlen:
return s
|
def is_equal_to_sum_even(n):
"""Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
Example
is_equal_to_sum_even(4) == False
is_equal_to_sum_even(6) == False
is_equal_to_sum_even(8) == True
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | return n%2 == 0 and n >= 8
|
from typing import List
def rescale_to_unit(numbers: List[float]) -> List[float]:
""" Given list of numbers (of at least two elements), apply a linear transform to that list,
such that the smallest number will become 0 and the largest will become 1
>>> rescale_to_unit([1.0, 2.0, 3.0, 4.0, 5.0])
[0.0, 0.25, 0.5, 0.75, 1.0]
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | min_number = min(numbers)
max_number = max(numbers)
return [(x - min_number) / (max_number - min_number) for x in numbers]
|
def count_distinct_characters(string: str) -> int:
""" Given a string, find out how many distinct characters (regardless of case) does it consist of
>>> count_distinct_characters('xyzXYZ')
3
>>> count_distinct_characters('Jerry')
4
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | return len(set(string.lower()))
|
def triples_sum_to_zero(l: list):
"""
triples_sum_to_zero takes a list of integers as an input.
it returns True if there are three distinct elements in the list that
sum to zero, and False otherwise.
>>> triples_sum_to_zero([1, 3, 5, 0])
False
>>> triples_sum_to_zero([1, 3, -2, 1])
True
>>> triples_sum_to_zero([1, 2, 3, 7])
False
>>> triples_sum_to_zero([2, 4, -5, 3, 9, 7])
True
>>> triples_sum_to_zero([1])
False
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | for i in range(len(l)):
for j in range(i + 1, len(l)):
for k in range(j + 1, len(l)):
if l[i] + l[j] + l[k] == 0:
return True
return False
|
def derivative(xs: list):
""" xs represent coefficients of a polynomial.
xs[0] + xs[1] * x + xs[2] * x^2 + ....
Return derivative of this polynomial in the same form.
>>> derivative([3, 1, 2, 4, 5])
[1, 4, 12, 20]
>>> derivative([1, 2, 3])
[2, 6]
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | return [(i * x) for i, x in enumerate(xs)][1:]
|
from typing import List
def filter_by_substring(strings: List[str], substring: str) -> List[str]:
""" Filter an input list of strings only for ones that contain given substring
>>> filter_by_substring([], 'a')
[]
>>> filter_by_substring(['abc', 'bacd', 'cde', 'array'], 'a')
['abc', 'bacd', 'array']
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | return [x for x in strings if substring in x]
|
def encode_cyclic(s: str):
"""
returns encoded string by cycling groups of three characters.
"""
# split string to groups. Each of length 3.
groups = [s[(3 * i):min((3 * i + 3), len(s))] for i in range((len(s) + 2) // 3)]
# cycle elements in each group. Unless group has fewer elements than 3.
groups = [(group[1:] + group[0]) if len(group) == 3 else group for group in groups]
return "".join(groups)
def decode_cyclic(s: str):
"""
takes as input string encoded with encode_cyclic function. Returns decoded string.
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | return encode_cyclic(encode_cyclic(s))
|
def reverse_delete(s,c):
"""Task
We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
then check if the result string is palindrome.
A string is called palindrome if it reads the same backward as forward.
You should return a tuple containing the result string and True/False for the check.
Example
For s = "abcde", c = "ae", the result should be ('bcd',False)
For s = "abcdef", c = "b" the result should be ('acdef',False)
For s = "abcdedcba", c = "ab", the result should be ('cdedc',True)
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | s = ''.join([char for char in s if char not in c])
return (s,s[::-1] == s)
|
def digitSum(s):
"""Task
Write a function that takes a string as input and returns the sum of the upper characters only'
ASCII codes.
Examples:
digitSum("") => 0
digitSum("abAB") => 131
digitSum("abcCd") => 67
digitSum("helloE") => 69
digitSum("woArBld") => 131
digitSum("aAaaaXa") => 153
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | if s == "": return 0
return sum(ord(char) if char.isupper() else 0 for char in s)
|
def greatest_common_divisor(a: int, b: int) -> int:
""" Return a greatest common divisor of two integers a and b
>>> greatest_common_divisor(3, 5)
1
>>> greatest_common_divisor(25, 15)
5
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | while b:
a, b = b, a % b
return a
|
def is_simple_power(x, n):
"""Your task is to write a function that returns true if a number x is a simple
power of n and false in other cases.
x is a simple power of n if n**int=x
For example:
is_simple_power(1, 4) => true
is_simple_power(2, 2) => true
is_simple_power(8, 2) => true
is_simple_power(3, 2) => false
is_simple_power(3, 1) => false
is_simple_power(5, 3) => false
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | if (n == 1):
return (x == 1)
power = 1
while (power < x):
power = power * n
return (power == x)
|
def fib(n: int):
"""Return n-th Fibonacci number.
>>> fib(10)
55
>>> fib(1)
1
>>> fib(8)
21
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | if n == 0:
return 0
if n == 1:
return 1
return fib(n - 1) + fib(n - 2)
|
def sum_squares(lst):
""""
This function will take a list of integers. For all entries in the list, the function shall square the integer entry if its index is a
multiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not
change the entries in the list whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries.
Examples:
For lst = [1,2,3] the output should be 6
For lst = [] the output should be 0
For lst = [-1,-5,2,-1,-5] the output should be -126
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | result =[]
for i in range(len(lst)):
if i %3 == 0:
result.append(lst[i]**2)
elif i % 4 == 0 and i%3 != 0:
result.append(lst[i]**3)
else:
result.append(lst[i])
return sum(result)
|
from typing import List
def factorize(n: int) -> List[int]:
""" Return list of prime factors of given integer in the order from smallest to largest.
Each of the factors should be listed number of times corresponding to how many times it appeares in factorization.
Input number should be equal to the product of all factors
>>> factorize(8)
[2, 2, 2]
>>> factorize(25)
[5, 5]
>>> factorize(70)
[2, 5, 7]
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | import math
fact = []
i = 2
while i <= int(math.sqrt(n) + 1):
if n % i == 0:
fact.append(i)
n //= i
else:
i += 1
if n > 1:
fact.append(n)
return fact
|
def histogram(test):
"""Given a string representing a space separated lowercase letters, return a dictionary
of the letter with the most repetition and containing the corresponding count.
If several letters have the same occurrence, return all of them.
Example:
histogram('a b c') == {'a': 1, 'b': 1, 'c': 1}
histogram('a b b a') == {'a': 2, 'b': 2}
histogram('a b c a b') == {'a': 2, 'b': 2}
histogram('b b b b a') == {'b': 4}
histogram('') == {}
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | dict1={}
list1=test.split(" ")
t=0
for i in list1:
if(list1.count(i)>t) and i!='':
t=list1.count(i)
if t>0:
for i in list1:
if(list1.count(i)==t):
dict1[i]=t
return dict1
|
from typing import List
def separate_paren_groups(paren_string: str) -> List[str]:
""" Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
separate those group into separate strings and return the list of those.
Separate groups are balanced (each open brace is properly closed) and not nested within each other
Ignore any spaces in the input string.
>>> separate_paren_groups('( ) (( )) (( )( ))')
['()', '(())', '(()())']
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | result = []
current_string = []
current_depth = 0
for c in paren_string:
if c == '(':
current_depth += 1
current_string.append(c)
elif c == ')':
current_depth -= 1
current_string.append(c)
if current_depth == 0:
result.append(''.join(current_string))
current_string.clear()
return result
|
from typing import List, Any
def filter_integers(values: List[Any]) -> List[int]:
""" Filter given list of any python values only for integers
>>> filter_integers(['a', 3.14, 5])
[5]
>>> filter_integers([1, 2, 3, 'abc', {}, []])
[1, 2, 3]
"""
| return [x for x in values if isinstance(x, int)]
|
|
def maximum(arr, k):
"""
Given an array arr of integers and a positive integer k, return a sorted list
of length k with the maximum k numbers in arr.
Example 1:
Input: arr = [-3, -4, 5], k = 3
Output: [-4, -3, 5]
Example 2:
Input: arr = [4, -4, 4], k = 2
Output: [4, 4]
Example 3:
Input: arr = [-3, 2, 1, 2, -1, -2, 1], k = 1
Output: [2]
Note:
1. The length of the array will be in the range of [1, 1000].
2. The elements in the array will be in the range of [-1000, 1000].
3. 0 <= k <= len(arr)
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | if k == 0:
return []
arr.sort()
ans = arr[-k:]
return ans
|
def is_bored(S):
"""
You'll be given a string of words, and your task is to count the number
of boredoms. A boredom is a sentence that starts with the word "I".
Sentences are delimited by '.', '?' or '!'.
For example:
>>> is_bored("Hello world")
0
>>> is_bored("The sky is blue. The sun is shining. I love this weather")
1
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | import re
sentences = re.split(r'[.?!]\s*', S)
return sum(sentence[0:2] == 'I ' for sentence in sentences)
|
def fizz_buzz(n: int):
"""Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
>>> fizz_buzz(50)
0
>>> fizz_buzz(78)
2
>>> fizz_buzz(79)
3
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | ns = []
for i in range(n):
if i % 11 == 0 or i % 13 == 0:
ns.append(i)
s = ''.join(list(map(str, ns)))
ans = 0
for c in s:
ans += (c == '7')
return ans
|
def intersection(interval1, interval2):
"""You are given two intervals,
where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
The given intervals are closed which means that the interval (start, end)
includes both start and end.
For each given interval, it is assumed that its start is less or equal its end.
Your task is to determine whether the length of intersection of these two
intervals is a prime number.
Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
which its length is 1, which not a prime number.
If the length of the intersection is a prime number, return "YES",
otherwise, return "NO".
If the two intervals don't intersect, return "NO".
[input/output] samples:
intersection((1, 2), (2, 3)) ==> "NO"
intersection((-1, 1), (0, 4)) ==> "NO"
intersection((-3, -1), (-5, 5)) ==> "YES"
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | def is_prime(num):
if num == 1 or num == 0:
return False
if num == 2:
return True
for i in range(2, num):
if num%i == 0:
return False
return True
l = max(interval1[0], interval2[0])
r = min(interval1[1], interval2[1])
length = r - l
if length > 0 and is_prime(length):
return "YES"
return "NO"
|
def truncate_number(number: float) -> float:
""" Given a positive floating point number, it can be decomposed into
and integer part (largest integer smaller than given number) and decimals
(leftover part always smaller than 1).
Return the decimal part of the number.
>>> truncate_number(3.5)
0.5
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | return number % 1.0
|
def special_factorial(n):
"""The Brazilian factorial is defined as:
brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
where n > 0
For example:
>>> special_factorial(4)
288
The function will receive an integer as input and should return the special
factorial of this integer.
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | fact_i = 1
special_fact = 1
for i in range(1, n+1):
fact_i *= i
special_fact *= fact_i
return special_fact
|
def solve(N):
"""Given a positive integer N, return the total sum of its digits in binary.
Example
For N = 1000, the sum of digits will be 1 the output should be "1".
For N = 150, the sum of digits will be 6 the output should be "110".
For N = 147, the sum of digits will be 12 the output should be "1100".
Variables:
@N integer
Constraints: 0 β€ N β€ 10000.
Output:
a string of binary number
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | return bin(sum(int(i) for i in str(N)))[2:]
|
from typing import List
def remove_duplicates(numbers: List[int]) -> List[int]:
""" From a list of integers, remove all elements that occur more than once.
Keep order of elements left the same as in the input.
>>> remove_duplicates([1, 2, 3, 2, 4])
[1, 3, 4]
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | import collections
c = collections.Counter(numbers)
return [n for n in numbers if c[n] <= 1]
|
def total_match(lst1, lst2):
'''
Write a function that accepts two lists of strings and returns the list that has
total number of chars in the all strings of the list less than the other list.
if the two lists have the same number of chars, return the first list.
Examples
total_match([], []) β []
total_match(['hi', 'admin'], ['hI', 'Hi']) β ['hI', 'Hi']
total_match(['hi', 'admin'], ['hi', 'hi', 'admin', 'project']) β ['hi', 'admin']
total_match(['hi', 'admin'], ['hI', 'hi', 'hi']) β ['hI', 'hi', 'hi']
total_match(['4'], ['1', '2', '3', '4', '5']) β ['4']
'''
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | l1 = 0
for st in lst1:
l1 += len(st)
l2 = 0
for st in lst2:
l2 += len(st)
if l1 <= l2:
return lst1
else:
return lst2
|
def tri(n):
"""Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
the last couple centuries. However, what people don't know is Tribonacci sequence.
Tribonacci sequence is defined by the recurrence:
tri(1) = 3
tri(n) = 1 + n / 2, if n is even.
tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
For example:
tri(2) = 1 + (2 / 2) = 2
tri(4) = 3
tri(3) = tri(2) + tri(1) + tri(4)
= 2 + 3 + 3 = 8
You are given a non-negative integer number n, you have to a return a list of the
first n + 1 numbers of the Tribonacci sequence.
Examples:
tri(3) = [1, 3, 2, 8]
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | if n == 0:
return [1]
my_tri = [1, 3]
for i in range(2, n + 1):
if i % 2 == 0:
my_tri.append(i / 2 + 1)
else:
my_tri.append(my_tri[i - 1] + my_tri[i - 2] + (i + 3) / 2)
return my_tri
|
def triangle_area(a, h):
"""Given length of a side and high return area for a triangle.
>>> triangle_area(5, 3)
7.5
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | return a * h / 2.0
|
def eat(number, need, remaining):
"""
You're a hungry rabbit, and you already have eaten a certain number of carrots,
but now you need to eat more carrots to complete the day's meals.
you should return an array of [ total number of eaten carrots after your meals,
the number of carrots left after your meals ]
if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
Example:
* eat(5, 6, 10) -> [11, 4]
* eat(4, 8, 9) -> [12, 1]
* eat(1, 10, 10) -> [11, 0]
* eat(2, 11, 5) -> [7, 0]
Variables:
@number : integer
the number of carrots that you have eaten.
@need : integer
the number of carrots that you need to eat.
@remaining : integer
the number of remaining carrots thet exist in stock
Constrain:
* 0 <= number <= 1000
* 0 <= need <= 1000
* 0 <= remaining <= 1000
Have fun :)
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | if(need <= remaining):
return [ number + need , remaining-need ]
else:
return [ number + remaining , 0]
|
def will_it_fly(q,w):
'''
Write a function that returns True if the object q will fly, and False otherwise.
The object q will fly if it's balanced (it is a palindromic list) and the sum of its elements is less than or equal the maximum possible weight w.
Example:
will_it_fly([1, 2], 5) β False
# 1+2 is less than the maximum possible weight, but it's unbalanced.
will_it_fly([3, 2, 3], 1) β False
# it's balanced, but 3+2+3 is more than the maximum possible weight.
will_it_fly([3, 2, 3], 9) β True
# 3+2+3 is less than the maximum possible weight, and it's balanced.
will_it_fly([3], 5) β True
# 3 is less than the maximum possible weight, and it's balanced.
'''
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | if sum(q) > w:
return False
i, j = 0, len(q)-1
while i<j:
if q[i] != q[j]:
return False
i+=1
j-=1
return True
|
from typing import List
def filter_by_prefix(strings: List[str], prefix: str) -> List[str]:
""" Filter an input list of strings only for ones that start with a given prefix.
>>> filter_by_prefix([], 'a')
[]
>>> filter_by_prefix(['abc', 'bcd', 'cde', 'array'], 'a')
['abc', 'array']
"""
| The prompt's code is written in Python. Write corresponding response code in Python, as well. | return [x for x in strings if x.startswith(prefix)]
|