0%

Codewars - Theme 1 Fundamental

0. Introduction

Learning by Doing : It’s highly efficient to train your programming skills every day.

1. Duplicate Encoder

1.1. Description

The goal of this exercise is to convert a string to a new string where each character in the new string is:

  • “(“ if that character appears only once in the original string.
  • “)” if that character appears more than once in the original string.
  • Ignore capitalization when determining if a character is a duplicate.

1.2. Examples

1
2
3
4
"din"      =>  "((("
"recede" => "()()()"
"Success" => ")())())"
"(( @" => "))(("

1.3. My Solution

1
2
3
4
5
6
7
8
9
10
11
12
def duplicate_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] == 1 else ')' for character in word])
return result

1.4. Excellent Solution

1
2
def duplicate_encode(word):
return "".join(["(" if word.lower().count(c) == 1 else ")" 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.

2.2. Examples

1
2
3
"is2 Thi1s T4est 3a"  -->  "Thi1s is2 3a T4est"
"4of Fo1r pe6ople g3ood th5e the2" --> "Fo1r the2 g3ood 4of th5e pe6ople"
"" --> ""

2.3. My Solution

1
2
3
4
5
6
7
8
def order(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

2.4. Excellent Solution

1
2
def order(sentence):
return ' '.join(sorted(sentence.split(), key=sorted))

3. Grasshopper - Summation

3.1. Description

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


def summation(num):
return reduce(lambda x, y: x + y, range(num+1))

3.4. Excellent Solution

1
2
3
4
5
6
7
def summation(num):
return sum(range(num + 1))

------

def summation(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
def find_even_index(arr):
arr.insert(0, 0)
arr_len = len(arr)
# Compare the summation from left and side with index
index = [i for i in range(0, arr_len) if sum(arr[:i]) == sum(arr[i+1:])]
if index and index[0] > 0:
return index[0] - 1
elif not index:
return -1
else:
return index[0]

4.4. Excellent Solution

1
2
3
4
5
6
7
def find_even_index(arr):
for i in range(len(arr)):
if sum(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
def disemvowel(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

5.4. Excellent Solution

1
2
3
def disemvowel(string):
new_string = string.translate(str.maketrans('','','aeiouAEIOU'))
return new_string

6. Complementary DNA

6.1. Description

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).

6.2. Examples

1
2
DNA_strand ("ATTGC") # return "TAACG"
DNA_strand ("GTAT") # return "CATA"

6.3. My Solution

1
2
3
def dna_strand(dna):
complementary_dna = dna.translate(str.maketrans('ATCG', 'TAGC'))
return complementary_dna

6.4. Excellent Solution

1
2
3
4
5
6
7
8
#(1)
def DNA_strand(dna):
return dna.translate(string.maketrans("ATCG","TAGC"))

#(2)
pairs = {'A':'T','T':'A','C':'G','G':'C'}
def DNA_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)

7.2. Examples

1
2
3
4
Test.assert_equals(tribonacci([1,1,1],10),[1,1,1,3,5,9,17,31,57,105])
Test.assert_equals(tribonacci([0,0,0],10),[0,0,0,0,0,0,0,0,0,0])
Test.assert_equals(tribonacci([1,1,1],1),[1])
Test.assert_equals(tribonacci([300,200,100],0),[])

7.3. My Solution

1
2
3
def tribonacci(signature, n):
[signature.append(sum(signature[-3:])) for i in range(3, n)]
return signature[:n]

7.4. Excellent Solution

1
2
3
4
5
6
7
8
9
10
11
12
#(1)
def tribonacci(signature, n):
res = signature[:n]
for i in range(n - 3): res.append(sum(res[-3:]))
return res

#(2)
def tribonacci(signature,n):
while len(signature) < n:
signature.append(sum(signature[-3:]))

return signature[:n]

8. Fibonacci, Tribonacci and friends

8.1. Description

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.

1
2
3
4
xbonacci {1,1,1,1} 10 = {1,1,1,1,4,7,13,25,49,94}
xbonacci {0,0,0,0,1} 10 = {0,0,0,0,1,1,2,4,8,16}
xbonacci {1,0,0,0,0,0,1} 10 = {1,0,0,0,0,0,1,2,3,6}
xbonacci {1,1} produces the Fibonacci sequence

8.3. My Solution

1
2
3
4
def Xbonacci(signature, n):
length = len(signature)
[signature.append(sum(signature[-length:])) for i in range(length, n)]
return signature[:n]

8.4. Excellent Solution

1
2
3
4
5
def Xbonacci(signature,n):
output, x = signature[:n], len(signature)
while len(output) < n:
output.append(sum(output[-x:]))
return output

9. Product of consecutive Fib numbers

9.1. Description

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
def productFib(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.

queue_time([2,3,10], 2)
# should return 12

10.3. My Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
def queue_time(customers, n):
# in case the empty customers
customers.append(0)
t = 0
# the number of customer <= the number of tills
if len(customers) <= n:
longest_time = max(customers)
else:
# initialize a "Double Dimensional Array":[[], [], ...]
till = [[] for i in range(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
def queue_time(customers, n):
l=[0]*n
for i in customers:
l[l.index(min(l))]+=i
return max(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…

11.3. My Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# number
def zero(*args):
length = len(args)
if length == 0:
return '0'
elif length == 1:
args[0].insert(0, '0')
return eval(" ".join(args[0]))


def one(*args):
length = len(args)
if length == 0:
return '1'
elif length == 1:
args[0].insert(0, '1')
return eval(" ".join(args[0]))


def two(*args):
length = len(args)
if length == 0:
return '2'
elif length == 1:
args[0].insert(0, '2')
return eval(" ".join(args[0]))


def three(*args):
length = len(args)
if length == 0:
return '3'
elif length == 1:
args[0].insert(0, '3')
return eval(" ".join(args[0]))


def four(*args):
length = len(args)
if length == 0:
return '4'
elif length == 1:
args[0].insert(0, '4')
return eval(" ".join(args[0]))


def five(*args):
length = len(args)
if length == 0:
return '5'
elif length == 1:
args[0].insert(0, '5')
return eval(" ".join(args[0]))


def six(*args):
length = len(args)
if length == 0:
return '6'
elif length == 1:
args[0].insert(0, '6')
return eval(" ".join(args[0]))


def seven(*args):
length = len(args)
if length == 0:
return '7'
elif length == 1:
args[0].insert(0, '7')
return eval(" ".join(args[0]))


def eight(*args):
length = len(args)
if length == 0:
return '8'
elif length == 1:
args[0].insert(0, '8')
return eval(" ".join(args[0]))


def nine(*args):
length = len(args)
if length == 0:
return '9'
elif length == 1:
args[0].insert(0, '9')
return eval(" ".join(args[0]))


# mathematical operations
def plus(*args):
return ["+", args[0]]


def minus(*args):
return ["-", args[0]]


def times(*args):
return ["*", args[0]]


def divided_by(*args):
return ["//", args[0]]

11.4. Excellent Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# (1)
def zero(f = None): return 0 if not f else f(0)
def one(f = None): return 1 if not f else f(1)
def two(f = None): return 2 if not f else f(2)
def three(f = None): return 3 if not f else f(3)
def four(f = None): return 4 if not f else f(4)
def five(f = None): return 5 if not f else f(5)
def six(f = None): return 6 if not f else f(6)
def seven(f = None): return 7 if not f else f(7)
def eight(f = None): return 8 if not f else f(8)
def nine(f = None): return 9 if not f else f(9)

def plus(y): return lambda x: x+y
def minus(y): return lambda x: x-y
def times(y): return lambda x: x*y
def divided_by(y): return lambda x: x/y

# (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

# (3)
def zero(arg=""): return eval("0" + arg)
def one(arg=""): return eval("1" + arg)
def two(arg=""): return eval("2" + arg)
def three(arg=""): return eval("3" + arg)
def four(arg=""): return eval("4" + arg)
def five(arg=""): return eval("5" + arg)
def six(arg=""): return eval("6" + arg)
def seven(arg=""): return eval("7" + arg)
def eight(arg=""): return eval("8" + arg)
def nine(arg=""): return eval("9" + arg)

def plus(n): return "+%s" % n
def minus(n): return "-%s" % n
def times(n): return "*%s" % n
def divided_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
def prime_factors(n):
prime_list = []
for i in range(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
def primeFactors(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 > 1 else '')
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.

13.2. Examples

1
2
group([3, 2, 6, 2, 1, 3])
>>> [[3, 3], [2, 2], [6], [1]]

13.3. My Solution

1
2
3
def group(arr):
counted_dict = Counter(arr)
return [list(itertools.repeat(element[0], element[1])) for element in counted_dict.items()]

13.4. Excellent Solution

1
2
3
4
from collections import Counter

def group(arr):
return [[k] * n for k, n in Counter(arr).items()]

14. ToDo

14.1. Description

14.2. Examples

1
2
3
4
```
## 14.3. My Solution
```Python

14.4. Excellent Solution

1