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

Maximum Length Difference Python Codewars

Task:

You are given two arrays a1 and a2 of strings. Each string is composed with letters from a to z. Let x be any string in the first array and y be any string in the second array.

Find max(abs(length(x) − length(y)))

If a1 and/or a2 are empty return -1 in each language except in Haskell (F#) where you will return Nothing (None).

Example:
a1 = ["hoqq", "bbllkw", "oox", "ejjuyyy", "plmiis", "xxxzgpsssa", "xxwwkktt", "znnnnfqknaz", "qqquuhii", "dvvvwz"]
a2 = ["cccooommaaqqoxii", "gggqaffhhh", "tttoowwwmmww"]
mxdiflg(a1, a2) --> 13

Solution:


def mxdiflg(a1, a2):
    if a1 == [] or a2 == []:
        return -1
    x = len(min(a1, key=len))
    y = len(max(a2, key=len))
    result1 = abs(x-y)
    x = len(max(a1, key=len))
    y = len(min(a2, key=len))
    result2 = abs(y-x)
    return result1 if result1 >= result2 else result2
def mxdiflg(a1, a2):
    if a1 and a2:
        return max(
            len(max(a1, key=len)) - len(min(a2, key=len)),
            len(max(a2, key=len)) - len(min(a1, key=len)))
    return -1

a1 = ["hoqq", "bbllkw", "oox", "ejjuyyy", "plmiis", "xxxzgpsssa", "xxwwkktt", "znnnnfqknaz", "qqquuhii", "dvvvwz"]
a2 = ["cccooommaaqqoxii", "gggqaffhhh", "tttoowwwmmww"]
print(mxdiflg(a1,a2))

Training on Maximum Length Difference | Codewars

Read more ...

Check the exam Python Codewars

Task:

The first input array is the key to the correct answers to an exam, like ["a", "a", "b", "d"]. The second one contains a student's submitted answers.

The two arrays are not empty and are the same length. Return the score for this array of answers, giving +4 for each correct answer, -1 for each incorrect answer, and +0 for each blank answer, represented as an empty string (in C the space character is used).

If the score < 0, return 0.

For example:

checkExam(["a", "a", "b", "b"], ["a", "c", "b", "d"]) → 6
checkExam(["a", "a", "c", "b"], ["a", "a", "b",  ""]) → 7
checkExam(["a", "a", "b", "c"], ["a", "a", "b", "c"]) → 16
checkExam(["b", "c", "b", "a"], ["",  "a", "a", "c"]) → 0

Solution:


def check_exam(arr1,arr2):
    total = 0
    if len(arr1) != len(arr2):
        return total
    for i in range(len(arr1)):
        if arr1[i] == arr2[i]:
            total += 4
        elif arr2[i] == '':
            total += 0
        else:
            total -= 1
    return total if total >= 0 else 0

print(check_exam(["a", "a", "c", "b"], ["", "c", "b", "d"]))

Training on Check the exam | Codewars

Read more ...

Thursday, February 24, 2022

Integers: Recreation One Python Codewars

Task:

Find all integers between m and n (m and n integers with 1 <= m <= n) such that the sum of their squared divisors is itself a square.

We will return an array of subarrays or of tuples (in C an array of Pair) or a string. The subarrays (or tuples or Pairs) will have two elements: first the number the squared divisors of which is a square and then the sum of the squared divisors.

Example:
list_squared(1, 250) --> [[1, 1], [42, 2500], [246, 84100]]
list_squared(42, 250) --> [[42, 2500], [246, 84100]]

Solution:


def divisors(n):
    divs = [1, n]
    for i in range(2, int(n**0.5)+1):
        if n % i == 0:
            divs.extend([i, int(n/i)])
    return set(divs)


def list_squared(m, n):
    sq_list = []
    for num in range(m, n):
        _sum = sum(item**2 for item in divisors(num))
        if (_sum ** 0.5).is_integer():
            sq_list.append([num, _sum])
    return sq_list

print(list_squared(42,250))

Integers: Recreation One Solutions | Codewars

Read more ...

Wednesday, February 23, 2022

Counting Duplicates Python Codewars

Task:

Write a function that will return the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric digits.

Example

"abcde" -> 0 # no characters repeats more than once
"aabbcde" -> 2 # 'a' and 'b'
"aabBcde" -> 2 # 'a' occurs twice and 'b' twice (`b` and `B`)
"indivisibility" -> 1 # 'i' occurs six times
"Indivisibilities" -> 2 # 'i' occurs seven times and 's' occurs twice
"aA11" -> 2 # 'a' and '1'
"ABBA" -> 2 # 'A' and 'B' each occur twice

Solution:


def duplicate_count(text):
    duplicate_letters = []
    for i in text.lower():
        if text.lower().count(i) > 1 and i not in duplicate_letters:
            duplicate_letters.append(i)
    return len(duplicate_letters)


def duplicate_count(s):
  return len([c for c in set(s.lower()) if s.lower().count(c)>1])
      
print(duplicate_count("MA00URYBSiCQXYcUEV3Tj229ql9ZNkYXI2Kh7SKJvLkR5bF1UtMx7"))

Counting Duplicates Solutions | Codewars

Read more ...

Rock Paper Scissors Python Codewars

Task:

Let's play! You have to return which player won! In case of a draw return Draw!.

Examples:

rps('scissors','paper') // Player 1 won!
rps('scissors','rock') // Player 2 won!
rps('paper','paper') // Draw!

Solution:


def rps(p1, p2):
    if p1 == p2:
        return 'Draw!'
    elif (p1 == 'rock' and p2 == 'scissors') or (p1 == 'scissors' and p2 == 'paper') or (p1 == 'paper' and p2 == 'rock'):
        return 'Player 1 won!'
    else:
        return 'Player 2 won!'

def rps(p1, p2):
    hand = {'rock':0, 'paper':1, 'scissors':2}
    results = ['Draw!', 'Player 1 won!', 'Player 2 won!']
    return results[hand[p1] - hand[p2]]

print(rps('rock', 'scissors'))

Rock Paper Scissors! Solutions | Codewars

Read more ...

Tortoise racing Python Codewars

Task:

Two tortoises named A and B must run a race. A starts with an average speed of 720 feet per hour. Young B knows she runs faster than A, and furthermore has not finished her cabbage.

When she starts, at last, she can see that A has a 70 feet lead but B's speed is 850 feet per hour. How long will it take B to catch A?

More generally: given two speeds v1 (A's speed, integer > 0) and v2 (B's speed, integer > 0) and a lead g (integer > 0) how long will it take B to catch A?

The result will be an array [hour, min, sec] which is the time needed in hours, minutes and seconds (round down to the nearest second) or a string in some languages.

If v1 >= v2 then return nil, nothing, null, None or {-1, -1, -1} for C++, C, Go, Nim, Pascal, COBOL, [-1, -1, -1] for Perl,[] for Kotlin or "-1 -1 -1".

Examples:

(form of the result depends on the language)

race(720, 850, 70) => [0, 32, 18] or "0 32 18"
race(80, 91, 37)   => [3, 21, 49] or "3 21 49"

Solution:


def race(v1, v2, g):
    if v1 >= v2:
        return None
    else:
        time = g / (v2 - v1)
        h = int(time)
        mn = int((time * 60) % 60)
        s = int((time*3600) % 60)
        time_required = [h, mn, s]
    return time_required

def race(v1, v2, g):
    t = 3600 * g/(v2-v1)
    return [t/3600, t/60%60, t%60] if v2 > v1 else None

print(race(720, 850, 70))

Training on Tortoise racing | Codewars

Read more ...

Tuesday, February 22, 2022

Find the middle element Python Codewars

Task:

As a part of this Kata, you need to create a function that when provided with a triplet, returns the index of the numerical element that lies between the other two elements.

The input to the function will be an array of three distinct numbers (Haskell: a tuple).

For example:

gimme([2, 3, 1]) => 0

2 is the number that fits between 1 and 3 and the index of 2 in the input array is 0.

Another example (just to make sure it is clear):

gimme([5, 10, 14]) => 1

10 is the number that fits between 5 and 14 and the index of 10 in the input array is 1.

 

Solution:


def gimme(input_array):
    sorted_list = sorted(input_array)
    return input_array.index(sorted_list[1])

def gimme(input_array):
    return input_array.index(sorted(input_array)[1])

print(gimme([5, 10, 14]))

Training on Find the middle element | Codewars

Read more ...

Maximum subarray sum Python Codewars

Task:

The maximum sum subarray problem consists in finding the maximum sum of a contiguous subsequence in an array or list of integers:

max_sequence([-2, 1, -3, 4, -1, 2, 1, -5, 4])
# should be 6: [4, -1, 2, 1]

Easy case is when the list is made up of only positive numbers and the maximum sum is the sum of the whole array. If the list is made up of only negative numbers, return 0 instead.

Empty list is considered to have zero greatest sum. Note that the empty list or array is also a valid sublist/subarray.

Solution:


def max_sequence(arr):
    max = 0
    sub_max = 0
    for i in arr:
        if sub_max > 0:
            sub_max += i
            if sub_max < 0:
                sub_max = 0
            elif sub_max > max:
                max = sub_max
        elif i > 0:
            sub_max += i

    return max

def maxSequence(arr):
    max,curr=0,0
    for x in arr:
        curr+=x
        if curr<0:curr=0
        if curr>max:max=curr
    return max


print(max_sequence([-2, 1, -3, 4, -1, 2, 3, -2, -5, 4]))


Training on Maximum subarray sum | Solution | Codewars

Read more ...

Monday, February 21, 2022

Transportation on vacation Python Codewars

Task:

After a hard quarter in the office you decide to get some rest on a vacation. So you will book a flight for you and your girlfriend and try to leave all the mess behind you.

You will need a rental car in order for you to get around in your vacation. The manager of the car rental makes you some good offers.

Every day you rent the car costs $40. If you rent the car for 7 or more days, you get $50 off your total. Alternatively, if you rent the car for 3 or more days, you get $20 off your total.

Write a code that gives out the total amount for different days(d).

 

Solution:


def rental_car_cost(d):
    result = d * 40
    if d >= 7:
        result -= 50
    elif d >= 3:
        result -= 20
    return result
    
print(rental_car_cost(8))

Transportation on vacation Solutions | Codewars

Read more ...

String incrementer Python Codewars

Task:

Your job is to write a function which increments a string, to create a new string.

  • If the string already ends with a number, the number should be incremented by 1.
  • If the string does not end with a number. the number 1 should be appended to the new string.

Examples:

foo -> foo1

foobar23 -> foobar24

foo0042 -> foo0043

foo9 -> foo10

foo099 -> foo100

Attention: If the number has leading zeros the amount of digits should be considered.

Solution:


def increment_string(strng):
    num = ''
    strn = ''
    head = strng.rstrip('0123456789')
    tail = strng[len(head):]
    for l in strng:
        if l.isdigit():
            num += l
        else:
            strn += l
    return strn+str(int(num)+1).zfill(len(tail))

print(increment_string("foobar0043"))

Read more ...

Is Palindrome Python Codewars

Task:

Write a function that checks if a given string (case insensitive) is a palindrome.

Solution:


def is_palindrome(s):
    return s.lower() == s[::-1].lower()

print(is_palindrome('Aba'))

 

Is it a palindrome? Solutions | Codewars

Read more ...

Sunday, February 20, 2022

Round up to the next multiple of 5 Python Codewars

Task:

Given an integer as input, can you round it to the next (meaning, "higher") multiple of 5?

Examples:

input:    output:
0    ->   0
2    ->   5
3    ->   5
12   ->   15
21   ->   25
30   ->   30
-2   ->   0
-5   ->   -5
etc.

Input may be any positive or negative integer (including 0).

You can assume that all inputs are valid integers.

Solution:


def round_to_next5(n):
    while n%5!=0:
        n+=1
    return n
print(round_to_next5(-2))

Round up to the next multiple of 5 Solutions | Codewars

Read more ...

Your order, please Python Codewars

Task:

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.

Note: 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.

Examples

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

Solution:


def order(sentence):
    if sentence == '':
        return ''
    res = []
    for i in range(1,len(sentence.split())+1):
        for word in sentence.split():            
            if str(i) in word:
                res.append(word)
    return ' '.join(res)

def order(words):
  return ' '.join(sorted(words.split(), key=lambda w:sorted(w)))

print(order("is2 Thi1s T4est 3a"))

Training on Your order, please | Codewars

Read more ...

Sum of two lowest positive integers Python Codewars

Task:

Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 positive integers. No floats or non-positive integers will be passed.

For example, when an array is passed like [19, 5, 42, 2, 77], the output should be 7.

[10, 343445353, 3453445, 3453545353453] should return 3453455.

Solution:


def sum_two_smallest_numbers(numbers):
    n = sorted(numbers)
    return sum(n[:2])

print(sum_two_smallest_numbers([25, 42, 12, 18, 22]))

Training on Sum of two lowest positive integers | Codewars

Read more ...

Enough is enough! Python Codewars

Task:

Given a list lst and a number N, create a new list that contains each number of lst at most N times without reordering. For example if N = 2, and the input is [1,2,3,1,2,1,2,3], you take [1,2,3,1,2], drop the next [1,2] since this would lead to 1 and 2 being in the result 3 times, and then take 3, which leads to [1,2,3,1,2,3].

Example:

  delete_nth ([1,1,1,1],2) # return [1,1]
  
  delete_nth ([20,37,20,21],1) # return [20,37,21]

Solution:


def delete_nth(order,max_e):
    res = []
    for o in order:
        if res.count(o) < max_e: res.append(o)
    return res

print(delete_nth([1,1,3,3,7,2,2,2,2], 3))

Delete occurrences of an element if it occurs more than n times Solutions | Codewars

Read more ...

Help the bookseller ! Python Codewars

Task:

A bookseller has lots of books classified in 26 categories labeled A, B, ... Z. Each book has a code c of 3, 4, 5 or more characters. The 1st character of a code is a capital letter which defines the book category.

In the bookseller's stocklist each code c is followed by a space and by a positive integer n (int n >= 0) which indicates the quantity of books of this code in stock.

For example an extract of a stocklist could be:

L = {"ABART 20", "CDXEF 50", "BKWRK 25", "BTSQZ 89", "DRTYM 60"}.
or
L = ["ABART 20", "CDXEF 50", "BKWRK 25", "BTSQZ 89", "DRTYM 60"] or ....

You will be given a stocklist (e.g. : L) and a list of categories in capital letters e.g :

M = {"A", "B", "C", "W"} 
or
M = ["A", "B", "C", "W"] or ...

and your task is to find all the books of L with codes belonging to each category of M and to sum their quantity according to each category.

For the lists L and M of example you have to return the string (in Haskell/Clojure/Racket a list of pairs):

(A : 20) - (B : 114) - (C : 50) - (W : 0)

where A, B, C, W are the categories, 20 is the sum of the unique book of category A, 114 the sum corresponding to "BKWRK" and "BTSQZ", 50 corresponding to "CDXEF" and 0 to category 'W' since there are no code beginning with W.

If L or M are empty return string is "" (Clojure and Racket should return an empty array/list instead).

Note:

In the result codes and their values are in the same order as in M.

Solution:



def stock_list(listOfArt, listOfCat):
    if (len(listOfArt) == 0) or (len(listOfCat) == 0):
        return ""
    result = ""
    for cat in listOfCat:
        total = 0
        for book in listOfArt:
            if (book[0] == cat[0]):
                total += int(book.split(" ")[1])
        if (len(result) != 0):
            result += " - "
        result += "(" + str(cat) + " : " + str(total) + ")"
    return result

b = ["ROXANNE 102", "RHODODE 123", "BKWRKAA 125", "BTSQZFG 239", "DRTYMKH 060"]
c = ["U", "V", "R"]
print(stock_list(b, c))

Help the bookseller ! Solutions | Codewars

Read more ...

Friday, February 18, 2022

Difference of Volumes of Cuboids Python Codewars

Task:

In this simple exercise, you will create a program that will take two lists of integers, a and b. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids a and b. You must find the difference of the cuboids' volumes regardless of which is bigger.

For example, if the parameters passed are ([2, 2, 3], [5, 4, 1]), the volume of a is 12 and the volume of b is 20. Therefore, the function should return 8.

Your function will be tested with pre-made examples as well as random ones.

Solution:

 


def find_difference(a, b):
    return abs((a[0]*a[1]*a[2])-b[0]*b[1]*b[2])

print(find_difference([3, 2, 5], [1, 4, 4]))

Training on Difference of Volumes of Cuboids | Codewars

Read more ...

Cat years, Dog years Python Codewars

Task:

I have a cat and a dog.

I got them at the same time as kitten/puppy. That was humanYears years ago.

Return their respective ages now as [humanYears,catYears,dogYears]

NOTES:

  • humanYears >= 1
  • humanYears are whole numbers only

Cat Years

  • 15 cat years for first year
  • +9 cat years for second year
  • +4 cat years for each year after that

Dog Years

  • 15 dog years for first year
  • +9 dog years for second year
  • +5 dog years for each year after that

Solution:


def human_years_cat_years_dog_years(human_years):
    result = []
    i = human_years
    if i == 1:
        result.append(i)
        result.append(15)
        result.append(15)
    if i == 2:
        result.append(i)
        result.append(15+9)
        result.append(15+9)
    if i >=3:
        result.append(i)
        result.append(15+9+(i-2)*4)
        result.append(15+9+(i-2)*5)       


    return result

print(human_years_cat_years_dog_years(10))

def human_years_cat_years_dog_years(x):
    return [x, 24+(x-2)*4 if (x != 1) else 15, 24+(x-2)*5 if (x != 1) else 15]

Training on Cat years, Dog years | Codewars

Read more ...

Thursday, February 17, 2022

Removing Elements Python Codewars

Take an array and remove every second element from the array. Always keep the first element and start removing with the next element.

Example:

["Keep", "Remove", "Keep", "Remove", "Keep", ...] --> ["Keep", "Keep", "Keep", ...]

None of the arrays will be empty, so you don't have to worry about that!


def remove_every_other(my_list):
    res = []
    for i in range(len(my_list)):
        if i % 2 == 0:
            res.append(my_list[i])
    return res
def remove_every_other(my_list):
    return my_list[::2]

print(remove_every_other(['Hello', 'Goodbye', 'Hello Again']))

Training on Removing Elements | Codewars

Read more ...

Count the Digit Python Codewars

Take an integer n (n >= 0) and a digit d (0 <= d <= 9) as an integer.

Square all numbers k (0 <= k <= n) between 0 and n.

Count the numbers of digits d used in the writing of all the k**2.

Call nb_dig (or nbDig or ...) the function taking n and d as parameters and returning this count.

Examples:
n = 10, d = 1 
the k*k are 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100
We are using the digit 1 in: 1, 16, 81, 100. The total count is then 4.

nb_dig(25, 1) returns 11 since
the k*k that contain the digit 1 are:
1, 16, 81, 100, 121, 144, 169, 196, 361, 441.
So there are 11 digits 1 for the squares of numbers between 0 and 25.

Note that 121 has twice the digit 1.


def nb_dig(n, d):
    count = 0
    for i in range(n+1):
        sq = i*i
        for i in str(sq):
            if i == str(d):
                count += 1
    return count

print(nb_dig(5750,0))

def nb_dig(n, d):
    return sum(str(i*i).count(str(d)) for i in range(n+1))

Training on Count the Digit | Codewars

Read more ...

Binary Addition Python Codewars

Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done before, or after the addition.

The binary number returned should be a string.

Examples:(Input1, Input2 --> Output (explanation)))

1, 1 --> "10" (1 + 1 = 2 in decimal or 10 in binary)
5, 9 --> "1110" (5 + 9 = 14 in decimal or 1110 in binary)


def add_binary(a,b):
    return format(a+b, "b")

print(add_binary(1,1))

Binary Addition | Codewars

Read more ...

Wednesday, February 16, 2022

Give me a Diamond Python Codewars

You need to return a string that looks like a diamond shape when printed on the screen, using asterisk (*) characters. Trailing spaces should be removed, and every line must be terminated with a newline character (\n).

Return null/nil/None/... if the input is an even number or negative, as it is not possible to print a diamond of even or negative size.

Examples

A size 3 diamond:

 *
***
 *

def diamond(n):
    if n < 1 or not n % 2:
        # n is negative or even
        return None
    s = ''
    for i in range(n):
        # Build asterisks for the line
        ast = '*'*(i*2 + 1) if i <= n/2 else '*'*((n-i)*2 - 1)
        # Add a line
        s += ' '*int((n-len(ast)) / 2) + ast + '\n'
    return s
def diamond(n):
    if n > 0 and n % 2 == 1:
        diamond = ""
        for i in range(n):
            diamond += " " * abs((n/2) - i)
            diamond += "*" * (n - abs((n-1) - 2 * i))
            diamond += "\n"
        return diamond
    else:
        return None

print(diamond(5))



Training on Give me a Diamond | Codewars

Read more ...

Expression Matter Python Codewars

Given three integers a ,b ,c, return the largest number obtained after inserting the following operators and brackets: +, *, ()

In other words , try every combination of a,b,c with [*+()] , and return the Maximum Obtained

Consider an Example :

With the numbers are 1, 2 and 3 , here are some ways of placing signs and brackets:

  • 1 * (2 + 3) = 5
  • 1 * 2 * 3 = 6
  • 1 + 2 * 3 = 7
  • (1 + 2) * 3 = 9

So the maximum value that you can obtain is 9.


def expression_matter(a, b, c):
     return max(a + b + c, (a + b) * c, a * (b + c), a * b * c)

print(expression_matter(1,2,3))

Training on Expressions Matter | Codewars

Read more ...

Sum of all the multiples of 3 or 5 Python Codewars

Your task is to write function findSum.

Upto and including n, this function will return the sum of all multiples of 3 and 5.

For example:

findSum(5) should return 8 (3 + 5)

findSum(10) should return 33 (3 + 5 + 6 + 9 + 10)


def find(n):
    sum = 0
    for i in range(n+1):
        print(i)
        if i % 3 == 0 or i % 5 == 0:
            sum += i
    return sum

def find(n):
    return sum(i for  i in range(n+1) if i % 3 == 0 or i % 5 == 0)
    
print(find(10))

 

Training on Sum of all the multiples of 3 or 5 | Codewars

Read more ...

Tuesday, February 15, 2022

Vowel Count Python Codewars

 

Return the number (count) of vowels in the given string.

We will consider a, e, i, o, u as vowels for this Kata (but not y).

The input string will only consist of lower case letters and/or spaces.


def get_count(sentence):
    vowels = 'aeiou'
    count_vowels = 0
    for x in sentence:
        if x in vowels:
            count_vowels += 1
    return count_vowels

def get_count(sentence):
    return sum(c in 'aeiou' for c in sentence)

Training on Vowel Count | Codewars

Read more ...

Welcome Python Codewars

Solution:


def greet(language):
    dic = {'english': 'Welcome',
    'czech': 'Vitejte',
    'danish': 'Velkomst',
    'dutch': 'Welkom',
    'estonian': 'Tere tulemast',
    'finnish': 'Tervetuloa',
    'flemish': 'Welgekomen',
    'french': 'Bienvenue',
    'german': 'Willkommen',
    'irish': 'Failte',
    'italian': 'Benvenuto',
    'latvian': 'Gaidits',
    'lithuanian': 'Laukiamas',
    'polish': 'Witamy',
    'spanish': 'Bienvenido',
    'swedish': 'Valkommen',
    'welsh': 'Croeso'}
    if language in dic:
        return dic[language]
    else:
        return 'Welcome'

Welcome! Solutions | Codewars

Read more ...

Student's Final Grade Python Codewars

Create a function finalGrade, which calculates the final grade of a student depending on two parameters: a grade for the exam and a number of completed projects.

This function should take two arguments: exam - grade for exam (from 0 to 100); projects - number of completed projects (from 0 and above);

This function should return a number (final grade). There are four types of final grades:

  • 100, if a grade for the exam is more than 90 or if a number of completed projects more than 10.
  • 90, if a grade for the exam is more than 75 and if a number of completed projects is minimum 5.
  • 75, if a grade for the exam is more than 50 and if a number of completed projects is minimum 2.
  • 0, in other cases

Examples(Inputs-->Output):

100, 12 --> 100
99, 0 --> 100
10, 15 --> 100

85, 5 --> 90

55, 3 --> 75

55, 0 --> 0
20, 2 --> 0

def final_grade(exam, projects):
    if exam > 90 or projects > 10:
        return 100
    elif exam > 75 and projects >= 5:
        return 90
    elif exam > 50 and projects >= 2:
        return 75
    else:
        return 0

print(final_grade(10, 15))

Student's Final Grade | Codewars

Read more ...

Sum of the first nth term of Series Python Codewars

Your task is to write a function which returns the sum of following series upto nth term(parameter).

Series: 1 + 1/4 + 1/7 + 1/10 + 1/13 + 1/16 +...

Rules:

  • You need to round the answer to 2 decimal places and return it as String.

  • If the given value is 0 then it should return 0.00

  • You will only be given Natural Numbers as arguments.

Examples:(Input --> Output)

1 --> 1 --> "1.00"
2 --> 1 + 1/4 --> "1.25"
5 --> 1 + 1/4 + 1/7 + 1/10 + 1/13 --> "1.57"

def series_sum(n):
    return '{:.2f}'.format(sum(1/(1+i*3) for i in range(n)))
print(series_sum(4))

Training on Sum of the first nth term of Series | Codewars

Read more ...

You're a square! Python Codewars

 

Given an integral number, determine if it's a square number:

In mathematics, a square number or perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself.

The tests will always use some integral number, so don't worry about that in dynamic typed languages.

Examples
-1  =>  false
 0  =>  true
 3  =>  false
 4  =>  true
25  =>  true
26  =>  false

def is_square(n):
    if n < 0:
        return False
    if n >= 0:
        if (n ** 0.5) % 1 == 0:
            return True
        else:
            return False
def is_square(n):    
    return n >= 0 and (n**0.5) % 1 == 0

print(is_square(9))

 

Training on You're a square! | Codewars

Read more ...

Monday, February 14, 2022

Testing 1-2-3 Python Codewars

Your team is writing a fancy new text editor and you've been tasked with implementing the line numbering.

Write a function which takes a list of strings and returns each line prepended by the correct number.

The numbering starts at 1. The format is n: string. Notice the colon and space in between.

Examples:

number([]) # => []
number(["a", "b", "c"]) # => ["1: a", "2: b", "3: c"]


def number(lines):
    count = 1
    line = []
    for x in lines:
        line.append(str(count) + ': ' + x)
        count += 1
    return line
def number(lines):
    return [f"{counter}: {line}" for counter, line in enumerate(lines, start=1)]

print(number(["a", "b", "c"]))

Training on Testing 1-2-3 | Codewars

Read more ...

Invert values Python Codewars

Given a set of numbers, return the additive inverse of each. Each positive becomes negatives, and the negatives become positives.

invert([1,2,3,4,5]) == [-1,-2,-3,-4,-5]
invert([1,-2,3,-4,5]) == [-1,2,-3,4,-5]
invert([]) == []

You can assume that all values are integers. Do not mutate the input array/list.


def invert(lst):
   return [i*-1 for i in lst]

print(invert([1,2,3,4,5]))

Invert values Solutions | Codewars

Read more ...

Ones and Zeros Python Codewars

 

Given an array of ones and zeroes, convert the equivalent binary value to an integer.

Eg: [0, 0, 0, 1] is treated as 0001 which is the binary representation of 1.

Examples:

Testing: [0, 0, 0, 1] ==> 1
Testing: [0, 0, 1, 0] ==> 2
Testing: [0, 1, 0, 1] ==> 5
Testing: [1, 0, 0, 1] ==> 9
Testing: [0, 0, 1, 0] ==> 2
Testing: [0, 1, 1, 0] ==> 6
Testing: [1, 1, 1, 1] ==> 15
Testing: [1, 0, 1, 1] ==> 11

However, the arrays can have varying lengths, not just limited to 4.

 


def binary_array_to_number(arr):
    return int(''.join([str(item) for item in arr]), 2)

def binary_array_to_number(arr):
    s = 0
    for digit in arr:
        s = s * 2 + digit

    return s
print(binary_array_to_number([0,0,0,1]))

Training on Ones and Zeros | Codewars

Read more ...

Who likes it? Python Codewars

 

You probably know the "like" system from Facebook and other pages. People can "like" blog posts, pictures or other items. We want to create the text that should be displayed next to such an item.

Implement the function which takes an array containing the names of people that like an item. It must return the display text as shown in the examples:

[]                                -->  "no one likes this"
["Peter"]                         -->  "Peter likes this"
["Jacob", "Alex"]                 -->  "Jacob and Alex like this"
["Max", "John", "Mark"]           -->  "Max, John and Mark like this"
["Alex", "Jacob", "Mark", "Max"]  -->  "Alex, Jacob and 2 others like this"

Note: For 4 or more names, the number in "and 2 others" simply increases.


def likes(names):
    if names == []:
        return 'no one likes this'
    elif len(names) == 1:
        return f'{names[0]} likes this'
    elif len(names) == 2:
        return f'{names[0]} and {names[1]} like this'
    elif len(names) == 3:
        return f'{names[0]}, {names[1]} and {names[2]} like this'
    else:
        others = len(names) - 2
        return f'{names[0]}, {names[1]} and {others} others like this'

def likes(names):
    # make a dictionary d of all the possible answers. Keys are the respective number
    # of people who liked it.
    
    # {} indicate placeholders. They do not need any numbers but are simply replaced/formatted
    # in the order the arguments in names are given to format
    # {others} can be replaced by its name; below the argument "others = length - 2"
    # is passed to str.format()
    d = {
        0: "no one likes this",
        1: "{} likes this",
        2: "{} and {} like this",
        3: "{}, {} and {} like this",
        4: "{}, {} and {others} others like this"
        }
    length = len(names)
    # d[min(4, length)] insures that the appropriate string is called from the dictionary
    # and subsequently returned. Min is necessary as len(names) may be > 4
    
    # The * in *names ensures that the list names is blown up and that format is called
    # as if each item in names was passed to format individually, i. e.
    # format(names[0], names[1], .... , names[n], others = length - 2
    return d[min(4, length)].format(*names, others = length - 2)

print(likes(['Alex', 'Jacob', 'Mark', 'Max']))

Who likes it? Solutions | Codewars

Read more ...

Sunday, February 13, 2022

Extract the domain name from a URL Python Codewars

Write a function that when given a URL as a string, parses out just the domain name and returns it as a string. For example:

domain_name("http://github.com/carbonfive/raygun") == "github" 
domain_name("http://www.zombie-bites.com") == "zombie-bites"
domain_name("https://www.cnet.com") == "cnet"


def domain_name(url):
    return url.split('//')[-1].split('www.')[-1].split('.')[0]



print(domain_name('http://hello.com'))

def domain_name(url):
    return url.split("://")[-1].split(".")[-2]

Extract the domain name from a URL Solutions | Codewars

Read more ...

Mexican Wave Python Codewars

Task

In this simple Kata your task is to create a function that turns a string into a Mexican Wave. You will be passed a string and you must return that string in an array where an uppercase letter is a person standing up. 

Rules

 1.  The input string will always be lower case but maybe empty.
2.  If the character in the string is whitespace then pass over it as if it was an empty seat

Example

wave("hello") => ["Hello", "hEllo", "heLlo", "helLo", "hellO"]

 


def wave(people):
    res = []
    for i in range(len(people)):
        if people[i]!=' ':
            res.append(people[:i]+people[i].upper()+people[i+1:])
    return res

def wave(str):
    return [str[:i] + str[i].upper() + str[i+1:] for i in range(len(str)) if str[i].isalpha()]

print(wave('hello'))

Training on Mexican Wave | Codewars

Read more ...

Fake Binary Python Codewars

 

Given a string of digits, you should replace any digit below 5 with '0' and any digit 5 and above with '1'. Return the resulting string.

Note: input will never be an empty string


def fake_bin(x):
    res = ''
    for n in str(x):
        if int(n) < 5:
            res += '0'
        if int(n) >= 5:
            res += '1'
    return res

def fake_bin(x):
    return ''.join('0' if c < '5' else '1' for c in x)

print(fake_bin(509321967506747))

Training on Fake Binary | Codewars

Read more ...

Saturday, February 12, 2022

Two Sum Python

Write a function that takes an array of numbers (integers for the tests) and a target number. It should find two different items in the array that, when added together, give the target value. The indices of these items should then be returned in a tuple like so: (index1, index2).

For the purposes of this kata, some tests may have multiple answers; any valid solutions will be accepted.

The input will always be valid (numbers will be an array of length 2 or greater, and all of the items will be numbers; target will always be the sum of two different items from that array).

Based on: http://oj.leetcode.com/problems/two-sum/

twoSum [1, 2, 3] 4 === (0, 2)

def two_sum(nums, t):
    for i, x in enumerate(nums):
        print('i>',i)
        for j, y in enumerate(nums):
            print('j>',j)
            if i != j and x + y == t:
                return [i, j]

print((two_sum([1,3,2], 4)))


Two Sum Solutions | Codewars

Read more ...

Count the divisors of a number Python Codewars

Count the number of divisors of a positive integer n.

Random tests go up to n = 500000.

Examples (input --> output)
4 --> 3 (1, 2, 4)
5 --> 2 (1, 5)
12 --> 6 (1, 2, 3, 4, 6, 12)
30 --> 8 (1, 2, 3, 5, 6, 10, 15, 30)

def divisors(n):
    count = 0
    for i in range(1, n+1):
        if n%i == 0:
            count += 1
    return count

def divisors(n):
    return sum(n%i==0 for i in range(1,n+1))
        

Training on Count the divisors of a number | Codewars

Read more ...

Friday, February 11, 2022

Unique In Order Python Codewars

 

Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements.

For example:

unique_in_order('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B']
unique_in_order('ABBCcAD')         == ['A', 'B', 'C', 'c', 'A', 'D']
unique_in_order([1,2,2,3,3])       == [1,2,3]

def unique_in_order(iterable):
    is_in = ''
    res = []
    for char in iterable:
        if char != is_in:
            is_in = char
            res.append(char)
    return res

def unique_in_order(iterable):
    r = []
    for x in iterable:
        x in r[-1:] or r.append(x)
    return r
 print(unique_in_order('AAAABBBCCDAABBB')) 

Training on Unique In Order | Codewars

Read more ...

Thinkful - Logic Drills: Traffic light Python Codewars

 

You're writing code to control your town's traffic lights. You need a function to handle each change from green, to yellow, to red, and then to green again.

Complete the function that takes a string as an argument representing the current state of the light and returns a string representing the state the light should change to.

For example, update_light('green') should return 'yellow'.


def update_light(current):
    order = ['green','yellow','red']
    if current == 'green':
        return 'yellow'
    if current == 'yellow':
        return 'red'
    if current == 'red':
        return 'green'

def update_light(current):
    light_order = {'red':'green', 'yellow':'red', 'green':'yellow'}    
    return light_order[current]

print(update_light('green'))

Thinkful - Logic Drills: Traffic light Solutions | Codewars

Read more ...

Count the smiley faces! Python Codewars

 

Given an array (arr) as an argument complete the function countSmileys that should return the total number of smiling faces.

Rules for a smiling face:

  • Each smiley face must contain a valid pair of eyes. Eyes can be marked as : or ;
  • A smiley face can have a nose but it does not have to. Valid characters for a nose are - or ~
  • Every smiling face must have a smiling mouth that should be marked with either ) or D

No additional characters are allowed except for those mentioned.

Valid smiley face examples: :) :D ;-D :~)
Invalid smiley faces: ;( :> :} :]

Example

countSmileys([':)', ';(', ';}', ':-D']);       // should return 2;
countSmileys([';D', ':-(', ':-)', ';~)']);     // should return 3;
countSmileys([';]', ':[', ';*', ':$', ';-D']); // should return 1;

Note

In case of an empty array return 0. You will not be tested with invalid input (input will always be an array). Order of the face (eyes, nose, mouth) elements will always be the same.


def count_smileys(arr):
    smileys = []
    for s in arr:
        if len(s) == 2 and s[0] in [":", ";"] and s[-1] in [")", "D"]:
            smileys.append(s)
        elif len(s) > 2 and s[0] in [":", ";"] and s[1] in ["-", "~"] and s[-1] in [")", "D"]:
            smileys.append(s)
    return len(smileys)

def count_smileys(arr):
    total = 0
    if not arr:
      return 0
    smileys =  [':)', ';)', ':~)', ';~)', ':-)', ';-)', ':D', ';D', ':~D', ';~D', ':-D', ';-D']
    for i in arr:
      if i in smileys:
        total += 1
    return total

print(count_smileys([':D',':~)',';~D',':)']))

Training on Count the smiley faces! | Codewars

Read more ...

Thursday, February 10, 2022

The Supermarket Queue Python Codewars

 

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.


Important

Please look at the examples and clarifications below, to ensure you understand the task correctly :)


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

N.B. You should assume that all the test input will be valid, as specified above.

P.S. The situation in this kata can be likened to the more-computer-science-related idea of a thread pool, with relation to running multiple processes at the same time: https://en.wikipedia.org/wiki/Thread_pool

def queue_time(customers, n):
    queues = [0] * n
    for i in customers:
        queues.sort()
        queues[0] += i
    return max(queues)
print(queue_time([2,3,10], 2))
# create a list of available checkouts, and iterate customers over checkouts

The Supermarket Queue Solutions | Codewars

Read more ...

Calculating with Functions Python Codewars

 

This time we want to write calculations using functions and get the results. Let's have a look at some examples:

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, divided_by
  • 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
  • Division should be integer division. For example, this should return 2, not 2.666666...:
eight(divided_by(three()))

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 '+' + str(n)
def minus(n):      return '-' + str(n)
def times(n):      return '*' + str(n)
def divided_by(n): return '//' + str(n)

print(seven(times(five())))
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

Python eval() (programiz.com)

Training on Calculating with Functions | Codewars

Read more ...

Write Number in Expanded Form Python Codewars

You will be given a number and you will need to return it as a string in Expanded Form. For example:

expanded_form(12) # Should return '10 + 2'
expanded_form(42) # Should return '40 + 2'
expanded_form(70304) # Should return '70000 + 300 + 4'

NOTE: All numbers will be whole numbers greater than 0.



def expanded_form(num):
    res = []
    for index,digit in enumerate(str(num)):
        if digit != '0':
            res.append(digit+'0'*(len(str(num)[index:])-1))
    return ' + '.join(res)

print(expanded_form(70304))

Training on Write Number in Expanded Form | Codewars

Read more ...

Wednesday, February 9, 2022

Regex validate PIN code Python Codewars

 

ATM machines allow 4 or 6 digit PIN codes and PIN codes cannot contain anything but exactly 4 digits or exactly 6 digits.

If the function is passed a valid PIN string, return true, else return false.

Examples (Input --> Output)

"1234"   -->  true
"12345"  -->  false
"a234"   -->  false

def validate_pin(pin):
    return len(pin) in (4, 6) and pin.isdigit()

print(validate_pin(1234))

Regex validate PIN code Solutions | Codewars

Read more ...

Count characters in your string Python Codewars

 

The main idea is to count all the occurring characters in a string. If you have a string like aba, then the result should be {'a': 2, 'b': 1}.

What if the string is empty? Then the result should be empty object literal, {}.

 


def count(string):
    return {char:string.count(char) for char in string}
# Count character for each in string
print(count('aba'))

Training on Count characters in your string | Codewars

Read more ...

Sentence Smash Python Codewars

 

Write a function that takes an array of words and smashes them together into a sentence and returns the sentence. You can ignore any need to sanitize words or add punctuation, but you should add spaces between each word. Be careful, there shouldn't be a space at the beginning or the end of the sentence!

Example

['hello', 'world', 'this', 'is', 'great']  =>  'hello world this is great'

 


def smash(words):
    return " ".join(words) 

Training on Sentence Smash | Codewars

Read more ...

Is he gonna survive?

 

A hero is on his way to the castle to complete his mission. However, he's been told that the castle is surrounded with a couple of powerful dragons! each dragon takes 2 bullets to be defeated, our hero has no idea how many bullets he should carry.. Assuming he's gonna grab a specific given number of bullets and move forward to fight another specific given number of dragons, will he survive?

Return True if yes, False otherwise :)

 


def hero(bullets, dragons):
    return bullets >= 2*dragons

print(hero(100, 40))

Training on Is he gonna survive? | Codewars

Read more ...

Build Tower Python Codewars

 

Build Tower by the following given argument:
number of floors (integer and always greater than 0).

Tower block is represented as *

  • Python: return a list;

for example, a tower of 3 floors looks like below

[
  '  *  ', 
  ' *** ', 
  '*****'
]

and a tower of 6 floors looks like below

[
  '     *     ', 
  '    ***    ', 
  '   *****   ', 
  '  *******  ', 
  ' ********* ', 
  '***********'
]

def tower_builder(n_floors):
    tower = []
    n = n_floors
    for i in range(n_floors):
        n -= 1
        tower.append(' ' * n + '*' * (i * 2 + 1) + ' ' * n)
    return tower

print(tower_builder(5))
def tower_builder(n):
    return [("*" * (i*2-1)).center(n*2-1) for i in range(1, n+1)]

 

Training on Build Tower | Codewars


Read more ...

Money, Money, Money Python Codewars

 

Mr. Scrooge has a sum of money 'P' that he wants to invest. Before he does, he wants to know how many years 'Y' this sum 'P' has to be kept in the bank in order for it to amount to a desired sum of money 'D'.

The sum is kept for 'Y' years in the bank where interest 'I' is paid yearly. After paying taxes 'T' for the year the new sum is re-invested.

Note to Tax: not the invested principal is taxed, but only the year's accrued interest

Example:

  Let P be the Principal = 1000.00      
  Let I be the Interest Rate = 0.05      
  Let T be the Tax Rate = 0.18      
  Let D be the Desired Sum = 1100.00


After 1st Year -->
  P = 1041.00
After 2nd Year -->
  P = 1083.86
After 3rd Year -->
  P = 1128.30

Thus Mr. Scrooge has to wait for 3 years for the initial principal to amount to the desired sum.

Your task is to complete the method provided and return the number of years 'Y' as a whole in order for Mr. Scrooge to get the desired sum.

Assumption: Assume that Desired Principal 'D' is always greater than the initial principal. However it is best to take into consideration that if Desired Principal 'D' is equal to Principal 'P' this should return 0 Years.

 



def calculate_years(principal, interest, tax, desired):
    yrs = 0

    while principal < desired:
        yrs += 1
        tot_int = principal * interest
        int_tax = tot_int * tax
        principal = principal + (tot_int - int_tax)

    return yrs

print(calculate_years(1000, 0.05, 0.18, 1100))

Training on Money, Money, Money | Codewars

Read more ...

Tuesday, February 8, 2022

Bouncing Balls Python

 

A child is playing with a ball on the nth floor of a tall building. The height of this floor, h, is known.

He drops the ball out of the window. The ball bounces (for example), to two-thirds of its height (a bounce of 0.66).

His mother looks out of a window 1.5 meters from the ground.

How many times will the mother see the ball pass in front of her window (including when it's falling and bouncing?

Three conditions must be met for a valid experiment:
  • Float parameter "h" in meters must be greater than 0
  • Float parameter "bounce" must be greater than 0 and less than 1
  • Float parameter "window" must be less than h.

If all three conditions above are fulfilled, return a positive integer, otherwise return -1.

Note:

The ball can only be seen if the height of the rebounding ball is strictly greater than the window parameter.

Examples:
- h = 3, bounce = 0.66, window = 1.5, result is 3

- h = 3, bounce = 1, window = 1.5, result is -1 

(Condition 2) not fulfilled).

def bouncing_ball(h, bounce, window):
    if h != 0 and bounce > 0 and bounce < 1 and window < h:
        count = 1
        current = h*bounce
        while current > window:
            current *= bounce
            count += 2
        return count 
    else: 
         return -1 

print(bouncing_ball(30, 0.66, 1.5))

Training on Bouncing Balls | Codewars

Read more ...

Find the next perfect square! Python

 

You might know some pretty large perfect squares. But what about the NEXT one?

Complete the findNextSquare method that finds the next integral perfect square after the one passed as a parameter. Recall that an integral perfect square is an integer n such that sqrt(n) is also an integer.

If the parameter is itself not a perfect square then -1 should be returned. You may assume the parameter is non-negative.

Examples:(Input --> Output)

121 --> 144
625 --> 676
114 --> -1 since 114 is not a perfect square
import math

def find_next_square(sq):
    root = math.sqrt(sq)
    print(root)
    if sq == int(root) ** 2:
        return int(root+1) ** 2
    else:
        return -1
        

def find_next_square(sq):
    root = sq ** 0.5
    if root.is_integer():
        return (root + 1)**2
    return -1
    
print(find_next_square(121))


Training on Find the next perfect square! | Codewars

Read more ...

Beginner Series #3 Sum of Numbers Python

 

Given two integers a and b, which can be positive or negative, find the sum of all the integers between and including them and return it. If the two numbers are equal return a or b.

Note: a and b are not ordered!

Examples (a, b) --> output (explanation)

(1, 0) --> 1 (1 + 0 = 1)
(1, 2) --> 3 (1 + 2 = 3)
(0, 1) --> 1 (0 + 1 = 1)
(1, 1) --> 1 (1 since both are same)
(-1, 0) --> -1 (-1 + 0 = -1)
(-1, 2) --> 2 (-1 + 0 + 1 + 2 = 2)

def get_sum(a,b):
    total = 0
    if a == b:
        return a
    for i in range(min(a,b), max(a,b)+1):
        total += i
    return total


def get_sum(a,b):
    return sum(range(min(a, b), max(a, b) + 1))

Training on Beginner Series #3 Sum of Numbers | Codewars

Read more ...

Count by X Python

 

Create a function with two arguments that will return an array of the first (n) multiples of (x).

Assume both the given number and the number of times to count will be positive numbers greater than 0.

Return the results as an array (or list in Python, Haskell or Elixir).

Examples:

count_by(1,10) #should return [1,2,3,4,5,6,7,8,9,10]
count_by(2,5) #should return [2,4,6,8,10]
def count_by(x, n):
    arr = []
    for num in range(1, n+1):
        result = x * num
        arr.append(result)
    return arr
def count_by(x, n):
    return range(x, x * n + 1, x)

print(count_by(3,5))


Training on Count by X | Codewars

Read more ...

Square Every Digit Python

 

Welcome. In this kata, you are asked to square every digit of a number and concatenate them.

For example, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1.

Note: The function accepts an integer and returns an integer



def square_digits(num):
    r = ''
    for l in str(num):
     r = r + str((int(l))**2)
    return int(r)
print(square_digits(9119))
def square_digits(num):
    return int(''.join(str(int(d)**2) for d in str(num)))

Training on Square Every Digit | Codewars

Read more ...

Exes and Ohs Python

 

Check to see if a string has the same amount of 'x's and 'o's. The method must return a boolean and be case insensitive. The string can contain any char.

Examples input/output:

XO("ooxx") => true
XO("xooxx") => false
XO("ooxXm") => true
XO("zpzpzpp") => true // when no 'x' and 'o' is present should return true
XO("zzoo") => false

def xo(s):
    count_o = 0
    count_x = 0
    for i in s:
        if i.lower() == 'x':
            count_x += 1
        if i.lower() == 'o':
            count_o += 1
    return True if count_o == count_x else False

print(xo("xxooo"))

def xo(s):
    s = s.lower()
    return s.count('x') == s.count('o')

Training on Exes and Ohs | Codewars

Read more ...

Monday, February 7, 2022

Total amount of points Python

 

Our football team finished the championship. The result of each match look like "x:y". Results of all matches are recorded in the collection.

For example: ["3:1", "2:2", "0:1", ...]

Write a function that takes such collection and counts the points of our team in the championship. Rules for counting points for each match:

  • if x>y - 3 points
  • if x<y - 0 point
  • if x=y - 1 point

Notes:

  • there are 10 matches in the championship
  • 0 <= x <= 4
  • 0 <= y <= 4


def points(games):
    total = 0
    for j in games:
        i = j.split(':')
        if i[0] > i[1]:
            total += 3
        if i[0] == i[1]:
            total += 1

    return total 

print(points(['1:0','2:0','3:0','4:0','2:1','3:1','4:1','3:2','4:2','4:3']))

Training on Total amount of points | Codewars

Read more ...

Take a Number And Sum Its Digits Raised To The Consecutive Powers And ....¡Eureka!! Python

 

The number 89 is the first integer with more than one digit that fulfills the property partially introduced in the title of this kata. What's the use of saying "Eureka"? Because this sum gives the same number.

In effect: 89 = 8^1 + 9^2

The next number in having this property is 135.

See this property again: 135 = 1^1 + 3^2 + 5^3

We need a function to collect these numbers, that may receive two integers a, b that defines the range [a, b] (inclusive) and outputs a list of the sorted numbers in the range that fulfills the property described above.

Let's see some cases:

sum_dig_pow(1, 10) == [1, 2, 3, 4, 5, 6, 7, 8, 9]

sum_dig_pow(1, 100) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 89]

If there are no numbers of this kind in the range [a, b] the function should output an empty list.

sum_dig_pow(90, 100) == []

Enjoy it!!



def sum_dig_pow(a, b):
    res = []
    for i in range(a, b+1):
        total_sum = sum(int(x) ** (index + 1) for index, x in enumerate(str(i)))
        if total_sum == i:
            res.append(i)
    return res
# Enumerate the number from the range, so you can sum the power

print(sum_dig_pow(1, 100))
def sum_dig_pow(a, b): return [x for x in range(a, b+1) if sum(int(d)**i for i, d in enumerate(str(x), 1)) == x]

Training on Take a Number And Sum Its Digits Raised To The Consecutive Powers And ....¡Eureka!! | Codewars

Read more ...

Diff.array Python

 

Your goal in this kata is to implement a difference function, which subtracts one list from another and returns the result.

It should remove all values from list a, which are present in list b keeping their order.

array_diff([1,2],[1]) == [2]

If a value is present in b, all of its occurrences must be removed from the other:

array_diff([1,2,2,2,3],[2]) == [1,3]

def array_diff(a, b):
    return [x for x in a if x not in b]

Array.diff Solutions | Codewars

Read more ...

Detect Pangram Python

 

A pangram is a sentence that contains every single letter of the alphabet at least once. For example, the sentence "The quick brown fox jumps over the lazy dog" is a pangram, because it uses the letters A-Z at least once (case is irrelevant).

Given a string, detect whether or not it is a pangram. Return True if it is, False if not. Ignore numbers and punctuation.

 



import string

def is_pangram(s):
    return set(s.lower()) >= set(string.ascii_lowercase)

# Use set to count and compare with ascii_lowercase        
pangram = "The quick, brown fox jumps over the lazy dog!"
print(is_pangram(pangram))

Training on Detect Pangram | Codewars

Read more ...

Sunday, February 6, 2022

Break Camelcase Python

Complete the solution so that the function will break up camel casing, using a space between words.

Example
"camelCasing"  =>  "camel Casing"
"identifier"   =>  "identifier"
""             =>  ""

def solution(s):
    new=''
    for i in s:
        if i.islower():
            new += i 
        else:
            new += ' '+i
    return new



def solution(s):
    return ''.join(' ' + c if c.isupper() else c for c in s)

Training on Break camelCase | Codewars

Read more ...

Better than average Codewars Python

 

There was a test in your class and you passed it. Congratulations!
But you're an ambitious person. You want to know if you're better than the average student in your class.

You receive an array with your peers' test scores. Now calculate the average and compare your score!

Return True if you're better, else False!

Note:

Your points are not included in the array of your class's points. For calculating the average point you may add your point to the given array!

 


def better_than_average(class_points, your_points):
    average = sum(class_points) / len(class_points)
    return bool(your_points > average)

Training on How good are you really? | Codewars

Read more ...

Product of consecutive Fib numbers Codewars Python

The Fibonacci numbers are the numbers in the following integer sequence (Fn):

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, ...

such as

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

F(n) * F(n+1) = prod.

Your function productFib takes an integer (prod) and returns an array:

[F(n), F(n+1), true] or {F(n), F(n+1), 1} or (F(n), F(n+1), True)

depending on the language if F(n) * F(n+1) = prod.

If you don't find two consecutive F(n) verifying F(n) * F(n+1) = prodyou will return

[F(n), F(n+1), false] or {F(n), F(n+1), 0} or (F(n), F(n+1), False)

F(n) being the smallest one such as F(n) * F(n+1) > prod.

Some Examples of Return:

(depend on the language)

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], 
productFib(800) # should return [34, 55, false], 
-----
productFib(714) # should return {21, 34, 1}, 
productFib(800) # should return {34, 55, 0},        
-----
productFib(714) # should return {21, 34, true}, 
productFib(800) # should return {34, 55, false}, 

def productFib(prod):
  a, b = 0, 1
  while prod > a * b:
    a, b = b, a + b
  return [a, b, prod == a * b]

print(productFib(714))

Product of consecutive Fib numbers Solutions | Codewars

Read more ...

Century From Year Codewars Python

 

The first century spans from the year 1 up to and including the year 100, the second century - from the year 101 up to and including the year 200, etc.

Task

Given a year, return the century it is in.

Examples
1705 --> 18
1900 --> 19
1601 --> 17
2000 --> 20
 
def century(year):
    return int(year / 100) + (year % 100 > 0)

Training on Century From Year | Codewars

Read more ...

Sum without highest and lowest number Codewars Python

 

Sum all the numbers of a given array ( cq. list ), except the highest and the lowest element ( by value, not by index! ).

The highest or lowest element respectively is a single element at each edge, even if there are more than one with the same value.

Mind the input validation.

Example

{ 6, 2, 1, 8, 10 } => 16
{ 1, 1, 11, 2, 3 } => 6

Input validation

If an empty value ( null, None, Nothing etc. ) is given instead of an array, or the given array is an empty list or a list with only 1 element, return 0.


def sum_array(arr):
    if arr == '' or arr is None or len(arr) == 1:
        return 0
    result = sum(sorted(arr)[1:-1])
    return result

Training on Sum without highest and lowest number | Codewars

Read more ...

Consecutive strings Codewars Python

Description:

You are given an array(list) strarr of strings and an integer k. Your task is to return the first longest string consisting of k consecutive strings taken in the array.

Examples:
strarr = ["tree", "foling", "trashy", "blue", "abcdef", "uvwxyz"], k = 2

Concatenate the consecutive strings of strarr by 2, we get:

treefoling   (length 10)  concatenation of strarr[0] and strarr[1]
folingtrashy ("      12)  concatenation of strarr[1] and strarr[2]
trashyblue   ("      10)  concatenation of strarr[2] and strarr[3]
blueabcdef   ("      10)  concatenation of strarr[3] and strarr[4]
abcdefuvwxyz ("      12)  concatenation of strarr[4] and strarr[5]

Two strings are the longest: "folingtrashy" and "abcdefuvwxyz".
The first that came is "folingtrashy" so 
longest_consec(strarr, 2) should return "folingtrashy".

In the same way:
longest_consec(["zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"], 2) --> "abigailtheta"

n being the length of the string array, if n = 0 or k > n or k <= 0 return "" (return Nothing in Elm).


def longest_consec(strarr, k):
  if k <= 0 or len(strarr) == 0 or k > len(strarr):
    return ''
  result = ''
  
  for i in range(len(strarr) - k + 1):
    sub_str = ''.join(strarr[i:i+k])
    if len(result) < len(sub_str):
      result = sub_str
  
  return result

print(longest_consec(["zone", "abigail", "theta", "form", "libe", "zas"], 2))

Consecutive strings Solutions | Codewars

Read more ...

Remove the minimum Codewars Python

 

Given an array of integers, remove the smallest value. Do not mutate the original array/list. If there are multiple elements with the same value, remove the one with a lower index. If you get an empty array/list, return an empty array/list.

Don't change the order of the elements that are left.

Examples
remove_smallest([1,2,3,4,5]) = [2,3,4,5]
remove_smallest([5,3,2,1,4]) = [5,3,2,4]
remove_smallest([2,2,1,2,1]) = [2,2,2,1]

def remove_smallest(numbers):
    a = numbers[:]
    if a:
        a.remove(min(a))
    return a

# The remove() method removes the first matching element (which is passed as an argument) from the list.
print(remove_smallest([1, 2, 3, 1, 1]))

Training on Remove the minimum | Codewars

Read more ...

Saturday, February 5, 2022

Complementary DNA Codewars Python

Deoxyribonucleic acid (DNA) is a chemical found in the nucleus of cells and carries the "instructions" for the development and functioning of living organisms.

If you want to know more: http://en.wikipedia.org/wiki/DNA

In DNA strings, symbols "A" and "T" are complements of each other, as "C" and "G". You function receives one side of the DNA (string, except for Haskell); you need to return the other complementary side. DNA strand is never empty or there is no DNA at all (again, except for Haskell).

More similar exercise are found here: http://rosalind.info/problems/list-view/ (source)

Example: (input --> output)

"ATTGC" --> "TAACG"
"GTAT" --> "CATA"
dnaStrand []        `shouldBe` []
dnaStrand [A,T,G,C] `shouldBe` [T,A,C,G]
dnaStrand [G,T,A,T] `shouldBe` [C,A,T,A]
dnaStrand [A,A,A,A] `shouldBe` [T,T,T,T]
 
def DNA_strand(dna):
    key = "ATGC"
    val = "TACG"
    transform = dict(zip(key, val))
    return ''.join(transform.get(char, char) for char in dna)

Training on Complementary DNA | Codewars

Read more ...

Number of People in the Bus Codewars Python

There is a bus moving in the city, and it takes and drop some people in each bus stop.

You are provided with a list (or array) of integer pairs. Elements of each pair represent number of people get into bus (The first item) and number of people get off the bus (The second item) in a bus stop.

Your task is to return number of people who are still in the bus after the last bus station (after the last array). Even though it is the last bus stop, the bus is not empty and some people are still in the bus, and they are probably sleeping there :D

Take a look on the test cases.

Please keep in mind that the test cases ensure that the number of people in the bus is always >= 0. So the return integer can't be negative.

The second value in the first integer array is 0, since the bus is empty in the first bus stop.


def number(bus_stops):
    people_in = 0
    people_out = 0
    for i in bus_stops:
        people_in += i[0]
        print(people_in)
        people_out += i[1]
        print(people_out)
    return people_in - people_out

def number(bus_stops):
    return sum([stop[0] - stop[1] for stop in bus_stops])



# Sum the first and last in the list and subtract

print(number([[10,0],[3,5],[5,8]]))


Training on Number of People in the Bus | Codewars

Read more ...

Friday, February 4, 2022

Rot13 Codewars Python

ROT13 is a simple letter substitution cipher that replaces a letter with the letter 13 letters after it in the alphabet. ROT13 is an example of the Caesar cipher.

Create a function that takes a string and returns the string ciphered with Rot13. If there are numbers or special characters included in the string, they should be returned as they are. Only letters from the latin/english alphabet should be shifted, like in the original Rot13 "implementation".



def rot13(message):
    key = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    val = "nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM"
    transform = dict(zip(key, val))
    return ''.join(transform.get(char, char) for char in message)

# generate key value pair using zip and get value for each in the string

Training on Rot13 | Codewars

Read more ...

Calculate BMI Codewars Python

Write function bmi that calculates body mass index (bmi = weight / height2).

if bmi <= 18.5 return "Underweight"

if bmi <= 25.0 return "Normal"

if bmi <= 30.0 return "Overweight"

if bmi > 30 return "Obese"


def bmi(weight, height):
    bmi = (weight / (height ** 2))
    print(bmi)
    if bmi <= 18.5:
        return "Underweight"
    elif bmi <= 25.0:
        return "Normal"
    elif bmi <= 30.0:
        return "Overweight"
    elif bmi > 30:
        return "Obese"


Calculate BMI | Codewars

Read more ...

Descending Order Codewars Python

Your task is to make a function that can take any non-negative integer as an argument and return it with its digits in descending order. Essentially, rearrange the digits to create the highest possible number.

Examples:

Input: 42145 Output: 54421

Input: 145263 Output: 654321

Input: 123456789 Output: 987654321

 


def descending_order(num):
    num_list = sorted(str(num))[::-1]
    return int("".join(x for x in num_list))


# Sort the number and join as int

 

Descending Order Solutions | Codewars

Read more ...

Thursday, February 3, 2022

Count of positives / sum of negatives Codewars Python

Given an array of integers.

Return an array, where the first element is the count of positives numbers and the second element is sum of negative numbers. 0 is neither positive nor negative.

If the input array is empty or null, return an empty array.

Example

For input [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15], you should return [10, -65].


def count_positives_sum_negatives(arr):
    if not arr: return []
    count = 0
    sum_list = 0
    for x in arr:
        if x > 0:
            count += 1
        if x < 0:
            sum_list += x
    return [count,sum_list]

def count_positives_sum_negatives(arr):
    return [len([x for x in arr if x > 0])] + [sum(y for y in arr if y < 0)] if arr else []

Training on Count of positives / sum of negatives | Codewars

Read more ...

Multiples of 3 or 5 Codewars Python

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in. Additionally, if the number is negative, return 0 (for languages that do have them).

Note: If the number is a multiple of both 3 and 5, only count it once.

 


def solution(number):
    # create a list to populate
    answers = []
    
    # loop through all numbers in the range
    for i in range(number):
        # if divisible by 3 or 5 and within range
        if (i%3==0 or i%5==0) and i0:
            # add to the answers list
            answers.append(i)
        
    # return the sum of the answers
    return sum(answers)

Multiples of 3 or 5 Solutions | Codewars

Read more ...

Convert number to reversed array of digits Codewars Python

 

Given a random non-negative number, you have to return the digits of this number within an array in reverse order.

Example:

348597 => [7,9,5,8,4,3]
0 => [0]

def digitize(n):
    new = []
    for i in str(n)[::-1]:
        new.append(int(i))
    return new

def digitize(n):
    return [int(s) for s in str(n)[::-1]]

# Revesre the string and convert to int and return as a list

Convert number to reversed array of digits Solutions | Codewars

Read more ...

Tribonacci Codewars Python

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. And, worse part of it, regrettably I won't get to hear non-native Italian speakers trying to pronounce it :(

So, if we are to start our Tribonacci sequence with [1, 1, 1] as a starting input (AKA signature), we have this sequence:

[1, 1 ,1, 3, 5, 9, 17, 31, ...]

def tribonacci(signature, n):
    if n <= 2:
        return signature[:n]
    res = 0
    for i in range(n - len(signature)):
        res = sum(signature[-3:])
        signature.append(res)
    return signature

def tribonacci(signature, n):
  res = signature[:n]
  for i in range(n - 3): res.append(sum(res[-3:]))
  return res
# For range in n - len(signature) sum the last three and append to the signature

Read more ...

Reverse words Codewars Python

Description:

Complete the function that accepts a string parameter, and reverses each word in the string. All spaces in the string should be retained.

Examples

"This is an example!" ==> "sihT si na !elpmaxe"
"double  spaces"      ==> "elbuod  secaps"

def reverse_words(text):
    new=[]
    for word in text.split(' '):
        new.append(word[::-1])
    return ' '.join(new)

def reverse_words(str):
    return ' '.join(s[::-1] for s in str.split(' '))

# Split the string with space delimiter and reverse each word and append
Read more ...

Wednesday, February 2, 2022

Alphabet Position Codewars Python

In this kata you are required to, given a string, replace every letter with its position in the alphabet.

If anything in the text isn't a letter, ignore it and don't return it.

"a" = 1, "b" = 2, etc.

Example

alphabet_position("The sunset sets at twelve o' clock.")

Should return "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11" ( as a string )

 


def alphabet_position(text):
    new=''
    for c in text.lower():
        if c.isalpha():
            new += (str(ord(c)- 96)) + ' '
    return new

def alphabet_position(text):
    return ' '.join(str(ord(c) - 96) for c in text.lower() if c.isalpha())

# ord() returns an integer representing the Unicode character
# ord(a) is 97, so we subtract 96 to get the position to 1
# isalpha() checks if character is an alphabet (a-z)

Replace With Alphabet Position | Codewars

Read more ...

Disemvowel Trolls Codewars Python

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.

For example, the string "This website is for losers LOL!" would become "Ths wbst s fr lsrs LL!".

Note: for this kata y isn't considered a vowel.


def disemvowel(string_):
    return ''.join([l for l in string_ if l not in 'aeiouAEIOU'])

# Return the letters in string if not vowel

Training on Disemvowel Trolls | Codewars

Read more ...