text_prompt stringlengths 100 17.7k ⌀ | code_prompt stringlengths 7 9.86k ⌀ |
|---|---|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def make_a_pile(n):
"""
Given a positive integer n, you have to make a pile of n levels of stones.
The first level has n stones.
The number of stone... | return [n + 2*i for i in range(n)]
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def words_string(s):
"""
You will be given a string of words separated by commas or spaces. Your task is
to split the string into words and return an ar... | if not s:
return []
s_list = []
for letter in s:
if letter == ',':
s_list.append(' ')
else:
s_list.append(letter)
s_list = "".join(s_list)
return s_list.split()
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def choose_num(x, y):
"""This function takes two positive numbers x and y and returns the
biggest even integer number that is in the range [x, y] inclusive.... | if x > y:
return -1
if y % 2 == 0:
return y
if x == y:
return -1
return y - 1
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
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... | if m < n:
return -1
summation = 0
for i in range(n, m+1):
summation += i
return bin(round(summation/(m - n + 1)))
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def unique_digits(x):
"""Given a list of positive integers x. return a sorted list of all
elements that hasn't any even digit.
Note: Returned list sho... | odd_digit_elements = []
for i in x:
if all (int(c) % 2 == 1 for c in str(i)):
odd_digit_elements.append(i)
return sorted(odd_digit_elements)
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def by_length(arr):
"""
Given an array of integers, sort the integers that are between 1 and 9 inclusive,
reverse the resulting array, and then replace ... | dic = {
1: "One",
2: "Two",
3: "Three",
4: "Four",
5: "Five",
6: "Six",
7: "Seven",
8: "Eight",
9: "Nine",
}
sorted_arr = sorted(arr, reverse=True)
new_arr = []
for var in sorted_arr:
try:
new_arr.append(dic[... |
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
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 facto... | 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
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def even_odd_palindrome(n):
"""
Given a positive integer n, return a tuple that has the number of even and odd
integer palindromes that fall within the ... | def is_palindrome(n):
return str(n) == str(n)[::-1]
even_palindrome_count = 0
odd_palindrome_count = 0
for i in range(1, n+1):
if i%2 == 1 and is_palindrome(i):
odd_palindrome_count += 1
elif i%2 == 0 and is_palindrome(i):
even_palindrome_count += 1
... |
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def count_nums(arr):
"""
Write a function count_nums which takes an array of integers and returns
the number of elements which has a sum of digits > 0.
... | 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 len(list(filter(lambda x: x > 0, [digits_sum(i) for i in arr])))
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def move_one_ball(arr):
"""We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
numbers in the array will be randomly ordered. Your task is ... | if len(arr)==0:
return True
sorted_array=sorted(arr)
my_arr=[]
min_value=min(arr)
min_index=arr.index(min_value)
my_arr=arr[min_index:]+arr[0:min_index]
for i in range(len(arr)):
if my_arr[i]!=sorted_array[i]:
return False
return True
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
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 perfor... | 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"
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def histogram(test):
"""Given a string representing a space separated lowercase letters, return a dictionary
of the letter with the most repetition and cont... | 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
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
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... | s = ''.join([char for char in s if char not in c])
return (s,s[::-1] == s)
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def odd_count(lst):
"""Given a list of strings, where each string consists of only digits, return a list.
Each element i of the output should be "the number... | res = []
for arr in lst:
n = sum(int(d)%2==1 for d in arr)
res.append("the number of odd elements " + str(n) + "n the str"+ str(n) +"ng "+ str(n) +" of the "+ str(n) +"nput.")
return res
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def minSubArraySum(nums):
"""
Given an array of integers nums, find the minimum sum of any non-empty sub-array
of nums.
Example
minSubArraySum([... | max_sum = 0
s = 0
for num in nums:
s += -num
if (s < 0):
s = 0
max_sum = max(s, max_sum)
if max_sum == 0:
max_sum = max(-i for i in nums)
min_sum = -max_sum
return min_sum
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def max_fill(grid, capacity):
import math
"""
You are given a rectangular grid of wells. Each row represents a single well,
and each 1 in a row repr... | return sum([math.ceil(sum(arr)/capacity) for arr in grid])
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def sort_array(arr):
"""
In this Kata, you have to sort an array of non-negative integers according to
number of ones in their binary representation in ... | return sorted(sorted(arr), key=lambda x: bin(x)[2:].count('1'))
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def select_words(s, n):
"""Given a string s and a natural number n, you have been tasked to implement
a function that returns a list of all words from stri... | result = []
for word in s.split():
n_consonants = 0
for i in range(0, len(word)):
if word[i].lower() not in ["a","e","i","o","u"]:
n_consonants += 1
if n_consonants == n:
result.append(word)
return result
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
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 ... | 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 ""
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def match_parens(lst):
'''
You are given a list of two strings, both strings consist of open
parentheses '(' or close parentheses ')' only.
Your job... | def check(s):
val = 0
for i in s:
if i == '(':
val = val + 1
else:
val = val - 1
if val < 0:
return False
return True if val == 0 else False
S1 = lst[0] + lst[1]
S2 = lst[1] + lst[0]
return 'Yes'... |
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
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.
... | if k == 0:
return []
arr.sort()
ans = arr[-k:]
return ans
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def solution(lst):
"""Given a non-empty list of integers, return the sum of all of the odd elements that are in even positions.
Examples
solution(... | return sum([x for idx, x in enumerate(lst) if idx%2==0 and x%2==1])
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
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 ... | return sum(elem for elem in arr[:k] if len(str(elem)) <= 2)
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
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 ... | 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)
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def valid_date(date):
"""You have to write a function which validates a given date string and
returns True if the date is valid otherwise False.
The dat... | try:
date = date.strip()
month, day, year = date.split('-')
month, day, year = int(month), int(day), int(year)
if month < 1 or month > 12:
return False
if month in [1,3,5,7,8,10,12] and day < 1 or day > 31:
return False
if month in [4,6,9,11] a... |
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def split_words(txt):
'''
Given a string of words, return a list of words split on whitespace, if no whitespaces exists in the text you
should split on ... | if " " in txt:
return txt.split()
elif "," in txt:
return txt.replace(',',' ').split()
else:
return len([i for i in txt if i.islower() and ord(i)%2 == 0])
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def is_sorted(lst):
'''
Given a list of numbers, return whether or not they are sorted
in ascending order. If list has more than 1 duplicate of the same... | count_digit = dict([(i, 0) for i in lst])
for i in lst:
count_digit[i]+=1
if any(count_digit[i] > 2 for i in lst):
return False
if all(lst[i-1] <= lst[i] for i in range(1, len(lst))):
return True
else:
return False
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def intersection(interval1, interval2):
"""You are given two intervals,
where each interval is a pair of integers. For example, interval = (start, end) = (1... | 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])
l... |
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def prod_signs(arr):
"""
You are given an array arr of integers and you need to return
sum of magnitudes of integers multiplied by product of all signs
... | if not arr: return None
prod = 0 if 0 in arr else (-1) ** len(list(filter(lambda x: x < 0, arr)))
return prod * sum([abs(i) for i in arr])
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def minPath(grid, k):
"""
Given a grid with N rows and N columns (N >= 2) and a positive integer k,
each cell of the grid contains a value. Every integ... | n = len(grid)
val = n * n + 1
for i in range(n):
for j in range(n):
if grid[i][j] == 1:
temp = []
if i != 0:
temp.append(grid[i - 1][j])
if j != 0:
temp.append(grid[i][j - 1])
if i !... |
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
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 ... | 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
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def digits(n):
"""Given a positive integer n, return the product of the odd digits.
Return 0 if all digits are even.
For example:
digits(1) == 1
... | product = 1
odd_count = 0
for digit in str(n):
int_digit = int(digit)
if int_digit%2 == 1:
product= product*int_digit
odd_count+=1
if odd_count ==0:
return 0
else:
return product
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def is_nested(string):
'''
Create a function that takes a string as input which contains only square brackets.
The function should return True if and on... | opening_bracket_index = []
closing_bracket_index = []
for i in range(len(string)):
if string[i] == '[':
opening_bracket_index.append(i)
else:
closing_bracket_index.append(i)
closing_bracket_index.reverse()
cnt = 0
i = 0
l = len(closing_bracket_index)
... |
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def sum_squares(lst):
"""You are given a list of numbers.
You need to return the sum of squared numbers in the given list,
round each element in the li... | import math
squared = 0
for i in lst:
squared += math.ceil(i)**2
return squared
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def check_if_last_char_is_a_letter(txt):
'''
Create a function that returns True if the last character
of a given string is an alphabetical character an... |
check = txt.split(' ')[-1]
return True if len(check) == 1 and (97 <= ord(check.lower()) <= 122) else False
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def can_arrange(arr):
"""Create a function which returns the largest index of an element which
is not greater than or equal to the element immediately prece... | ind=-1
i=1
while i<len(arr):
if arr[i]<arr[i-1]:
ind=i
i+=1
return ind
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def largest_smallest_integers(lst):
'''
Create a function that returns a tuple (a, b), where 'a' is
the largest of negative integers, and 'b' is the sma... | smallest = list(filter(lambda x: x < 0, lst))
largest = list(filter(lambda x: x > 0, lst))
return (max(smallest) if smallest else None, min(largest) if largest else None)
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def compare_one(a, b):
"""
Create a function that takes integers, floats, or strings representing
real numbers, and returns the larger variable in its g... | 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
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
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... | return n%2 == 0 and n >= 8
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def special_factorial(n):
"""The Brazilian factorial is defined as:
brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
where n > 0
For exampl... | fact_i = 1
special_fact = 1
for i in range(1, n+1):
fact_i *= i
special_fact *= fact_i
return special_fact
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def fix_spaces(text):
"""
Given a string text, replace all spaces in it with underscores,
and if a string has more than 2 consecutive spaces,
then... | new_text = ""
i = 0
start, end = 0, 0
while i < len(text):
if text[i] == " ":
end += 1
else:
if end - start > 2:
new_text += "-"+text[i]
elif end - start > 0:
new_text += "_"*(end - start)+text[i]
else:
... |
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def file_name_check(file_name):
"""Create a function which takes a string representing a file's name, and returns
'Yes' if the the file's name is valid, and... | suf = ['txt', 'exe', 'dll']
lst = file_name.split(sep='.')
if len(lst) != 2:
return 'No'
if not lst[1] in suf:
return 'No'
if len(lst[0]) == 0:
return 'No'
if not lst[0][0].isalpha():
return 'No'
t = len([x for x in lst[0] if x.isdigit()])
if t > 3:
... |
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
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 ind... | 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)
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def words_in_sentence(sentence):
"""
You are given a string representing a sentence,
the sentence contains some words separated by a space,
and you ... | 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)
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
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... | 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
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
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... | 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)
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def specialFilter(nums):
"""Write a function that takes an array of numbers as input and returns
the number of elements in the array that are greater than ... |
count = 0
for num in nums:
if num > 10:
odd_digits = (1, 3, 5, 7, 9)
number_as_string = str(num)
if int(number_as_string[0]) in odd_digits and int(number_as_string[-1]) in odd_digits:
count += 1
return count
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def get_max_triples(n):
"""
You are given a positive integer n. You have to create an integer array a of length n.
For each i (1 ≤ i ≤ n), the value... | A = [i*i - i + 1 for i in range(1,n+1)]
ans = []
for i in range(n):
for j in range(i+1,n):
for k in range(j+1,n):
if (A[i]+A[j]+A[k])%3 == 0:
ans += [(A[i],A[j],A[k])]
return len(ans)
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def bf(planet1, planet2):
'''
There are eight planets in our solar system: the closerst to the Sun
is Mercury, the next one is Venus, then Earth, Mars,... | planet_names = ("Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune")
if planet1 not in planet_names or planet2 not in planet_names or planet1 == planet2:
return ()
planet1_index = planet_names.index(planet1)
planet2_index = planet_names.index(planet2)
if planet1_ind... |
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def sorted_list_sum(lst):
"""Write a function that accepts a list of strings as a parameter,
deletes the strings that have odd lengths from it,
and retu... | lst.sort()
new_lst = []
for i in lst:
if len(i)%2 == 0:
new_lst.append(i)
return sorted(new_lst, key=len)
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def x_or_y(n, x, y):
"""A simple program which should return the value of x if n is
a prime number and should return the value of y otherwise.
Example... | if n == 1:
return y
for i in range(2, n):
if n % i == 0:
return y
break
else:
return x
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def double_the_difference(lst):
'''
Given a list of numbers, return the sum of squares of the numbers
in the list that are odd. Ignore numbers that are ... | return sum([i**2 for i in lst if i > 0 and i%2!=0 and "." not in str(i)])
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
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 ... | return [abs(x-y) for x,y in zip(game,guess)]
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
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... | 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()])
i... |
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def cycpattern_check(a , b):
"""You are given 2 words. You need to return True if the second word or any of its rotations is a substring in the first word
c... | l = len(b)
pat = b + b
for i in range(len(a) - l + 1):
for j in range(l + 1):
if a[i:i+l] == pat[j:j+l]:
return True
return False
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def even_odd_count(num):
"""Given an integer. return a tuple that has the number of even and odd digits respectively.
Example:
even_odd_count(-12)... | even_count = 0
odd_count = 0
for i in str(abs(num)):
if int(i)%2==0:
even_count +=1
else:
odd_count +=1
return (even_count, odd_count)
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def int_to_mini_roman(number):
"""
Given a positive integer, obtain its roman numeral equivalent as a string,
and return it in lowercase.
Restrictio... | num = [1, 4, 5, 9, 10, 40, 50, 90,
100, 400, 500, 900, 1000]
sym = ["I", "IV", "V", "IX", "X", "XL",
"L", "XC", "C", "CD", "D", "CM", "M"]
i = 12
res = ''
while number:
div = number // num[i]
number %= num[i]
while div:
res += sym[i... |
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
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, ... | return a*a == b*b + c*c or b*b == a*a + c*c or c*c == a*a + b*b
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def find_max(words):
"""Write a function that accepts a list of strings.
The list contains different words. Return the word with maximum number
of uniqu... | return sorted(words, key = lambda x: (-len(set(x)), x))[0]
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
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 carro... | if(need <= remaining):
return [ number + need , remaining-need ]
else:
return [ number + remaining , 0]
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def do_algebra(operator, operand):
"""
Given two lists operator, and operand. The first list has basic algebra operations, and
the second list is a lis... | expression = str(operand[0])
for oprt, oprn in zip(operator, operand[1:]):
expression+= oprt + str(oprn)
return eval(expression)
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def solve(s):
"""You are given a string s.
if s[i] is a letter, reverse its case from lower to upper or vise versa,
otherwise keep it as it is.
If ... | flg = 0
idx = 0
new_str = list(s)
for i in s:
if i.isalpha():
new_str[idx] = i.swapcase()
flg = 1
idx += 1
s = ""
for i in new_str:
s += i
if flg == 0:
return s[len(s)::-1]
return s
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def string_to_md5(text):
"""
Given a string 'text', return its md5 hash equivalent string.
If 'text' is an empty string, return None.
>>> string_to... | import hashlib
return hashlib.md5(text.encode('ascii')).hexdigest() if text else None
|
<SYSTEM_TASK:>
Given the following code description, write Python code to implement the functionality described below
<END_TASK>
<USER_TASK:>
Description:
def generate_integers(a, b):
"""
Given two positive integers a and b, return the even digits between a
and b, in ascending order.
For example:
... | lower = max(2, min(a, b))
upper = min(8, max(a, b))
return [i for i in range(lower, upper+1) if i % 2 == 0]
|
<SYSTEM_TASK:>
Run Graph-Cut segmentation with refinement of low resolution multiscale graph.
<END_TASK>
<USER_TASK:>
Description:
def __multiscale_gc_lo2hi_run(self): # , pyed):
"""
Run Graph-Cut segmentation with refinement of low resolution multiscale graph.
In first step is performed normal... |
# from PyQt4.QtCore import pyqtRemoveInputHook
# pyqtRemoveInputHook()
self._msgc_lo2hi_resize_init()
self.__msgc_step0_init()
hard_constraints = self.__msgc_step12_low_resolution_segmentation()
# ===== high resolution data processing
seg = self.__msgc_step3_dis... |
<SYSTEM_TASK:>
Run Graph-Cut segmentation with simplifiyng of high resolution multiscale graph.
<END_TASK>
<USER_TASK:>
Description:
def __multiscale_gc_hi2lo_run(self): # , pyed):
"""
Run Graph-Cut segmentation with simplifiyng of high resolution multiscale graph.
In first step is performed no... |
# from PyQt4.QtCore import pyqtRemoveInputHook
# pyqtRemoveInputHook()
self.__msgc_step0_init()
hard_constraints = self.__msgc_step12_low_resolution_segmentation()
# ===== high resolution data processing
seg = self.__msgc_step3_discontinuity_localization()
nlink... |
<SYSTEM_TASK:>
Function computes multiscale indexes of ndarray.
<END_TASK>
<USER_TASK:>
Description:
def __hi2lo_multiscale_indexes(self, mask, orig_shape): # , zoom):
"""
Function computes multiscale indexes of ndarray.
mask: Says where is original resolution (0) and where is small
re... |
mask_orig = zoom_to_shape(mask, orig_shape, dtype=np.int8)
inds_small = np.arange(mask.size).reshape(mask.shape)
inds_small_in_orig = zoom_to_shape(inds_small, orig_shape, dtype=np.int8)
inds_orig = np.arange(np.prod(orig_shape)).reshape(orig_shape)
# inds_orig = inds_orig * ... |
<SYSTEM_TASK:>
Interactive seed setting with 3d seed editor
<END_TASK>
<USER_TASK:>
Description:
def interactivity(self, min_val=None, max_val=None, qt_app=None):
"""
Interactive seed setting with 3d seed editor
""" |
from .seed_editor_qt import QTSeedEditor
from PyQt4.QtGui import QApplication
if min_val is None:
min_val = np.min(self.img)
if max_val is None:
max_val = np.max(self.img)
window_c = (max_val + min_val) / 2 # .astype(np.int16)
window_w = max_v... |
<SYSTEM_TASK:>
Run the Graph Cut segmentation according to preset parameters.
<END_TASK>
<USER_TASK:>
Description:
def run(self, run_fit_model=True):
"""
Run the Graph Cut segmentation according to preset parameters.
:param run_fit_model: Allow to skip model fit when the model is prepared befor... |
if run_fit_model:
self.fit_model(self.img, self.voxelsize, self.seeds)
self._start_time = time.time()
if self.segparams["method"].lower() in ("graphcut", "gc"):
self.__single_scale_gc_run()
elif self.segparams["method"].lower() in (
"multiscale_grap... |
<SYSTEM_TASK:>
Compute edge values for graph cut tlinks based on image intensity
<END_TASK>
<USER_TASK:>
Description:
def __similarity_for_tlinks_obj_bgr(
self,
data,
voxelsize,
# voxels1, voxels2,
# seeds, otherfeatures=None
):
"""
Compute edge values for gra... |
# self.fit_model(data, voxelsize, seeds)
# There is a need to have small vaues for good fit
# R(obj) = -ln( Pr (Ip | O) )
# R(bck) = -ln( Pr (Ip | B) )
# Boykov2001b
# ln is computed in likelihood
tdata1 = (-(self.mdl.likelihood_from_image(data, voxelsize, 1))) *... |
<SYSTEM_TASK:>
Setting of data.
<END_TASK>
<USER_TASK:>
Description:
def _ssgc_prepare_data_and_run_computation(
self,
# voxels1, voxels2,
hard_constraints=True,
area_weight=1,
):
"""
Setting of data.
You need set seeds if you want use hard_constraints.
... |
# from PyQt4.QtCore import pyqtRemoveInputHook
# pyqtRemoveInputHook()
# import pdb; pdb.set_trace() # BREAKPOINT
unariesalt = self.__create_tlinks(
self.img,
self.voxelsize,
# voxels1, voxels2,
self.seeds,
area_weight,
... |
<SYSTEM_TASK:>
Smart zoom for sparse matrix. If there is resize to bigger resolution
<END_TASK>
<USER_TASK:>
Description:
def seed_zoom(seeds, zoom):
"""
Smart zoom for sparse matrix. If there is resize to bigger resolution
thin line of label could be lost. This function prefers labels larger
then zero.... |
# import scipy
# loseeds=seeds
labels = np.unique(seeds)
# remove first label - 0
labels = np.delete(labels, 0)
# @TODO smart interpolation for seeds in one block
# loseeds = scipy.ndimage.interpolation.zoom(
# seeds, zoom, order=0)
loshape = np.ceil(np.array(seeds... |
<SYSTEM_TASK:>
Zoom data to specific shape.
<END_TASK>
<USER_TASK:>
Description:
def zoom_to_shape(data, shape, dtype=None):
"""
Zoom data to specific shape.
""" |
import scipy
import scipy.ndimage
zoomd = np.array(shape) / np.array(data.shape, dtype=np.double)
import warnings
datares = scipy.ndimage.interpolation.zoom(data, zoomd, order=0, mode="reflect")
if datares.shape != shape:
logger.warning("Zoom with different output shape")
dataout... |
<SYSTEM_TASK:>
Crop the data.
<END_TASK>
<USER_TASK:>
Description:
def crop(data, crinfo):
"""
Crop the data.
crop(data, crinfo)
:param crinfo: min and max for each axis - [[minX, maxX], [minY, maxY], [minZ, maxZ]]
""" |
crinfo = fix_crinfo(crinfo)
return data[
__int_or_none(crinfo[0][0]) : __int_or_none(crinfo[0][1]),
__int_or_none(crinfo[1][0]) : __int_or_none(crinfo[1][1]),
__int_or_none(crinfo[2][0]) : __int_or_none(crinfo[2][1]),
] |
<SYSTEM_TASK:>
Combine two crinfos. First used is crinfo1, second used is crinfo2.
<END_TASK>
<USER_TASK:>
Description:
def combinecrinfo(crinfo1, crinfo2):
"""
Combine two crinfos. First used is crinfo1, second used is crinfo2.
""" |
crinfo1 = fix_crinfo(crinfo1)
crinfo2 = fix_crinfo(crinfo2)
crinfo = [
[crinfo1[0][0] + crinfo2[0][0], crinfo1[0][0] + crinfo2[0][1]],
[crinfo1[1][0] + crinfo2[1][0], crinfo1[1][0] + crinfo2[1][1]],
[crinfo1[2][0] + crinfo2[2][0], crinfo1[2][0] + crinfo2[2][1]],
]
return c... |
<SYSTEM_TASK:>
Create crinfo of minimum orthogonal nonzero block in input data.
<END_TASK>
<USER_TASK:>
Description:
def crinfo_from_specific_data(data, margin=0):
"""
Create crinfo of minimum orthogonal nonzero block in input data.
:param data: input data
:param margin: add margin to minimum block
... |
# hledáme automatický ořez, nonzero dá indexy
logger.debug("crinfo")
logger.debug(str(margin))
nzi = np.nonzero(data)
logger.debug(str(nzi))
if np.isscalar(margin):
margin = [margin] * 3
x1 = np.min(nzi[0]) - margin[0]
x2 = np.max(nzi[0]) + margin[0] + 1
y1 = np.min(nzi[1]... |
<SYSTEM_TASK:>
Put some boundary to input image.
<END_TASK>
<USER_TASK:>
Description:
def uncrop(data, crinfo, orig_shape, resize=False, outside_mode="constant", cval=0):
"""
Put some boundary to input image.
:param data: input data
:param crinfo: array with minimum and maximum index along each axis
... |
if crinfo is None:
crinfo = list(zip([0] * data.ndim, orig_shape))
elif np.asarray(crinfo).size == data.ndim:
crinfo = list(zip(crinfo, np.asarray(crinfo) + data.shape))
crinfo = fix_crinfo(crinfo)
data_out = np.ones(orig_shape, dtype=data.dtype) * cval
# print 'uncrop ', crinfo
... |
<SYSTEM_TASK:>
Function recognize order of crinfo and convert it to proper format.
<END_TASK>
<USER_TASK:>
Description:
def fix_crinfo(crinfo, to="axis"):
"""
Function recognize order of crinfo and convert it to proper format.
""" |
crinfo = np.asarray(crinfo)
if crinfo.shape[0] == 2:
crinfo = crinfo.T
return crinfo |
<SYSTEM_TASK:>
Generate list of edges for a base grid.
<END_TASK>
<USER_TASK:>
Description:
def gen_grid_2d(shape, voxelsize):
"""
Generate list of edges for a base grid.
""" |
nr, nc = shape
nrm1, ncm1 = nr - 1, nc - 1
# sh = nm.asarray(shape)
# calculate number of edges, in 2D: (nrows * (ncols - 1)) + ((nrows - 1) * ncols)
nedges = 0
for direction in range(len(shape)):
sh = copy.copy(list(shape))
sh[direction] += -1
nedges += nm.prod(sh)
... |
<SYSTEM_TASK:>
Add new nodes at the end of the list.
<END_TASK>
<USER_TASK:>
Description:
def add_nodes(self, coors, node_low_or_high=None):
"""
Add new nodes at the end of the list.
""" |
last = self.lastnode
if type(coors) is nm.ndarray:
if len(coors.shape) == 1:
coors = coors.reshape((1, coors.size))
nadd = coors.shape[0]
idx = slice(last, last + nadd)
else:
nadd = 1
idx = self.lastnode
right_... |
<SYSTEM_TASK:>
Return features selected by seeds and unique_cls or selection from features and corresponding seed classes.
<END_TASK>
<USER_TASK:>
Description:
def return_fv_by_seeds(fv, seeds=None, unique_cls=None):
"""
Return features selected by seeds and unique_cls or selection from features and correspondi... |
if seeds is not None:
if unique_cls is not None:
return select_from_fv_by_seeds(fv, seeds, unique_cls)
else:
raise AssertionError("Input unique_cls has to be not None if seeds is not None.")
else:
return fv |
<SYSTEM_TASK:>
Expands logical constructions.
<END_TASK>
<USER_TASK:>
Description:
def expand(self, expression):
"""Expands logical constructions.""" |
self.logger.debug("expand : expression %s", str(expression))
if not is_string(expression):
return expression
result = self._pattern.sub(lambda var: str(self._variables[var.group(1)]), expression)
result = result.strip()
self.logger.debug('expand : %s - result : %s'... |
<SYSTEM_TASK:>
Creates gutter clients and memoizes them in a registry for future quick access.
<END_TASK>
<USER_TASK:>
Description:
def get_gutter_client(
alias='default',
cache=CLIENT_CACHE,
**kwargs
):
"""
Creates gutter clients and memoizes them in a registry for future quick access.
... |
from gutter.client.models import Manager
if not alias:
return Manager(**kwargs)
elif alias not in cache:
cache[alias] = Manager(**kwargs)
return cache[alias] |
<SYSTEM_TASK:>
The mod operator is prone to floating point errors, so use decimal.
<END_TASK>
<USER_TASK:>
Description:
def _modulo(self, decimal_argument):
"""
The mod operator is prone to floating point errors, so use decimal.
101.1 % 100
>>> 1.0999999999999943
decimal_contex... |
_times, remainder = self._context.divmod(decimal_argument, 100)
# match the builtin % behavior by adding the N to the result if negative
return remainder if remainder >= 0 else remainder + 100 |
<SYSTEM_TASK:>
Checks to see if this switch is enabled for the provided input.
<END_TASK>
<USER_TASK:>
Description:
def enabled_for(self, inpt):
"""
Checks to see if this switch is enabled for the provided input.
If ``compounded``, all switch conditions must be ``True`` for the switch
t... |
signals.switch_checked.call(self)
signal_decorated = partial(self.__signal_and_return, inpt)
if self.state is self.states.GLOBAL:
return signal_decorated(True)
elif self.state is self.states.DISABLED:
return signal_decorated(False)
conditions_dict = Co... |
<SYSTEM_TASK:>
Returns if the condition applies to the ``inpt``.
<END_TASK>
<USER_TASK:>
Description:
def call(self, inpt):
"""
Returns if the condition applies to the ``inpt``.
If the class ``inpt`` is an instance of is not the same class as the
condition's own ``argument``, then ``Fal... |
if inpt is Manager.NONE_INPUT:
return False
# Call (construct) the argument with the input object
argument_instance = self.argument(inpt)
if not argument_instance.applies:
return False
application = self.__apply(argument_instance, inpt)
if sel... |
<SYSTEM_TASK:>
List of all switches currently registered.
<END_TASK>
<USER_TASK:>
Description:
def switches(self):
"""
List of all switches currently registered.
""" |
results = [
switch for name, switch in self.storage.iteritems()
if name.startswith(self.__joined_namespace)
]
return results |
<SYSTEM_TASK:>
Returns the switch with the provided ``name``.
<END_TASK>
<USER_TASK:>
Description:
def switch(self, name):
"""
Returns the switch with the provided ``name``.
If ``autocreate`` is set to ``True`` and no switch with that name
exists, a ``DISABLED`` switch will be with that... |
try:
switch = self.storage[self.__namespaced(name)]
except KeyError:
if not self.autocreate:
raise ValueError("No switch named '%s' registered in '%s'" % (name, self.namespace))
switch = self.__create_and_register_disabled_switch(name)
switc... |
null | null |
<SYSTEM_TASK:>
Central interface to verify interactions.
<END_TASK>
<USER_TASK:>
Description:
def verify(obj, times=1, atleast=None, atmost=None, between=None,
inorder=False):
"""Central interface to verify interactions.
`verify` uses a fluent interface::
verify(<obj>, times=2).<method_name... |
if isinstance(obj, str):
obj = get_obj(obj)
verification_fn = _get_wanted_verification(
times=times, atleast=atleast, atmost=atmost, between=between)
if inorder:
verification_fn = verification.InOrder(verification_fn)
# FIXME?: Catch error if obj is neither a Mock nor a known... |
<SYSTEM_TASK:>
Central interface to stub functions on a given `obj`
<END_TASK>
<USER_TASK:>
Description:
def when(obj, strict=None):
"""Central interface to stub functions on a given `obj`
`obj` should be a module, a class or an instance of a class; it can be
a Dummy you created with :func:`mock`. ``when``... |
if isinstance(obj, str):
obj = get_obj(obj)
if strict is None:
strict = True
theMock = _get_mock(obj, strict=strict)
class When(object):
def __getattr__(self, method_name):
return invocation.StubbedInvocation(
theMock, method_name, strict=strict)
... |
<SYSTEM_TASK:>
Stub a function call with the given arguments
<END_TASK>
<USER_TASK:>
Description:
def when2(fn, *args, **kwargs):
"""Stub a function call with the given arguments
Exposes a more pythonic interface than :func:`when`. See :func:`when` for
more documentation.
Returns `AnswerSelector` inte... |
obj, name = get_obj_attr_tuple(fn)
theMock = _get_mock(obj, strict=True)
return invocation.StubbedInvocation(theMock, name)(*args, **kwargs) |
<SYSTEM_TASK:>
Stub a function call, and set up an expected call count.
<END_TASK>
<USER_TASK:>
Description:
def expect(obj, strict=None,
times=None, atleast=None, atmost=None, between=None):
"""Stub a function call, and set up an expected call count.
Usage::
# Given `dog` is an instance of... |
if strict is None:
strict = True
theMock = _get_mock(obj, strict=strict)
verification_fn = _get_wanted_verification(
times=times, atleast=atleast, atmost=atmost, between=between)
class Expect(object):
def __getattr__(self, method_name):
return invocation.StubbedInv... |
<SYSTEM_TASK:>
Unstubs all stubbed methods and functions
<END_TASK>
<USER_TASK:>
Description:
def unstub(*objs):
"""Unstubs all stubbed methods and functions
If you don't pass in any argument, *all* registered mocks and
patched modules, classes etc. will be unstubbed.
Note that additionally, the under... |
if objs:
for obj in objs:
mock_registry.unstub(obj)
else:
mock_registry.unstub_all() |
<SYSTEM_TASK:>
Verify that no methods have been called on given objs.
<END_TASK>
<USER_TASK:>
Description:
def verifyZeroInteractions(*objs):
"""Verify that no methods have been called on given objs.
Note that strict mocks usually throw early on unexpected, unstubbed
invocations. Partial mocks ('monkeypatc... |
for obj in objs:
theMock = _get_mock_or_raise(obj)
if len(theMock.invocations) > 0:
raise VerificationError(
"\nUnwanted interaction: %s" % theMock.invocations[0]) |
<SYSTEM_TASK:>
Verifies that expectations set via `expect` are met
<END_TASK>
<USER_TASK:>
Description:
def verifyNoUnwantedInteractions(*objs):
"""Verifies that expectations set via `expect` are met
E.g.::
expect(os.path, times=1).exists(...).thenReturn(True)
os.path('/foo')
verifyNoU... |
if objs:
theMocks = map(_get_mock_or_raise, objs)
else:
theMocks = mock_registry.get_registered_mocks()
for mock in theMocks:
for i in mock.stubbed_invocations:
i.verify() |
<SYSTEM_TASK:>
Ensure stubs are actually used.
<END_TASK>
<USER_TASK:>
Description:
def verifyStubbedInvocationsAreUsed(*objs):
"""Ensure stubs are actually used.
This functions just ensures that stubbed methods are actually used. Its
purpose is to detect interface changes after refactorings. It is meant
... |
if objs:
theMocks = map(_get_mock_or_raise, objs)
else:
theMocks = mock_registry.get_registered_mocks()
for mock in theMocks:
for i in mock.stubbed_invocations:
if not i.allow_zero_invocations and i.used < len(i.answers):
raise VerificationError("\nUnus... |
<SYSTEM_TASK:>
Destructure a given function into its host and its name.
<END_TASK>
<USER_TASK:>
Description:
def get_function_host(fn):
"""Destructure a given function into its host and its name.
The 'host' of a function is a module, for methods it is usually its
instance or its class. This is safe only fo... |
obj = None
try:
name = fn.__name__
obj = fn.__self__
except AttributeError:
pass
if obj is None:
# Due to how python imports work, everything that is global on a module
# level must be regarded as not safe here. For now, we go for the extra
# mile, TBC,... |
<SYSTEM_TASK:>
Return obj for given dotted path.
<END_TASK>
<USER_TASK:>
Description:
def get_obj(path):
"""Return obj for given dotted path.
Typical inputs for `path` are 'os' or 'os.path' in which case you get a
module; or 'os.path.exists' in which case you get a function from that
module.
Just ... |
# Since we usually pass in mocks here; duck typing is not appropriate
# (mocks respond to every attribute).
if not isinstance(path, str):
return path
if path.startswith('.'):
raise TypeError('relative imports are not supported')
parts = path.split('.')
head, tail = parts[0], p... |
<SYSTEM_TASK:>
Spy an object.
<END_TASK>
<USER_TASK:>
Description:
def spy(object):
"""Spy an object.
Spying means that all functions will behave as before, so they will
be side effects, but the interactions can be verified afterwards.
Returns Dummy-like, almost empty object as proxy to `object`.
... |
if inspect.isclass(object) or inspect.ismodule(object):
class_ = None
else:
class_ = object.__class__
class Spy(_Dummy):
if class_:
__class__ = class_
def __getattr__(self, method_name):
return RememberedProxyInvocation(theMock, method_name)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.