from code.unittestSingleton import test #Digital Root #--------------------------------------------------------- # Digital root is the recursive sum of all the digits in a number. # Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. # The input will be a non-negative integer. #--------------------------------------------------------- #solution #------------ def digital_root(n): #parse the number into individual digits and sum them digital_sum = sum([int(num) for num in str(n)]) #recursively call digital_root() until the sum is one digit while digital_sum > 9: digital_sum = digital_root(digital_sum) return digital_sum #sample tests test.assert_equals(digital_root(16), 7) test.assert_equals(digital_root(942), 6) test.assert_equals(digital_root(132189), 6) test.assert_equals(digital_root(493193), 2)
from code.unittestSingleton import test #Explosive Sum #--------------------------------------------------------- # In number theory and combinatorics, a partition of a positive integer n, also called an integer partition, is a way of writing n as a sum of positive integers. # Two sums that differ only in the order of their summands are considered the same partition. If order matters, the sum becomes a composition. # For example, 4 can be partitioned in five distinct ways. Write a function to find the amount of ways to partition an integer. #--------------------------------------------------------- #solution #------------ def exp_sum(n): if n < 0: return 0 dp = [1]+[0]*n #n+1 to inlcude the number itself as a soution for num in range(1,n+1): for i in range(num,n+1): dp[i] += dp[i-num] return dp[-1] #sample tests test.assert_equals(exp_sum(1), 1) test.assert_equals(exp_sum(2), 2) test.assert_equals(exp_sum(3), 3) test.assert_equals(exp_sum(4), 5) test.assert_equals(exp_sum(5), 7) test.assert_equals(exp_sum(10), 42)
#--------------------------------------------------------- # Write a function cakes(), which takes the recipe (object) and the available ingredients (also an object) and returns the maximum number of cakes Pete can bake (integer). # For simplicity there are no units for the amounts (e.g. 1 lb of flour or 200 g of sugar are simply 1 or 200). # Ingredients that are not present in the objects, can be considered as 0. #--------------------------------------------------------- #solution #------------ from math import floor def cakes(recipe, available): try: ingredient_availablity = [] #find the quotient of ingredients available/the recipe for (k, v) in recipe.items(): ingredient_availablity.append(available[k] / v) return floor(min(ingredient_availablity)) #if missing an ingredient, return 0 except: return 0 #sample tests recipe = {"flour": 500, "sugar": 200, "eggs": 1} available = {"flour": 1200, "sugar": 1200, "eggs": 5, "milk": 200} test.assert_equals(cakes(recipe, available), 2, 'example #1') recipe = {"apples": 3, "flour": 300, "sugar": 150, "milk": 100, "oil": 100} available = {"sugar": 500, "flour": 2000, "milk": 2000} test.assert_equals(cakes(recipe, available), 0, 'example #2')
# Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number. # You can guarantee that input is non-negative. # Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case #--------------------------------------------------------- #solution #------------ def count_bits(n): #convert the number to binary with bin() and use count(substring) to find how many '1's in the binary conversion return bin(n).count('1') #not using bin() def manual_count_bits(n): #init binary and quotient values binary='' quotient=n #while the quotient is greater than 0, get the binary value while quotient>0: remainder=str(quotient%2) quotient=int(quotient/2) binary+=remainder #return the number of '1's in the final binary value return binary.count('1') #sample tests test.assert_equals(count_bits(0), 0) test.assert_equals(count_bits(4), 1) test.assert_equals(count_bits(7), 3) test.assert_equals(count_bits(9), 2) test.assert_equals(count_bits(10), 2)
anchor = 0 for rail_length in rail_lengths: rails.append(string[anchor:rail_length + anchor]) anchor += rail_length #create decoded string sequence = [i for i in range(n)] + [i for i in range(1, n - 1)][::-1] decoded_string = '' while len(string) > 0: for i in sequence: if rails[i] != '': decoded_string += rails[i][0] rails[i] = rails[i][1:] string = string[1:] return decoded_string #sample tests test.assert_equals(encode_rail_fence_cipher("WEAREDISCOVEREDFLEEATONCE", 3), "WECRLTEERDSOEEFEAOCAIVDEN") test.assert_equals(encode_rail_fence_cipher("Hello, World!", 3), "Hoo!el,Wrdl l") test.assert_equals(encode_rail_fence_cipher("WADCEDETCOEFROIREESVELANE", 3), "WECREEEACDTOFOREVLNDEEISA") test.assert_equals(encode_rail_fence_cipher("", 3), "") test.assert_equals(decode_rail_fence_cipher("H !e,Wdloollr", 4), "Hello, World!") test.assert_equals(decode_rail_fence_cipher("WECRLTEERDSOEEFEAOCAIVDEN", 3), "WEAREDISCOVEREDFLEEATONCE") test.assert_equals(decode_rail_fence_cipher("", 3), "")
row_begin += 1 #get all of the items in the last column for i in range(row_begin, row_end+1): res.append(matrix[i][col_end]) col_end -= 1 #get all of the items in the last row if row_begin is not the last row if row_begin <= row_end: for i in range(col_end, col_begin-1, -1): res.append(matrix[row_end][i]) row_end -= 1 #get all of the items in the first column if col_begin is not the last column if col_begin <= col_end: for i in range(row_end, row_begin-1, -1): res.append(matrix[i][col_begin]) col_begin += 1 return res #sample tests array = [[1,2,3], [4,5,6], [7,8,9]] expected = [1,2,3,6,9,8,7,4,5] test.assert_equals(snail(array), expected) array = [[1,2,3], [8,9,4], [7,6,5]] expected = [1,2,3,4,5,6,7,8,9] test.assert_equals(snail(array), expected)
from code.unittestSingleton import test #Pep8 Variable Converter #--------------------------------------------------------- # Write simple pep8 variable converter method # All words must have a "_" between them. #--------------------------------------------------------- #solution #------------ def pep8_variable_converter(string): #for each word in the string, join the words by "_" pep8_string = '_'.join([word for word in string.split(' ')]) #sample tests test.assert_equals(pep8_variable_converter("test case"), "test_case") test.assert_equals(pep8_variable_converter("camel case method"), "camel_case_method") test.assert_equals(pep8_variable_converter("say hello "), "say_hello") test.assert_equals(pep8_variable_converter(" camel case word"), "camel_case_world") test.assert_equals(pep8_variable_converter(""), "")
# Write a method that takes an array of consecutive (increasing) letters as input and that returns the missing letter in the array. # You will always get an valid array. And it will be always exactly one letter be missing. The length of the array will always be at least 2. # The array will always contain letters in only one case. # Example: # ['a','b','c','d','f'] -> 'e' ['O','Q','R','S'] -> 'P' #--------------------------------------------------------- #solution #------------ import string def find_missing_letter(chars): starting_position = 0 #find the position of the first letter in chars for i, val in enumerate(string.ascii_letters): if chars[0] == val: starting_position = i #get the correct slice with the missing letter slice_with_missing_letter = string.ascii_letters[ starting_position:starting_position + len(chars) + 1] #check to see which letter is missing and return it for char in slice_with_missing_letter: if char not in chars: return char #sample tests test.describe("kata tests") test.it("example tests") test.assert_equals(find_missing_letter(['a', 'b', 'c', 'd', 'f']), 'e') test.assert_equals(find_missing_letter(['O', 'Q', 'R', 'S']), 'P')
# init temporary holder list to store consecutive values holder = [args[0]] # for each number in args after the 0 position, check if the previous number is in the holder variable and if not, add the range to the extraction list for i in args[1:]: if i - 1 in holder: holder.append(i) else: if len(holder) > 2: extraction_list.append(str(holder[0]) + '-' + str(holder[-1])) else: [extraction_list.append(str(item)) for item in holder] holder = [] holder.append(i) # after looping through args, if there are items in holder, get range and add them to extraction if len(holder) > 2: extraction_list.append(str(holder[0]) + '-' + str(holder[-1])) else: [extraction_list.append(str(item)) for item in holder] return ','.join(extraction_list) #sample tests test.assert_equals( range_extraction([ -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 ]), '-6,-3-1,3-5,7-11,14,15,17-20') test.assert_equals(range_extraction([-3, -2, -1, 2, 10, 15, 16, 18, 19, 20]), '-3--1,2,10,15,16,18-20')
# Only letters from the latin/english alphabet should be shifted, like in the original Rot13 "implementation". #--------------------------------------------------------- #solution #------------ import string def rot13(message): ciphered = '' alphabet = [char for char in string.ascii_lowercase] for char in message: try: rot13_position = alphabet.index(char.lower()) + 13 #if the adjusted position is outside the length of alphabet, go back to the beginning if rot13_position > 25: rot13_position = rot13_position - 26 #if char is uppercase, return rot13 in uppercase if char.isupper(): ciphered += alphabet[rot13_position].upper() else: #if the character is not in the alphabet, add it to ciphered as it is ciphered += alphabet[rot13_position] except: ciphered += char return ciphered #sample tests test.assert_equals(rot13("test"), "grfg") test.assert_equals(rot13("Test"), "Grfg")
hashtag = '#' #if string is not empty and less than 140 characters if s != '' and len(s) <= 140: #separate into words words = list(s.split(' ')) #capitalize each word and concat it with hashtag for word in words: if word != '': hashtag += word[0].upper() + word[1:].lower() return hashtag else: return False #sample tests test.assert_equals(generate_hashtag(''), False, 'Expected an empty string to return False') test.assert_equals( generate_hashtag('Do We have A Hashtag')[0], '#', 'Expeted a Hashtag (#) at the beginning.') test.assert_equals(generate_hashtag('Codewars'), '#Codewars', 'Should handle a single word.') test.assert_equals(generate_hashtag('Codewars '), '#Codewars', 'Should handle trailing whitespace.') test.assert_equals(generate_hashtag('Codewars Is Nice'), '#CodewarsIsNice', 'Should remove spaces.') test.assert_equals(generate_hashtag('codewars is nice'), '#CodewarsIsNice', 'Should capitalize first letters of words.') test.assert_equals( generate_hashtag('CodeWars is nice'), '#CodewarsIsNice', 'Should capitalize all letters of words - all lower case but the first.') test.assert_equals(
from code.unittestSingleton import test #Counting Duplicates #--------------------------------------------------------- # 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. #--------------------------------------------------------- #solution #------------ def duplicate_count(text): #init count of duplicate characters and set text to lowercase duplicate_chars = 0 text = text.lower() for char in text: #if there is more than one occurence of the character if text.count(char) > 1: duplicate_chars += 1 #remove the character from the string text = text.replace(char, '') return duplicate_chars #sample tests test.assert_equals(duplicate_count(""), 0) test.assert_equals(duplicate_count("abcde"), 0) test.assert_equals(duplicate_count("abcdeaa"), 1) test.assert_equals(duplicate_count("abcdeaB"), 2) test.assert_equals(duplicate_count("Indivisibilities"), 2)