Greetings fellow problem solvers! π€
As I am learning programming, I decided to spend more time on my problem-solving skills. Practice is a key aspect of the learning process and a great way to stay motivated.
With this new post series, I would like to share with you some code katas' solution. If you feel like it, don't hesitate to take those challenges on your own and share your solutions.
Algorithm/problem solving is just like a muscle that we must often train in order to improve. Today's problems are beginner-friendly, I will slowly bring harder problems on the table as this series is growing up.
Depending on my mood, I will provide solutions written in JavaScript, Python or C#. I can't wait to have your feedbacks and advices!
Table of Contents
Multiples of 3 & 5
From Codewars
The problem:
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.
My solution (Python):
def solution(number):
# Return 0 if argument is negative
if number <= 0: return 0
# Create a list to store multiples
multiples_list = []
# Loop from 1 to argument
for i in range(1, number):
if (i % 3 == 0) or (i % 5 == 0):
# Add multiples to the list
multiples_list.append(i)
# Return the sum
return sum(multiples_list)
Valid Braces
From Codewars
The problem:
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.
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.
Example:
"(){}[]" => True
"([{}])" => True
"(}" => False
"[(])" => False
"[({})](]" => False
My solution (Python):
def validBraces(string):
# Return False if arg is not a string
if type(string) is not str: return False
# Return False if arg's length is not even
if len(string) % 2 is not 0: return False
# Convert string to list
braces_list = list(string)
# Create a braces dictionnary
braces_dictionnary = {
"(": ")",
"{": "}",
"[": "]"
}
# Create a list of 'opened' braces
opened_braces = []
# Loop through the list generated by the string
for brace in braces_list:
# It is an opening brace
if brace in braces_dictionnary:
# Push it at the end of our opened braces list
opened_braces.append(brace)
# It is a closing brace
else:
# Check if opened braces list is empty
if len(opened_braces) == 0:
return False
# Check if the last encountered opening brace corresponds
if braces_dictionnary[opened_braces[-1]] == brace:
# It is the same so we remove it from the opened list
opened_braces.pop()
# They are different, string is not valid!
else:
return False
# Check if there are still opened braces in the list
if len(opened_braces) > 0:
return False
else:
return True
Roman Numerals Encoder
From Codewars
The problem:
Create a function taking a positive integer as its parameter and returning a string containing the Roman Numeral representation of that integer.
Modern Roman numerals are written by expressing each digit separately starting with the left most digit and skipping any digit with a value of zero. In Roman numerals 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC. 2008 is written as 2000=MM, 8=VIII; or MMVIII. 1666 uses each Roman symbol in descending order: MDCLXVI.
Help
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1,000
Example:
solution(1000) # should return 'M'
My solution (Python):
def solution(n):
# Check that n is an integer
if type(n) is not int:
return False
# Symbols sorted by index
sym_dictionnary = {
0: { 1: 'M' },
1: { 9: "CM", 5: "D", 4: "CD", 1: "C" },
2: { 9: "XC", 5: "L", 4: "XL", 1: "X" },
3: { 9: "IX", 5: "V", 4: "IV", 1: "I" },
}
# Create a digit list from n
digit_list = list(str(n / 10000))[2:]
# We will build the result with this list
result_list = []
# Loop through the digit list
for i in range(0, len(digit_list)):
current_digit = int(digit_list[i])
# Until the current digit reaches 0
while current_digit > 0:
# Find the appropriate symbol in the dictionnary and push it to the result list
for key in sym_dictionnary[i]:
if current_digit - key >= 0:
current_digit -= key
result_list.append(sym_dictionnary[i][key])
break;
# Convert to string and return the result
return "".join(result_list)
Pascal's Triangle
From Codewars
The problem:
In mathematics, Pascal's triangle is a triangular array of the binomial coefficients expressed with formula
Task
Write a function that, given a depth n, returns n top rows of Pascal's Triangle flattened into a one-dimensional list/array.
Example:
n = 1: [1]
n = 2: [1, 1, 1]
n = 4: [1, 1, 1, 1, 2, 1, 1, 3, 3, 1]
My solution (JavaScript):
function pascalsTriangle(n) {
// Helper variable that represents the pyramid as an array of arrays
const pyramid = [[1]];
// Result variable that will be returned
const result = [1];
// Loop until our pyramid has enough rows
for (let i = 1; i < n; i++) {
const newRow = [];
// Populate every slots in a row
for (let j = 0; j <= i; j++){
// The current number is the sum of the number at the current index and current index - 1 from the previous row
const currentNum = (pyramid[i-1][j] || 0) + (pyramid[i - 1][j - 1] || 0);
newRow[j] = currentNum;
result.push(currentNum)
}
// Append a new populated row at the end of every iteration
pyramid.push(newRow);
}
return result;
}
Persistent Bugger
From Codewars
The problem:
Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.
Example:
persistence(39) => 3 # Because 3*9 = 27, 2*7 = 14, 1*4=4
# and 4 has only one digit.
persistence(999) => 4 # Because 9*9*9 = 729, 7*2*9 = 126,
# 1*2*6 = 12, and finally 1*2 = 2.
persistence(4) => 0 # Because 4 is already a one-digit number.
My solution (Python):
def persistence(n):
# Convert a number to a list of digits
digit_list = [int(char) for char in str(n)]
# Count every loop iteration
count = 0
# Loop until we have 1 digit left
while len(digit_list) > 1:
# Multiply every digits in the list
newNumber = 1
for digit in digit_list: newNumber *= digit
# Update count and current number values
count += 1
digit_list = [int(char) for char in str(newNumber)]
return count
Top comments (0)