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 stones in the next level is:
- the next odd number if n is odd.
- the next even number if n is even.
Return the number of stones in each level in a list, where element at index
i represents the number of stones in the level (i+1).
Examples:
>>> make_a_pile(3)
[3, 5, 7]
"""
| 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 array of the words.
For example:
words_string("Hi, my name is John") == ["Hi", "my", "name", "is", "John"]
words_string("One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"]
"""
| 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
there's no such number, then the function should return -1.
For example:
choose_num(12, 15) = 14
choose_num(13, 12) = -1
"""
| 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 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"
"""
| 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 should be sorted in increasing order.
For example:
>>> unique_digits([15, 33, 1422, 1])
[1, 15, 33]
>>> unique_digits([152, 323, 1422, 10])
[]
"""
| 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 each digit by its corresponding name from
"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
For example:
arr = [2, 1, 1, 4, 5, 8, 2, 3]
-> sort arr -> [1, 1, 2, 2, 3, 4, 5, 8]
-> reverse arr -> [8, 5, 4, 3, 2, 2, 1, 1]
return ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
If the array is empty, return an empty array:
arr = []
return []
If the array has any strange number ignore it:
arr = [1, -1 , 55]
-> sort arr -> [-1, 1, 55]
-> reverse arr -> [55, 1, -1]
return = ['One']
"""
| 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[var])
except:
pass
return new_arr
|
<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 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]
"""
| 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 range(1, n), inclusive.
Example 1:
Input: 3
Output: (1, 2)
Explanation:
Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
Example 2:
Input: 12
Output: (4, 6)
Explanation:
Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
Note:
1. 1 <= n <= 10^3
2. returned tuple has the number of even and odd integer palindromes respectively.
"""
| 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
return (even_palindrome_count, odd_palindrome_count)
|
<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.
If a number is negative, then its first signed digit will be negative:
e.g. -123 has signed digits -1, 2, and 3.
>>> count_nums([]) == 0
>>> count_nums([-1, 11, -11]) == 1
>>> count_nums([1, 1, 2]) == 3
"""
| 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 to determine if
it is possible to get an array sorted in non-decreasing order by performing
the following operation on the given array:
You are allowed to perform right shift operation any number of times.
One right shift operation means shifting all elements of the array by one
position in the right direction. The last element of the array will be moved to
the starting position in the array i.e. 0th index.
If it is possible to obtain the sorted array by performing the above operation
then return True else return False.
If the given array is empty then return True.
Note: The given list is guaranteed to have unique elements.
For Example:
move_one_ball([3, 4, 5, 1, 2])==>True
Explanation: By performin 2 right shift operations, non-decreasing order can
be achieved for the given array.
move_one_ball([3, 5, 4, 1, 2])==>False
Explanation:It is not possible to get non-decreasing order for the given
array by performing any number of right shift operations.
"""
| 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 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.
"""
| 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 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('') == {}
"""
| 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 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)
"""
| 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 of odd elements in the
string i of the input." where all the i's should be replaced by the number
of odd digits in the i'th string of the input.
>>> odd_count(['1234567'])
["the number of odd elements 4n the str4ng 4 of the 4nput."]
>>> odd_count(['3',"11111111"])
["the number of odd elements 1n the str1ng 1 of the 1nput.",
"the number of odd elements 8n the str8ng 8 of the 8nput."]
"""
| 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([2, 3, 4, 1, 2, 4]) == 1
minSubArraySum([-1, -2, -3]) == -6
"""
| 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 represents a single unit of water.
Each well has a corresponding bucket that can be used to extract water from it,
and all buckets have the same capacity.
Your task is to use the buckets to empty the wells.
Output the number of times you need to lower the buckets.
Example 1:
Input:
grid : [[0,0,1,0], [0,1,0,0], [1,1,1,1]]
bucket_capacity : 1
Output: 6
Example 2:
Input:
grid : [[0,0,1,1], [0,0,0,0], [1,1,1,1], [0,1,1,1]]
bucket_capacity : 2
Output: 5
Example 3:
Input:
grid : [[0,0,0], [0,0,0]]
bucket_capacity : 5
Output: 0
Constraints:
* all wells have the same length
* 1 <= grid.length <= 10^2
* 1 <= grid[:,1].length <= 10^2
* grid[i][j] -> 0 | 1
* 1 <= capacity <= 10
"""
| 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 ascending order.
For similar number of ones, sort based on decimal value.
It must be implemented like this:
>>> sort_array([1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
>>> sort_array([-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
>>> sort_array([1, 0, 2, 3, 4]) [0, 1, 2, 3, 4]
"""
| 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 string s that contain exactly
n consonants, in order these words appear in the string s.
If the string s is empty then the function should return an empty list.
Note: you may assume the input string contains only letters and spaces.
Examples:
select_words("Mary had a little lamb", 4) ==> ["little"]
select_words("Mary had a little lamb", 3) ==> ["Mary", "lamb"]
select_words("simple white space", 2) ==> []
select_words("Hello world", 4) ==> ["world"]
select_words("Uncle sam", 3) ==> ["Uncle"]
"""
| 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 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") ==> ""
"""
| 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 is to check if it is possible to concatenate the two strings in
some order, that the resulting string will be good.
A string S is considered to be good if and only if all parentheses in S
are balanced. For example: the string '(())()' is good, while the string
'())' is not.
Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
Examples:
match_parens(['()(', ')']) == 'Yes'
match_parens([')', ')']) == 'No'
'''
| 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' if check(S1) or check(S2) else 'No'
|
<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.
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)
"""
| 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([5, 8, 7, 1]) ==> 12
solution([3, 3, 3, 3, 3]) ==> 9
solution([30, 13, 24, 321]) ==>0
"""
| 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 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)
"""
| 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 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.
"""
| 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 date is valid if all of the following rules are satisfied:
1. The date string is not empty.
2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
3. The months should not be less than 1 or higher than 12.
4. The date should be in the format: mm-dd-yyyy
for example:
valid_date('03-11-2000') => True
valid_date('15-01-2012') => False
valid_date('04-0-2040') => False
valid_date('06-04-2020') => True
valid_date('06/04/2020') => False
"""
| 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] and day < 1 or day > 30:
return False
if month == 2 and day < 1 or day > 29:
return False
except:
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 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 commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
Examples
split_words("Hello world!") ➞ ["Hello", "world!"]
split_words("Hello,world!") ➞ ["Hello", "world!"]
split_words("abcdef") == 3
'''
| 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
number, return False. Assume no negative numbers and only integers.
Examples
is_sorted([5]) ➞ True
is_sorted([1, 2, 3, 4, 5]) ➞ True
is_sorted([1, 3, 2, 4, 5]) ➞ False
is_sorted([1, 2, 3, 4, 5, 6]) ➞ True
is_sorted([1, 2, 3, 4, 5, 6, 7]) ➞ True
is_sorted([1, 3, 2, 4, 5, 6, 7]) ➞ False
is_sorted([1, 2, 2, 3, 3, 4]) ➞ True
is_sorted([1, 2, 2, 2, 3, 4]) ➞ False
'''
| 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, 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"
"""
| 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"
|
<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
of each number in the array, represented by 1, -1 or 0.
Note: return None for empty arr.
Example:
>>> prod_signs([1, 2, 2, -4]) == -9
>>> prod_signs([0, 1]) == 0
>>> prod_signs([]) == None
"""
| 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 integer in the range [1, N * N]
inclusive appears exactly once on the cells of the grid.
You have to find the minimum path of length k in the grid. You can start
from any cell, and in each step you can move to any of the neighbor cells,
in other words, you can go to cells which share an edge with you current
cell.
Please note that a path of length k means visiting exactly k cells (not
necessarily distinct).
You CANNOT go off the grid.
A path A (of length k) is considered less than a path B (of length k) if
after making the ordered lists of the values on the cells that A and B go
through (let's call them lst_A and lst_B), lst_A is lexicographically less
than lst_B, in other words, there exist an integer index i (1 <= i <= k)
such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
lst_A[j] = lst_B[j].
It is guaranteed that the answer is unique.
Return an ordered list of the values on the cells that the minimum path go through.
Examples:
Input: grid = [ [1,2,3], [4,5,6], [7,8,9]], k = 3
Output: [1, 2, 1]
Input: grid = [ [5,9,3], [4,1,6], [7,8,2]], k = 1
Output: [1]
"""
| 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 != n - 1:
temp.append(grid[i + 1][j])
if j != n - 1:
temp.append(grid[i][j + 1])
val = min(temp)
ans = []
for i in range(k):
if i % 2 == 0:
ans.append(1)
else:
ans.append(val)
return ans
|
<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 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]
"""
| 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
digits(4) == 0
digits(235) == 15
"""
| 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 only if there is a valid subsequence of brackets
where at least one bracket in the subsequence is nested.
is_nested('[[]]') ➞ True
is_nested('[]]]]]]][[[[[]') ➞ False
is_nested('[][]') ➞ False
is_nested('[]') ➞ False
is_nested('[[][]]') ➞ True
is_nested('[[]][[') ➞ True
'''
| 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)
for idx in opening_bracket_index:
if i < l and idx < closing_bracket_index[i]:
cnt += 1
i += 1
return cnt >= 2
|
<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 list to the upper int(Ceiling) first.
Examples:
For lst = [1,2,3] the output should be 14
For lst = [1,4,9] the output should be 98
For lst = [1,3,5,7] the output should be 84
For lst = [1.4,4.2,0] the output should be 29
For lst = [-2.4,1,1] the output should be 6
"""
| 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 and is not
a part of a word, and False otherwise.
Note: "word" is a group of characters separated by space.
Examples:
check_if_last_char_is_a_letter("apple pie") ➞ False
check_if_last_char_is_a_letter("apple pi e") ➞ True
check_if_last_char_is_a_letter("apple pi e ") ➞ False
check_if_last_char_is_a_letter("") ➞ False
'''
|
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 preceding it. If
no such element exists then return -1. The given array will not contain
duplicate values.
Examples:
can_arrange([1,2,4,3,5]) = 3
can_arrange([1,2,3]) = -1
"""
| 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 smallest
of positive integers in a list.
If there is no negative or positive integers, return them as None.
Examples:
largest_smallest_integers([2, 4, 1, 3, 5, 7]) == (None, 1)
largest_smallest_integers([]) == (None, None)
largest_smallest_integers([0]) == (None, None)
'''
| 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 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
"""
| 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_even(4) == False
is_equal_to_sum_even(6) == False
is_equal_to_sum_even(8) == True
"""
| 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 example:
>>> special_factorial(4)
288
The function will receive an integer as input and should return the special
factorial of this integer.
"""
| 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 replace all consecutive spaces with -
fix_spaces("Example") == "Example"
fix_spaces("Example 1") == "Example_1"
fix_spaces(" Example 2") == "_Example_2"
fix_spaces(" Example 3") == "_Example-3"
"""
| 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:
new_text += text[i]
start, end = i+1, i+1
i+=1
if end - start > 2:
new_text += "-"
elif end - start > 0:
new_text += "_"
return new_text
|
<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 returns 'No' otherwise.
A file's name is considered to be valid if and only if all the following conditions
are met:
- There should not be more than three digits ('0'-'9') in the file's name.
- The file's name contains exactly one dot '.'
- The substring before the dot should not be empty, and it starts with a letter from
the latin alphapet ('a'-'z' and 'A'-'Z').
- The substring after the dot should be one of these: ['txt', 'exe', 'dll']
Examples:
file_name_check("example.txt") # => 'Yes'
file_name_check("1example.dll") # => 'No' (the name should start with a latin alphapet letter)
"""
| 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:
return 'No'
return 'Yes'
|
<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 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
"""
| 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 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
"""
| 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 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
"""
| 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: 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([]) == []
"""
| 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 10 and both
first and last digits of a number are odd (1, 3, 5, 7, 9).
For example:
specialFilter([15, -73, 14, -15]) => 1
specialFilter([33, -2, -3, 45, 21, 109]) => 2
"""
|
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 of a[i] = i * i - i + 1.
Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
and a[i] + a[j] + a[k] is a multiple of 3.
Example :
Input: n = 5
Output: 1
Explanation:
a = [1, 3, 7, 13, 21]
The only valid triple is (1, 7, 13).
"""
| 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, Jupiter, Saturn,
Uranus, Neptune.
Write a function that takes two planet names as strings planet1 and planet2.
The function should return a tuple containing all planets whose orbits are
located between the orbit of planet1 and the orbit of planet2, sorted by
the proximity to the sun.
The function should return an empty tuple if planet1 or planet2
are not correct planet names.
Examples
bf("Jupiter", "Neptune") ==> ("Saturn", "Uranus")
bf("Earth", "Mercury") ==> ("Venus")
bf("Mercury", "Uranus") ==> ("Venus", "Earth", "Mars", "Jupiter", "Saturn")
'''
| 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_index < planet2_index:
return (planet_names[planet1_index + 1: planet2_index])
else:
return (planet_names[planet2_index + 1 : planet1_index])
|
<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 returns the resulted list with a sorted order,
The list is always a list of strings and never an array of numbers,
and it may contain duplicates.
The order of the list should be ascending by length of each word, and you
should return the list sorted by that rule.
If two words have the same length, sort the list alphabetically.
The function should return a list of strings in sorted order.
You may assume that all words will have the same length.
For example:
assert list_sort(["aa", "a", "aaa"]) => ["aa"]
assert list_sort(["ab", "a", "aaa", "cd"]) => ["ab", "cd"]
"""
| 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.
Examples:
for x_or_y(7, 34, 12) == 34
for x_or_y(15, 8, 5) == 5
"""
| 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 negative or not integers.
double_the_difference([1, 3, 2, 0]) == 1 + 9 + 0 + 0 = 10
double_the_difference([-1, -2, 0]) == 0
double_the_difference([9, -2]) == 81
double_the_difference([0]) == 0
If the input list is empty, return 0.
'''
| 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 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]
"""
| 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 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'
"""
| 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
|
<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
cycpattern_check("abcd","abd") => False
cycpattern_check("hello","ell") => True
cycpattern_check("whassup","psus") => False
cycpattern_check("abab","baa") => True
cycpattern_check("efef","eeff") => False
cycpattern_check("himenss","simen") => True
"""
| 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) ==> (1, 1)
even_odd_count(123) ==> (1, 2)
"""
| 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.
Restrictions: 1 <= num <= 1000
Examples:
>>> int_to_mini_roman(19) == 'xix'
>>> int_to_mini_roman(152) == 'clii'
>>> int_to_mini_roman(426) == 'cdxxvi'
"""
| 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]
div -= 1
i -= 1
return res.lower()
|
<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, 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
'''
| 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 unique characters. If multiple strings have maximum number of unique
characters, return the one which comes first in lexicographical order.
find_max(["name", "of", "string"]) == "string"
find_max(["name", "enam", "game"]) == "enam"
find_max(["aaaaaaa", "bb" ,"cc"]) == ""aaaaaaa"
"""
| 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 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 :)
"""
| 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 list of integers. Use the two given lists to build the algebric
expression and return the evaluation of this expression.
The basic algebra operations:
Addition ( + )
Subtraction ( - )
Multiplication ( * )
Floor division ( // )
Exponentiation ( ** )
Example:
operator['+', '*', '-']
array = [2, 3, 4, 5]
result = 2 + 3 * 4 - 5
=> result = 9
Note:
The length of operator list is equal to the length of operand list minus one.
Operand is a list of of non-negative integers.
Operator list has at least one operator, and operand list has at least two operands.
"""
| 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 the string contains no letters, reverse the string.
The function should return the resulted string.
Examples
solve("1234") = "4321"
solve("ab") = "AB"
solve("#a@C") = "#A@c"
"""
| 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_md5('Hello world') == '3e25960a79dbc69b674cd4ec67a72c62'
"""
| 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:
generate_integers(2, 8) => [2, 4, 6, 8]
generate_integers(8, 2) => [2, 4, 6, 8]
generate_integers(10, 14) => []
"""
| 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 GC on low resolution data
Second step construct finer grid on edges of segmentation from first
step.
There is no option for use without `use_boundary_penalties`
""" |
# 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_discontinuity_localization()
self.stats["t3.1"] = (time.time() - self._start_time)
graph = Graph(
seg,
voxelsize=self.voxelsize,
nsplit=self.segparams["block_size"],
edge_weight_table=self._msgc_npenalty_table,
compute_low_nodes_index=True,
)
# graph.run() = graph.generate_base_grid() + graph.split_voxels()
# graph.run()
graph.generate_base_grid()
self.stats["t3.2"] = (time.time() - self._start_time)
graph.split_voxels()
self.stats["t3.3"] = (time.time() - self._start_time)
self.stats.update(graph.stats)
self.stats["t4"] = (time.time() - self._start_time)
mul_mask, mul_val = self.__msgc_tlinks_area_weight_from_low_segmentation(seg)
area_weight = 1
unariesalt = self.__create_tlinks(
self.img,
self.voxelsize,
self.seeds,
area_weight=area_weight,
hard_constraints=hard_constraints,
mul_mask=None,
mul_val=None,
)
# N-links prepared
self.stats["t5"] = (time.time() - self._start_time)
un, ind = np.unique(graph.msinds, return_index=True)
self.stats["t6"] = (time.time() - self._start_time)
self.stats["t7"] = (time.time() - self._start_time)
unariesalt2_lo2hi = np.hstack(
[unariesalt[ind, 0, 0].reshape(-1, 1), unariesalt[ind, 0, 1].reshape(-1, 1)]
)
nlinks_lo2hi = np.hstack([graph.edges, graph.edges_weights.reshape(-1, 1)])
if self.debug_images:
import sed3
ed = sed3.sed3(unariesalt[:, :, 0].reshape(self.img.shape))
ed.show()
import sed3
ed = sed3.sed3(unariesalt[:, :, 1].reshape(self.img.shape))
ed.show()
# ed = sed3.sed3(seg)
# ed.show()
# import sed3
# ed = sed3.sed3(graph.data)
# ed.show()
# import sed3
# ed = sed3.sed3(graph.msinds)
# ed.show()
# nlinks, unariesalt2, msinds = self.__msgc_step45678_construct_graph(area_weight, hard_constraints, seg)
# self.__msgc_step9_finish_perform_gc_and_reshape(nlinks, unariesalt2, msinds)
self.__msgc_step9_finish_perform_gc_and_reshape(
nlinks_lo2hi, unariesalt2_lo2hi, graph.msinds
)
self._msgc_lo2hi_resize_clean_finish() |
<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 normal GC on low resolution data
Second step construct finer grid on edges of segmentation from first
step.
There is no option for use without `use_boundary_penalties`
""" |
# 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()
nlinks, unariesalt2, msinds = self.__msgc_step45678_hi2lo_construct_graph(
hard_constraints, seg
)
self.__msgc_step9_finish_perform_gc_and_reshape(nlinks, unariesalt2, msinds) |
<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
resolution (1). Mask is in small resolution.
orig_shape: Original shape of input data.
zoom: Usually number greater then 1
result = [[0 1 2],
[3 4 4],
[5 4 4]]
""" |
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 * mask_orig
inds_orig += np.max(inds_small_in_orig) + 1
# print 'indexes'
# import py3DSeedEditor as ped
# import pdb; pdb.set_trace() # BREAKPOINT
# '==' is not the same as 'is' for numpy.array
inds_small_in_orig[mask_orig == True] = inds_orig[mask_orig == True] # noqa
inds = inds_small_in_orig
# print np.max(inds)
# print np.min(inds)
inds = relabel_squeeze(inds)
logger.debug(
"Index after relabeling: %s", scipy.stats.describe(inds, axis=None)
)
# logger.debug("Minimal index after relabeling: " + str(np.min(inds)))
# inds_orig[mask_orig==True] = 0
# inds_small_in_orig[mask_orig==False] = 0
# inds = (inds_orig + np.max(inds_small_in_orig) + 1) + inds_small_in_orig
return inds, mask_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_val - min_val # .astype(np.int16)
if qt_app is None:
qt_app = QApplication(sys.argv)
pyed = QTSeedEditor(
self.img,
modeFun=self.interactivity_loop,
voxelSize=self.voxelsize,
seeds=self.seeds,
volume_unit=self.volume_unit,
)
pyed.changeC(window_c)
pyed.changeW(window_w)
qt_app.exec_() |
<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 before
:return:
""" |
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_graphcut",
"multiscale_gc",
"msgc",
"msgc_lo2hi",
"lo2hi",
"multiscale_graphcut_lo2hi",
):
logger.debug("performing multiscale Graph-Cut lo2hi")
self.__multiscale_gc_lo2hi_run()
elif self.segparams["method"].lower() in (
"msgc_hi2lo",
"hi2lo",
"multiscale_graphcut_hi2lo",
):
logger.debug("performing multiscale Graph-Cut hi2lo")
self.__multiscale_gc_hi2lo_run()
else:
logger.error("Unknown segmentation method: " + self.segparams["method"]) |
<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 graph cut tlinks based on image intensity
and texture.
""" |
# 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))) * 10
tdata2 = (-(self.mdl.likelihood_from_image(data, voxelsize, 2))) * 10
# to spare some memory
dtype = np.int16
if np.any(tdata1 > 32760):
dtype = np.float32
if np.any(tdata2 > 32760):
dtype = np.float32
if self.segparams["use_apriori_if_available"] and self.apriori is not None:
logger.debug("using apriori information")
gamma = self.segparams["apriori_gamma"]
a1 = (-np.log(self.apriori * 0.998 + 0.001)) * 10
a2 = (-np.log(0.999 - (self.apriori * 0.998))) * 10
# logger.debug('max ' + str(np.max(tdata1)) + ' min ' + str(np.min(tdata1)))
# logger.debug('max ' + str(np.max(tdata2)) + ' min ' + str(np.min(tdata2)))
# logger.debug('max ' + str(np.max(a1)) + ' min ' + str(np.min(a1)))
# logger.debug('max ' + str(np.max(a2)) + ' min ' + str(np.min(a2)))
tdata1u = (((1 - gamma) * tdata1) + (gamma * a1)).astype(dtype)
tdata2u = (((1 - gamma) * tdata2) + (gamma * a2)).astype(dtype)
tdata1 = tdata1u
tdata2 = tdata2u
# logger.debug(' max ' + str(np.max(tdata1)) + ' min ' + str(np.min(tdata1)))
# logger.debug(' max ' + str(np.max(tdata2)) + ' min ' + str(np.min(tdata2)))
# logger.debug('gamma ' + str(gamma))
# import sed3
# ed = sed3.show_slices(tdata1)
# ed = sed3.show_slices(tdata2)
del tdata1u
del tdata2u
del a1
del a2
# if np.any(tdata1 < 0) or np.any(tdata2 <0):
# logger.error("Problem with tlinks. Likelihood is < 0")
# if self.debug_images:
# self.__show_debug_tdata_images(tdata1, tdata2, suptitle="likelihood")
return tdata1, tdata2 |
<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,
hard_constraints,
)
# některém testu organ semgmentation dosahují unaries -15. což je podiné
# stačí vyhodit print před if a je to vidět
logger.debug("unaries %.3g , %.3g" % (np.max(unariesalt), np.min(unariesalt)))
# create potts pairwise
# pairwiseAlpha = -10
pairwise = -(np.eye(2) - 1)
pairwise = (self.segparams["pairwise_alpha"] * pairwise).astype(np.int32)
# pairwise = np.array([[0,30],[30,0]]).astype(np.int32)
# print pairwise
self.iparams = {}
if self.segparams["use_boundary_penalties"]:
sigma = self.segparams["boundary_penalties_sigma"]
# set boundary penalties function
# Default are penalties based on intensity differences
boundary_penalties_fcn = lambda ax: self._boundary_penalties_array(
axis=ax, sigma=sigma
)
else:
boundary_penalties_fcn = None
nlinks = self.__create_nlinks(
self.img, boundary_penalties_fcn=boundary_penalties_fcn
)
self.stats["tlinks shape"].append(unariesalt.reshape(-1, 2).shape)
self.stats["nlinks shape"].append(nlinks.shape)
# we flatten the unaries
# result_graph = cut_from_graph(nlinks, unaries.reshape(-1, 2),
# pairwise)
start = time.time()
if self.debug_images:
self._debug_show_unariesalt(unariesalt)
result_graph = pygco.cut_from_graph(nlinks, unariesalt.reshape(-1, 2), pairwise)
elapsed = time.time() - start
self.stats["gc time"] = elapsed
result_labeling = result_graph.reshape(self.img.shape)
return result_labeling |
<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. If there is only one small voxel in larger volume with zeros
it is selected.
""" |
# 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.shape) * 1.0 / zoom).astype(np.int)
loseeds = np.zeros(loshape, dtype=np.int8)
loseeds = loseeds.astype(np.int8)
for label in labels:
a, b, c = np.where(seeds == label)
loa = np.round(a // zoom)
lob = np.round(b // zoom)
loc = np.round(c // zoom)
# loseeds = np.zeros(loshape)
loseeds[loa, lob, loc] += label
# this is to detect conflict seeds
loseeds[loseeds > label] = 100
# remove conflict seeds
loseeds[loseeds > 99] = 0
# import py3DSeedEditor
# ped = py3DSeedEditor.py3DSeedEditor(loseeds)
# ped.show()
return loseeds |
<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 = np.zeros(shape, dtype=dtype)
shpmin = np.minimum(dataout.shape, shape)
dataout[: shpmin[0], : shpmin[1], : shpmin[2]] = datares[
: shpmin[0], : shpmin[1], : shpmin[2]
]
return datares |
<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 crinfo |
<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
:return:
""" |
# 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]) - margin[0]
y2 = np.max(nzi[1]) + margin[0] + 1
z1 = np.min(nzi[2]) - margin[0]
z2 = np.max(nzi[2]) + margin[0] + 1
# ošetření mezí polí
if x1 < 0:
x1 = 0
if y1 < 0:
y1 = 0
if z1 < 0:
z1 = 0
if x2 > data.shape[0]:
x2 = data.shape[0] - 1
if y2 > data.shape[1]:
y2 = data.shape[1] - 1
if z2 > data.shape[2]:
z2 = data.shape[2] - 1
# ořez
crinfo = [[x1, x2], [y1, y2], [z1, z2]]
return crinfo |
<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
[[minX, maxX],[minY, maxY],[minZ, maxZ]]. If crinfo is None, the whole input image is placed into [0, 0, 0].
If crinfo is just series of three numbers, it is used as an initial point for input image placement.
:param orig_shape: shape of uncropped image
:param resize: True or False (default). Usefull if the data.shape does not fit to crinfo shape.
:param outside_mode: 'constant', 'nearest'
:return:
""" |
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
# print orig_shape
# print data.shape
if resize:
data = resize_to_shape(data, crinfo[:, 1] - crinfo[:, 0])
startx = np.round(crinfo[0][0]).astype(int)
starty = np.round(crinfo[1][0]).astype(int)
startz = np.round(crinfo[2][0]).astype(int)
data_out[
# np.round(crinfo[0][0]).astype(int):np.round(crinfo[0][1]).astype(int)+1,
# np.round(crinfo[1][0]).astype(int):np.round(crinfo[1][1]).astype(int)+1,
# np.round(crinfo[2][0]).astype(int):np.round(crinfo[2][1]).astype(int)+1
startx : startx + data.shape[0],
starty : starty + data.shape[1],
startz : startz + data.shape[2],
] = data
if outside_mode == "nearest":
# for ax in range(data.ndims):
# ax = 0
# copy border slice to pixels out of boundary - the higher part
for ax in range(data.ndim):
# the part under the crop
start = np.round(crinfo[ax][0]).astype(int)
slices = [slice(None), slice(None), slice(None)]
slices[ax] = start
repeated_slice = np.expand_dims(data_out[slices], ax)
append_sz = start
if append_sz > 0:
tile0 = np.repeat(repeated_slice, append_sz, axis=ax)
slices = [slice(None), slice(None), slice(None)]
slices[ax] = slice(None, start)
# data_out[start + data.shape[ax] : , :, :] = tile0
data_out[slices] = tile0
# plt.imshow(np.squeeze(repeated_slice))
# plt.show()
# the part over the crop
start = np.round(crinfo[ax][0]).astype(int)
slices = [slice(None), slice(None), slice(None)]
slices[ax] = start + data.shape[ax] - 1
repeated_slice = np.expand_dims(data_out[slices], ax)
append_sz = data_out.shape[ax] - (start + data.shape[ax])
if append_sz > 0:
tile0 = np.repeat(repeated_slice, append_sz, axis=ax)
slices = [slice(None), slice(None), slice(None)]
slices[ax] = slice(start + data.shape[ax], None)
# data_out[start + data.shape[ax] : , :, :] = tile0
data_out[slices] = tile0
# plt.imshow(np.squeeze(repeated_slice))
# plt.show()
return data_out |
<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)
nedges_old = ncm1 * nr + nrm1 * nc
edges = nm.zeros((nedges, 2), dtype=nm.int16)
edge_dir = nm.zeros((ncm1 * nr + nrm1 * nc,), dtype=nm.bool)
nodes = nm.zeros((nm.prod(shape), 3), dtype=nm.float32)
# edges
idx = 0
row = nm.zeros((ncm1, 2), dtype=nm.int16)
row[:, 0] = nm.arange(ncm1)
row[:, 1] = nm.arange(ncm1) + 1
for ii in range(nr):
edges[slice(idx, idx + ncm1), :] = row + nc * ii
idx += ncm1
edge_dir[slice(0, idx)] = 0 # horizontal dir
idx0 = idx
col = nm.zeros((nrm1, 2), dtype=nm.int16)
col[:, 0] = nm.arange(nrm1) * nc
col[:, 1] = nm.arange(nrm1) * nc + nc
for ii in range(nc):
edges[slice(idx, idx + nrm1), :] = col + ii
idx += nrm1
edge_dir[slice(idx0, idx)] = 1 # vertical dir
# nodes
idx = 0
row = nm.zeros((nc, 3), dtype=nm.float32)
row[:, 0] = voxelsize[0] * (nm.arange(nc) + 0.5)
row[:, 1] = voxelsize[1] * 0.5
for ii in range(nr):
nodes[slice(idx, idx + nc), :] = row
row[:, 1] += voxelsize[1]
idx += nc
return nodes, edges, edge_dir |
<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_dimension = coors.shape[1]
self.nodes[idx, :right_dimension] = coors
self.node_flag[idx] = True
self.lastnode += nadd
self.nnodes += nadd |
<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 corresponding seed classes.
:param fv: ndarray with lineariezed feature. It's shape is MxN, where M is number of image pixels and N is number
of features
:param seeds: ndarray with seeds. Does not to be linear.
:param unique_cls: number of used seeds clases. Like [1, 2]
:return: fv, sd - selection from feature vector and selection from seeds or just fv for whole image
""" |
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', expression, result)
if is_number(result):
if result.isdigit():
self.logger.debug(' expand is integer !!!')
return int(result)
else:
self.logger.debug(' expand is float !!!')
return float(result)
return result |
<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.
Args:
alias (str or None): Name of the client. Used for caching.
If name is falsy then do not use the cache.
cache (dict): cache to store gutter managers in.
**kwargs: kwargs to be passed the Manger class.
Returns (Manager):
A gutter client.
""" |
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_context.divmod(Decimal('100.1'), 100)
>>> (Decimal('1'), Decimal('0.1'))
""" |
_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
to be enabled. Otherwise, *any* condition needs to be ``True`` for the
switch to be enabled.
The switch state is then checked to see if it is ``GLOBAL`` or
``DISABLED``. If it is not, then the switch is ``SELECTIVE`` and each
condition is checked.
Keyword Arguments:
inpt -- An instance of the ``Input`` class.
""" |
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 = ConditionsDict.from_conditions_list(self.conditions)
conditions = conditions_dict.get_by_input(inpt)
if conditions:
result = self.__enabled_func(
cond.call(inpt)
for cond
in conditions
if cond.argument(inpt).applies
)
else:
result = None
return signal_decorated(result) |
<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 ``False`` is returned. This also
applies to the ``NONE`` input.
Otherwise, ``argument`` is called, with ``inpt`` as the instance and
the value is compared to the ``operator`` and the Value is returned. If
the condition is ``negative``, then then ``not`` the value is returned.
Keyword Arguments:
inpt -- An instance of the ``Input`` class.
""" |
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 self.negative:
application = not application
return application |
<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 name.
Keyword Arguments:
name -- A name of a switch.
""" |
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)
switch.manager = self
return switch |
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>(<args>)
`args` can be as concrete as necessary. Often a catch-all is enough,
especially if you're working with strict mocks, bc they throw at call
time on unwanted, unconfigured arguments::
from mockito import ANY, ARGS, KWARGS
when(manager).add_tasks(1, 2, 3)
...
# no need to duplicate the specification; every other argument pattern
# would have raised anyway.
verify(manager).add_tasks(1, 2, 3) # duplicates `when`call
verify(manager).add_tasks(*ARGS)
verify(manager).add_tasks(...) # Py3
verify(manager).add_tasks(Ellipsis) # Py2
""" |
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 stubbed obj
theMock = _get_mock_or_raise(obj)
class Verify(object):
def __getattr__(self, method_name):
return invocation.VerifiableInvocation(
theMock, method_name, verification_fn)
return Verify() |
<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`` exposes a fluent interface
where you configure a stub in three steps::
when(<obj>).<method_name>(<args>).thenReturn(<value>)
Compared to simple *patching*, stubbing in mockito requires you to specify
conrete `args` for which the stub will answer with a concrete `<value>`.
All invocations that do not match this specific call signature will be
rejected. They usually throw at call time.
Stubbing in mockito's sense thus means not only to get rid of unwanted
side effects, but effectively to turn function calls into constants.
E.g.::
# Given ``dog`` is an instance of a ``Dog``
when(dog).bark('Grrr').thenReturn('Wuff')
when(dog).bark('Miau').thenRaise(TypeError())
# With this configuration set up:
assert dog.bark('Grrr') == 'Wuff'
dog.bark('Miau') # will throw TypeError
dog.bark('Wuff') # will throw unwanted interaction
Stubbing can effectively be used as monkeypatching; usage shown with
the `with` context managing::
with when(os.path).exists('/foo').thenReturn(True):
...
Most of the time verifying your interactions is not necessary, because
your code under tests implicitly verifies the return value by evaluating
it. See :func:`verify` if you need to, see also :func:`expect` to setup
expected call counts up front.
If your function is pure side effect and does not return something, you
can omit the specific answer. The default then is `None`::
when(manager).do_work()
`when` verifies the method name, the expected argument signature, and the
actual, factual arguments your code under test uses against the original
object and its function so its easier to spot changing interfaces.
Sometimes it's tedious to spell out all arguments::
from mockito import ANY, ARGS, KWARGS
when(requests).get('http://example.com/', **KWARGS).thenReturn(...)
when(os.path).exists(ANY)
when(os.path).exists(ANY(str))
.. note:: You must :func:`unstub` after stubbing, or use `with`
statement.
Set ``strict=False`` to bypass the function signature checks.
See related :func:`when2` which has a more pythonic interface.
""" |
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)
return When() |
<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` interface which exposes `thenReturn`,
`thenRaise`, and `thenAnswer` as usual. Always `strict`.
Usage::
# Given `dog` is an instance of a `Dog`
when2(dog.bark, 'Miau').thenReturn('Wuff')
.. note:: You must :func:`unstub` after stubbing, or use `with`
statement.
""" |
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 a `Dog`
expect(dog, times=1).bark('Wuff').thenReturn('Miau')
dog.bark('Wuff')
dog.bark('Wuff') # will throw at call time: too many invocations
# maybe if you need to ensure that `dog.bark()` was called at all
verifyNoUnwantedInteractions()
.. note:: You must :func:`unstub` after stubbing, or use `with`
statement.
See :func:`when`, :func:`when2`, :func:`verifyNoUnwantedInteractions`
""" |
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.StubbedInvocation(
theMock, method_name, verification=verification_fn,
strict=strict)
return Expect() |
<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 underlying registry will be cleaned.
After an `unstub` you can't :func:`verify` anymore because all
interactions will be forgotten.
""" |
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 ('monkeypatched' objects or modules) do not
support this functionality at all, bc only for the stubbed invocations
the actual usage gets recorded. So this function is of limited use,
nowadays.
""" |
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')
verifyNoUnwantedInteractions(os.path) # ok, called once
If you leave out the argument *all* registered objects will
be checked.
.. note:: **DANGERZONE**: If you did not :func:`unstub` correctly,
it is possible that old registered mocks, from other tests
leak.
See related :func:`expect`
""" |
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
to be invoked usually without arguments just before :func:`unstub`.
""" |
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("\nUnused stub: %s" % i) |
<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 for methods, for module wide,
globally declared names it must be considered experimental.
For all reasonable fn: ``getattr(*get_function_host(fn)) == fn``
Returns tuple (host, fn-name)
Otherwise should raise TypeError
""" |
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, because just specifying `os.path.exists` would be 'cool'.
#
# TLDR;:
# E.g. `inspect.getmodule(os.path.exists)` returns `genericpath` bc
# that's where `exists` is defined and comes from. But from the point
# of view of the user `exists` always comes and is used from `os.path`
# which points e.g. to `ntpath`. We thus must patch `ntpath`.
# But that's the same for most imports::
#
# # b.py
# from a import foo
#
# Now asking `getmodule(b.foo)` it tells you `a`, but we access and use
# `b.foo` and we therefore must patch `b`.
obj, name = find_invoking_frame_and_try_parse()
# safety check!
assert getattr(obj, name) == fn
return obj, name |
<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 returns the given input in case it is not a str.
Note: Relative imports not supported.
Raises ImportError or AttributeError as appropriate.
""" |
# 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], parts[1:]
obj = importlib.import_module(head)
# Normally a simple reduce, but we go the extra mile
# for good exception messages.
for i, name in enumerate(tail):
try:
obj = getattr(obj, name)
except AttributeError:
# Note the [:i] instead of [:i+1], so we get the path just
# *before* the AttributeError, t.i. the part of it that went ok.
module = '.'.join([head] + tail[:i])
try:
importlib.import_module(module)
except ImportError:
raise AttributeError(
"object '%s' has no attribute '%s'" % (module, name))
else:
raise AttributeError(
"module '%s' has no attribute '%s'" % (module, name))
return obj |
<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`.
The *returned* object must be injected and used by the code under test;
after that all interactions can be verified as usual.
T.i. the original object **will not be patched**, and has no further
knowledge as before.
E.g.::
import time
time = spy(time)
# inject time
do_work(..., time)
verify(time).time()
""" |
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)
def __repr__(self):
name = 'Spied'
if class_:
name += class_.__name__
return "<%s id=%s>" % (name, id(self))
obj = Spy()
theMock = Mock(obj, strict=True, spec=object)
mock_registry.register(obj, theMock)
return obj |