Tasks:
Task 1. Count number of vowels
Task 2. Find the divisors
Task 3. Binary Search
Task 4. Find the unique number
Task 5. Who likes it?
Task 6. Make an arithmetic function
Task 7. Duplicate Encoder
Task 8. Square of squares
Task 9. Consecutive strings
Task 1. Count number of vowels
>>Return to Menu
- Return the number (count) of vowels in the given string.
- We will consider a, e, i, o, u as vowels.
- The input string will only consist of lower case letters and/or spaces.
Solution 1:
def get_count(sentence):
return sum(1 for i in sentence if i in "aeiouAEIOU")
Solution 2:
def get_count(sentence):
return sum(i in 'aeiou' for i in sentence)
Solution 3:
def get_count(sentence):
vowels_count = 0
for i in sentence:
if i in "aeiouAEIOU":
vowels_count += 1
return vowels_count
Solution 4:
import re
def get_count(sentence):
return len(re.findall('[aeiou]', sentence, re.IGNORECASE))
Task 2. Find the divisors
>>Return to Menu
- Create a function named divisors that takes an integer (n > 1) and returns an array with all of the integer's divisors(except for 1 and the number itself), from smallest to largest.
- If the number is prime return the string ‘(integer) is prime’.
Example:
divisors(12); #should return [2,3,4,6]
divisors(25); #should return [5]
divisors(13); #should return "13 is prime"
Solution 1:
def divisors(integer):
l = [a for a in range(2,integer) if integer%a == 0]
if len(l) == 0:
return str(integer) + " is prime"
return l
Solution 2:
def divisors(integer):
divisor_list = [i for i in range(2,integer) if integer%i == 0]
return divisor_list if divisor_list != [] else f"{integer} is prime"
Task 3. Binary Search
>>Return to Menu
- Write a function that takes in a sorted array of integers as well as a target integer.
- The function should use the Binary Search algorithm to determine if the target integer is contained in the array and should return its index if it is, otherwise -1 .
Solution 1:
def binarySearch(array, target):
array.sort()
left = 0
right = len(array) - 1
while left <= right:
mid = (left + right)//2
if target == array[mid]:
return mid
elif target < array[mid]:
right = mid - 1
else:
left = mid + 1
return -1
Solution 2:
def binarySearch(array, target):
left = 0
right = len(array) - 1
def repeat_func(left,right):
if left > right:
return -1
mid = (left + right)//2
if target == array[mid]:
return mid
elif target < array[mid]:
return repeat_func(left,mid-1)
else:
return repeat_func(mid+1,right)
return repeat_func(left,right)
Task 4. Find the unique number
>>Return to Menu
- There is an array with some numbers. All numbers are equal except for one. Try to find it!
For Example:
find_uniq([ 1, 1, 1, 2, 1, 1 ]) == 2 find_uniq([ 0, 0, 0.55, 0, 0 ]) == 0.55
Solution 1
def find_uniq(arr):
a, b = set(arr)
return a if arr.count(a) == 1 else b
Solution 2
def find_uniq(arr):
[n] = [i for i in set(arr) if arr.count(i) == 1]
return n
Task 5. Who likes it?
>>Return to Menu
- 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"
Solution 1:
def likes(names):
n = len(names)
return {
0: 'no one likes this',
1: '{} likes this',
2: '{} and {} like this',
3: '{}, {} and {} like this',
4: '{}, {} and {others} others like this'
}[min(4, n)].format(*names[:3], others=n-2)
Solution 2:
def likes(names):
arr_len = len(names)
if arr_len < 1:
return "no one likes this"
elif arr_len == 1:
[a] = names
return f"{a} likes this"
elif arr_len == 2:
[a,b] = names
return f"{a} and {b} like this"
elif arr_len == 3:
[a,b,c] = names
return f"{a}, {b} and {c} like this"
[a,b,*c] = names
c_len = len(c)
return f"{a}, {b} and {c_len} others like this"
Task 6. Make an arithmetic function
>>Return to Menu
- Given two numbers and an arithmetic operator (the name of it, as a string), return the result of the two numbers having that operator used on them.
- a and b will both be positive integers, and a will always be the first number in the operation, and b always the second.
- The four operators are "add", "subtract", "divide", "multiply".
For Example:
5, 2, "add" --> 7
5, 2, "subtract" --> 3
5, 2, "multiply" --> 10
5, 2, "divide" --> 2.5
Solution 1:
def arithmetic(a, b, operator):
return {
'add': a + b,
'subtract': a - b,
'multiply': a * b,
'divide': a / b,
}[operator]
Solution 2:
def arithmetic(a, b, operator):
if operator == 'add':
return a + b
elif operator == 'subtract':
return a - b
elif operator == 'multiply':
return a * b
elif operator == 'divide':
return a / b
Task 7. Duplicate Encoder
>>Return to Menu
- The goal of this exercise is to convert a string to a new string where each character in the new string is "(" if that character appears only once in the original string, or ")" if that character appears more than once in the original string.
- Ignore capitalization when determining if a character is a duplicate.
For Example:
"din" => "(((" "recede" => "()()()" "Success" => ")())())" "(( @" => "))(("
Solution 1:
def duplicate_encode(word):
return "".join(["(" if word.lower().count(c) == 1 else ")" for c in word.lower()])
Solution 2:
from collections import Counter
def duplicate_encode(word):
word = word.lower()
counter = Counter(word)
return ''.join(('(' if counter[c] == 1 else ')') for c in word)
Solution 3:
def duplicate_encode(word):
obj = {}
value = ""
for i in word:
i = i.lower()
if not i in obj:
obj[i] = 1
else:
obj[i] += 1
for i in word:
i = i.lower()
if obj[i] == 1:
value += "("
else:
value += ")"
return value
Task 8. Square of squares
>>Return to Menu
You have to check if a number is a perfect square. For Example:
-1 => false
0 => true
3 => false
4 => true
25 => true
26 => false
Solution 1:
import math
def is_square(n):
return n > -1 and math.sqrt(n) % 1 == 0
Solution 2:
from math import sqrt as sqrt
def is_square(n):
return bool(str(n).isdigit() and sqrt(n).is_integer())
Solution 3:
import math
def is_square(n):
if n < 0:
return False
sqrt = math.sqrt(n)
return sqrt.is_integer()
Solution 4:
def is_square(n):
if str(n).isdigit():
rlist = "{:.3f}".format(n**0.5)
dot_index = rlist.index(".")
if rlist[dot_index+1] + rlist[dot_index+2] == "00":
return True
return False
Task 9. Consecutive strings
>>Return to Menu
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. For example:
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"
Solution 1:
def longest_consec(strarr, k):
result = ""
if k > 0 and len(strarr) >= k:
for index in range(len(strarr) - k + 1):
s = ''.join(strarr[index:index+k])
if len(s) > len(result):
result = s
return result
Solution 2:
def longest_consec(strarr, k):
word = ''
for x in range(len(strarr)):
if x+k <= len(strarr):
newword = ''
for y in range(k):
newword += strarr[x+y]
if len(newword) > len(word):
word = newword
return(word)
Solution 3:
def longest_consec(s, k):
return max(["".join(s[i:i+k]) for i in range(len(s)-k+1)], key=len) if s and 0 < k <= len(s) else ""
#End
Hope you enjoyed this! :) Follow me for more contents...
Get in Touch:
ifeanyiomeata.com
contact@ifeanyiomeata.com
Youtube: youtube.com/c/IfeanyiOmeata
Linkedin: linkedin.com/in/omeatai
Twitter: twitter.com/iomeata
Github: github.com/omeatai
Stackoverflow: stackoverflow.com/users/2689166/omeatai
Hashnode: hashnode.com/@omeatai
Medium: medium.com/@omeatai
© 2022