defduplicate_encode(word): # Ignore capitalization word = word.lower() # Get all the character, remove duplication all_character = set(word) # Count the number of each character num_iter = map(lambda character: word.count(character), all_character) # Use a dict to store character:num dic = dict(zip(all_character, num_iter)) # Replace word with )/( result = "".join(['('if dic[character] == 1else')'for character in word]) return result
1.4. Excellent Solution
1 2
defduplicate_encode(word): return"".join(["("if word.lower().count(c) == 1else")"for c in word.lower()])
2. Your order, please
2.1. Description
Your task is to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result.
Numbers can be from 1 to 9. So 1 will be the first word (not 0).
If the input string is empty, return an empty string.
The words in the input String will only contain valid consecutive numbers.
deforder(sentence): # Transform str to list, split by space word_list = sentence.split(" ") # Extract the number of each word and make tuple, then Sort it sorted_list = sorted([(character, word) for word in word_list for character in word if character.isdigit()]) # Make the new string result = " ".join([item[1] for item in sorted_list]) return result
Write a program that finds the summation of every number from 1 to num. The number will always be a positive integer greater than 0.
3.2. Examples
1 2 3 4 5
summation(2) -> 3 1 + 2
summation(8) -> 36 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8
3.3. My Solution
1 2 3 4 5
from functools import reduce
defsummation(num): return reduce(lambda x, y: x + y, range(num+1))
3.4. Excellent Solution
1 2 3 4 5 6 7
defsummation(num): returnsum(range(num + 1))
------
defsummation(num): return (1+num) * num / 2
4. Equal Sides Of An Array
4.1. Description
You are going to be given an array of integers. Your job is to take that array and find an index N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N. If there is no index that would make this happen, return -1. Note: If you are given an array with multiple answers, return the lowest correct index.
4.2. Examples
1 2 3
{1,2,3,4,3,2,1} -> N==3, {1,2,3} -- {3,2,1}, both equal 6. {1,100,50,-51,1,1} -> N==1, {1} -- {50,-51,1,1}, both euqal 1. {20,10,-80,10,10,15,35} -> N==0, {} -- {10,-80,10,10,15,35}, both equal 0.
4.3. My Solution
1 2 3 4 5 6 7 8 9 10 11
deffind_even_index(arr): arr.insert(0, 0) arr_len = len(arr) # Compare the summation from left and side with index index = [i for i inrange(0, arr_len) ifsum(arr[:i]) == sum(arr[i+1:])] if index and index[0] > 0: return index[0] - 1 elifnot index: return -1 else: return index[0]
4.4. Excellent Solution
1 2 3 4 5 6 7
deffind_even_index(arr): for i inrange(len(arr)): ifsum(arr[:i]) == sum(arr[i+1:]): return i return -1
#Has a bug when meet the list like [10,-10] or [10,-80,10,10,15,35] and so on.
5. Disemvowel Trolls
5.1. Description
Trolls are attacking your comment section! A common way to deal with this situation is to remove all of the vowels from the trolls’ comments, neutralizing the threat.
Your task is to write a function that takes a string and return a new string with all vowels removed.
Note: for this kata y isn’t considered a vowel.
5.2. Examples
1 2 3 4
The string: "This website is for losers LOL!" would become -> "Ths wbst s fr lsrs LL!".
5.3. My Solution
1 2 3 4 5 6
defdisemvowel(string): vowel = 'aAeEiIoOuU' sentence_list = list(string) [sentence_list.remove(character) for character in string if character in vowel] new_string = "".join(sentence_list) return new_string
Deoxyribonucleic acid (DNA) is a chemical found in the nucleus of cells and carries the “instructions” for the development and functioning of living organisms. In DNA strings, symbols “A” and “T” are complements of each other, as “C” and “G”. You have function with one side of the DNA (string, except for Haskell); you need to get the other complementary side. DNA strand is never empty or there is no DNA at all (again, except for Haskell).
#(2) pairs = {'A':'T','T':'A','C':'G','G':'C'} defDNA_strand(dna): return''.join([pairs[x] for x in dna])
7. Tribonacci Sequence
7.1. Description
Well met with Fibonacci bigger brother, AKA Tribonacci. As the name may already reveal, it works basically like a Fibonacci, but summing the last 3 (instead of 2) numbers of the sequence to generate the next. Signature will always contain 3 numbers; n will always be a non-negative number; if n == 0, then return an empty array (except in C return NULL)
Well, time to expand the family a little more: think of a Quadribonacci starting with a signature of 4 elements and each following element is the sum of the 4 previous, a Pentabonacci (well Cinquebonacci would probably sound a bit more italian, but it would also sound really awful) with a signature of 5 elements and each following element is the sum of the 5 previous, and so on.
8.2. Examples
Well, guess what? You have to build a Xbonacci function that takes a signature of X elements - and remember each next element is the sum of the last X elements - and returns the first n elements of the so seeded sequence.
The Fibonacci numbers : F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1. Given a number, say prod (for product), we search two Fibonacci numbers F(n) and F(n+1) verifying:
1 2 3 4
if F(n) * F(n+1) = prod: return [F(n), F(n+1), true] or {F(n), F(n+1), 1} or (F(n), F(n+1), True) elif F(n) * F(n+1) > prod: return [F(n), F(n+1), false] or {F(n), F(n+1), 0} or (F(n), F(n+1), False)
9.2. Examples
1 2 3 4 5 6 7 8
productFib(714) # should return (21, 34, true), # since F(8) = 21, F(9) = 34 and 714 = 21 * 34
productFib(800) # should return (34, 55, false), # since F(8) = 21, F(9) = 34, F(10) = 55 and 21 * 34 < 800 < 34 * 55 ----- productFib(714) # should return [21, 34, true/True/1], productFib(800) # should return [34, 55, false/False/0],
9.3. My Solution
1 2 3 4 5
defproductFib(prod): a, b = 0, 1 while a * b < prod: a, b = b, a + b return [a, b, a * b == prod]
10. The Supermarket Queue
10.1. Description
There is a queue for the self-checkout tills at the supermarket. Your task is write a function to calculate the total time required for all the customers to check out! input:
customers: an array of positive integers representing the queue. Each integer represents a customer, and its value is the amount of time they require to check out.
n: a positive integer, the number of checkout tills. output:
The function should return an integer, the total time required. Clarifications:
There is only ONE queue serving many tills, and
The order of the queue NEVER changes, and
The front person in the queue (i.e. the first element in the array/list) proceeds to a till as soon as it becomes free.
10.2. Examples
1 2 3 4 5 6 7 8 9 10 11
queue_time([5,3,4], 1) # should return 12 # because when n=1, the total time is just the sum of the times
queue_time([10,2,3,3], 2) # should return 10 # because here n=2 and the 2nd, 3rd, and 4th people in the # queue finish before the 1st person has finished.
defqueue_time(customers, n): # in case the empty customers customers.append(0) t = 0 # the number of customer <= the number of tills iflen(customers) <= n: longest_time = max(customers) else: # initialize a "Double Dimensional Array":[[], [], ...] till = [[] for i inrange(n)] # fill the array by customers for customer in customers[:n]: till[t].append(customer) t += 1 # the next customer always after the shortest time in the array for customer in customers[n:]: till = sorted(till, key=sum) till[0].append(customer) till = sorted(till, key=sum) longest_time = sum(till[-1]) return longest_time
10.4. Excellent Solution
1 2 3 4 5
defqueue_time(customers, n): l=[0]*n for i in customers: l[l.index(min(l))]+=i returnmax(l)
11. Calculating with Functions
11.1. Description
This time we want to write calculations using functions and get the results.
11.2. Examples
1 2 3 4
seven(times(five())) # must return 35 four(plus(nine())) # must return 13 eight(minus(three())) # must return 5 six(divided_by(two())) # must return 3
Requirements:
There must be a function for each number from 0 (“zero”) to 9 (“nine”)
There must be a function for each of the following mathematical operations: plus, minus, times, dividedBy (divided_by in Ruby and Python)
Each calculation consist of exactly one operation and two numbers
The most outer function represents the left operand, the most inner function represents the right operand
Divison should be integer division. For example, eight(divided_by(three())) should return 2, not 2.666666…
# (2) id_ = lambda x: x number = lambda x: lambda f=id_: f(x) zero, one, two, three, four, five, six, seven, eight, nine = map(number, range(10)) plus = lambda x: lambda y: y + x minus = lambda x: lambda y: y - x times = lambda x: lambda y: y * x divided_by = lambda x: lambda y: y / x
defplus(n):return"+%s" % n defminus(n):return"-%s" % n deftimes(n):return"*%s" % n defdivided_by(n):return"/%s" % n
12. Primes in numbers
12.1. Description
Given a positive number n > 1 find the prime factor decomposition of n.
12.2. Examples
1 2 3 4 5
# formula "(p1**n1)(p2**n2)...(pk**nk)"
# example n = 86240 should return "(2**5)(5)(7**2)(11)"
12.3. My Solution
1 2 3 4 5 6 7 8 9 10 11 12 13
defprime_factors(n): prime_list = [] for i inrange(2, n+1): num = 0 while n % i == 0: num += 1 n /= i if num == 1: prime_list.append('(' + str(i) + ')') elif num > 1: prime_list.append('(' + str(i)+'**'+str(num) + ')') if n % i == n: return"".join(prime_list)
12.4. Excellent Solution
1 2 3 4 5 6 7 8 9 10 11
defprimeFactors(n): ret = '' for i in xrange(2, n + 1): num = 0 while(n % i == 0): num += 1 n /= i if num > 0: ret += '({}{})'.format(i, '**%d' % num if num > 1else'') if n == 1: return ret
13. Organise duplicate numbers in list
13.1. Description
Given an array of numbers, your function should return an array of arrays, where each subarray contains all the duplicates of a particular number. Subarrays should be in the same order as the first occurence of the number they contain.