Wednesday, November 9, 2022

List Functions and Examples in Python

 

Function Operation Example
list.append(x) Append x to end of the list >>> list=[1,2,3]
>>> list.append(4)
>>> print(list)
[1, 2, 3, 4]
list.count(x) Count the no of x >>> list.count(1)
1
list.index(x) Return the index of x >>> list.index(2)
1
list.insert(i,x) Insert x before index  i >>> list.insert(1,5)
>>> print(list)
[1, 5, 2, 3, 4]
1
list.pop(i) Remove and return the item at index i >>> list.pop(3)
3
list.remove(x) Remove x from the list >>> list.remove(5)
>>> print(list)
[1, 2, 4]
list.reverse() Reverse the sequence of list >>> list.reverse()
>>> print(list)
[4, 2, 1]
list.sort() Sort the elements in list >>> list.sort()
>>> print(list)
[1, 2, 4]
list.extend(x) Appends the contents of x to list >>> x=[7,8,9]
>>> list.extend(x)
>>> print(list)
[1, 2, 4, 7, 8, 9]
len(list) Return the length of list >>> print(len(list))
6
max(list) Return the max from the list >>> print(max(list))
9
min(list) Return the min from the list >>> print(min(list))
1
Read more ...

Saturday, April 23, 2022

Turn with a Compass Python Codewars

Task:

You have an 8-wind compass, like this:

You receive the direction you are facing (one of the 8 directions: N, NE, E, SE, S, SW, W, NW) and a certain degree to turn (a multiple of 45, between -1080 and 1080); positive means clockwise, and negative means counter-clockwise.

Return the direction you will face after the turn.

Examples

"S",  180  -->  "N"
"SE", -45  -->  "E"
"W",  495  -->  "NE"

Solution:



def direction(facing, turn):
    dir = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW']
    turns = turn//45
    start_idx = dir.index(facing)
    end_idx = (turns+start_idx) % 8
    return dir[end_idx]

print(direction('SE', -45))

Turn with a Compass Solutions | Codewars

Read more ...

Wednesday, April 20, 2022

Fibonacci Python Codewars

Task:

Create function fib that returns n'th element of Fibonacci sequence (classic programming task).

Solution:


def fibonacci(n: int) -> int:
    x, y = 0, 1
    for i in range(n):
        x, y = y, y + x
    return x

print(fibonacci(34))

Fibonacci Solutions | Codewars

Read more ...

Tuesday, April 19, 2022

Find the vowels Python Codewars

Task:

We want to know the index of the vowels in a given word, for example, there are two vowels in the word super (the second and fourth letters).

So given a string "super", we should return a list of [2, 4].

Some examples:
Mmmm  => []
Super => [2,4]
Apple => [1,5]
YoMama -> [1,2,4,6]
NOTES
  • Vowels in this context refers to: a e i o u y (including upper case)
  • This is indexed from [1..n] (not zero indexed!)

Solution:


def vowel_indices(word):
    vowels='aeiouy'
    res=[]
    for n,c in enumerate(word, start=1):
        if c.lower() in vowels:
            res.append(n)
    return res

print(vowel_indices("apple"))

Training on Find the vowels | Codewars

Read more ...

Monday, April 18, 2022

Barista Problem Python Codewars

Task:

Given a list of the times you need to brew each coffee, return the minimum total waiting time.

  • If you have three customers with times [4,3,2], the first customer is going to wait 4 minutes for his coffee, the second customer is going to wait 4 minutes (the time needed for the first customer to get his coffee), another 2 minutes (the time needed to clean the machine) and 3 more minutes (the time you need to brew his coffee), so in total 9 minutes. The third customer, by the same logic, is about to wait 9 minutes (for the first two customers) + 2 more minutes(cleaning) + 2 minutes (his coffee brewing time). This order of brewing the coffee will end up in a total waiting time of 26 minutes, but note that this may not be the minimum time needed. This time depends on the order you choose to brew the cups of coffee.

  • The order in which you brew the coffee is totally up to you.

  • coffees = [3,2,5,10,9]  ->  85
    coffees = [20,5]        ->  32
    coffees = [4,3,2]       ->  22

Solution:


def barista(coffees):
    time, total = 0, 0
    for e in sorted(coffees):
        time += e
        total += time
        time += 2
    return total

print(barista([20,5]))

Barista problem Solutions | Codewars

Read more ...

Sunday, April 17, 2022

Alphabet symmetry Python Codewars

Task:

Consider the word "abode". We can see that the letter a is in position 1 and b is in position 2. In the alphabet, a and b are also in positions 1 and 2. Notice also that d and e in abode occupy the positions they would occupy in the alphabet, which are positions 4 and 5.

Given an array of words, return an array of the number of letters that occupy their positions in the alphabet for each word. For example,

solve(["abode","ABc","xyzD"]) = [4, 3, 1]

See test cases for more examples.

Input will consist of alphabet characters, both uppercase and lowercase. No spaces.

Solution:


def solve(arr):
    alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    nums = range(1,27)
    alpha_dict = dict(zip(alphabet, nums))
    res  = []
    
    for i in arr:
        count = 0
        for n, c in enumerate(i, start=1):
            print(i.index(c)+1)
            if n == alpha_dict.get(c.upper()):
                count += 1
        res.append(count)
    return res

print(solve(["IAMDEFANDJKL","thedefgh","xyzDEFghijabc"]))

Alphabet symmetry Solutions | Codewars
Read more ...

Wednesday, April 13, 2022

Filter unused digits Python Codewars

Task:

Given a varying number of integer arguments, return the digits that are not present in any of them.

Example:

[12, 34, 56, 78]  =>  "09"
[2015, 8, 26]     =>  "3479"

Note: the digits in the resulting string should be sorted.

Solution:


def unused_digits(*args):
    digits='0123456789'
    return "".join(n for n in digits if n not in str(args))


print(unused_digits(12, 34, 56, 78))

Filter unused digits Solutions | Codewars

Read more ...

Friday, April 8, 2022

Playing with passphrases Python Codewars

Task:

Everyone knows passphrases. One can choose passphrases from poems, songs, movies names and so on but frequently they can be guessed due to common cultural references. You can get your passphrases stronger by different means. One is the following:

choose a text in capital letters including or not digits and non alphabetic characters,

  1. shift each letter by a given number but the transformed letter must be a letter (circular shift),
  2. replace each digit by its complement to 9,
  3. keep such as non alphabetic and non digit characters,
  4. downcase each letter in odd position, upcase each letter in even position (the first character is in position 0),
  5. reverse the whole result.
Example:

your text: "BORN IN 2015!", shift 1

1 + 2 + 3 -> "CPSO JO 7984!"

4 "CpSo jO 7984!"

5 "!4897 Oj oSpC"

With longer passphrases it's better to have a small and easy program. Would you write it

Solution:


def play_pass(s, n):
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    output = ''
    for i, char in enumerate(s):
        if char.isalpha():
            indx = alphabet.index(char.lower()) 
            new_char = alphabet[(indx+n)%26]
            if i % 2 == 0:
                new_char = new_char.upper()
        elif char.isdigit():
            new_char = str(9-int(char))
        else:
            new_char = char
        output += new_char
    return output[::-1]

print(play_pass("I LOVE YOU!!!", 1))

Training on Playing with passphrases | Codewars

Read more ...

Thursday, April 7, 2022

Number-Star ladder Python Codewars

Task:

Using n as a parameter in the function pattern, where n>0, complete the codes to get the pattern (take the help of examples):

Note: There is no newline in the end (after the pattern ends)

Examples

pattern(3) should return "1\n1*2\n1**3", e.g. the following:

1
1*2
1**3

pattern(10): should return the following:

1
1*2
1**3
1***4
1****5
1*****6
1******7
1*******8
1********9
1*********10

Solution:


def pattern(n):
    res = []
    for i in range(0,n):
        j = i+1
        if j > 1:
            res.append('1'+'*'*i+str(j))
        else:
            res.append(str(j))
    return '\n'.join(res)
    
print(pattern(5))

Number-Star ladder Solutions | Codewars

Read more ...

Wednesday, April 6, 2022

Sort two arrays Python Codewars

Task:

Description:

Give you two arrays arr1 and arr2. They have the same length(length>=2). The elements of two arrays always be integer.

Sort arr1 according to the ascending order of arr2; Sort arr2 according to the ascending order of arr1. Description is not easy to understand, for example:

arr1=[5,4,3,2,1], 
arr2=[6,5,7,8,9]

Let us try to sorting arr1. First, we need know the ascending order of arr2:

[5,6,7,8,9]

We can see, after sort arr2 to ascending order, some elements' index are changed:

unsort arr2      ascending order arr2
[6,5,7,8,9]--->      [5,6,7,8,9]

index0(6)  --->      index1
index1(5)  --->      index0
index2(7)            index2(no change)
index3(8)            index3(no change)
index4(9)            index4(no change)

So, wo need according to these changes to sorting arr1:

unsort arr1          sorted arr1
[5,4,3,2,1]--->      [4,5,3,2,1]

index0(5)  --->      index1
index1(4)  --->      index0
index2(3)            index2(no change)
index3(2)            index3(no change)
index4(1)            index4(no change)

So: sorted arr1= [4,5,3,2,1]

And then, we sorting arr2 with the same process:

unsort arr1      ascending order arr1
[5,4,3,2,1]--->      [1,2,3,4,5]

index0(5)  --->      index4
index1(4)  --->      index3
index2(3)            index2(no change)
index3(2)  --->      index1
index4(1)  --->      index0

unsort arr2          sorted arr2
[6,5,7,8,9]--->      [9,8,7,5,6]

index0(6)  --->      index4
index1(5)  --->      index3
index2(7)            index2(no change)
index3(8)  --->      index1
index4(9)  --->      index0

So: sorted arr2= [9,8,7,5,6]

Finally, returns the sorted arrays by a 2D array: [sorted arr1, sorted arr2]

Note: In ascending order sorting process(not the final sort), if some elements have same value, sort them according to their index; You can modify the original array, but I advise you not to do that. ;-)

Some Examples and explain
sortArrays([5,4,3,2,1],[6,5,7,8,9]) should return
[[4,5,3,2,1],[9,8,7,5,6]]

sortArrays([2,1,3,4,5],[5,6,7,8,9]) should return
[[2,1,3,4,5],[6,5,7,8,9]]

sortArrays([5,6,9,2,6,5],[3,6,7,4,8,1]) should return
[[5,5,2,6,9,6],[4,3,1,6,8,7]]

Solution:


def sort_two_arrays(arr1, arr2):
    a1 = sorted((x, i) for i, x in enumerate(arr1))
    a2 = sorted((x, i) for i, x in enumerate(arr2))
    return [[arr1[i] for i in [x[1] for x in a2]], [arr2[i] for i in [x[1] for x in a1]]]

print(sort_two_arrays([5,4,3,2,1], [6,5,7,8,9]))

Sort two arrays Solutions | Codewars

Read more ...

Monday, April 4, 2022

Matrix Transpose Python Codewars

Task:

Write a function that outputs the transpose of a matrix - a new matrix where the columns and rows of the original are swapped.

For example, the transpose of:

| 1 2 3 |
| 4 5 6 |

is

| 1 4 |
| 2 5 |
| 3 6 |

The input to your function will be an array of matrix rows. You can assume that each row has the same length, and that the height and width of the matrix are both positive.

Solution:


def transpose(matrix):
    return [list(x) for x in zip(*matrix)]

print(transpose([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))

Matrix Transpose Solutions | Codewars

Read more ...

Sunday, April 3, 2022

How Green Is My Valley? Python Codewars

Task:

  • Input : an array of integers.

  • Output : this array, but sorted in such a way that there are two wings:

  • the left wing with numbers decreasing,

  • the right wing with numbers increasing.

  • the two wings have the same length. If the length of the array is odd the wings are around the bottom, if the length is even the bottom is considered to be part of the right wing.

  • each integer l of the left wing must be greater or equal to its counterpart r in the right wing, the difference l - r being as small as possible. In other words the right wing must be nearly as steep as the left wing.

The function is make_valley or makeValley or make-valley.

a = [79, 35, 54, 19, 35, 25]
make_valley(a) --> [79, 35, 25, *19*, 35, 54]
The bottom is 19, left wing is [79, 35, 25], right wing is [*19*, 35, 54].
79..................54
    35..........35
        25. 
          ..19

Solution:


def make_valley(arr):
    lst = sorted(arr)
    if len(lst)% 2 == 1:
        center = [lst.pop(0)]
    else:
        center = []
    left = []
    right = []
    for idx in range(0,len(lst)):
        if idx % 2 == 0:
            right.append(lst[idx])
        else:
            left.append(lst[idx])
    left.sort(reverse=True)
    return left + center + right

print(make_valley([17, 17, 15, 14, 8, 7, 7, 5, 4, 4, 1]))

How Green Is My Valley? Solutions | Codewars

Read more ...

Saturday, April 2, 2022

Follow the spy Python Codewars

Task

You are given an array of routes of his itineraries. List down the only places where he will go in correct order based on his itineraries.

Example

Given the following routes:

[ [USA, BRA], [JPN, PHL], [BRA, UAE], [UAE, JPN] ]

The result will be:

"USA, BRA, UAE, JPN, PHL"

Note:

  • It is safe to assume that there will be no repeating place with a different route.
  • There are no empty routes.
  • There will be at least one (1) route (from one waypoint to another).

Solution:


def find_routes(routes):
    routes = dict(routes)
    places = list(routes.keys() - routes.values()) # Get the starting element for route
    try:
        for place in places:
            places.append(routes[place])
    finally:
        return ', '.join(places)

print(find_routes([('ITA','GER'), ('GER','BEL'), ('BEL','CAN')]))   

Follow that Spy Solutions | Codewars

Read more ...

Friday, April 1, 2022

Rectangle into Squares Python Codewars

Task:

The drawing below gives an idea of how to cut a given "true" rectangle into squares ("true" rectangle meaning that the two dimensions are different).

alternative text

Can you translate this drawing into an algorithm?

You will be given two dimensions

  1. a positive integer length
  2. a positive integer width

You will return a collection or a string (depending on the language; Shell bash, PowerShell, Pascal and Fortran return a string) with the size of each of the squares.

Examples in general form:

(depending on the language)

  sqInRect(5, 3) should return [3, 2, 1, 1]
  sqInRect(3, 5) should return [3, 2, 1, 1]
  
  You can see examples for your language in **"SAMPLE TESTS".**

Solution:


def sqInRect(a, b):
    if a == b:
        return None
    res = []
    while b:
        b, a = sorted([a, b])
        res += [b]
        a, b = b, a-b    
    return res

print(sqInRect(5,3))

Rectangle into Squares Solutions | Codewars

Read more ...

Thursday, March 31, 2022

Fibonacci, Tribonacci and friends Python Codewars

Task:

If you have completed the Tribonacci sequence kata, you would know by now that mister Fibonacci has at least a bigger brother. If not, give it a quick look to get how things work.

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.

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.

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

Solution:


def Xbonacci(signature,n):
    res = signature[:n]
    for i in range(n - len(signature)): 
	res.append(sum(res[-len(signature):]))
    return res

print(Xbonacci([1,0,0,0,0,0,0,0,0,0],20))

Fibonacci, Tribonacci and friends Solutions | Codewars

Read more ...

Wednesday, March 30, 2022

Salesman's Travel Python Codewars

Task:

A traveling salesman has to visit clients. He got each client's address e.g. "432 Main Long Road St. Louisville OH 43071" as a list.

The basic zipcode format usually consists of two capital letters followed by a white space and five digits. The list of clients to visit was given as a string of all addresses, each separated from the others by a comma, e.g. :

"123 Main Street St. Louisville OH 43071,432 Main Long Road St. Louisville OH 43071,786 High Street Pollocksville NY 56432".

To ease his travel he wants to group the list by zipcode.

Task

The function travel will take two parameters r (addresses' list of all clients' as a string) and zipcode and returns a string in the following format:

zipcode:street and town,street and town,.../house number,house number,...

The street numbers must be in the same order as the streets where they belong.

If a given zipcode doesn't exist in the list of clients' addresses return "zipcode:/"

Examples
r = "123 Main Street St. Louisville OH 43071,432 Main Long Road St. Louisville OH 43071,786 High Street Pollocksville NY 56432"

travel(r, "OH 43071") --> "OH 43071:Main Street St. Louisville,Main Long Road St. Louisville/123,432"

travel(r, "NY 56432") --> "NY 56432:High Street Pollocksville/786"

travel(r, "NY 5643") --> "NY 5643:/"

Solution:


def travel(r, zipcode):  # #2
    streets = []
    houses = []
    addresses = r.split(",")
    for x in addresses:
        if " ".join(x.split()[-2:]) == zipcode:
            streets.append(" ".join(x.split()[1:-2]))
            houses += x.split()[:1]
    return zipcode + ':' + ','.join(streets) + '/' + ','.join(houses)

ad = ("123 Main Street St. Louisville OH 43071,432 Main Long Road St. Louisville OH 43071,786 High Street Pollocksville NY 56432,"
  "54 Holy Grail Street Niagara Town ZP 32908,3200 Main Rd. Bern AE 56210,1 Gordon St. Atlanta RE 13000,"
  "10 Pussy Cat Rd. Chicago EX 34342,10 Gordon St. Atlanta RE 13000,58 Gordon Road Atlanta RE 13000,"
  "22 Tokyo Av. Tedmondville SW 43098,674 Paris bd. Abbeville AA 45521,10 Surta Alley Goodtown GG 30654,"
  "45 Holy Grail Al. Niagara Town ZP 32908,320 Main Al. Bern AE 56210,14 Gordon Park Atlanta RE 13000,"
  "100 Pussy Cat Rd. Chicago EX 34342,2 Gordon St. Atlanta RE 13000,5 Gordon Road Atlanta RE 13000,"
  "2200 Tokyo Av. Tedmondville SW 43098,67 Paris St. Abbeville AA 45521,11 Surta Avenue Goodtown GG 30654,"
  "45 Holy Grail Al. Niagara Town ZP 32918,320 Main Al. Bern AE 56215,14 Gordon Park Atlanta RE 13200,"
  "100 Pussy Cat Rd. Chicago EX 34345,2 Gordon St. Atlanta RE 13222,5 Gordon Road Atlanta RE 13001,"
  "2200 Tokyo Av. Tedmondville SW 43198,67 Paris St. Abbeville AA 45522,11 Surta Avenue Goodville GG 30655,"
  "2222 Tokyo Av. Tedmondville SW 43198,670 Paris St. Abbeville AA 45522,114 Surta Avenue Goodville GG 30655,"
  "2 Holy Grail Street Niagara Town ZP 32908,3 Main Rd. Bern AE 56210,77 Gordon St. Atlanta RE 13000")

print(travel(ad, "AA 45522"))

 

Salesman's Travel Solutions | Codewars

Read more ...

Tuesday, March 29, 2022

Valid Braces Python Codewars

Task:

Write a function that takes a string of braces, and determines if the order of the braces is valid. It should return true if the string is valid, and false if it's invalid.

This Kata is similar to the Valid Parentheses Kata, but introduces new characters: brackets [], and curly braces {}. Thanks to @arnedag for the idea!

All input strings will be nonempty, and will only consist of parentheses, brackets and curly braces: ()[]{}.

What is considered Valid?

A string of braces is considered valid if all braces are matched with the correct brace.

Examples

"(){}[]"   =>  True
"([{}])"   =>  True
"(}"       =>  False
"[(])"     =>  False
"[({})](]" =>  False

Solution:


def valid_braces(s):
  while '{}' in s or '()' in s or '[]' in s:
      s=s.replace('{}','')
      s=s.replace('[]','')
      s=s.replace('()','')
  return s==''

print(valid_braces('[{()]'))

Valid Braces Solutions | Codewars

Read more ...

Sunday, March 27, 2022

Numerical Palindrome #1.5 Python Codewars

Task:

A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are:

2332
110011
54322345

You'll be given 2 numbers as arguments: (num,s). Write a function which returns an array of s number of numerical palindromes that come after num. If num is a palindrome itself, it should be included in the count.

Return "Not valid" instead if any one of the inputs is not an integer or is less than 0.

For this kata, single digit numbers will NOT be considered numerical palindromes.

palindrome(6,4) => [11,22,33,44]
palindrome(59,3) => [66,77,88]
palindrome(101,2) => [101,111]
palindrome("15651",5) => "Not valid" 
palindrome(1221,"8") => "Not valid" 

Solution:


def palindrome(num,s):
    if not (type(num) == type(s) == int) or num < 0 or s < 0:
        return 'Not valid'
    
    res = []
    num = max(num, 11)
    while len(res) != s:
        if str(num) == str(num)[::-1]:
            res.append(num)
        num += 1
    return res

print(palindrome(6,4))

Numerical Palindrome #1.5 Solutions | Codewars

Read more ...

Saturday, March 26, 2022

Nice Array Python Codewars

Task:

A Nice array is defined to be an array where for every value n in the array, there is also an element n - 1 or n + 1 in the array.

examples:

[2, 10, 9, 3] is a nice array because

 2 =  3 - 1
10 =  9 + 1
 3 =  2 + 1
 9 = 10 - 1

[4, 2, 3] is a nice array because

4 = 3 + 1
2 = 3 - 1
3 = 2 + 1 (or 3 = 4 - 1)

[4, 2, 1] is a not a nice array because

for n = 4, there is neither n - 1 = 3 nor n + 1 = 5

Write a function named isNice/IsNice that returns true if its array argument is a Nice array, else false. An empty array is not considered nice.

Solution:


def is_nice(arr):
    for x in arr:
        if x + 1 not in arr and x - 1 not in arr:
            return False
    return True and len(arr) > 0

print(is_nice([2,10,9,3]))

Training on Nice Array | Codewars

Read more ...

Determine the date by the day number Python Codewars

Task:

What date corresponds to the nth day of the year?
The answer depends on whether the year is a leap year or not.

Write a function that will help you determine the date if you know the number of the day in the year, as well as whether the year is a leap year or not.
The function accepts the day number and a boolean value isLeap as arguments, and returns the corresponding date of the year as a string "Month, day".
Only valid combinations of a day number and isLeap will be tested.

Examples:
* With input `41, false` => return "February, 10"
* With input `60, false` => return "March, 1
* With input `60, true` => return "February, 29"
* With input `365, false` => return "December, 31"
* With input `366, true` => return "December, 31"

Solution:


def get_day(days, is_leap): 
    calendar = {
        "January": 31,
        "February": 28+(1 if is_leap else 0),
        "March": 31,
        "April": 30,
        "May": 31,
        "June": 30,
        "July": 31,
        "August": 31,
        "September": 30,
        "October": 31,
        "November": 30,
        "December": 31
      }
    for month in calendar:
        if days <= calendar[month]:
            return f'{month}, {days}'
        days -= calendar[month]

print(get_day(62,1))

Training on Determine the date by the day number | Codewars

Read more ...

Thursday, March 24, 2022

Case swapping Python Codewars

Task:

Given a string, swap the case for each of the letters.

e.g. CodEwArs --> cODeWaRS

Examples
""           ->   ""
"CodeWars"   ->   "cODEwARS"
"abc"        ->   "ABC"
"ABC"        ->   "abc"
"123235"     ->   "123235"

Solution:


def swap(string_):
    new = ''
    for i in string_:
        if i.islower():
            i = i.upper()
        else:
            i = i.lower()
        new += ''.join(i)
            
    return new

print(swap('HelloWorld'))
Training on Case swapping | Codewars
Read more ...

Take a Ten Minute Walk Python Codewars

Task:

You live in the city of Cartesia where all roads are laid out in a perfect grid. You arrived ten minutes too early to an appointment, so you decided to take the opportunity to go for a short walk. The city provides its citizens with a Walk Generating App on their phones -- everytime you press the button it sends you an array of one-letter strings representing directions to walk (eg. ['n', 's', 'w', 'e']). You always walk only a single block for each letter (direction) and you know it takes you one minute to traverse one city block, so create a function that will return true if the walk the app gives you will take you exactly ten minutes (you don't want to be early or late!) and will, of course, return you to your starting point. Return false otherwise.

Solution:


def is_valid_walk(walk):
    if (walk.count('n') == walk.count('s') and 
        walk.count('e') == walk.count('w') and
        len(walk) == 10):
            return True
    return False

print(is_valid_walk(['w','e','w','e','w','e','w','e','w','e','w','e']))

Take a Ten Minute Walk Solutions | Codewars

Read more ...

Wednesday, March 23, 2022

Sequence classifier Python Codewars

A series or sequence of numbers is usually the product of a function and can either be infinite or finite.

Task:

In this kata we will only consider finite series and you are required to return a code according to the type of sequence:

Code Example

0 unordered [3,5,8,1,14,3]

1 strictly increasing [3,5,8,9,14,23]

2 not decreasing [3,5,8,8,14,14]

3 strictly decreasing [14,9,8,5,3,1]

4 not increasing [14,14,8,8,5,3]

5 constant [8,8,8,8,8,8]

You can expect all the inputs to be non-empty and completely numerical arrays/lists - no need to validate the data; do not go for sloppy code, as rather large inputs might be tested.

Solution:


def sequence_classifier(arr):
    if len(set(arr)) == 1: return 5
    elif sorted(arr) == arr and len(arr) == len(set(arr)): return 1
    elif sorted(arr) == arr: return 2
    elif sorted(arr[::-1]) == arr[::-1] and len(arr) == len(set(arr)): return 3
    elif sorted(arr[::-1]) == arr[::-1]: return 4
    else: return 0

print(sequence_classifier([3,5,8,8,14,23]))

Sequence classifier Solutions | Codewars

Read more ...

Tuesday, March 22, 2022

Sum of Digits / Digital Root Python Codewars

Task:

Digital root is the recursive sum of all the digits in a number.

Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. The input will be a non-negative integer.

Examples

    16  -->  1 + 6 = 7
   942  -->  9 + 4 + 2 = 15  -->  1 + 5 = 6
132189  -->  1 + 3 + 2 + 1 + 8 + 9 = 24  -->  2 + 4 = 6
493193  -->  4 + 9 + 3 + 1 + 9 + 3 = 29  -->  2 + 9 = 11  -->  1 + 1 = 2

Solution:


def digital_root(n):
    return n if n < 10 else digital_root(sum(map(int,str(n))))

print(digital_root(493193))

Training on Sum of Digits / Digital Root | Codewars

Read more ...

Monday, March 21, 2022

Checkerboard Resolution Python Codewars

Task

In this kata we will be counting the the black squares on a special checkerboard. It is special because it has a resolution which determines how the black and white squares are laid out.

The resolution refers to the dimensions of squares of a single colour. See below for an example with dimensions 11x6:

With resolution = 1:

Number of black squares = 33

And now with resolution = 2:

Number of black squares = 32

And one more example, resolution = 5:

Number of black squares = 31

Credit to awesomead for the pretty images!

As you may have noticed the top left square is always white, and we are counting the INDIVIDUAL black squares on the board.

Task

You are required to write a function that will take in three parameters:

  • width -> The width of the board
  • height -> The height of the board
  • resolution -> The size of the coloured squares on the checkerboard (as shown above)

And returns the total count of all individual black squares.

Additional Info
  • All inputs will be valid
  • 0 <= width <= 10**32
  • 0 <= height <= 10**32
  • 1 <= resolution <= 10**32

Solution:


def count_checkerboard(width, height, resolution):
    p = resolution * 2
    sw = width // p * resolution + min(width % p, resolution)
    print(sw)
    sh = height // p * resolution + min(height % p, resolution)
    print(sh)
    return (width - sw) * sh + sw * (height - sh)

print(count_checkerboard(9, 5, 2))

Training on Checkerboard Resolution | Codewars

Read more ...

Sunday, March 20, 2022

Repeated Substring Python Codewars

Task:

For a given nonempty string s find a minimum substring t and the maximum number k, such that the entire string s is equal to t repeated k times.

The input string consists of lowercase latin letters.

Your function should return :

  • a tuple (t, k) (in Python)
  • an array [t, k] (in Ruby and JavaScript)
  • in C, return k and write to the string t passed in parameter

Example #1:

for string

s = "ababab";

the answer is

("ab", 3)

Example #2:

for string

s = "abcde"

the answer is

("abcde", 1)

because for this string "abcde" the minimum substring t, such that s is t repeated k times, is itself.

Solution:


def f(s):
    for i in range(1, len(s) + 1):
        t, k = s[:i], int(len(s) / i)
        if t * k == s:
            return (t, k)

print(f("efefef"))

Repeated Substring Solutions | Codewars

Read more ...

Saturday, March 19, 2022

How many pages in a book? Python Codewars

Task:

Every book has n amount of pages. You will be given the summary which was made by adding up the number of digits contained in each page number in a book(from 1 to n). The task is to find how many pages a book has- n.

Example

When input is 25 (summary). The output must be 17(n). There are 9 one-digit pages and 8 two-digit pages(8 ones and 8 digits from 0 to 7)

Be aware that you'll get enormous books having up to 100.000 pages.

All input will be valid

Solution:


def amount_of_pages(summary):
    pages = 0
    page_num = 1
    while summary > 0:
        print(summary)
        summary -= len(str(page_num))
        pages += 1
        page_num += 1
    return pages

print(amount_of_pages(25))

Training on How many pages in a book? | Codewars

Read more ...

Friday, March 18, 2022

Find the smallest Python Codewars

Task:

Return an array or a tuple or a string depending on the language (see "Sample Tests") with

    1. the smallest number you got
    1. the index i of the digit d you took, i as small as possible
    1. the index j (as small as possible) where you insert this digit d to have the smallest number.
Examples:
smallest(261235) --> [126235, 2, 0] or (126235, 2, 0) or "126235, 2, 0"

126235 is the smallest number gotten by taking 1 at index 2 and putting it at index 0

smallest(209917) --> [29917, 0, 1] or ...

[29917, 1, 0] could be a solution too but index `i` in [29917, 1, 0] is greater than 
index `i` in [29917, 0, 1].

29917 is the smallest number gotten by taking 2 at index 0 and putting it at index 1 which gave 029917 which is the number 29917.

smallest(1000000) --> [1, 0, 6] or ...

Solution:


def smallest(n):
    m = n
    s = str(n)
    rg = range(len(s))
    for i in rg:
        for j in rg:
            li = list(s)
            d = li.pop(i)
            li.insert(j, d)
            z = int(''.join(li))
            if z < m:
                m = z
                x = i
                y = j
    return [m, x, y]

print(smallest(261235))

Find the smallest Solutions | Codewars

Read more ...

Thursday, March 17, 2022

Rainfall Python Codewars

Task:

  • function: mean(town, strng) should return the average of rainfall for the city town and the strng data or data1 (In R and Julia this function is called avg).
  • function: variance(town, strng) should return the variance of rainfall for the city town and the strng data or data1.

Examples:

mean("London", data), 51.19(9999999999996) 
variance("London", data), 57.42(833333333374)

Solution:


import statistics
import re

def get_records(town, strng):
    for line in strng.split('\n'):
        if line.startswith(town + ':'):
            return [float(i) for i in re.findall('\d+\.\d+', line)]

def mean(town, strng):
    x = get_records(town, strng)
    return statistics.mean(x) if x else -1


def variance(town, strng):
    x = get_records(town, strng)
    return statistics.pvariance(x) if x else -1
   


data = """Rome:Jan 81.2,Feb 63.2,Mar 70.3,Apr 55.7,May 53.0,Jun 36.4,Jul 17.5,Aug 27.5,Sep 60.9,Oct 117.7,Nov 111.0,Dec 97.9
London:Jan 48.0,Feb 38.9,Mar 39.9,Apr 42.2,May 47.3,Jun 52.1,Jul 59.5,Aug 57.2,Sep 55.4,Oct 62.0,Nov 59.0,Dec 52.9
Paris:Jan 182.3,Feb 120.6,Mar 158.1,Apr 204.9,May 323.1,Jun 300.5,Jul 236.8,Aug 192.9,Sep 66.3,Oct 63.3,Nov 83.2,Dec 154.7
NY:Jan 108.7,Feb 101.8,Mar 131.9,Apr 93.5,May 98.8,Jun 93.6,Jul 102.2,Aug 131.8,Sep 92.0,Oct 82.3,Nov 107.8,Dec 94.2
Vancouver:Jan 145.7,Feb 121.4,Mar 102.3,Apr 69.2,May 55.8,Jun 47.1,Jul 31.3,Aug 37.0,Sep 59.6,Oct 116.3,Nov 154.6,Dec 171.5
Sydney:Jan 103.4,Feb 111.0,Mar 131.3,Apr 129.7,May 123.0,Jun 129.2,Jul 102.8,Aug 80.3,Sep 69.3,Oct 82.6,Nov 81.4,Dec 78.2
Bangkok:Jan 10.6,Feb 28.2,Mar 30.7,Apr 71.8,May 189.4,Jun 151.7,Jul 158.2,Aug 187.0,Sep 319.9,Oct 230.8,Nov 57.3,Dec 9.4
Tokyo:Jan 49.9,Feb 71.5,Mar 106.4,Apr 129.2,May 144.0,Jun 176.0,Jul 135.6,Aug 148.5,Sep 216.4,Oct 194.1,Nov 95.6,Dec 54.4
Beijing:Jan 3.9,Feb 4.7,Mar 8.2,Apr 18.4,May 33.0,Jun 78.1,Jul 224.3,Aug 170.0,Sep 58.4,Oct 18.0,Nov 9.3,Dec 2.7
Lima:Jan 1.2,Feb 0.9,Mar 0.7,Apr 0.4,May 0.6,Jun 1.8,Jul 4.4,Aug 3.1,Sep 3.3,Oct 1.7,Nov 0.5,Dec 0.7"""


print(mean('Tokyo', data))
print(variance('Lima', data))

Training on Rainfall | Codewars

Read more ...

Deal a Shuffled Deck of Cards Python Codewars

Task:

A normal deck of 52 playing cards contains suits 'H', 'C', 'D', 'S' - Hearts, Clubs, Diamonds, Spades respectively - and cards with values from Ace (1) to King (13): 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13

Complete the function that returns a shuffled deck of 52 playing cards without repeats.

Each card should have format "{suit} {value}", e.g. the Queen of Hearts is "H 12" and the Ace of Spades is "S 1". The order of the cards must be different each time the function is called.

Solution:


from random import shuffle

def shuffled_deck():
    num_list = list(range(1,14))
    alpha_list = ['H','C','D','S']
    deck = []
    for x in alpha_list:
        for y in num_list:
            deck.append(x+' '+str(y))
    shuffle(deck)
    return deck



def shuffled_deck():
    deck = [f'{x} {i}' for x in "HCDS" for i in range(1, 14)]
    shuffle(deck)
    return deck

print(shuffled_deck())

Deal a Shuffled Deck of Cards Solutions | Codewars

Read more ...

Wednesday, March 16, 2022

Sort the inner content in descending order Python Codewars

Task:

You have to sort the inner content of every word of a string in descending order.

The inner content is the content of a word without first and the last char.

Some examples:

"sort the inner content in descending order"  -->  "srot the inner ctonnet in dsnnieedcg oredr"
"wait for me"        -->  "wiat for me"
"this kata is easy"  -->  "tihs ktaa is esay"

Words are made up of lowercase letters and are separated by a single space. There will be no leading/trailing spaces.

Solution:


def sort_the_inner_content(str):
    words = str.split()
    output = []
    
    for word in words:
        if len(word) > 2:
            output.append(word[0] + ''.join(sorted(word[1:-1], reverse=True)) + word[-1])            
        else: output.append(word)
        
    return ' '.join(output)
print(sort_the_inner_content('sort the inner content i descending order'))

Training on Srot the inner ctonnet in dsnnieedcg oredr | Codewars

Read more ...

Most Frequent Weekdays Python Codewars

Task:

You are given a year as integer (e. g. 2001). You should return the most frequent day(s) of the week in that year. The result has to be a list of days sorted by the order of days in week (e. g. ['Monday', 'Tuesday'], ['Saturday', 'Sunday'], ['Monday', 'Sunday']). Week starts with Monday.

Input: Year as an int.

Output: The list of most frequent days sorted by the order of days in week (from Monday to Sunday).

Preconditions:

  • Week starts on Monday.
  • Year is between 1583 and 4000.
  • Calendar is Gregorian.
Examples (input -> output):
* 2427 -> ['Friday']
* 2185 -> ['Saturday']
* 2860 -> ['Thursday', 'Friday']

Solution:


from calendar import weekday, day_name

def most_frequent_days(year):
    print(sorted( {weekday(year, 1, 1), weekday(year, 12, 31)} ))
    for day in sorted( {weekday(year, 1, 1), weekday(year, 12, 31)} ):
        return [ day_name[day]  ]

print(most_frequent_days(2023))

Most Frequent Weekdays Solutions | Codewars

Read more ...

Tuesday, March 15, 2022

Explosive Sum Python Codewars

Task

How many ways can you make the sum of a number?

From wikipedia: https://en.wikipedia.org/wiki/Partition_(number_theory)#

In number theory and combinatorics, a partition of a positive integer n, also called an integer partition, is a way of writing n as a sum of positive integers. Two sums that differ only in the order of their summands are considered the same partition. If order matters, the sum becomes a composition. For example, 4 can be partitioned in five distinct ways:

4
3 + 1
2 + 2
2 + 1 + 1
1 + 1 + 1 + 1

Examples

Basic
exp_sum(1) # 1
exp_sum(2) # 2  -> 1+1 , 2
exp_sum(3) # 3 -> 1+1+1, 1+2, 3
exp_sum(4) # 5 -> 1+1+1+1, 1+1+2, 1+3, 2+2, 4
exp_sum(5) # 7 -> 1+1+1+1+1, 1+1+1+2, 1+1+3, 1+2+2, 1+4, 5, 2+3

exp_sum(10) # 42
Explosive
exp_sum(50) # 204226
exp_sum(80) # 15796476
exp_sum(100) # 190569292

Solution:



def exp_sum(n):
    if n < 0:
        return 0
    dp = [1]+[0]*n
    for num in range(1,n+1):
        for i in range(num,n+1):
            dp[i] += dp[i-num]
    return dp[-1]

print(exp_sum(10))

Explosive Sum Solutions | Codewars

Read more ...

Monday, March 14, 2022

String Mix Python Codewars

Task:

The task is to produce a string in which each lowercase letters of s1 or s2 appears as many times as its maximum if this maximum is strictly greater than 1; these letters will be prefixed by the number of the string where they appear with their maximum value and :. If the maximum is in s1 as well as in s2 the prefix is =:.

In the result, substrings (a substring is for example 2:nnnnn or 1:hhh; it contains the prefix) will be in decreasing order of their length and when they have the same length sorted in ascending lexicographic order (letters and digits - more precisely sorted by codepoint); the different groups will be separated by '/'. See examples and "Example Tests".

Hopefully other examples can make this clearer.

s1 = "my&friend&Paul has heavy hats! &"
s2 = "my friend John has many many friends &"
mix(s1, s2) --> "2:nnnnn/1:aaaa/1:hhh/2:mmm/2:yyy/2:dd/2:ff/2:ii/2:rr/=:ee/=:ss"

s1 = "mmmmm m nnnnn y&friend&Paul has heavy hats! &"
s2 = "my frie n d Joh n has ma n y ma n y frie n ds n&"
mix(s1, s2) --> "1:mmmmmm/=:nnnnnn/1:aaaa/1:hhh/2:yyy/2:dd/2:ff/2:ii/2:rr/=:ee/=:ss"

s1="Are the kids at home? aaaaa fffff"
s2="Yes they are here! aaaaa fffff"
mix(s1, s2) --> "=:aaaaaa/2:eeeee/=:fffff/1:tt/2:rr/=:hh"

Solution:


def mix(s1, s2):
    s = []
    lett = "abcdefghijklmnopqrstuvwxyz"
    for ch in lett:
        val1, val2 = s1.count(ch), s2.count(ch)
        if max(val1, val2) >= 2:
            if val1 > val2: s.append("1:"+val1*ch)
            elif val1 < val2: s.append("2:"+val2*ch)
            else: s.append("=:"+val1*ch)
            
    s.sort()
    s.sort(key=len, reverse=True)
    return "/".join(s)
    

print(mix("Are they here", "yes, they are here"))

Strings Mix Solutions | Codewars

Read more ...

Largest pair sum in array Python Codewars

Task:

Given a sequence of numbers, find the largest pair sum in the sequence.

For example

[10, 14, 2, 23, 19] -->  42 (= 23 + 19)
[99, 2, 2, 23, 19]  --> 122 (= 99 + 23)

Input sequence contains minimum two elements and every element is an integer.

Solution:


def largest_pair_sum(nums):
    sort_list = sorted(nums)
    return sum(sort_list[-2:])

print(largest_pair_sum([10,14,2,23,19]))

Training on Largest pair sum in array | Codewars

Read more ...

Sunday, March 13, 2022

Parts of a list Python Codewars

Task:

Write a function partlist that gives all the ways to divide a list (an array) of at least two elements into two non-empty parts.

  • Each two non empty parts will be in a pair (or an array for languages without tuples or a structin C - C: see Examples test Cases - )
  • Each part will be in a string
  • Elements of a pair must be in the same order as in the original array.
Examples of returns in different languages:
a = ["az", "toto", "picaro", "zone", "kiwi"] -->
[["az", "toto picaro zone kiwi"], ["az toto", "picaro zone kiwi"], ["az toto picaro", "zone kiwi"], ["az toto picaro zone", "kiwi"]] 
or
 a = {"az", "toto", "picaro", "zone", "kiwi"} -->
{{"az", "toto picaro zone kiwi"}, {"az toto", "picaro zone kiwi"}, {"az toto picaro", "zone kiwi"}, {"az toto picaro zone", "kiwi"}}
or
a = ["az", "toto", "picaro", "zone", "kiwi"] -->
[("az", "toto picaro zone kiwi"), ("az toto", "picaro zone kiwi"), ("az toto picaro", "zone kiwi"), ("az toto picaro zone", "kiwi")]
or 
a = [|"az", "toto", "picaro", "zone", "kiwi"|] -->
[("az", "toto picaro zone kiwi"), ("az toto", "picaro zone kiwi"), ("az toto picaro", "zone kiwi"), ("az toto picaro zone", "kiwi")]
or
a = ["az", "toto", "picaro", "zone", "kiwi"] -->
"(az, toto picaro zone kiwi)(az toto, picaro zone kiwi)(az toto picaro, zone kiwi)(az toto picaro zone, kiwi)"

Solution:


def partlist(arr):
    return [(" ".join(arr[:i]), " ".join(arr[i:])) for i in range(1, len(arr))]
        

print(partlist(["I", "wish", "I", "hadn't", "come"]))

Training on Parts of a list | Codewars

Read more ...

Saturday, March 12, 2022

The Coupon Code Python Codewars

Task

Your mission:
Write a function called checkCoupon which verifies that a coupon code is valid and not expired.

A coupon is no more valid on the day AFTER the expiration date. All dates will be passed as strings in this format: "MONTH DATE, YEAR".

Examples:

checkCoupon("123", "123", "July 9, 2015", "July 9, 2015")  == True
checkCoupon("123", "123", "July 9, 2015", "July 2, 2015")  == False

Solution:


import datetime
def check_coupon(entered_code, correct_code, current_date, expiration_date):
    if entered_code is correct_code:
        return(datetime.datetime.strptime(current_date,'%B %d, %Y') <= datetime.datetime.strptime(expiration_date,'%B %d, %Y'))
    return False

The Coupon Code Solutions | Codewars

Read more ...

Friday, March 11, 2022

Training on Battle of the characters Python Codewars

Task:

Groups of characters decided to make a battle. Help them to figure out what group is more powerful. Create a function that will accept 2 variables and return the one who's stronger.

Rules
  • Each character has its own power:
      A = 1, B = 2, ... Y = 25, Z = 26
      a = 0.5, b = 1, ... y = 12.5, z = 13
    
  • Only alphabetical characters can and will participate in a battle.
  • Only two groups to a fight.
  • Group whose total power (a + B + c + ...) is bigger wins.
  • If the powers are equal, it's a tie.
Examples
"One", "Two"  -->  "Two"
"ONE", "NEO"  -->  "Tie!"

Solution:


def battle(x,y):
    NUM = 26
    num_list = list(range(1,NUM+1))
    alpha_list = [chr(c) for c in list(range(ord('A'),ord('Z')+1))]
    my_dict = dict(zip(alpha_list, num_list))
    sum_x, sum_y = 0,0
    for c in x:
        if c.islower():
            sum_x += my_dict.get(c.upper())/2
        else:
            sum_x += my_dict.get(c)
    sum_x = sum_x
    for c in y:
        if c.islower():
            sum_y += my_dict.get(c.upper())/2
        else:
            sum_y += my_dict.get(c)
    sum_y = sum_y
    if sum_x == sum_y:
        return 'Tie!'
    elif sum_x > sum_y:
        return x
    else:
        return y    

def battle(x: str, y: str) -> str:
    first = sum(ord(char)%64 if char.isupper() else .5*(ord(char)%96) for char in x)
    second = sum(ord(char)%64 if char.isupper() else .5*(ord(char)%96) for char in y)
    
    return x if first > second else y if first < second else "Tie!"


print(battle('Hi', 'AB'))

Training on Battle of the characters (Medium) | Codewars

Read more ...

Find the first non-consecutive number Python Codewars

Task:

Your task is to find the first element of an array that is not consecutive.

By not consecutive we mean not exactly 1 larger than the previous element of the array.

E.g. If we have an array [1,2,3,4,6,7,8] then 1 then 2 then 3 then 4 are all consecutive but 6 is not, so that's the first non-consecutive number.

If the whole array is consecutive then return null2.

The array will always have at least 2 elements1 and all elements will be numbers. The numbers will also all be unique and in ascending order. The numbers could be positive or negative and the first non-consecutive could be either too!

Solution:


def first_non_consecutive(arr):
    prev = arr[0]
    first = None
    for num in arr[1:]:
        if (prev + 1) != num:
            first = num
            break
        prev += 1
    return first


print(first_non_consecutive([1,2,3,5,6,7,8]))


Find the first non-consecutive number Solutions | Codewars

Read more ...

Thursday, March 10, 2022

bread sandwiches Python Codewars

Task:

If you're not familiar with the fantastic culinary delights of the British Isles you may not know about the bread sandwich.

The idea is very simple - if you have a slice of bread between two other slices of bread, then it's a bread sandwich. Additionally, if you have a bread sandwich between two other slices of bread, you get a bread sandwich sandwich, and so on.

In this kata, we will define the following terms like so:

  • Sandwich - Two slices of bread which may or may not have a filling
  • Bread Sandwich - Two slices of bread which contains one slice of bread in the middle as a filling

You will need to build two functions:

  • Given the number of slices of bread, return the phrase used to refer to the sandwich
     2 - 'sandwich'
     5 - 'bread sandwich sandwich'
    
  • The reverse function - given the name of the sandwich, return how many slices of bread there are in the sandwich
    'bread sandwich' - 3
    'sandwich sandwich' - 4
    
  • You should return None if there is no input / the input is invalid / there is no sandwich

Solution:


def slices_to_name(n):
    res = ''
    if type(n) != int or n < 2:
        return None
    if n >= 2:
        if n % 2 == 0:
            res += 'sandwich '* int(n/2)
        else:
            res += 'bread sandwich ' + 'sandwich '* int((n - 3)/2)
    return res.rstrip(' ')

def name_to_slices(name):
    print(name)
    if type(name) != str or name == '':
        return None
    name_s = name.split()
    if len(name_s) == 1 and name_s[0] == 'sandwich':
        return 2
    elif len(name_s) == 2:
        if name_s[0] == 'bread' and name_s[1] == 'sandwich':
            return 3
        elif name_s[0] == 'sandwich' and name_s[1] == 'sandwich':
            return 4
    elif len(name_s) > 2:
        if 'bread' in name_s[2:]:
            return None
        elif name_s[0] == 'bread' and name_s[1] == 'sandwich':
            return 3 + (len(name_s[2:])*2 )
        elif name_s[0] == 'sandwich' and name_s[1] == 'sandwich':
            return 4 + (len(name_s[2:])*2)

    else:
        return None

def slices_to_name(n):
    return (('bread '*(n%2) + 'sandwich '*(n//2)).strip() if isinstance(n, int) and n > 1 else None)

def name_to_slices(name):
    if not (isinstance(name, str) and 'sandwich' in name): return

    if name.find('bread') < 1:
        return name.count('sandwich')*2 + name.count('bread')

bread sandwiches Solutions | Codewars

Read more ...

Wednesday, March 9, 2022

IP Address to Number Python Codewars

Task:

An IPv4 address is a 32-bit number that identifies a device on the internet.

While computers read and write IP addresses as a 32-bit number, we prefer to read them in dotted-decimal notation, which is basically the number split into 4 chunks of 8 bits, converted to decimal, and delmited by a dot.

In this kata, you will create the function ipToNum that takes an ip address and converts it to a number, as well as the function numToIp that takes a number and converts it to an IP address string. Input will always be valid.

Conversion Example

//original IP address
192.168.1.1

//breaks down into 4 binary octets
11000000 . 10101000 . 00000001 . 00000001

//which are merged together (unsigned 32-bit binary)
11000000101010000000000100000001

//and finally converted to base 10
3232235777
ipToNum
ipToNum('192.168.1.1') //returns 3232235777
ipToNum('10.0.0.0') //returns 167772160
ipToNum('176.16.0.1') //returns 2953838593
numToIp
numToIp(3232235777) //returns '192.168.1.1'
numToIp(167772160) //returns '10.0.0.0'
numToIp(2953838593) //returns '176.16.0.1'

Solution:


def ip_to_num(ip):
    b = ''
    for i in ip.split('.'):
        b += format(int(i), "08b")
    return int(b,2)

def num_to_ip(num):
    binary = bin(num).lstrip('0b').zfill(32)
    ip=[]
    for i in range(0, len(binary), 8):
        octet = binary[i:i+8]
        ip.append(str(int(str(octet),2)))
    return '.'.join((ip))

print(ip_to_num('176.16.0.1'))
print(num_to_ip(2953838593))

Training on IP Address to Number | Codewars

Read more ...

How to delete placement groups using aws command line

To delete placement groups from aws, you can use the aws command line to get the list and delete in a loop. Below, I am filtering based on the group name using a wildcard.


group_del_list=$(aws ec2 describe-palcement-groups --filters Name='group-name',Values='some-app*' | jq --raw-output .PlacementGroups[].GroupName)


for item in ${group_del_list} ; do aws ec2 delete-palcement-group --group-name ${item} ; done

More info at aws documentation.

Read more ...

Tuesday, March 8, 2022

Number of Proper Fractions with Denominator d Python Codewars

Task:

If n is the numerator and d the denominator of a fraction, that fraction is defined a (reduced) proper fraction if and only if GCD(n,d)==1.

For example 5/16 is a proper fraction, while 6/16 is not, as both 6 and 16 are divisible by 2, thus the fraction can be reduced to 3/8.

Now, if you consider a given number d, how many proper fractions can be built using d as a denominator?

For example, let's assume that d is 15: you can build a total of 8 different proper fractions between 0 and 1 with it: 1/15, 2/15, 4/15, 7/15, 8/15, 11/15, 13/15 and 14/15.

You are to build a function that computes how many proper fractions you can build with a given denominator:

proper_fractions(1)==0
proper_fractions(2)==1
proper_fractions(5)==4
proper_fractions(15)==8
proper_fractions(25)==20

Be ready to handle big numbers.

Solution:


def proper_fractions(n):
    if n==1: return 0
    phi = n
    for p in range(2, int(n**.5)+1):
        if n%p==0: # these p's will always be primes
            phi -= phi/p
            while n%p==0: # take out all the powers of this prime
                n /= p
    if n>1: # if n itself is a prime
        phi -= phi/n
    return int(phi)

print(proper_fractions(6))

Number of Proper Fractions with Denominator d Solutions | Codewars

Read more ...

Sum of Odd Cubed Numbers Python Codewars

Task:

Find the sum of the odd numbers within an array, after cubing the initial integers. The function should return undefined/None/nil/NULL if any of the values aren't numbers.

Note: Booleans should not be considered as numbers.

Solution:


def cube_odd(arr):
    total = 0 
    for num in arr:
        if (type(num) != int):
            return None
        if num % 2 != 0:
            total += num**3
    return total

print(cube_odd(["a",12,9,"z",42]))	

Training on Sum of Odd Cubed Numbers | Codewars

Read more ...

Monday, March 7, 2022

Duck Duck Goose Python Codewars

Task:

Task: Given an array of Player objects (an array of associative arrays in PHP) and an index (1-based), return the name of the chosen Player(name is a property of Player objects, e.g Player.name)

Example:

duck_duck_goose([a, b, c, d], 1) should return a.name
duck_duck_goose([a, b, c, d], 5) should return a.name
duck_duck_goose([a, b, c, d], 4) should return d.name

Solution:


def duck_duck_goose(players, goose):
    return players[(goose % len(players)) - 1].name

print(duck_duck_goose(['a', 'b', 'c', 'd'], 5))

Duck Duck Goose Solutions | Codewars

Read more ...

Data Reverse Python Codewars

Task:

A stream of data is received and needs to be reversed.

Each segment is 8 bits long, meaning the order of these segments needs to be reversed, for example:

11111111  00000000  00001111  10101010
 (byte1)   (byte2)   (byte3)   (byte4)

should become:

10101010  00001111  00000000  11111111
 (byte4)   (byte3)   (byte2)   (byte1)

The total number of bits will always be a multiple of 8.

The data is given in an array as such:

[1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,0]

Solution:


def data_reverse(data):
    temp = []
    res = []
    for i in range(len(data)//8):
        temp.append(data[i*8:(i+1)*8])

    for item in temp[::-1]:
        res += item
    return res
    
data1 = [1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,0]
print(data_reverse(data1))

Training on Data Reverse | Codewars

Read more ...

Sunday, March 6, 2022

Multi-tap Keypad Text Entry on an Old Mobile Phone Python Codewars

Task:

Prior to having fancy iPhones, teenagers would wear out their thumbs sending SMS messages on candybar-shaped feature phones with 3x4 numeric keypads.

------- ------- -------
|     | | ABC | | DEF |
|  1  | |  2  | |  3  |
------- ------- -------
------- ------- -------
| GHI | | JKL | | MNO |
|  4  | |  5  | |  6  |
------- ------- -------
------- ------- -------
|PQRS | | TUV | | WXYZ|
|  7  | |  8  | |  9  |
------- ------- -------
------- ------- -------
|     | |space| |     |
|  *  | |  0  | |  #  |
------- ------- -------

Prior to the development of T9 (predictive text entry) systems, the method to type words was called "multi-tap" and involved pressing a button repeatedly to cycle through the possible values.

For example, to type a letter "R" you would press the 7 key three times (as the screen display for the current character cycles through P->Q->R->S->7). A character is "locked in" once the user presses a different key or pauses for a short period of time (thus, no extra button presses are required beyond what is needed for each letter individually). The zero key handles spaces, with one press of the key producing a space and two presses producing a zero.

In order to send the message "WHERE DO U WANT 2 MEET L8R" a teen would have to actually do 47 button presses. No wonder they abbreviated.

For this assignment, write a module that can calculate the amount of button presses required for any phrase. Punctuation can be ignored for this exercise. Likewise, you can assume the phone doesn't distinguish between upper/lowercase characters (but you should allow your module to accept input in either for convenience).

Hint: While it wouldn't take too long to hard code the amount of keypresses for all 26 letters by hand, try to avoid doing so! (Imagine you work at a phone manufacturer who might be testing out different keyboard layouts, and you want to be able to test new ones rapidly.)

Solution:


def presses(phrase):
    taps = {
            1 : '1ADGJMPTW *#',
            2 : 'BEHKNQUX0',
            3 : 'CFILORVY',
            4 : '23456S8Z',
            5 : '79'
            }
    output = 0
    for letter in (phrase):
        for key, value in taps.items():
            if letter.upper() in value:
                output += key
    return output
def presses(phrase):
    x = 0
    for letter in phrase:
        if letter.lower() in list('1*#adgjmptw '): x+= 1
        elif letter.lower() in list('0behknqux'): x+= 2
        elif letter.lower() in list('cfilorvy'): x+= 3
        elif letter.lower() in list('234568sz'): x+= 4
        elif letter.lower() in list('79'): x+= 5
    return x

print(presses("HOW R U"))

Training on Multi-tap Keypad Text Entry on an Old Mobile Phone | Codewars

Read more ...

Multiple of index Python Codewars

Task:

Return a new array consisting of elements which are multiple of their own index in input array (length > 1).

Some cases:

[22, -6, 32, 82, 9, 25] => [-6, 32, 25]

[68, -1, 1, -7, 10, 10] => [-1, 10]

[-56,-85,72,-26,-14,76,-27,72,35,-21,-67,87,0,21,59,27,-92,68] => [-85, 72, 0, 68]

Solution:




def multiple_of_index(arr):
    res = []
    for i,n in enumerate(arr):
        if i > 0:
            if n % i == 0:
                res.append(n)
    return res
print(multiple_of_index([22, -6, 32, 82, 9, 25]))


Training on Multiple of index | Codewars

Read more ...

Sum of Triangular Numbers Python Codewars

Task:

Your task is to return the sum of Triangular Numbers up-to-and-including the nth Triangular Number.

Triangular Number: "any of the series of numbers (1, 3, 6, 10, 15, etc.) obtained by continued summation of the natural numbers 1, 2, 3, 4, 5, etc."

[01]
02 [03]
04 05 [06]
07 08 09 [10]
11 12 13 14 [15]
16 17 18 19 20 [21]

e.g. If 4 is given: 1 + 3 + 6 + 10 = 20.

Triangular Numbers cannot be negative so return 0 if a negative number is given.

Solution:


def sum_triangular_numbers(n):
    sum_= 0
    temp_ = 0
    for i in range(1,n+1):
        temp_ += i
        sum_ += temp_
        
    return sum_

print(sum_triangular_numbers(4))

Sum of Triangular Numbers Solutions | Codewars

Read more ...

Saturday, March 5, 2022

Dashatize it Python Codewars

Task:

Given a variable n,

If n is an integer, Return a string with dash'-'marks before and after each odd integer, but do not begin or end the string with a dash mark. If n is negative, then the negative sign should be removed.

If n is not an integer, return an empty value.

Ex:

dashatize(274) -> '2-7-4'
dashatize(6815) -> '68-1-5'

Solution:


def dashatize(num):
    num_str = str(num)
    for i in ['1','3','5','7','9']:
        num_str = num_str.replace(i,'-' + i + '-')
    return num_str.strip('-').replace('--','-')

print(dashatize(2741))

Dashatize it Solutions | Codewars

Read more ...

Thursday, March 3, 2022

Title Case Python Codewars

Task:

A string is considered to be in title case if each word in the string is either (a) capitalised (that is, only the first letter of the word is in upper case) or (b) considered to be an exception and put entirely into lower case unless it is the first word, which is always capitalised.

Write a function that will convert a string into title case, given an optional list of exceptions (minor words). The list of minor words will be given as a string with each word separated by a space. Your function should ignore the case of the minor words string -- it should behave in the same way even if the case of the minor word string is changed.

title_case('a clash of KINGS', 'a an the of') # should return: 'A Clash of Kings'
title_case('THE WIND IN THE WILLOWS', 'The In') # should return: 'The Wind in the Willows'
title_case('the quick brown fox') # should return: 'The Quick Brown Fox'

Solution:


def title_case(title, minor_words=''):
    minor_words = [word.lower() for word in minor_words.split(' ')]
    title_case = []
    for i, word in enumerate(title.split()):
        
        if i == 0:
            title_case.append(word.title())
            continue
        if word.lower() in minor_words:
            title_case.append(word.lower())
            continue
        title_case.append(word.title())
    
    return ' '.join(title_case)

def title_case(title, minor_words=''):
    title = title.capitalize().split()
    minor_words = minor_words.lower().split()
    return ' '.join([word if word in minor_words else word.capitalize() for word in title])

print(title_case('THE WIND IN THE WILLOWS', 'The In'))

Title Case Solutions | Codewars

Read more ...

Wednesday, March 2, 2022

Simple validation of a username with regex Python Codewars

Task:

Write a simple regex to validate a username. Allowed characters are:

  • lowercase letters,
  • numbers,
  • underscore

Length should be between 4 and 16 characters (both included).

Solution:


import re

def validate_usr(username):
    return bool(re.match(r'^[a-z0-9_]{4,16}$', username))

print(validate_usr('asddsa'))

Simple validation of a username with regex Solutions | Codewars

Read more ...

Add Length Python Codewars

Task:

What if we need the length of the words separated by a space to be added at the end of that same word and have it returned as an array?

add_length('apple ban') => ["apple 5", "ban 3"]
add_length('you will win') => ["you 3", "will 4", "win 3"]

Your task is to write a function that takes a String and returns an Array/list with the length of each word added to each element .

Note: String will have at least one element; words will always be separated by a space.

Solution:


def add_length(str_):
    res = []
    for word in str_.split():
        res.append(word+' '+str(len(word)))
    return res

def add_length(str_):
    return [f"{word} {len(word)}" for word in str_.split()]

print(add_length('apple ban'))

Add Length Solutions | Codewars

Read more ...

Multiplication table Python Codewars

Task:

Your task, is to create NxN multiplication table, of size provided in parameter.

for example, when given size is 3:

1 2 3
2 4 6
3 6 9

for given example, the return value should be: [[1,2,3],[2,4,6],[3,6,9]]

Solution:



def multiplication_table(size):
    
    res = []
    for i in range(1,size+1):
        row = []
        for j in range(1,size+1):
            row.append(j*i)
        res.append(row)
    return res

def multiplicationTable(size):
    return [[j*i for j in range(1, size+1)] for i in range(1, size+1)]

print(multiplication_table(3))

Training on Multiplication table | Codewars

Read more ...

Find the stray number Python Codewars

Task:

You are given an odd-length array of integers, in which all of them are the same, except for one single number.

Complete the method which accepts such an array, and returns that single different number.

The input array will always be valid! (odd-length >= 3)

Examples

[1, 1, 2] ==> 2
[17, 17, 3, 17, 17, 17, 17] ==> 3

Solution:


def stray(arr):
    for x in arr:
        if arr.count(x) == 1:
            return x
print(stray([3,2,2,2,2]))



Find the stray number Solutions | Codewars

Read more ...

Tuesday, March 1, 2022

Form The Minimum Python Codewars

Task:

Given a list of digits, return the smallest number that could be formed from these digits, using the digits only once (ignore duplicates).

minValue ({1, 3, 1})  ==> return (13)

Solution:


def min_value(digits):
    digit = list(sorted(set(digits)))
    return int(''.join(map(str, digit)))

def min_value(digits):
     return int("".join(map(str,sorted(set(digits)))))

print(min_value([4, 8, 1, 4]))

 

Form The Minimum Solutions | Codewars

Read more ...

Sum of Minimums! Python Codewars

Task:

Given a 2D ( nested ) list ( array, vector, .. ) of size m * n, your task is to find the sum of the minimum values in each row.

For Example:

[ [ 1, 2, 3, 4, 5 ]        #  minimum value of row is 1
, [ 5, 6, 7, 8, 9 ]        #  minimum value of row is 5
, [ 20, 21, 34, 56, 100 ]  #  minimum value of row is 20
]

So the function should return 26 because the sum of the minimums is 1 + 5 + 20 = 26.

Note: You will always be given a non-empty list containing positive values.

Solution:


def sum_of_minimums(numbers):
    res = 0
    for i in numbers:
        res += sorted(i)[0]
    return res

def sum_of_minimums(numbers):
    return sum(map(min, numbers))
    
print(sum_of_minimums([ [ 7,9,8,6,2 ], [6,3,5,4,3], [5,8,7,4,5] ]))

Sum of Minimums! Solutions | Codewars

Read more ...

Monday, February 28, 2022

Encrypt this! Python Codewars

Task:

Encrypt this!

You want to create secret messages which can be deciphered by the Decipher this! kata. Here are the conditions:

  1. Your message is a string containing space separated words.
  2. You need to encrypt each word in the message using the following rules:
    • The first letter must be converted to its ASCII code.
    • The second letter must be switched with the last letter
  3. Keepin' it simple: There are no special characters in the input.

Examples:

encrypt_this("Hello") == "72olle"
encrypt_this("good") == "103doo"
encrypt_this("hello world") == "104olle 119drlo"

Solution:


def encrypt_this(text):
    words = text.split()
    for k, w in enumerate(words):
        if len(w) > 2 :
            words[k] = str(ord(w[0])) + w[-1] + w[2:-1] + w[1]
        else:
            words[k] = str(ord(w[0])) + w[1:]
    return " ".join(words)

print(encrypt_this('A wise old owl lived in an oak'))

Encrypt this! | Codewars

Read more ...

Deodorant Evaporator Python Codewars

Task:

This program tests the life of an evaporator containing a gas.

We know the content of the evaporator (content in ml), the percentage of foam or gas lost every day (evap_per_day) and the threshold (threshold) in percentage beyond which the evaporator is no longer useful. All numbers are strictly positive.

The program reports the nth day (as an integer) on which the evaporator will be out of use.

Example:

evaporator(10, 10, 5) -> 29

Solution:



def evaporator(content, evap_per_day, threshold):
    days = 0
    limit = threshold/100*content
    while content >= limit:
        content -= evap_per_day/100*content
        days += 1
    return days

print(evaporator(10, 10, 10))

Training on Deodorant Evaporator | Codewars

Read more ...

Regex Password Validation Python Codewars

You need to write regex that will validate a password to make sure it meets the following criteria:

  • At least six characters long
  • contains a lowercase letter
  • contains an uppercase letter
  • contains a number

Valid passwords will only be alphanumeric characters.


regex = (
    '^'            # start line
    '(?=.*\d)'     # must contain one digit from 0-9
    '(?=.*[a-z])'  # must contain one lowercase characters
    '(?=.*[A-Z])'  # must contain one uppercase characters
    '[a-zA-Z\d]'   # permitted characters (alphanumeric only)
    '{6,}'         # length at least 6 chars
    '$'            # end line
)


Read more ...

Alternate capitalization Python Codewars

Task:

Given a string, capitalize the letters that occupy even indexes and odd indexes separately, and return as shown below. Index 0 will be considered even.

For example, capitalize("abcdef") = ['AbCdEf', 'aBcDeF']. See test cases for more examples.

The input will be a lowercase string with no spaces.

Good luck!

Solution:


	
def capitalize(s):
    res1 = ''
    res2 = ''
    for i, j in enumerate(s):
        if i % 2 == 0:
            res1 += j.upper()
        else:
            res1 += j
        if i % 2 != 0:
            res2 += j.upper()
        else:
            res2 += j
    return [res1, res2]

def capitalize(s):
    s = ''.join(c if i%2 else c.upper() for i,c in enumerate(s))
    return [s, s.swapcase()]
    
print(capitalize("abcdef"))

Alternate capitalization Solutions | Codewars

Read more ...

Reverse Letter Python Codewars

Task

Given a string str, reverse it omitting all non-alphabetic characters.

Example

For str = "krishan", the output should be "nahsirk".

For str = "ultr53o?n", the output should be "nortlu".

Solution:


def reverse_letter(string):
    return ''.join(c for c in string[::-1] if c.isalpha())

Simple Fun #176: Reverse Letter Solutions | Codewars

Read more ...

Sunday, February 27, 2022

Factorial Python Codewars

Task:

Write a function to calculate factorial for a given input.

Solution:



def factorial(n):
    f = 1
    if n == 0:
        return f
    elif n < 0 or n > 12:
        raise ValueError("value out of range")
    else:
        for i in range(1,n+1):
            f *= i
    return f

print(factorial(13))

Factorial Solutions | Codewars

Read more ...

Saturday, February 26, 2022

A wolf in sheep's clothing Python Codewars

Task:

Wolves have been reintroduced to Great Britain. You are a sheep farmer, and are now plagued by wolves which pretend to be sheep. Fortunately, you are good at spotting them.

Warn the sheep in front of the wolf that it is about to be eaten. Remember that you are standing at the front of the queue which is at the end of the array:

[sheep, sheep, sheep, sheep, sheep, wolf, sheep, sheep]      (YOU ARE HERE AT THE FRONT OF THE QUEUE)
   7      6      5      4      3            2      1

If the wolf is the closest animal to you, return "Pls go away and stop eating my sheep". Otherwise, return "Oi! Sheep number N! You are about to be eaten by a wolf!" where N is the sheep's position in the queue.

Note: there will always be exactly one wolf in the array.

Examples

Input: ["sheep", "sheep", "sheep", "wolf", "sheep"]
Output: "Oi! Sheep number 1! You are about to be eaten by a wolf!"

Input: ["sheep", "sheep", "wolf"]
Output: "Pls go away and stop eating my sheep"

Solution:


def warn_the_sheep(queue):
    queue = queue[::-1]
    wolf_counter = None
    for i, animal in enumerate(queue):
        if animal == 'wolf':
            wolf_counter = i
    if wolf_counter == 0:
        return 'Pls go away and stop eating my sheep'
    return f'Oi! Sheep number {wolf_counter}! You are about to be eaten by a wolf!'
        

def warn_the_sheep(queue):
    i = queue[::-1].index('wolf')
    if i == 0:
        return 'Pls go away and stop eating my sheep'
    return f'Oi! Sheep number {i}! You are about to be eaten by a wolf!'
    
print(warn_the_sheep(['sheep', 'sheep', 'sheep', 'sheep', 'sheep', 'wolf', 'sheep', 'sheep']))

A wolf in sheep's clothing Solutions | Codewars

Read more ...

Reverse or Rotate Python Codewars

Task:

The input is a string str of digits. Cut the string into chunks (a chunk here is a substring of the initial string) of size sz (ignore the last chunk if its size is less than sz).

If a chunk represents an integer such as the sum of the cubes of its digits is divisible by 2, reverse that chunk; otherwise rotate it to the left by one position. Put together these modified chunks and return the result as a string.

If

  • sz is <= 0 or if str is empty return ""
  • sz is greater (>) than the length of str it is impossible to take a chunk of size sz hence return "".
Examples:
revrot("123456987654", 6) --> "234561876549"
revrot("123456987653", 6) --> "234561356789"
revrot("66443875", 4) --> "44668753"
revrot("66443875", 8) --> "64438756"
revrot("664438769", 8) --> "67834466"
revrot("123456779", 8) --> "23456771"
revrot("", 8) --> ""
revrot("123456779", 0) --> "" 
revrot("563000655734469485", 4) --> "0365065073456944"
Example of a string rotated to the left by one position:
s = "123456" gives "234561".

Solution:


def revrot(s, n):
    if not s or n < 1 or n > len(s):
        return ""
    res = ''
    while len(s) >= n:
        group = s[:n]
        if sum([int(d)**3 for d in group]) % 2 == 0:
            res += group[::-1]
        else:
            res += group[1:] + group[0]
        s = s[n:]
    
    return res


print(revrot("123456987654", 6))

Training on Reverse or rotate? | Codewars

Read more ...