├── readme.txt ├── litres.py ├── mean.py ├── __pycache__ └── array.cpython-37.pyc ├── shape-area.py ├── sum-mixed-array.py ├── summation.py ├── blood_moon.py ├── capitalize-and-mutability.py ├── remove-exclamation.py ├── repeater.py ├── reverse-list.py ├── reverser.py ├── 99-problems.py ├── remove-anchor.py ├── squirrel-and-tree.py ├── binary-addition.py ├── is-divisible.py ├── greet_me.py ├── enough-space.py ├── keep-hydrated.py ├── simple_beads_count.py ├── sort_numbers.py ├── find_min_and_max.py ├── functional-addition.py ├── over_the_road.py ├── all_unique.py ├── are_the_numbers-in_order.py ├── counting-sheep.py ├── divisible-by.py ├── hero.py ├── potatoes.py ├── reversed_words.py ├── two_to_one.py ├── filling_an_array.py ├── list_filtering.py ├── minimum_to_multiple.py ├── remove-first-last.py ├── who-is-paying.py ├── convert_a_string_to_an_array.py ├── drone_fly_by.py ├── incorrect_division_method.py ├── maximum_multiple.py ├── move_ten.py ├── point_in_a_unit_circle.py ├── pyramid_array.py ├── breaking_chocolate.py ├── detect_pangram.py ├── count_the_divisible_numbers.py ├── evens_and_odds.py ├── number_of_occurrences.py ├── series_of_integers_from_m_to_n.py ├── string-ending.py ├── sum_of_minimums.py ├── consecutive_letters.py ├── javascript_array_filter.py ├── sort_by_length.py ├── testing_1_2_3.py ├── nth_smallest_element_array_series_4.py ├── simple_fun_37_house_numbers_sum.py ├── spacify.py ├── the_wide_mouthed_frog.py ├── thinkful_string_drills_quotable.py ├── will_you_make_it.py ├── abbreviate-two-word-name.py ├── beginner_series_3_sum_of_numbers.py ├── camel_case_method.py ├── number_zoo_patrol.py ├── split_strings.py ├── wave_sorting.py ├── credit-card-mask.py ├── find_multiples_of_a_number.py ├── find_the_vowels.py ├── is_there_a_vowel_in_there.py ├── largest_pair_sum_in_array.py ├── love_vs_friendship.py ├── maximum_product.py ├── number_to_digit_tiers.py ├── return_substring_instance_count.py ├── simple_fun_152_invite_more_women.py ├── sum-positive.py ├── between_extremes.py ├── some_but_not_all.py ├── suzuki-stairs.py ├── switcheroo.py ├── array_combinations.py ├── four_seven.py ├── herons_formula.py ├── printer-error.py ├── sort_arrays.py ├── sort_my_animals.py ├── number-of-decimal-digits.py ├── unique_in_order.py ├── array.py ├── filter-geese.py ├── how_many_lightsabers_do_you_own.py ├── limit_string_length_1.py ├── numbers_in_strings.py ├── santas_naughty_list.py ├── count_by_x.py ├── help_bob_count_letters_and_digits.py ├── minminmax.py ├── two_joggers.py ├── banjo-player.py ├── data_reverse.py ├── dna-to-rna.py ├── happy_birthday.py ├── highest_and_lowest.py ├── sort-the-gift-code.py ├── consecutive_items.py ├── count-squares.py ├── even-numbers.py ├── ladies-eniac.py ├── prefill_an_array.py ├── square_every_digit.py ├── sum_of_integers_in_a_string.py ├── summing_a_numbers_digits.py ├── basic_math_add_or_subtract.py ├── convert_string_to_camel_case.py ├── form_the_largest.py ├── how_good_are_you_really.py ├── odd-or-even.py ├── partlist.py ├── peak_array_index.py ├── regexp_basics_is_it_a_digit.py ├── regexp_basics_is_it_a_vowel.py ├── thinking-and-testing-true-or-false.py ├── two_oldest_ages.py ├── GCD_sum.py ├── bit-counting.py ├── blue-marbles.py ├── extra_perfect_numbers_special_numbers_series_7.py ├── reverse_a_number.py ├── simple_fun_176_reverse_letter.py ├── thinking_and_testing_uniq_or_not_uniq.py ├── absent_vowel.py ├── deoderant_evaporator.py ├── first_character_that_repeats.py ├── halving_sum.py ├── happy_birthday_darling.py ├── maximum_gap_array_series_4.py ├── minimize_sum_of_array_array_series_1.py ├── reverse-words.py ├── tail_swap.py ├── alternate_case.py ├── band_name_generator.py ├── complete_the_pattern_1.py ├── sum_it_continuously.py ├── debug_sum_of_digits_of_a_number.py ├── find_the_longest_gap.py ├── get_the_middle_character.py ├── l2_triple_x.py ├── regexp_basics_is_it_a_letter.py ├── triangular-numbers.py ├── wealth-equality-finally.py ├── bonuses.py ├── moving_average.py ├── put_a_letter_in_a_column.py ├── return_a_sorted_list_of_objects.py ├── substituting_variables_into_strings_padded_numbers.py ├── alan_partridge_2_apple_turnover.py ├── bases_everywhere.py ├── complementary_dna.py ├── lazy_repeater.py ├── multiples_of_3_or_5.py ├── no-oddities-here.py ├── permutations.py ├── return_a_strings_even_characters.py ├── return_the_first_m_multiples_of_n.py ├── sum_of_intervals.py ├── count_salutes.py ├── draw_stairs.py ├── geometry_basics_distance_between_two_points.py ├── is-triangle.py ├── rearrange_a_number_to_get_its_maximum.py ├── sort-by-last-char.py ├── sum-pairs.py ├── automorphic_number_special_numbers_series_6.py ├── descending-order.py ├── exclamation_marks_series_7.py ├── find_the_divisors.py ├── find_within_array.py ├── retrieve_array_value_by_index_with_default.py ├── twice-as-old.py ├── basic-mathematics.py ├── count_characters_in_your_string.py ├── milk-and-cookies.py ├── quadrants_2_segments.py ├── row-odd-triangle.py ├── count_letters_in_string.py ├── find_the_first_non_consecutive_number.py ├── pluck.py ├── simple_consecutive_pairs.py ├── array_deep_count.py ├── consecutive_count.py ├── running_out_of_space.py ├── shortest-word.py ├── valid_spacing.py ├── factorial.py ├── the_wheat_rice_and_chessboard_problem.py ├── special_number_special_number_series_5.py ├── closest-elevator.py ├── consecutive-ducks.py ├── convert_lambda_to_def.py ├── diagonals_sum.py ├── equal_sides_of_an_array.py ├── longest-vowel-chain.py ├── ones-and-zeros.py ├── power-of-two.py ├── array_leaders_array_series_3.py ├── conference_traveller.py ├── form-the-minimum.py ├── last_digits_of_a_number.py ├── the_office_VI_sabbatical.py ├── the_old_switcheroo.py ├── two_sum.py ├── weird_string_case.py ├── which_are_in.py ├── enumerable-magic#5.py ├── find-the-speedcubers-times.py ├── find_the_missing_letter.py ├── kids_and_candies.py ├── odd-triangle-row.py ├── even_times_last.py ├── extract_the_domain_name_from_a_URL.py ├── mumbling.py ├── sort_out_the_men_from_boys.py ├── all_star_coding_challenge_15.py ├── almost_even.py ├── final-grade.py ├── from_a_to_z.py ├── how_many_reindeers?.py ├── plus_one_array.py ├── round_by_0.5_steps.py ├── string_array_duplicates.py ├── sum_of_odd_cubed_numbers.py ├── duplicate_sandwich.py ├── grouped_by_commas.py ├── help-the-fruit-guy.py ├── how_much_hex_is_the_fish.py ├── maximum-triplet-sum.py ├── simple_fun_136_missing_values.py ├── squash_the_bugs.py ├── alphabetical_addition.py ├── emotional_sort.py ├── simple_missing_sum.py ├── array_exchange.py ├── collatz.py ├── keystroking.py ├── largest_5_digit_number_in_a_series.py ├── simple_fun_79_delete_a_digit.py ├── sum-digits-digital-root.py ├── ticker.py ├── traffic_count.py ├── very_even_numbers.py ├── double_sort.py ├── loose_change.py ├── simple_fun_23_square_digits_sequence.py ├── stones_on_the_table.py ├── sum_of_array_singles.py ├── thinking_and_testing_a_times_b.py ├── dashatize_it.py ├── find-screen-size.py ├── greatest_common_factor_of_an_array.py ├── prime-number.py ├── conver_pascalcase_into_snakecase.py ├── integrate.py ├── person_class_bug.py ├── row-weights.py ├── ahh-grabscrab.py ├── odder-than-the-rest.py ├── redacted.py ├── difference-of-two.py ├── disarium_number_special_numbers_series_3.py ├── english_beggars.py ├── lambdas_as_a_mechanism_for_open_and_closed.py ├── number-of-trailing-zeros.py ├── sum_of_roots_of_quadratic.py ├── points.py ├── remove_consecutive_duplicate_words.py ├── simple_fun_110_array_operations.py ├── simple_fun_247_to_and_from.py ├── unique_string_characters.py ├── valid_parantheses.py ├── your_order_please.py ├── count-the-digit.py ├── find-all-occurrences.py ├── generic-algorithm-series#3.py ├── genetic-algorithm-series#3.py ├── maximum_subarray_sum.py ├── small-enough.py ├── suitcase.py ├── sum_square_even_root_odd.py ├── evening_up_a_workload.py ├── hofstadter_q.py ├── jumping_number_special_number_series_4.py ├── number_of_measurements_to_spot_the_counterfeit_coin.py ├── pete-the-baker.py ├── alphabet_symmetry.py ├── calculate_number_of_inversions_in_array.py ├── fill-hdd.py ├── string_letter_counting.py ├── validate_credit_card_number.py ├── get_planet_name_by_ID.py ├── sum_of_odd_numbers.py ├── sums_of_parts.py ├── consecutive_differences.py ├── count_the_divisors_of_a_number.py ├── even-odd-pattern#1.py ├── stray-number.py ├── counting_duplicates.py ├── find_the_unique_number.py ├── noisy_cell_counts.py ├── adjacent_repeated_words_in_a_string.py ├── count_IP_addresses.py ├── find_the_index_of_the_second_occurance.py ├── hells_kitchen.py ├── remove_duplicate_words.py ├── status_arrays.py ├── magnet-particules.py ├── the_@_operator.py ├── cryptanalysis_word_patterns.py ├── going-to-the-cinema.py ├── regexp-eight-bit-unsigned.py ├── ultimate-array-reverser.py ├── crack_the_pin.py ├── exes-and-ohs.py ├── half-life.py ├── next-happy-year.py ├── break-camelcase.py ├── fizzbuzz_backwards.py ├── maximum-length-difference.py ├── simple_letter_removal.py ├── word_values.py ├── are_we_alternate.py ├── exercise_in_summing.py ├── longest_alphabetical_substring.py ├── lottery_machine.py ├── most_sales.py ├── sort_the_vowels.py ├── briefcase_lock.py ├── find_the_capitals.py ├── fix_string_case.py ├── reduce-pyramid.py ├── scaling_squared_strings.py ├── strong_number_special_numbers_series_2.py ├── ball_upwards.py ├── create_string_for_array_of_objects.py ├── fun-with-lists-length.py ├── mispelled_word.py ├── n_smallest_elements_in_original_order.py ├── weekday.py ├── baby_shark_lyrics_generator.py ├── find_the_unique_string.py ├── identify_ball_bearings.py ├── mexican_wave.py ├── simple-pig-latin.py ├── sum-powers-of-two.py ├── sum_consecutives.py ├── backspaces-in-string.py ├── even_and_odd.py ├── format_words_into_a_sentence.py ├── minimum-steps.py ├── sixteen_plus_eighteen_equals_214.py ├── counting_duplicates_across_multiple_lists.py ├── how_many_unique_consonants.py ├── reach_me_and_sum_my_digits.py ├── create-phone-number.py ├── decode_the_morse_code.py ├── interview_question_easy.py ├── sort_the_odd.py ├── responsible-drinking.py ├── weight_for_weight.py ├── which-section-did-you-scroll-to.py ├── yoga-class.py ├── IQ_test.py ├── are-same-squared.py ├── poet-and-pendulum.py ├── consecutive_strings.py ├── numericals_of_a_string.py ├── ski_jump.py ├── square-up-array.py ├── swap_case_using_N.py ├── ten-minute-walk.py ├── van_ecks_sequence.py ├── message_validator.py ├── pillow_on_the_fridge.py ├── reverse_every_other_word_in_the_string.py ├── sort_only_integers_in_nested_list.py ├── how_much_coffee_do_you_need.py ├── lets_recycle.py ├── search_for_letters.py ├── tortoise-racing.py ├── largest-product-in-a-series.py ├── thinking_and_testing_something_capitalized.py ├── yes-no-yes-no.py ├── cyclops-number.py ├── evenly_distribute_values_in_array.py ├── thue-morse-sequence.py ├── bobs-reversing-obfuscator.py ├── find_the_nth_occurrence_of_a_word_in_a_string.py ├── making-change.py ├── simple_fun_305_typist.py ├── sum-numbers-0-n.py ├── complete-the-pattern#2.py ├── pairs_of_bears.py ├── simple_equation_reversal.py ├── string_prefix_and_suffix.py ├── title_case.py ├── find-all-non-consecutive-numbers.py ├── next-number-same-1-bits.py ├── alternate-capitalisation.py ├── bouncing-ball.py ├── integer-to-whitespace.py ├── pandemia.py ├── rule-of-divisibility-13.py ├── count_the_smiley_faces.py ├── duplicates_duplicates_everywhere.py ├── josephus-surviror.py ├── oring_arrays.py ├── product-array.py ├── simple_fun_160_cut_the_ropes.py ├── delta_generators.py ├── cartesian-plane-function.py ├── life_path_number.py ├── string_doubles.py ├── the_speed_of_letters.py ├── simple_string_expansion.py ├── sms_lottery_bet_validator.py ├── the_lamp.py ├── simple_fun_250_prefix_to_suffix.py ├── the_vowel_code.py ├── who_has_the_most_money.py ├── the_5_love_languages.py ├── character_with_longest_consecutive_repetition.py ├── make_a_window.py ├── sort_the_number_sequence.py ├── find_the_parity_outlier.py ├── speed_limit.py ├── tetris_series_1_scoring_system.py ├── who_likes_it.py ├── the_alphabet_product.py ├── minimum_number_of_taxis.py ├── remove_the_parantheses.py ├── simple_fun_112_array_erasing.py ├── tracking_sums_in_a_process.py ├── help_the_bookseller.py ├── naughty_or_nice.py ├── primordial_of_a_number.py ├── simple_fun_74_growing_plant.py ├── simpsons-rule.py ├── find-next-higher-number-with-same-1s.py ├── flatten.py ├── ip-validation.py ├── simple_frequency_sort.py ├── simple_fun_162.py ├── split_and_then_add_both_sides_of_an_array_together.py ├── consonant-value.py ├── make-the-deadfish-swim.py ├── roman_numerals_decoder.py ├── simple_max_digit_sum.py ├── cats_and_shelves.py ├── last-digit-powers.py ├── ordered-count.py └── sort_and_transform.py /readme.txt: -------------------------------------------------------------------------------- 1 | My solutions for codewars Python challenges. 2 | -------------------------------------------------------------------------------- /litres.py: -------------------------------------------------------------------------------- 1 | def litres(time): 2 | '''Returns number of litres based on the duration'' 3 | return int(time*0.5) -------------------------------------------------------------------------------- /mean.py: -------------------------------------------------------------------------------- 1 | def get_average(marks): 2 | '''Returns the mean of an array''' 3 | return int((sum(marks))/(len(marks))) -------------------------------------------------------------------------------- /__pycache__/array.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ellismckenzielee/codewars-python/HEAD/__pycache__/array.cpython-37.pyc -------------------------------------------------------------------------------- /shape-area.py: -------------------------------------------------------------------------------- 1 | def shape_area(n): 2 | '''Finds the area of an odd polygon, described in the kata''' 3 | return (n*n) + ((n-1)*(n-1)) -------------------------------------------------------------------------------- /sum-mixed-array.py: -------------------------------------------------------------------------------- 1 | def sum_mix(arr): 2 | '''Calculates the sum of numbers in a mixed array''' 3 | return sum([int(x) for x in arr]) -------------------------------------------------------------------------------- /summation.py: -------------------------------------------------------------------------------- 1 | def summation(num): 2 | '''Finds the summation of every number from one to num''' 3 | return sum(list(range(1,num+1))) -------------------------------------------------------------------------------- /blood_moon.py: -------------------------------------------------------------------------------- 1 | #blood moon kata 2 | #https://www.codewars.com/kata/5cba04533e6dce000eaf6126 3 | 4 | def blood_moon(r): 5 | return r**2/4 -------------------------------------------------------------------------------- /capitalize-and-mutability.py: -------------------------------------------------------------------------------- 1 | def capitalizeWord(word): 2 | '''Returns the word, but capitalized''' 3 | return word[0].upper() + word[1:] -------------------------------------------------------------------------------- /remove-exclamation.py: -------------------------------------------------------------------------------- 1 | def remove_exclamation_marks(s): 2 | '''Removes exclamation marks from a string''' 3 | return s.replace('!', '') -------------------------------------------------------------------------------- /repeater.py: -------------------------------------------------------------------------------- 1 | def repeater(string, n): 2 | '''Function returns a new string where input string is repeated n times''' 3 | return string*n -------------------------------------------------------------------------------- /reverse-list.py: -------------------------------------------------------------------------------- 1 | def reverse_list(l): 2 | '''Returns a list with the reverse order of l''' 3 | return [l[-x] for x in range(1, len(l)+1)] -------------------------------------------------------------------------------- /reverser.py: -------------------------------------------------------------------------------- 1 | #reverser kata 2 | #https://www.codewars.com/kata/58069e4cf3c13ef3a6000168 3 | 4 | def reverse(n): 5 | return int(str(n)[::-1]) -------------------------------------------------------------------------------- /99-problems.py: -------------------------------------------------------------------------------- 1 | ##99 PROBLEM, #1 LAST IN LIST 2 | ## Returns last element in list 3 | 4 | def last(lst): 5 | return lst[-1] if lst else None -------------------------------------------------------------------------------- /remove-anchor.py: -------------------------------------------------------------------------------- 1 | import re 2 | def remove_url_anchor(url): 3 | '''Remove the anchor from a URL''' 4 | return re.sub(r'[#]\w*$','', url) 5 | -------------------------------------------------------------------------------- /squirrel-and-tree.py: -------------------------------------------------------------------------------- 1 | #Find the distance a squirrel travelled up a tree in < 52 characters 2 | squirrel = lambda h,H,S: round(H/h*(h*h+S*S)**.5,4) -------------------------------------------------------------------------------- /binary-addition.py: -------------------------------------------------------------------------------- 1 | def add_binary(a,b): 2 | '''Function adds two numbers and returns their sum in binary''' 3 | return str(bin(a+b)).split('b')[1] -------------------------------------------------------------------------------- /is-divisible.py: -------------------------------------------------------------------------------- 1 | def is_divisible(n,x,y): 2 | '''Returns whether or not n is divisible by both x and y''' 3 | return ((n%x) == 0) and ((n%y) == 0) -------------------------------------------------------------------------------- /greet_me.py: -------------------------------------------------------------------------------- 1 | #Greet Me kata 2 | #https://www.codewars.com/kata/535474308bb336c9980006f2 3 | 4 | def greet(name): 5 | return 'Hello {}!'.format(name.title()) -------------------------------------------------------------------------------- /enough-space.py: -------------------------------------------------------------------------------- 1 | def enough(cap, on, wait): 2 | '''Return whether or not there will be enough space on a bus''' 3 | return 0 if on+wait <= cap else (wait+on-cap) -------------------------------------------------------------------------------- /keep-hydrated.py: -------------------------------------------------------------------------------- 1 | ##KEEP HYDRATED KATA 2 | ##Returns the number of litres to stay hydrated, based upon the time 3 | 4 | def litres(time): 5 | return int(time*0.5) -------------------------------------------------------------------------------- /simple_beads_count.py: -------------------------------------------------------------------------------- 1 | # Simple Beads Count 2 | # https://www.codewars.com/kata/58712dfa5c538b6fc7000569 3 | 4 | def count_red_beads(n): 5 | return (n - 1) * 2 6 | -------------------------------------------------------------------------------- /sort_numbers.py: -------------------------------------------------------------------------------- 1 | #sort numbers kata 2 | #https://www.codewars.com/kata/5174a4c0f2769dd8b1000003 3 | 4 | def solution(nums): 5 | return sorted(nums) if nums else [] -------------------------------------------------------------------------------- /find_min_and_max.py: -------------------------------------------------------------------------------- 1 | #find min and max kata 2 | #https://www.codewars.com/kata/57a1ae8c7cb1f31e4e000130 3 | 4 | def get_min_max(seq): 5 | return (min(seq), max(seq)) -------------------------------------------------------------------------------- /functional-addition.py: -------------------------------------------------------------------------------- 1 | def add(n): 2 | '''Function that returns a function that adds n to any number''' 3 | def add2(k): 4 | return n + k 5 | return add2 -------------------------------------------------------------------------------- /over_the_road.py: -------------------------------------------------------------------------------- 1 | #over the road kata 2 | #https://www.codewars.com/kata/5f0ed36164f2bc00283aed07 3 | 4 | def over_the_road(address, n): 5 | return (n*2) + 1 - address -------------------------------------------------------------------------------- /all_unique.py: -------------------------------------------------------------------------------- 1 | #all unique kata 2 | #https://www.codewars.com/kata/553e8b195b853c6db4000048 3 | 4 | def has_unique_chars(string): 5 | return len(string) == len(set(string)) -------------------------------------------------------------------------------- /are_the_numbers-in_order.py: -------------------------------------------------------------------------------- 1 | #Are the numbers in order? 2 | #https://www.codewars.com/kata/56b7f2f3f18876033f000307 3 | 4 | def in_asc_order(arr): 5 | return arr==sorted(arr) -------------------------------------------------------------------------------- /counting-sheep.py: -------------------------------------------------------------------------------- 1 | def count_sheep(n): 2 | '''Return a sheep string depending on integer given ''' 3 | return ''.join([(str(c) + ' sheep...') for c in list(range(1,n+1))]) -------------------------------------------------------------------------------- /divisible-by.py: -------------------------------------------------------------------------------- 1 | def divisible_by(numbers, divisor): 2 | '''Return numbers in numbers list divisible by the divisor''' 3 | return [x for x in numbers if (x % divisor == 0)] -------------------------------------------------------------------------------- /hero.py: -------------------------------------------------------------------------------- 1 | def hero(bullets, dragons): 2 | '''Checks bullets per dragon and bullet count to see if will survive''' 3 | return True if dragons == 0 else (bullets/dragons) >= 2 -------------------------------------------------------------------------------- /potatoes.py: -------------------------------------------------------------------------------- 1 | def potatoes(p0, w0, p1): 2 | '''Returns mass of dried potatoes, based on the percentage water before and after''' 3 | return int(((w0*100)-(p0*w0))/(100-p1)) -------------------------------------------------------------------------------- /reversed_words.py: -------------------------------------------------------------------------------- 1 | #reversed words kata 2 | #https://www.codewars.com/kata/51c8991dee245d7ddf00000e 3 | 4 | def reverseWords(str): 5 | return (' '.join(str.split(' ')[::-1])) -------------------------------------------------------------------------------- /two_to_one.py: -------------------------------------------------------------------------------- 1 | #Two to One kata 2 | #https://www.codewars.com/kata/5656b6906de340bd1b0000ac 3 | 4 | def longest(a1, a2): 5 | return ''.join(sorted(set([*a1, *a2]))) 6 | -------------------------------------------------------------------------------- /filling_an_array.py: -------------------------------------------------------------------------------- 1 | #filling an array (part 1) kata 2 | #https://www.codewars.com/kata/571d42206414b103dc0006a1 3 | 4 | def arr(n=None): 5 | return list(range(0,n)) if n else [] -------------------------------------------------------------------------------- /list_filtering.py: -------------------------------------------------------------------------------- 1 | #List filtering kata 2 | #https://www.codewars.com/kata/53dbd5315a3c69eed20002dd 3 | 4 | def filter_list(l): 5 | return list(filter(lambda x: type(x) != str, l)) -------------------------------------------------------------------------------- /minimum_to_multiple.py: -------------------------------------------------------------------------------- 1 | #minimum to multiple kata 2 | #https://www.codewars.com/kata/5e030f77cec18900322c535d 3 | 4 | def minimum(a, x): 5 | return min(a % x, ((a // x) + 1)*x - a) -------------------------------------------------------------------------------- /remove-first-last.py: -------------------------------------------------------------------------------- 1 | ##REMOVE FIRST AND LAST CHARACTER KATA 2 | ##Strips the first and last character from a string and returns it 3 | 4 | def remove_char(s): 5 | return s[1:-1] -------------------------------------------------------------------------------- /who-is-paying.py: -------------------------------------------------------------------------------- 1 | def who_is_paying(name): 2 | '''Returns who will pay for the wall based on length of the name''' 3 | return [name] if len(name) <= 2 else [name, name[0:2]] -------------------------------------------------------------------------------- /convert_a_string_to_an_array.py: -------------------------------------------------------------------------------- 1 | #Convert a string to an array kata 2 | #https://www.codewars.com/kata/57e76bc428d6fbc2d500036d 3 | 4 | def string_to_array(s): 5 | return s.split(' ') -------------------------------------------------------------------------------- /drone_fly_by.py: -------------------------------------------------------------------------------- 1 | #drone fly-by kata 2 | #https://www.codewars.com/kata/58356a94f8358058f30004b5 3 | 4 | def fly_by(lamps, drone): 5 | return lamps.replace('x','o', drone.index('T')+1) -------------------------------------------------------------------------------- /incorrect_division_method.py: -------------------------------------------------------------------------------- 1 | #incorrect division method kata 2 | #https://www.codewars.com/kata/54d1c59aba326343c80000e7 3 | 4 | def divide_numbers(x,y): 5 | return float(x) / float(y) -------------------------------------------------------------------------------- /maximum_multiple.py: -------------------------------------------------------------------------------- 1 | #maximum multiple kata 2 | #https://www.codewars.com/kata/5aba780a6a176b029800041c 3 | 4 | def max_multiple(divisor, bound): 5 | return bound - (bound % divisor) -------------------------------------------------------------------------------- /move_ten.py: -------------------------------------------------------------------------------- 1 | #Move 10 kata 2 | #https://www.codewars.com/kata/57cf50a7eca2603de0000090 3 | 4 | def move_ten(st): 5 | return ''.join(list(map(lambda x: chr(((ord(x)-87)%26)+97), st))) -------------------------------------------------------------------------------- /point_in_a_unit_circle.py: -------------------------------------------------------------------------------- 1 | #point in a unit circle kata 2 | #https://www.codewars.com/kata/58da7ae9b340a2440500009c 3 | 4 | def point_in_circle(x, y): 5 | return (x**2 + y**2)**0.5 < 1 -------------------------------------------------------------------------------- /pyramid_array.py: -------------------------------------------------------------------------------- 1 | #pyramid array kata 2 | #https://www.codewars.com/kata/515f51d438015969f7000013 3 | 4 | def pyramid(n): 5 | return [[1 for i in range(n+(j-n))] for j in range(1, n+1)] -------------------------------------------------------------------------------- /breaking_chocolate.py: -------------------------------------------------------------------------------- 1 | #breaking chocolate problem kata 2 | #https://www.codewars.com/kata/534ea96ebb17181947000ada 3 | 4 | def breakChocolate(n, m): 5 | return (n*m)-1 if n*m >0 else 0 -------------------------------------------------------------------------------- /detect_pangram.py: -------------------------------------------------------------------------------- 1 | #detect pangram kata 2 | #https://www.codewars.com/kata/545cedaa9943f7fe7b000048 3 | 4 | def is_pangram(s): 5 | return len(set(filter(lambda x: x.isalpha(),s.lower()))) == 26 -------------------------------------------------------------------------------- /count_the_divisible_numbers.py: -------------------------------------------------------------------------------- 1 | #count the divisible numbers kata 2 | #https://www.codewars.com/kata/55a5c82cd8e9baa49000004c 3 | 4 | def divisible_count(x,y,k): 5 | return (y // k) - ((x-1) // k) -------------------------------------------------------------------------------- /evens_and_odds.py: -------------------------------------------------------------------------------- 1 | #Evens and Odds kata 2 | #https://www.codewars.com/kata/583ade15666df5a64e000058 3 | 4 | def evens_and_odds(n): 5 | return bin(n).split('b')[1] if n%2 == 0 else hex(n).split('x')[1] -------------------------------------------------------------------------------- /number_of_occurrences.py: -------------------------------------------------------------------------------- 1 | #number of occurrences kata 2 | #https://www.codewars.com/kata/52829c5fe08baf7edc00122b 3 | 4 | def number_of_occurrences(element, sample): 5 | return sample.count(element) -------------------------------------------------------------------------------- /series_of_integers_from_m_to_n.py: -------------------------------------------------------------------------------- 1 | #Series of integers from m to n kata 2 | #https://www.codewars.com/kata/5841f680c5c9b092950001ae 3 | 4 | def generate_integers(m, n): 5 | return list(range(m, n+1)) -------------------------------------------------------------------------------- /string-ending.py: -------------------------------------------------------------------------------- 1 | def solution(string, ending): 2 | '''Checks to see if the string ends in ending, and returns 3 | True or False''' 4 | return True if string[-len(ending):] == ending else False -------------------------------------------------------------------------------- /sum_of_minimums.py: -------------------------------------------------------------------------------- 1 | #sum of minimums! kata 2 | #https://www.codewars.com/kata/5d5ee4c35162d9001af7d699 3 | 4 | def sum_of_minimums(numbers): 5 | return sum(list(map(lambda x: sorted(x)[0], numbers))) -------------------------------------------------------------------------------- /consecutive_letters.py: -------------------------------------------------------------------------------- 1 | #consecutive letters kata 2 | #https://www.codewars.com/kata/5ce6728c939bf80029988b57 3 | 4 | def solve(st): 5 | return ''.join(sorted(list(st))) in 'abcdefghijklmnopqrstuvwxyz' -------------------------------------------------------------------------------- /javascript_array_filter.py: -------------------------------------------------------------------------------- 1 | #javascript array filter kata 2 | #https://www.codewars.com/kata/514a6336889283a3d2000001 3 | 4 | def get_even_numbers(arr): 5 | return list(filter(lambda x: x%2 == 0, arr)) -------------------------------------------------------------------------------- /sort_by_length.py: -------------------------------------------------------------------------------- 1 | # Sort By Length kata 2 | # https://www.codewars.com/kata/57ea5b0b75ae11d1e800006c/train/python 3 | 4 | def sort_by_length(arr): 5 | return sorted(arr, key=lambda arr: len(arr)) 6 | -------------------------------------------------------------------------------- /testing_1_2_3.py: -------------------------------------------------------------------------------- 1 | #testing 1-2-3 kata 2 | #https://www.codewars.com/kata/54bf85e3d5b56c7a05000cf9 3 | 4 | def number(lines): 5 | return ['{}: {}'.format(i+1, str(line)) for i, line in enumerate(lines)] -------------------------------------------------------------------------------- /nth_smallest_element_array_series_4.py: -------------------------------------------------------------------------------- 1 | #nth smallest element (array series #4) kata 2 | #https://www.codewars.com/kata/5a512f6a80eba857280000fc 3 | 4 | def nth_smallest(arr, pos): 5 | return sorted(arr)[pos-1] -------------------------------------------------------------------------------- /simple_fun_37_house_numbers_sum.py: -------------------------------------------------------------------------------- 1 | #simple fun #37: house numbers sum kata 2 | #https://www.codewars.com/kata/58880c6e79a0a3e459000004 3 | 4 | def house_numbers_sum(inp): 5 | return sum(inp[:inp.index(0)]) -------------------------------------------------------------------------------- /spacify.py: -------------------------------------------------------------------------------- 1 | ###Spacify - codewars kata 2 | ###https://www.codewars.com/kata/57f8ee485cae443c4d000127 3 | 4 | def spacify(string): 5 | '''Returns string but spacified''' 6 | return ' '.join(list(string)) -------------------------------------------------------------------------------- /the_wide_mouthed_frog.py: -------------------------------------------------------------------------------- 1 | #the wide-mouthed frog! kata 2 | #https://www.codewars.com/kata/57ec8bd8f670e9a47a000f89 3 | 4 | def mouth_size(animal): 5 | return 'small' if animal.lower() == 'alligator' else 'wide' -------------------------------------------------------------------------------- /thinkful_string_drills_quotable.py: -------------------------------------------------------------------------------- 1 | #thinkful - string drills: quotable kata 2 | #https://www.codewars.com/kata/5859c82bd41fc6207900007a 3 | 4 | def quotable(name, quote): 5 | return f'{name} said: "{quote}"' -------------------------------------------------------------------------------- /will_you_make_it.py: -------------------------------------------------------------------------------- 1 | #will you make it? kata 2 | #https://www.codewars.com/kata/5861d28f124b35723e00005e 3 | 4 | def zero_fuel(distance_to_pump, mpg, fuel_left): 5 | return fuel_left * mpg >= distance_to_pump -------------------------------------------------------------------------------- /abbreviate-two-word-name.py: -------------------------------------------------------------------------------- 1 | def abbrevName(name): 2 | '''Return initials of a name in uppercase and with a dot''' 3 | return str(name.split(' ')[0][0]).upper() + '.' + str(name.split(' ')[1][0]).upper() 4 | -------------------------------------------------------------------------------- /beginner_series_3_sum_of_numbers.py: -------------------------------------------------------------------------------- 1 | #beginner series #3: sum of numbers kata 2 | #https://www.codewars.com/kata/55f2b110f61eb01779000053 3 | 4 | def get_sum(a,b): 5 | return sum(list(range(min(a,b), max(a,b)+1))) -------------------------------------------------------------------------------- /camel_case_method.py: -------------------------------------------------------------------------------- 1 | #CamelCase Method kata 2 | #https://www.codewars.com/kata/587731fda577b3d1b0001196 3 | 4 | def camel_case(string): 5 | return ''.join([word.title() for word in string.strip(' ').split(' ')]) -------------------------------------------------------------------------------- /number_zoo_patrol.py: -------------------------------------------------------------------------------- 1 | #Number zoo partrol kata 2 | #https://www.codewars.com/kata/5276c18121e20900c0000235 3 | 4 | def find_missing_number(numbers): 5 | return sum(list(range(1, len(numbers)+2))) - sum(numbers) -------------------------------------------------------------------------------- /split_strings.py: -------------------------------------------------------------------------------- 1 | #split strings kata 2 | #https://www.codewars.com/kata/515de9ae9dcfc28eb6000001 3 | 4 | def solution(s): 5 | return [s[i:i+2] if len(s[i:i+2]) == 2 else s[i] + '_' for i in range(0, len(s), 2)] -------------------------------------------------------------------------------- /wave_sorting.py: -------------------------------------------------------------------------------- 1 | #wave sorting kata 2 | #https://www.codewars.com/kata/596f28fd9be8ebe6ec0000c1 3 | 4 | def wave_sort(a): 5 | a.sort() 6 | for i in range(0, len(a)-1, 2): 7 | a[i], a[i+1] = a[i+1], a[i] -------------------------------------------------------------------------------- /credit-card-mask.py: -------------------------------------------------------------------------------- 1 | # Credit Card Mask kata 2 | # https://www.codewars.com/kata/5412509bd436bd33920011bc/train/python 3 | 4 | # return masked string 5 | def maskify(cc): 6 | return '#' * (len(cc) - 4) + cc[-4:] 7 | -------------------------------------------------------------------------------- /find_multiples_of_a_number.py: -------------------------------------------------------------------------------- 1 | #find multiples of a number kata 2 | #https://www.codewars.com/kata/58ca658cc0d6401f2700045f 3 | 4 | def find_multiples(integer, limit): 5 | return list(range(integer, limit+1, integer)) -------------------------------------------------------------------------------- /find_the_vowels.py: -------------------------------------------------------------------------------- 1 | #Find the vowels kata 2 | #https://www.codewars.com/kata/5680781b6b7c2be860000036 3 | 4 | def vowel_indices(word): 5 | return [i + 1 for i, letter in enumerate(word) if letter.lower() in 'aeiouy'] -------------------------------------------------------------------------------- /is_there_a_vowel_in_there.py: -------------------------------------------------------------------------------- 1 | #is there a vowel in there? kata 2 | #https://www.codewars.com/kata/57cff961eca260b71900008f 3 | 4 | def is_vow(inp): 5 | return [chr(num) if chr(num) in 'aeiou' else num for num in inp] -------------------------------------------------------------------------------- /largest_pair_sum_in_array.py: -------------------------------------------------------------------------------- 1 | ## Largest pair sum in array kata 2 | ## https://www.codewars.com/kata/556196a6091a7e7f58000018 3 | 4 | def largest_pair_sum(numbers): 5 | return sum(sorted(numbers, reverse=True)[0:2]) -------------------------------------------------------------------------------- /love_vs_friendship.py: -------------------------------------------------------------------------------- 1 | #love vs friendship kata 2 | #https://www.codewars.com/kata/59706036f6e5d1e22d000016 3 | 4 | def words_to_marks(s): 5 | return sum(list(map(lambda x: 'abcdefghijklmnopqrstuvwxyz'.index(x) + 1, s))) -------------------------------------------------------------------------------- /maximum_product.py: -------------------------------------------------------------------------------- 1 | #maximum product kata 2 | #https://www.codewars.com/kata/5a4138acf28b82aa43000117 3 | 4 | def adjacent_element_product(array): 5 | return max(map(lambda x: x[0]*x[1], zip(array[0:-1], array[1:]))) -------------------------------------------------------------------------------- /number_to_digit_tiers.py: -------------------------------------------------------------------------------- 1 | #Number to digit tiers kata 2 | #https://www.codewars.com/kata/586bca7fa44cfc833e00005c 3 | 4 | def create_array_of_tiers(n): 5 | n = str(n) 6 | return [n[:i+1] for i, x in enumerate(n)] -------------------------------------------------------------------------------- /return_substring_instance_count.py: -------------------------------------------------------------------------------- 1 | #return substring instance count kata 2 | #https://www.codewars.com/kata/5168b125faced29f66000005 3 | 4 | def solution(full_text, search_text): 5 | return full_text.count(search_text) -------------------------------------------------------------------------------- /simple_fun_152_invite_more_women.py: -------------------------------------------------------------------------------- 1 | #simple fun #152: invite more women? kata 2 | #https://www.codewars.com/kata/58acfe4ae0201e1708000075 3 | 4 | def invite_more_women(arr): 5 | return not arr.count(-1) >= arr.count(1) -------------------------------------------------------------------------------- /sum-positive.py: -------------------------------------------------------------------------------- 1 | def positive_sum(arr): 2 | '''Return the sum of the positive numbers''' 3 | total = 0 4 | for num in arr: 5 | if num > 0: 6 | total = total + num 7 | 8 | return total -------------------------------------------------------------------------------- /between_extremes.py: -------------------------------------------------------------------------------- 1 | # Between Extremes kata 2 | # https://www.codewars.com/kata/56d19b2ac05aed1a20000430/train/python 3 | 4 | def between_extremes(numbers): 5 | numbers.sort() 6 | return numbers[-1] - numbers[0] 7 | -------------------------------------------------------------------------------- /some_but_not_all.py: -------------------------------------------------------------------------------- 1 | #Some (but not all) kata 2 | #https://www.codewars.com/kata/60dda5a66c4cf90026256b75 3 | 4 | def some_but_not_all(seq, pred): 5 | return len(list(filter(lambda x: pred(x), seq))) in range(1, len(seq)) -------------------------------------------------------------------------------- /suzuki-stairs.py: -------------------------------------------------------------------------------- 1 | def stairs_in_20(stairs): 2 | '''Calculates how many stairs suzuki will climb if he climbs 20 per day''' 3 | total = 0 4 | for day in stairs: 5 | total += sum(day) 6 | return total*20 -------------------------------------------------------------------------------- /switcheroo.py: -------------------------------------------------------------------------------- 1 | #Switcheroo kata 2 | #https://www.codewars.com/kata/57f759bb664021a30300007d 3 | 4 | def switcheroo(string): 5 | return ''.join([char if char =='c' else ['a','b'][1-['a','b'].index(char)] for char in string]) -------------------------------------------------------------------------------- /array_combinations.py: -------------------------------------------------------------------------------- 1 | #array combinations kata 2 | #https://www.codewars.com/kata/59e66e48fc3c499ec5000103 3 | 4 | def solve(arr): 5 | total = 1 6 | for array in arr: 7 | total *= len(set(array)) 8 | return total -------------------------------------------------------------------------------- /four_seven.py: -------------------------------------------------------------------------------- 1 | #Four/Seven kata 2 | #https://www.codewars.com/kata/5ff50f64c0afc50008861bf0 3 | 4 | def solution(n): 5 | vals = [4,7] 6 | try: 7 | return vals[vals.index(n)-1] 8 | except: 9 | return False -------------------------------------------------------------------------------- /herons_formula.py: -------------------------------------------------------------------------------- 1 | # Heron's Formula kata 2 | # https://www.codewars.com/kata/57aa218e72292d98d500240f 3 | 4 | import math 5 | def heron(a, b, c): 6 | s = (a + b + c) / 2 7 | return round(math.sqrt(s*(s-a)*(s-b)*(s-c)),2) 8 | -------------------------------------------------------------------------------- /printer-error.py: -------------------------------------------------------------------------------- 1 | import re 2 | def printer_error(s): 3 | '''Counts the number of printer errors (denoted by a letter not in a-m)''' 4 | matches = re.findall(r'[a-m]',s) 5 | return str(len(s)-len(matches))+'/'+str(len(s)) -------------------------------------------------------------------------------- /sort_arrays.py: -------------------------------------------------------------------------------- 1 | #sort arrays - 3 kata 2 | #https://www.codewars.com/kata/51f42b1de8f176db5a0002ae 3 | 4 | def sort_me(courses): 5 | courses = sorted(courses, key=lambda x: (x.split('-')[1],x.split('-')[0])) 6 | return courses -------------------------------------------------------------------------------- /sort_my_animals.py: -------------------------------------------------------------------------------- 1 | # Sort My Animals 2 | # https://www.codewars.com/kata/58ff1c8b13b001a5a50005b4/train/python 3 | 4 | def sort_animals(lst): 5 | return sorted(lst, key=lambda animal: (animal.number_of_legs, animal.name)) 6 | -------------------------------------------------------------------------------- /number-of-decimal-digits.py: -------------------------------------------------------------------------------- 1 | ###Number of Decimal Digits - codewars kata 2 | ###https://www.codewars.com/kata/58fa273ca6d84c158e000052 3 | 4 | def digits(n): 5 | '''Returns the number of digits in n''' 6 | return str(n).__len__() -------------------------------------------------------------------------------- /unique_in_order.py: -------------------------------------------------------------------------------- 1 | #unique in order kata 2 | #https://www.codewars.com/kata/54e6533c92449cc251001667 3 | 4 | from itertools import groupby 5 | def unique_in_order(iterable): 6 | return [elem for elem, _ in groupby(iterable)] 7 | -------------------------------------------------------------------------------- /array.py: -------------------------------------------------------------------------------- 1 | ###Array.diff - codewars kata 2 | ###https://www.codewars.com/kata/523f5d21c841566fde000009 3 | 4 | def array_diff(a, b): 5 | '''Removes all values from list a, that are present in b''' 6 | return [x for x in a if x not in b] -------------------------------------------------------------------------------- /filter-geese.py: -------------------------------------------------------------------------------- 1 | geese = {"African", "Roman Tufted", "Toulouse", "Pilgrim", "Steinbacher"} 2 | 3 | def goose_filter(birds): 4 | '''Return a list of the birds without the geese''' 5 | return [bird for bird in birds if bird not in geese] -------------------------------------------------------------------------------- /how_many_lightsabers_do_you_own.py: -------------------------------------------------------------------------------- 1 | #how many lightsabers do you own? kata 2 | #https://www.codewars.com/kata/51f9d93b4095e0a7200001b8 3 | 4 | def how_many_light_sabers_do_you_own(name='stan'): 5 | return 18 if name == 'Zach' else 0 6 | -------------------------------------------------------------------------------- /limit_string_length_1.py: -------------------------------------------------------------------------------- 1 | #Limit string length - 1 kata 2 | #https://www.codewars.com/kata/5208fc3cb613bc725f000142 3 | 4 | def solution(st, limit): 5 | print(len(st), limit) 6 | return st[0:limit] + '...' if limit < len(st) else st -------------------------------------------------------------------------------- /numbers_in_strings.py: -------------------------------------------------------------------------------- 1 | #numbers in strings kata 2 | #https://www.codewars.com/kata/59dd2c38f703c4ae5e000014 3 | 4 | import re 5 | def solve(s): 6 | nums = re.findall('[\d]+', s) 7 | nums = list(map(int, nums)) 8 | return max(nums) -------------------------------------------------------------------------------- /santas_naughty_list.py: -------------------------------------------------------------------------------- 1 | #santa's naughty list kata 2 | #https://www.codewars.com/kata/5a0b4dc2ffe75f72f70000ef 3 | 4 | def find_children(santas_list, children): 5 | return sorted(set([child for child in children if child in santas_list])) -------------------------------------------------------------------------------- /count_by_x.py: -------------------------------------------------------------------------------- 1 | #count by x kata 2 | #https://www.codewars.com/kata/5513795bd3fafb56c200049e 3 | 4 | def count_by(x, n): 5 | """ 6 | Return a sequence of numbers counting by `x` `n` times. 7 | """ 8 | return list(range(x, (x*n)+1, x)) -------------------------------------------------------------------------------- /help_bob_count_letters_and_digits.py: -------------------------------------------------------------------------------- 1 | #help bob count letters and digits kata 2 | #https://www.codewars.com/kata/5738f5ea9545204cec000155 3 | 4 | import re 5 | def count_letters_and_digits(s): 6 | return len(re.findall('[a-zA-Z0-9]', s)) 7 | -------------------------------------------------------------------------------- /minminmax.py: -------------------------------------------------------------------------------- 1 | #minminmax kata 2 | #https://www.codewars.com/kata/58d3487a643a3f6aa20000ff 3 | 4 | def minMinMax(arr): 5 | arr = sorted(arr) 6 | return [arr[0], min([x if x not in arr else arr[-1] for x in range(arr[0]+1,arr[-1])]), arr[-1]] -------------------------------------------------------------------------------- /two_joggers.py: -------------------------------------------------------------------------------- 1 | #Two Joggers kata 2 | #https://www.codewars.com/kata/5274d9d3ebc3030802000165 3 | 4 | def nbr_of_laps(x, y): 5 | i = min(x,y) 6 | while i % x or i % y != 0: 7 | i += min(x,y) 8 | return (i / x, i/y) 9 | -------------------------------------------------------------------------------- /banjo-player.py: -------------------------------------------------------------------------------- 1 | def areYouPlayingBanjo(name): 2 | '''Return is playing banjo, if name begins with r or R''' 3 | if name[0].lower() == 'r': 4 | return name + ' plays banjo' 5 | else: 6 | return name + ' does not play banjo' -------------------------------------------------------------------------------- /data_reverse.py: -------------------------------------------------------------------------------- 1 | #Data Reverse kata 2 | #https://www.codewars.com/kata/569d488d61b812a0f7000015 3 | 4 | def data_reverse(data): 5 | bytes = [] 6 | for i in range(len(data), -1, -8): 7 | bytes.extend(data[i:i+8]) 8 | return bytes -------------------------------------------------------------------------------- /dna-to-rna.py: -------------------------------------------------------------------------------- 1 | def DNAtoRNA(dna): 2 | '''Convert DNA to RNA by switching T to U''' 3 | return ''.join(list(map(tTou, dna))) 4 | 5 | def tTou(letter): 6 | if letter == 'T': 7 | return 'U' 8 | else: 9 | return letter -------------------------------------------------------------------------------- /happy_birthday.py: -------------------------------------------------------------------------------- 1 | #happy birthday kata 2 | #https://www.codewars.com/kata/5d65fbdfb96e1800282b5ee0/solutions/python 3 | 4 | def wrap(height, width, length): 5 | dim = sorted([height, width, length]) 6 | return 20 + dim[0]*4 + (dim[1]+dim[2]) * 2 -------------------------------------------------------------------------------- /highest_and_lowest.py: -------------------------------------------------------------------------------- 1 | #highest and lowest kata 2 | #https://www.codewars.com/kata/554b4ac871d6813a03000035 3 | 4 | def high_and_low(numbers): 5 | numbers = list(map(int, numbers.split(' '))) 6 | return '{} {}'.format(max(numbers), min(numbers)) -------------------------------------------------------------------------------- /sort-the-gift-code.py: -------------------------------------------------------------------------------- 1 | ###Sort the Gift Code - codewars kata 2 | ###https://www.codewars.com/kata/52aeb2f3ad0e952f560005d3 3 | 4 | def sort_gift_code(code): 5 | '''Sort and return the code in alphabetical order''' 6 | return ''.join(sorted(code)) -------------------------------------------------------------------------------- /consecutive_items.py: -------------------------------------------------------------------------------- 1 | #consecutive items kata 2 | #https://www.codewars.com/kata/5f6d533e1475f30001e47514 3 | 4 | def consecutive(arr, a, b): 5 | return True if sorted([a, b]) in [sorted([arr[i], arr[i+1]]) for i in range(len(arr)-1)] else False 6 | -------------------------------------------------------------------------------- /count-squares.py: -------------------------------------------------------------------------------- 1 | def count_squares(cuts): 2 | '''Count the number of cubes with paint on kata. If a cube is cut in 3 dimensions multiple times 3 | return the number of cubes which have atleast one red face''' 4 | return (cuts+1)**(3)-(cuts-1)**3 -------------------------------------------------------------------------------- /even-numbers.py: -------------------------------------------------------------------------------- 1 | def even_numbers(arr,n): 2 | '''Returns the last n numbers of a list of even numbers from array arr''' 3 | output = [] 4 | for num in arr: 5 | if num % 2 == 0: 6 | output.append(num) 7 | return output[-n:] -------------------------------------------------------------------------------- /ladies-eniac.py: -------------------------------------------------------------------------------- 1 | ##THE LADIES OF ENIAC KATA 2 | ##Returns the name of people in a list of characters 3 | 4 | import re 5 | def rad_ladies(name): 6 | letters = re.findall('[a-zA-Z !]', name) 7 | return ''.join([letter.upper() for letter in letters]) -------------------------------------------------------------------------------- /prefill_an_array.py: -------------------------------------------------------------------------------- 1 | #Prefill an array kata 2 | #https://www.codewars.com/kata/54129112fb7c188740000162 3 | 4 | def prefill(n,v='undefined'): 5 | try: 6 | return [v] * int(n) 7 | except: 8 | raise TypeError(f'{n} is invalid') 9 | -------------------------------------------------------------------------------- /square_every_digit.py: -------------------------------------------------------------------------------- 1 | #square every digit kata 2 | #https://www.codewars.com/kata/546e2562b03326a88e000020 3 | 4 | def square_digits(num): 5 | total = '' 6 | for num in map(int, str(num)): 7 | total += str(num**2) 8 | return int(total) -------------------------------------------------------------------------------- /sum_of_integers_in_a_string.py: -------------------------------------------------------------------------------- 1 | ##sum of integers in a string kata 2 | ##https://www.codewars.com/kata/598f76a44f613e0e0b000026 3 | 4 | import re 5 | 6 | def sum_of_integers_in_string(s): 7 | return sum(map(lambda x: int(x), re.findall('[0-9]+', s))) -------------------------------------------------------------------------------- /summing_a_numbers_digits.py: -------------------------------------------------------------------------------- 1 | #summing a number's digits kata 2 | #https://www.codewars.com/kata/52f3149496de55aded000410 3 | 4 | import re 5 | def sum_digits(number): 6 | digits = re.findall('\d', str(number)) 7 | return sum(list((map(int,digits)))) -------------------------------------------------------------------------------- /basic_math_add_or_subtract.py: -------------------------------------------------------------------------------- 1 | #basic math (add or subtract) kata 2 | #https://www.codewars.com/kata/5809b62808ad92e31b000031 3 | 4 | import re 5 | def calculate(s): 6 | s = re.sub('plus', '+', s) 7 | s = re.sub('minus','-', s) 8 | return str(eval(s)) -------------------------------------------------------------------------------- /convert_string_to_camel_case.py: -------------------------------------------------------------------------------- 1 | #convert string to camel case kata 2 | #https://www.codewars.com/kata/517abf86da9663f1d2000003 3 | 4 | import re 5 | def to_camel_case(text): 6 | p = re.sub('[_-]\w', lambda x: x.group()[-1:].upper(), text) 7 | return p -------------------------------------------------------------------------------- /form_the_largest.py: -------------------------------------------------------------------------------- 1 | #form the largest kata 2 | #https://www.codewars.com/kata/5a4ea304b3bfa89a9900008e 3 | 4 | def max_number(n): 5 | n = list(map(int, str(n))) 6 | n = sorted(n, reverse=True) 7 | n = list(map(str, n)) 8 | return int(''.join(n)) -------------------------------------------------------------------------------- /how_good_are_you_really.py: -------------------------------------------------------------------------------- 1 | #how good are you really? kata 2 | #https://www.codewars.com/kata/5601409514fc93442500010b 3 | 4 | def better_than_average(class_points, your_points): 5 | return True if your_points > sum(class_points)/len(class_points) else False -------------------------------------------------------------------------------- /odd-or-even.py: -------------------------------------------------------------------------------- 1 | ###Odd or Even? - codewars kata 2 | ###https://www.codewars.com/kata/5949481f86420f59480000e7/train/python 3 | 4 | def odd_or_even(arr): 5 | '''Returns even if sum of arr is even else odd''' 6 | return 'even' if sum(arr) % 2 == 0 else 'odd' -------------------------------------------------------------------------------- /partlist.py: -------------------------------------------------------------------------------- 1 | def partlist(arr): 2 | '''Returns all the ways to divide a list''' 3 | output_list = [] 4 | for i in range(0,len(arr)-1): 5 | output_list.append((' '.join(arr[:i+1]), ' '.join(arr[i+1:]),)) 6 | 7 | return output_list -------------------------------------------------------------------------------- /peak_array_index.py: -------------------------------------------------------------------------------- 1 | #peak array index kata 2 | #https://www.codewars.com/kata/5a61a846cadebf9738000076 3 | 4 | def peak(arr): 5 | for peak in range(0,len(arr)): 6 | if sum(arr[:peak]) == sum(arr[peak+1:]): 7 | return peak 8 | return -1 -------------------------------------------------------------------------------- /regexp_basics_is_it_a_digit.py: -------------------------------------------------------------------------------- 1 | #regexp basics - is it a digit? kata 2 | #https://www.codewars.com/kata/567bf4f7ee34510f69000032 3 | 4 | import re 5 | def is_digit(n): 6 | match = re.findall('[\d]', n) 7 | return match[0] == n if match else False 8 | -------------------------------------------------------------------------------- /regexp_basics_is_it_a_vowel.py: -------------------------------------------------------------------------------- 1 | #regexp basics - is it a vowel? kata 2 | #https://www.codewars.com/kata/567bed99ee3451292c000025 3 | 4 | import re 5 | def is_vowel(s): 6 | vowel = re.findall('^[aeiou]\Z', s.lower()) 7 | return True if vowel else False -------------------------------------------------------------------------------- /thinking-and-testing-true-or-false.py: -------------------------------------------------------------------------------- 1 | ###Thinking & Testing: True or False 2 | ###https://www.codewars.com/kata/56d931ecc443d475d5000003 3 | 4 | def testit(n): 5 | '''Returns the number of 0's in the binary form of n''' 6 | return bin(n)[1:].count('1') -------------------------------------------------------------------------------- /two_oldest_ages.py: -------------------------------------------------------------------------------- 1 | ###Two Oldest Ages - codewars kata 2 | ###https://www.codewars.com/kata/511f11d355fe575d2c000001/python 3 | 4 | def two_oldest_ages(ages): 5 | '''Return the two largest numbers, from smallest to largest''' 6 | return sorted(ages)[-2:] -------------------------------------------------------------------------------- /GCD_sum.py: -------------------------------------------------------------------------------- 1 | #GCD sum kata 2 | #https://www.codewars.com/kata/5dd259444228280032b1ed2a 3 | 4 | def solve(s,g): 5 | for i in range(g, s+1, g): 6 | remainder = s - i 7 | if remainder % g == 0: 8 | return (i, remainder) 9 | return -1 -------------------------------------------------------------------------------- /bit-counting.py: -------------------------------------------------------------------------------- 1 | ###Bit Counting - codewars kata 2 | ###https://www.codewars.com/kata/526571aae218b8ee490006f4 3 | 4 | def countBits(n): 5 | '''Returns the number of 1's in binary representation 6 | of a number''' 7 | return bin(n).split('b')[1].count('1') -------------------------------------------------------------------------------- /blue-marbles.py: -------------------------------------------------------------------------------- 1 | def guess_blue(blue_start, red_start, blue_pulled, red_pulled): 2 | '''Returns probability of picking a blue based on the numbers pulled out of a bag previously''' 3 | return (blue_start-blue_pulled)/(blue_start-blue_pulled+red_start-red_pulled) -------------------------------------------------------------------------------- /extra_perfect_numbers_special_numbers_series_7.py: -------------------------------------------------------------------------------- 1 | #extra perfect numbers (special numbers series #7) 2 | #https://www.codewars.com/kata/5a662a02e626c54e87000123 3 | 4 | def extra_perfect(n): 5 | return list(range(1, n+1, 2)) if n % 2 == 1 else list(range(1,n,2)) -------------------------------------------------------------------------------- /reverse_a_number.py: -------------------------------------------------------------------------------- 1 | #Reverse a number kata 2 | #https://www.codewars.com/kata/555bfd6f9f9f52680f0000c5 3 | 4 | def reverse_number(n): 5 | n, flag = str(n), 1 6 | if n[0] == '-': 7 | flag = -1 8 | n = n[1:] 9 | return flag*int(str(n)[::-1]) -------------------------------------------------------------------------------- /simple_fun_176_reverse_letter.py: -------------------------------------------------------------------------------- 1 | #simple fun #176: reverse letter kata 2 | #https://www.codewars.com/kata/58b8c94b7df3f116eb00005b 3 | 4 | def reverse_letter(string): 5 | return ''.join(list(map(lambda x: x if x.isalpha() else '', string))[::-1]) 6 | 7 | -------------------------------------------------------------------------------- /thinking_and_testing_uniq_or_not_uniq.py: -------------------------------------------------------------------------------- 1 | #thinking and testing: uniq or not uniq kata 2 | #https://www.codewars.com/kata/56d949281b5fdc7666000004 3 | 4 | def testit(a, b): 5 | a = list(set(a)) 6 | b = list(set(b)) 7 | a.extend(b) 8 | return sorted(a) -------------------------------------------------------------------------------- /absent_vowel.py: -------------------------------------------------------------------------------- 1 | #absent vowel kata 2 | #https://www.codewars.com/kata/56414fdc6488ee99db00002c 3 | 4 | def absent_vowel(x): 5 | letters = set(x) 6 | for i, vowel in enumerate(['a','e','i','o','u']): 7 | if vowel not in letters: 8 | return i -------------------------------------------------------------------------------- /deoderant_evaporator.py: -------------------------------------------------------------------------------- 1 | #deoderant evaporator kata 2 | #https://www.codewars.com/kata/5506b230a11c0aeab3000c1f 3 | 4 | import math 5 | def evaporator(content, evap_per_day, threshold): 6 | return math.ceil(math.log((threshold/100))/math.log((100-evap_per_day)/100)) -------------------------------------------------------------------------------- /first_character_that_repeats.py: -------------------------------------------------------------------------------- 1 | #first character that repeats kata 2 | #https://www.codewars.com/kata/54f9f4d7c41722304e000bbb 3 | 4 | 5 | def first_dup(s): 6 | for letter in s: 7 | if s.count(letter) > 1: 8 | return letter 9 | -------------------------------------------------------------------------------- /halving_sum.py: -------------------------------------------------------------------------------- 1 | #halving sum kata 2 | #https://www.codewars.com/kata/5a58d46cfd56cb4e8600009d 3 | 4 | def halving_sum(n): 5 | num = n 6 | total = n 7 | while num > 0.1: 8 | num //= 2 9 | total += num 10 | return total -------------------------------------------------------------------------------- /happy_birthday_darling.py: -------------------------------------------------------------------------------- 1 | #Happy Birthday, Darling! kata 2 | #https://www.codewars.com/kata/5e96332d18ac870032eb735f 3 | 4 | def womens_age(n): 5 | base = n // 2 6 | remainder = n % 2 7 | return "{}? That's just {}, in base {}!".format(n, 20 + remainder, base) -------------------------------------------------------------------------------- /maximum_gap_array_series_4.py: -------------------------------------------------------------------------------- 1 | #maximum gap (array series #4) kata 2 | #https://www.codewars.com/kata/5a7893ef0025e9eb50000013 3 | 4 | import numpy as np 5 | def max_gap(numbers): 6 | numbers = np.array(sorted(numbers)) 7 | return np.max(numbers[1:]-numbers[:-1]) -------------------------------------------------------------------------------- /minimize_sum_of_array_array_series_1.py: -------------------------------------------------------------------------------- 1 | #minimize sum of array (array series #1) kata 2 | #https://www.codewars.com/kata/5a523566b3bfa84c2e00010b 3 | 4 | def min_sum(arr): 5 | arr = sorted(arr) 6 | return sum([arr[i] * arr[-i-1] for i in range(int(len(arr)/2))]) -------------------------------------------------------------------------------- /reverse-words.py: -------------------------------------------------------------------------------- 1 | def reverse_words(text): 2 | n = text.count(' ') 3 | if n == 0: 4 | return text[::-1] 5 | text_split = text.split() 6 | spaces = ' '*int((n/(len(text_split) -1))) 7 | return spaces.join([section[::-1] for section in text_split]) -------------------------------------------------------------------------------- /tail_swap.py: -------------------------------------------------------------------------------- 1 | #tail swap kata 2 | #https://www.codewars.com/kata/5868812b15f0057e05000001 3 | 4 | def tail_swap(strings): 5 | split_1 = strings[0].split(':') 6 | split_2 = strings[1].split(':') 7 | return [split_1[0]+':'+split_2[1],split_2[0]+':'+split_1[1]] -------------------------------------------------------------------------------- /alternate_case.py: -------------------------------------------------------------------------------- 1 | #alternate case kata 2 | #https://www.codewars.com/kata/57a62154cf1fa5b25200031e 3 | 4 | def alternateCase(s): 5 | return s.swapcase() 6 | 7 | def alternateCase(s): 8 | return ''.join([char.lower() if char.isupper() else char.upper() for char in s ]) -------------------------------------------------------------------------------- /band_name_generator.py: -------------------------------------------------------------------------------- 1 | # Band name generator 2 | # https://www.codewars.com/kata/59727ff285281a44e3000011/train/python 3 | 4 | def band_name_generator(name): 5 | if name[0] == name[-1]: 6 | return name.title() + name[1:] 7 | return f'The {name.title()}' 8 | -------------------------------------------------------------------------------- /complete_the_pattern_1.py: -------------------------------------------------------------------------------- 1 | #complete the pattern #1 kata 2 | #https://www.codewars.com/kata/5572f7c346eb58ae9c000047 3 | 4 | def pattern(n): 5 | output = '' 6 | for num in range(1,n+1): 7 | output += str(num)*num + '\n' 8 | return output[:-1] 9 | -------------------------------------------------------------------------------- /sum_it_continuously.py: -------------------------------------------------------------------------------- 1 | #sum it continuously kata 2 | #https://www.codewars.com/kata/59b44d00bf10a439dd00006f 3 | 4 | def add(l): 5 | output = [0] 6 | for i in range(len(l)): 7 | total = l[i] + output[i] 8 | output.append(total) 9 | return output[1:] -------------------------------------------------------------------------------- /debug_sum_of_digits_of_a_number.py: -------------------------------------------------------------------------------- 1 | #Debug sum of digits of a number 2 | #https://www.codewars.com/kata/563d59dd8e47a5ed220000ba 3 | 4 | def get_sum_of_digits(num): 5 | sum = 0 6 | digits = list(str(num)) 7 | for x in digits: 8 | sum += int(x) 9 | return sum -------------------------------------------------------------------------------- /find_the_longest_gap.py: -------------------------------------------------------------------------------- 1 | #find the longest gap kata 2 | #https://www.codewars.com/kata/55b86beb1417eab500000051 3 | 4 | def gap(num): 5 | binary = str(bin(num)).strip('0').split('b')[1] 6 | binary = binary.split('1') 7 | return max(list(map(lambda x: len(x), binary))) -------------------------------------------------------------------------------- /get_the_middle_character.py: -------------------------------------------------------------------------------- 1 | #Get the middle character kata 2 | #https://www.codewars.com/kata/56747fd5cb988479af000028 3 | 4 | def get_middle(s): 5 | i, j = 1, 0 6 | if len(s) % 2 == 0: 7 | i = 2 8 | j = -1 9 | return s[int(len(s)/2+j):int(len(s)/2)+i+j] -------------------------------------------------------------------------------- /l2_triple_x.py: -------------------------------------------------------------------------------- 1 | #L2: Triple X kata 2 | #https://www.codewars.com/kata/568dc69683322417eb00002c 3 | 4 | def triple_x(s): 5 | for i, elem in enumerate(s[:-2]): 6 | if elem == 'x': 7 | return elem == s[i+1] and elem == s[i+2] 8 | return False 9 | -------------------------------------------------------------------------------- /regexp_basics_is_it_a_letter.py: -------------------------------------------------------------------------------- 1 | #regexp basics - is it a letter? kata 2 | #https://www.codewars.com/kata/567de72e8b3621b3c300000b 3 | 4 | def is_letter(s): 5 | print(s) 6 | return (ord(s.lower()) > 96 and ord(s.lower()) < 123) if (s.isalnum() and len(s) == 1) else False -------------------------------------------------------------------------------- /triangular-numbers.py: -------------------------------------------------------------------------------- 1 | ###SUM of Triangular Numbers Kata 2 | def sum_triangular_numbers(n): 3 | '''Uses formula to find triangular numbers and adds these to total''' 4 | total = 0 5 | for i in range(n+1): 6 | total += sum(list(range(1,i+1))) 7 | return total -------------------------------------------------------------------------------- /wealth-equality-finally.py: -------------------------------------------------------------------------------- 1 | ## Wealth Equality, Finally! kata 2 | ## https://www.codewars.com/kata/5815f7e789063238b30001aa 3 | 4 | def redistribute_wealth(wealth): 5 | average = sum(wealth) / len(wealth) 6 | for i in range(len(wealth)): 7 | wealth[i] = average 8 | -------------------------------------------------------------------------------- /bonuses.py: -------------------------------------------------------------------------------- 1 | #bonuses kata 2 | #https://www.codewars.com/kata/5d68d05e7a60ba002b0053f6 3 | 4 | def bonus(arr, s): 5 | minimum = min(arr) 6 | ratios = [(num/minimum)**-1 for num in arr] 7 | total = sum(ratios) 8 | return [round(s*ratio/total) for ratio in ratios] 9 | -------------------------------------------------------------------------------- /moving_average.py: -------------------------------------------------------------------------------- 1 | #moving average kata 2 | #https://www.codewars.com/kata/5c745b30f6216a301dc4dda5 3 | 4 | def moving_average(values,n): 5 | print(n) 6 | print(values) 7 | return [sum(values[i:i+n])/n for i in range(len(values)-n+1)] if n != 0 and n <= len(values) else None -------------------------------------------------------------------------------- /put_a_letter_in_a_column.py: -------------------------------------------------------------------------------- 1 | #Put a letter in a column kata 2 | #https://www.codewars.com/kata/563d54a7329a7af8f4000059 3 | 4 | def build_row_text(index, character): 5 | output = list('| | | | | | | | | |') 6 | output[index*2+1] = character 7 | return ''.join(output) 8 | -------------------------------------------------------------------------------- /return_a_sorted_list_of_objects.py: -------------------------------------------------------------------------------- 1 | ## return a sorted list of objects kata 2 | ## https://www.codewars.com/kata/52705ed65de62b733f000064 3 | 4 | 5 | def sort_list(sort_by, lst): 6 | sorted_lst = sorted(lst, key=lambda obj: obj[sort_by], reverse=True) 7 | return sorted_lst 8 | -------------------------------------------------------------------------------- /substituting_variables_into_strings_padded_numbers.py: -------------------------------------------------------------------------------- 1 | #substituting variables into strings: padded numbers kata 2 | #https://www.codewars.com/kata/51c89385ee245d7ddf000001 3 | 4 | def solution(value): 5 | value = str(value) 6 | return 'Value is ' + '0'*(5-len(value)) + value 7 | -------------------------------------------------------------------------------- /alan_partridge_2_apple_turnover.py: -------------------------------------------------------------------------------- 1 | #alan partridge 2 - apple turnover kata 2 | #https://www.codewars.com/kata/580a094553bd9ec5d800007d 3 | 4 | def apple(x): 5 | return 'It\'s hotter than the sun!!' if int(x)**2 > 1000 else "Help yourself to a honeycomb Yorkie for the glovebox." 6 | -------------------------------------------------------------------------------- /bases_everywhere.py: -------------------------------------------------------------------------------- 1 | #bases everywhere kata 2 | #https://www.codewars.com/kata/5f47e79e18330d001a195b55 3 | 4 | def base_finder(seq): 5 | sorted_seq = sorted(list(map(lambda x: int(x), seq))) 6 | sorted_seq = list(map(lambda x: x % 10, sorted_seq)) 7 | return max(sorted_seq) + 1 -------------------------------------------------------------------------------- /complementary_dna.py: -------------------------------------------------------------------------------- 1 | #complementary DNA kata 2 | #https://www.codewars.com/kata/554e4a2f232cdd87d9000038 3 | 4 | def complementary(letter): 5 | return ['A','T','C','G'][['T','A','G','C'].index(letter)] 6 | 7 | def DNA_strand(dna): 8 | return ''.join(list(map(complementary, dna))) -------------------------------------------------------------------------------- /lazy_repeater.py: -------------------------------------------------------------------------------- 1 | #Lazy Repeater kata 2 | #https://www.codewars.com/kata/51fc3beb41ecc97ee20000c3 3 | 4 | def make_looper(string): 5 | global x 6 | x = list(string) 7 | return func 8 | 9 | def func(): 10 | y = x.pop(0) 11 | x.append(y) 12 | return y 13 | -------------------------------------------------------------------------------- /multiples_of_3_or_5.py: -------------------------------------------------------------------------------- 1 | #multiples of 3 or 5 kata 2 | #https://www.codewars.com/kata/514b92a657cdc65150000006 3 | 4 | def solution(number): 5 | threes = list(range(3,number, 3)) 6 | fives = list(range(5, number, 5)) 7 | unique = set(threes + fives) 8 | return sum(unique) 9 | -------------------------------------------------------------------------------- /no-oddities-here.py: -------------------------------------------------------------------------------- 1 | ###No oddities here - codewars kata 2 | ### https://www.codewars.com/kata/51fd6bc82bc150b28e0000ce/train/python 3 | 4 | def no_odds(values): 5 | '''Returns a list of even values from values array''' 6 | return [value for value in values if value % 2 == 0] 7 | -------------------------------------------------------------------------------- /permutations.py: -------------------------------------------------------------------------------- 1 | #permutations kata 2 | #https://www.codewars.com/kata/5254ca2719453dcc0b00027d 3 | 4 | import itertools 5 | def permutations(string): 6 | perms = itertools.permutations(string, len(string)) 7 | perms = set(list(map(lambda x: ''.join(x), perms))) 8 | return perms -------------------------------------------------------------------------------- /return_a_strings_even_characters.py: -------------------------------------------------------------------------------- 1 | #return a string's even characters kata 2 | #https://www.codewars.com/kata/566044325f8fddc1c000002c 3 | 4 | def even_chars(st): 5 | if len(st) < 2 or len(st) > 100: 6 | return "invalid string" 7 | else: 8 | return list(st[1::2]) -------------------------------------------------------------------------------- /return_the_first_m_multiples_of_n.py: -------------------------------------------------------------------------------- 1 | #Return the first M multiples of N kata 2 | #https://www.codewars.com/kata/593c9175933500f33400003e 3 | 4 | def multiples(m, n): 5 | output = [] 6 | for i in range(0, m): 7 | output.append((i+1)*n) 8 | return output 9 | -------------------------------------------------------------------------------- /sum_of_intervals.py: -------------------------------------------------------------------------------- 1 | #sum of intervals kata 2 | #https://www.codewars.com/kata/52b7ed099cdc285c300001cd 3 | 4 | def sum_of_intervals(intervals): 5 | output = set([]) 6 | for interval in intervals: 7 | output.update(range(interval[0], interval[1])) 8 | return len(output) -------------------------------------------------------------------------------- /count_salutes.py: -------------------------------------------------------------------------------- 1 | #Count salutes kata 2 | #https://www.codewars.com/kata/605ae9e1d2be8a0023b494ed 3 | 4 | def count_salutes(hallway): 5 | total = 0 6 | for i, char in enumerate(hallway): 7 | if char == '>': 8 | total += hallway[i:].count('<') 9 | return total * 2 -------------------------------------------------------------------------------- /draw_stairs.py: -------------------------------------------------------------------------------- 1 | #draw stairs kata 2 | #https://www.codewars.com/kata/5b4e779c578c6a898e0005c5 3 | 4 | def draw_stairs(n): 5 | output_string = '' 6 | for num in range(0,n-1): 7 | output_string += ' '*num + 'I\n' 8 | output_string += ' '*(n-1) + 'I' 9 | return output_string -------------------------------------------------------------------------------- /geometry_basics_distance_between_two_points.py: -------------------------------------------------------------------------------- 1 | # Geometry Basics: Distance Between Two Points in 2D kata 2 | # https://www.codewars.com/kata/58dced7b702b805b200000be/train/python 3 | 4 | import math 5 | def distance_between_points(a, b): 6 | return math.sqrt((b.y-a.y)**2 + (b.x -a.x)**2) 7 | -------------------------------------------------------------------------------- /is-triangle.py: -------------------------------------------------------------------------------- 1 | def is_triangle(a, b, c): 2 | '''Accepts 3 integer values and returns True/False depending on whether a triangle''' 3 | x = a + b 4 | y = a + c 5 | z = b + c 6 | if (x <= c) or (y <= b) or (z <= a): 7 | return False 8 | else: 9 | return True -------------------------------------------------------------------------------- /rearrange_a_number_to_get_its_maximum.py: -------------------------------------------------------------------------------- 1 | #Rearrange number to get its maximum kata 2 | #https://www.codewars.com/kata/563700da1ac8be8f1e0000dc 3 | 4 | def max_redigit(num): 5 | num = str(num) 6 | if int(num) > 0 and len(num) == 3: 7 | return int(''.join(sorted(num, reverse=True))) -------------------------------------------------------------------------------- /sort-by-last-char.py: -------------------------------------------------------------------------------- 1 | ###Sort by last char - codewars kata 2 | ###https://www.codewars.com/kata/57eba158e8ca2c8aba0002a0 3 | 4 | def last(x): 5 | '''Return x but with elements sorted by last character''' 6 | x_list = (x.split(' ')) 7 | x_list.sort(key=lambda x:x[-1]) 8 | return x_list -------------------------------------------------------------------------------- /sum-pairs.py: -------------------------------------------------------------------------------- 1 | def sum_pairs(ints, s): 2 | '''Find the first occurence of two numbers that add to equal s''' 3 | myset = set() 4 | for num in ints: 5 | required = s - num 6 | if required in myset: 7 | return [required, num] 8 | myset.add(num) -------------------------------------------------------------------------------- /automorphic_number_special_numbers_series_6.py: -------------------------------------------------------------------------------- 1 | #automorphic number (special number series #6) kata 2 | #https://www.codewars.com/kata/5a58d889880385c2f40000aa 3 | 4 | def automorphic(n): 5 | n_squared = n**2 6 | return 'Automorphic' if str(n) == str(n_squared)[-len(str(n)):] else 'Not!!' 7 | -------------------------------------------------------------------------------- /descending-order.py: -------------------------------------------------------------------------------- 1 | def Descending_Order(num): 2 | '''Function takes non-negative integer and returns digits in descending order''' 3 | num_list = list(map(int,str(num))) 4 | num_list = sorted(num_list,reverse=True) 5 | output = ''.join(map(str, num_list)) 6 | return int(output) -------------------------------------------------------------------------------- /exclamation_marks_series_7.py: -------------------------------------------------------------------------------- 1 | ##exclamation marks series #7: remove words from the sentence if it 2 | ##contains one exclamation mark 3 | ##https://www.codewars.com/kata/57fafb6d2b5314c839000195 4 | 5 | def remove(s): 6 | return ' '.join(filter(lambda word: word.count('!') != 1, s.split(' '))) -------------------------------------------------------------------------------- /find_the_divisors.py: -------------------------------------------------------------------------------- 1 | #Find the divisors! kata 2 | #https://www.codewars.com/kata/544aed4c4a30184e960010f4 3 | 4 | def divisors(integer): 5 | divisor_list = [num for num in range(2,integer) if integer % num == 0 ] 6 | return divisor_list if divisor_list != [] else '{} is prime'.format(integer) -------------------------------------------------------------------------------- /find_within_array.py: -------------------------------------------------------------------------------- 1 | #find within array kata 2 | #https://www.codewars.com/kata/51f082ba7297b8f07f000001 3 | 4 | def find_in_array(seq, predicate): 5 | if seq: 6 | for i, item in enumerate(seq): 7 | if predicate(item, i) == True: 8 | return i 9 | return -1 -------------------------------------------------------------------------------- /retrieve_array_value_by_index_with_default.py: -------------------------------------------------------------------------------- 1 | #Retrieve array value by index with default kata 2 | #https://www.codewars.com/kata/515ceaebcc1dde8870000001 3 | 4 | def solution(items, index, default_value): 5 | try: 6 | return items[index] 7 | except: 8 | return default_value -------------------------------------------------------------------------------- /twice-as-old.py: -------------------------------------------------------------------------------- 1 | def twice_as_old(dad_years_old, son_years_old): 2 | '''Calculates how many years ago the father was twice as old as his son, or how many years til he will be''' 3 | twice_sons_age = 2*son_years_old 4 | difference = dad_years_old - twice_sons_age 5 | return abs(difference) -------------------------------------------------------------------------------- /basic-mathematics.py: -------------------------------------------------------------------------------- 1 | def basic_op(operator, value1, value2): 2 | '''Outputs a value based upon the operator provided''' 3 | outputs = { 4 | '+': value1 + value2, 5 | '-': value1 - value2, 6 | '*': value1 * value2, 7 | '/': value1 / value2 8 | } 9 | return outputs[operator] -------------------------------------------------------------------------------- /count_characters_in_your_string.py: -------------------------------------------------------------------------------- 1 | #Count characters in your string kata 2 | #https://www.codewars.com/kata/52efefcbcdf57161d4000091 3 | 4 | def count(string): 5 | chars = set(string) 6 | diction = {} 7 | for char in chars: 8 | diction[char] = string.count(char) 9 | return diction -------------------------------------------------------------------------------- /milk-and-cookies.py: -------------------------------------------------------------------------------- 1 | def time_for_milk_and_cookies(dt): 2 | '''Checks the data, and returns whether Santa needs milk and cookies''' 3 | date_str = str(dt) 4 | date_split = date_str.split('-') 5 | if date_split[1] == '12' and date_split[2] == '24': 6 | return True 7 | return False -------------------------------------------------------------------------------- /quadrants_2_segments.py: -------------------------------------------------------------------------------- 1 | # Quadrants 2: Segments kata 2 | # https://www.codewars.com/kata/643ea1adef815316e5389d17/train/python 3 | 4 | def quadrant_segment(A, B): 5 | x = A.x > 0 and B.x > 0 or A.x < 0 and B.x < 0 6 | y = A.y > 0 and B.y > 0 or A.y < 0 and B.y < 0 7 | return not (x and y) 8 | -------------------------------------------------------------------------------- /row-odd-triangle.py: -------------------------------------------------------------------------------- 1 | ###Row of the odd triangle - codewars kata 2 | ###Find and return row 'n' of an odd triangle, which starts with one 3 | def odd_row(n): 4 | multipliers = list(map(lambda x: x*2, list(range(n)))) 5 | start = sum(multipliers) + 1 6 | return list(range(start, start + (2*n), 2)) -------------------------------------------------------------------------------- /count_letters_in_string.py: -------------------------------------------------------------------------------- 1 | #Count letters in string kata 2 | #https://www.codewars.com/kata/5808ff71c7cfa1c6aa00006d 3 | 4 | def letter_count(s): 5 | letters = set(s) 6 | output = {} 7 | for letter in letters: 8 | output[letter] = s.count(letter) 9 | return output 10 | -------------------------------------------------------------------------------- /find_the_first_non_consecutive_number.py: -------------------------------------------------------------------------------- 1 | #find the first non-consecutive number kata 2 | #https://www.codewars.com/kata/58f8a3a27a5c28d92e000144 3 | 4 | def first_non_consecutive(arr): 5 | for i, num in enumerate(arr[1:]): 6 | if arr[i] != num-1: 7 | return num 8 | 9 | -------------------------------------------------------------------------------- /pluck.py: -------------------------------------------------------------------------------- 1 | #pluck kata 2 | #https://www.codewars.com/kata/530017aac7c0f49926000084 3 | 4 | def pluck(objs, name): 5 | output = [] 6 | for obj in objs: 7 | if name in obj: 8 | output.append(obj[name]) 9 | else: 10 | output.append(None) 11 | return output -------------------------------------------------------------------------------- /simple_consecutive_pairs.py: -------------------------------------------------------------------------------- 1 | #simple consecutive pairs kata 2 | #https://www.codewars.com/kata/5a3e1319b6486ac96f000049 3 | 4 | def pairs(ar): 5 | total = 0 6 | for i in range(0, len(ar)-1,2): 7 | if abs(ar[i] - ar[i+1]) == 1: 8 | total += 1 9 | return total 10 | -------------------------------------------------------------------------------- /array_deep_count.py: -------------------------------------------------------------------------------- 1 | # Array Deep Count 2 | # https://www.codewars.com/kata/596f72bbe7cd7296d1000029/ 3 | 4 | def deep_count(a): 5 | count = 0 6 | for item in a: 7 | if type(item) == list: 8 | count += deep_count(item) 9 | count += 1 10 | return count 11 | 12 | -------------------------------------------------------------------------------- /consecutive_count.py: -------------------------------------------------------------------------------- 1 | #Consevutive Count kata 2 | #https://www.codewars.com/kata/59c3e819d751df54e9000098 3 | 4 | import re 5 | def get_consective_items(items, key): 6 | items, key = str(items), str(key) 7 | matches = re.findall(rf'{key}+', items) 8 | return max(list(map(lambda x: len(x), matches)) + [0]) -------------------------------------------------------------------------------- /running_out_of_space.py: -------------------------------------------------------------------------------- 1 | #running out of space kata 2 | #https://www.codewars.com/kata/56576f82ab83ee8268000059 3 | 4 | def spacey(array): 5 | output = [] 6 | combined = '' 7 | for word in array: 8 | combined += word 9 | output.append(combined) 10 | return output 11 | -------------------------------------------------------------------------------- /shortest-word.py: -------------------------------------------------------------------------------- 1 | def find_short(s): 2 | '''Return the length of the shortest word in a string of words''' 3 | words = s.split(" ") 4 | l = len(words[0]) 5 | for word in words: 6 | if len(word) < l: 7 | l = len(word) 8 | print(l) 9 | return l # l: shortest word length -------------------------------------------------------------------------------- /valid_spacing.py: -------------------------------------------------------------------------------- 1 | #valid spacing kata 2 | #https://www.codewars.com/kata/5f77d62851f6bc0033616bd8 3 | 4 | import re 5 | 6 | def valid_spacing(s): 7 | for resp in [re.findall('^ ',s), re.findall(' ', s), re.findall(' $', s)]: 8 | if resp: 9 | return False 10 | return True 11 | -------------------------------------------------------------------------------- /factorial.py: -------------------------------------------------------------------------------- 1 | #factorial kata 2 | #https://www.codewars.com/kata/54ff0d1f355cfd20e60001fc 3 | 4 | def factorial(n): 5 | total = 1 6 | if n < 0 or n > 12: 7 | raise ValueError('Value Error') 8 | else: 9 | for num in range(1, n+1): 10 | total *= num 11 | return total -------------------------------------------------------------------------------- /the_wheat_rice_and_chessboard_problem.py: -------------------------------------------------------------------------------- 1 | #the wheat/rice and chessboard problem kata 2 | #https://www.codewars.com/kata/5b0d67c1cb35dfa10b0022c7 3 | 4 | def squares_needed(grains): 5 | square = 0 6 | ans = 1 7 | while ans <= grains: 8 | ans *= 2 9 | square += 1 10 | return square -------------------------------------------------------------------------------- /special_number_special_number_series_5.py: -------------------------------------------------------------------------------- 1 | #special number (special numbers series #5) kata 2 | #https://www.codewars.com/kata/5a55f04be6be383a50000187 3 | 4 | def special_number(number): 5 | return 'Special!!' if sum([1 if num in ['1','2','3','4','5','0'] else 0 for num in str(number)]) == len(str(number)) else 'NOT!!' -------------------------------------------------------------------------------- /closest-elevator.py: -------------------------------------------------------------------------------- 1 | def elevator(left, right, call): 2 | '''Return the closest elevator depending on the floor (call). If both are the same, return right''' 3 | left_distance = abs(call-left) 4 | right_distance = abs(call-right) 5 | if right_distance <= left_distance: 6 | return 'right' 7 | return 'left' -------------------------------------------------------------------------------- /consecutive-ducks.py: -------------------------------------------------------------------------------- 1 | ###Consecutive Ducks - codewars kata 2 | ###https://www.codewars.com/kata/5dae2599a8f7d90025d2f15f 3 | import math 4 | def consecutive_ducks(n): 5 | '''Returns True if number n can be expressed as the sum of two or more consecutive 6 | positive numbers''' 7 | return not math.log(n, 2).is_integer() -------------------------------------------------------------------------------- /convert_lambda_to_def.py: -------------------------------------------------------------------------------- 1 | #Convert lambda to def kata 2 | #https://www.codewars.com/kata/605d25f4f24c030033da9afb 3 | 4 | def convert_lambda_to_def(string): 5 | name, rhs = string.split(' = ') 6 | lmdba, rtn = rhs.split(': ') 7 | param = lmdba.split('lambda ')[-1] 8 | return f"def {name}({param}):\n return {rtn}" -------------------------------------------------------------------------------- /diagonals_sum.py: -------------------------------------------------------------------------------- 1 | #diagonals sum kata 2 | #https://www.codewars.com/kata/5592fc599a7f40adac0000a8 3 | 4 | def sum_diagonals(matrix): 5 | total = 0 6 | range_vals = list(range(0, len(matrix))) 7 | for i, j in list(zip(range_vals, range_vals[::-1])): 8 | total += matrix[i][i] + matrix [j][i] 9 | return total -------------------------------------------------------------------------------- /equal_sides_of_an_array.py: -------------------------------------------------------------------------------- 1 | #Equal sides of an array kata 2 | #https://www.codewars.com/kata/5679aa472b8f57fb8c000047 3 | 4 | def find_even_index(arr): 5 | for i in range(0,len(arr)): 6 | LHS = sum(arr[:i]) 7 | RHS = sum(arr[i+1:]) 8 | if LHS == RHS: 9 | return i 10 | return -1 -------------------------------------------------------------------------------- /longest-vowel-chain.py: -------------------------------------------------------------------------------- 1 | ###Longest Vowel Chain - codewars kata 2 | ###https://www.codewars.com/kata/59c5f4e9d751df43cf000035 3 | 4 | import re 5 | def solve(s): 6 | '''Find and returns the length of the longest chain of vowels within s''' 7 | matches = re.findall('[aeiou]+', s) 8 | return max(list(map(len, matches))) -------------------------------------------------------------------------------- /ones-and-zeros.py: -------------------------------------------------------------------------------- 1 | ##ONES AND ZEROS KATA 2 | #Given an array of ones and zeros, program converts equivalent binary value into an integer 3 | 4 | def binary_array_to_number(arr): 5 | total = 0 6 | i = 1 7 | for num in arr[::-1]: 8 | total += (i*num) 9 | i *= 2 10 | return total 11 | -------------------------------------------------------------------------------- /power-of-two.py: -------------------------------------------------------------------------------- 1 | def power_of_two(x): 2 | '''Find if a number can be obtained via 2^n''' 3 | current_number = 0 4 | counter = 0 5 | while current_number <= x: 6 | current_number = 2**counter 7 | counter+=1 8 | if current_number == x: 9 | return True 10 | return False -------------------------------------------------------------------------------- /array_leaders_array_series_3.py: -------------------------------------------------------------------------------- 1 | #array leaders (array series #3) kata 2 | #https://www.codewars.com/kata/5a651865fd56cb55760000e0 3 | 4 | def array_leaders(numbers): 5 | output = [] 6 | for i in range(0, len(numbers)): 7 | if numbers[i] > sum(numbers[i+1:]): 8 | output.append(numbers[i]) 9 | return output -------------------------------------------------------------------------------- /conference_traveller.py: -------------------------------------------------------------------------------- 1 | #conference traveller kata 2 | #https://www.codewars.com/kata/56f5594a575d7d3c0e000ea0 3 | 4 | def conference_picker(cities_visited, cities_offered): 5 | for city in cities_offered: 6 | if city not in cities_visited: 7 | return city 8 | return 'No worthwhile conferences this year!' -------------------------------------------------------------------------------- /form-the-minimum.py: -------------------------------------------------------------------------------- 1 | ###Form the Minimum - codewars kata 2 | ###https://www.codewars.com/kata/5ac6932b2f317b96980000ca 3 | 4 | def min_value(digits): 5 | '''Returns the smallest number that could be formed using unique values in digits''' 6 | digits = sorted(list(set(digits))) 7 | return int(''.join(list(map(str,digits)))) -------------------------------------------------------------------------------- /last_digits_of_a_number.py: -------------------------------------------------------------------------------- 1 | #last digits of a number kata 2 | #https://www.codewars.com/kata/5cd5ba1ce4471a00256930c0 3 | 4 | def solution(n,d): 5 | n = list(str(n)) 6 | if d > len(n): 7 | return list(map(int, n)) 8 | elif d <= 0: 9 | return [] 10 | else: 11 | return list(map(int, n[-d:])) -------------------------------------------------------------------------------- /the_office_VI_sabbatical.py: -------------------------------------------------------------------------------- 1 | #the office VI - sabbatical kata 2 | #https://www.codewars.com/kata/57fe50d000d05166720000b1 3 | 4 | import re 5 | def sabb(s, value, happiness): 6 | letters = re.findall('[sabatical]', s) 7 | return 'Sabbatical! Boom!' if len(letters) + value + happiness > 22 else 'Back to your desk, boy.' 8 | -------------------------------------------------------------------------------- /the_old_switcheroo.py: -------------------------------------------------------------------------------- 1 | #the old switcheroo kata 2 | #https://www.codewars.com/kata/55d410c492e6ed767000004f 3 | 4 | def vowel_2_index(string): 5 | output = '' 6 | for i, char in enumerate(string): 7 | if char.lower() in 'aeiou': 8 | char = str(i+1) 9 | output += char 10 | return output -------------------------------------------------------------------------------- /two_sum.py: -------------------------------------------------------------------------------- 1 | #Two Sum kata 2 | #https://www.codewars.com/kata/52c31f8e6605bcc646000082 3 | 4 | def two_sum(numbers, target): 5 | for i, num in enumerate(numbers): 6 | other_num = target - num 7 | if other_num in numbers and numbers.index(other_num) != i: 8 | return [i, numbers.index(target-num)] 9 | -------------------------------------------------------------------------------- /weird_string_case.py: -------------------------------------------------------------------------------- 1 | #WeIrD StRiNg CaSe kata 2 | #https://www.codewars.com/kata/52b757663a95b11b3d00062d 3 | 4 | def to_weird_case(string): 5 | output = '' 6 | for word in string.split(' '): 7 | output += ' ' + ''.join([char.title() if i%2 == 0 else char for i, char in enumerate(word) ]) 8 | return output.strip(' ') -------------------------------------------------------------------------------- /which_are_in.py: -------------------------------------------------------------------------------- 1 | #Which are in? kata 2 | #https://www.codewars.com/kata/550554fd08b86f84fe000a58 3 | 4 | def in_array(array1, array2): 5 | output = set() 6 | for word1 in array1: 7 | for word2 in array2: 8 | if word1 in word2: 9 | output.add(word1) 10 | return sorted(list(output)) -------------------------------------------------------------------------------- /enumerable-magic#5.py: -------------------------------------------------------------------------------- 1 | ###Enumerable Magic #5 - True for Just One? - codewars kata 2 | ###https://www.codewars.com/kata/54599705cbae2aa60b0011a4 3 | 4 | def one(sq, fun): 5 | '''Returns True if the function fun, applied to each element of 6 | sq, returns True only in one instance''' 7 | return list(map(fun, sq)).count(True) == 1 -------------------------------------------------------------------------------- /find-the-speedcubers-times.py: -------------------------------------------------------------------------------- 1 | ###Find the speecuber's times - codewars kata 2 | ###https://www.codewars.com/kata/5d7c7697e8ad48001e642964/python 3 | 4 | def cube_times(times): 5 | '''Returns the average of the three middle times and the fastest time''' 6 | times = sorted(times) 7 | return (round(sum(times[1:4])/3,2), times[0]) -------------------------------------------------------------------------------- /find_the_missing_letter.py: -------------------------------------------------------------------------------- 1 | #Find the missing letter kata 2 | #https://www.codewars.com/kata/5839edaa6754d6fec10000a2 3 | 4 | def find_missing_letter(chars): 5 | previous = ord(chars[0])-1 6 | for char in chars: 7 | if ord(char) != previous + 1: 8 | return chr(previous+1) 9 | previous += 1 10 | -------------------------------------------------------------------------------- /kids_and_candies.py: -------------------------------------------------------------------------------- 1 | # Kids and candies kata 2 | # https://www.codewars.com/kata/56cca888a9d0f25985000036/train/python 3 | 4 | import math 5 | def candies_to_buy(amount_of_kids_invited): 6 | lcm = 1 7 | for num in range(1, amount_of_kids_invited+1): 8 | lcm = lcm * num // math.gcd(lcm, num) 9 | return lcm 10 | -------------------------------------------------------------------------------- /odd-triangle-row.py: -------------------------------------------------------------------------------- 1 | ###Row of the odd triangle kata 2 | ###https://www.codewars.com/kata/5d5a7525207a674b71aa25b5 3 | 4 | def odd_row(n): 5 | '''Returns the row (n) of an odd triangle''' 6 | multipliers = list(map(lambda x: x*2, list(range(n)))) 7 | start = sum(multipliers) + 1 8 | return list(range(start, start + (2*n), 2)) -------------------------------------------------------------------------------- /even_times_last.py: -------------------------------------------------------------------------------- 1 | #Even times last kata 2 | #https://www.codewars.com/kata/5a1a9e5032b8b98477000004 3 | 4 | def even_last(numbers): 5 | total = 0 6 | if numbers: 7 | last = numbers[-1] 8 | numbers = [num for i, num in enumerate(numbers) if i % 2 ==0] 9 | total = sum(numbers) * last 10 | return total -------------------------------------------------------------------------------- /extract_the_domain_name_from_a_URL.py: -------------------------------------------------------------------------------- 1 | #Extract the domain name from a URL kata 2 | #https://www.codewars.com/kata/514a024011ea4fb54200004b 3 | 4 | def domain_name(url): 5 | for itm in ['http://', 'www.', 'https://']: 6 | if itm in url: 7 | url = url.split(itm)[1] 8 | return url.split('.')[0] 9 | 10 | -------------------------------------------------------------------------------- /mumbling.py: -------------------------------------------------------------------------------- 1 | def accum(s): 2 | '''accum("abcd") -> "A-Bb-Ccc-Dddd" 3 | accum("RqaEzty") -> "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy" 4 | accum("cwAt") -> "C-Ww-Aaa-Tttt"''' 5 | output = [] 6 | for count, letter in enumerate(s): 7 | output.append(letter.upper() + letter.lower()*(count)) 8 | return '-'.join(output) -------------------------------------------------------------------------------- /sort_out_the_men_from_boys.py: -------------------------------------------------------------------------------- 1 | #sort out the men from boys kata 2 | #https://www.codewars.com/kata/5af15a37de4c7f223e00012d 3 | 4 | import numpy as np 5 | def men_from_boys(arr): 6 | arr = np.array(arr) 7 | men = set(arr[arr % 2 == 0]) 8 | boys = set(arr[arr % 2 ==1]) 9 | return sorted(list(men)) + sorted(list(boys), reverse=True) -------------------------------------------------------------------------------- /all_star_coding_challenge_15.py: -------------------------------------------------------------------------------- 1 | # All Start Coding Challenge #15 2 | # https://www.codewars.com/kata/586560a639c5ab3a260000f3/train/python 3 | 4 | def rotate(str_): 5 | rotations = [] 6 | for i in range(len(str_)): 7 | str_ = str_[1:] + str_[0:1] 8 | rotations.append(str_) 9 | return rotations 10 | 11 | -------------------------------------------------------------------------------- /almost_even.py: -------------------------------------------------------------------------------- 1 | #Almost Even kata 2 | #https://www.codewars.com/kata/529e2e1f16cb0fcccb000a6b 3 | 4 | def split_integer(num, parts): 5 | output = [num // parts for i in range(parts)] 6 | remainder = num % parts 7 | if remainder > 0: 8 | for i in range(remainder): 9 | output[i] += 1 10 | return sorted(output) -------------------------------------------------------------------------------- /final-grade.py: -------------------------------------------------------------------------------- 1 | def final_grade(exam, projects): 2 | '''Return grade based on input criteria''' 3 | grade = 0 4 | if exam > 90 or projects > 10: 5 | grade = 100 6 | elif exam > 75 and projects >= 5: 7 | grade = 90 8 | elif exam > 50 and projects >= 2: 9 | grade = 75 10 | 11 | return grade -------------------------------------------------------------------------------- /from_a_to_z.py: -------------------------------------------------------------------------------- 1 | # From A to Z kata 2 | # https://www.codewars.com/kata/6512b3775bf8500baea77663/train/python 3 | 4 | def gimme_the_letters(sp): 5 | first_letter, last_letter = sp.split('-') 6 | sequence = '' 7 | for i in range(ord(first_letter), ord(last_letter) + 1): 8 | sequence += chr(i) 9 | return sequence 10 | -------------------------------------------------------------------------------- /how_many_reindeers?.py: -------------------------------------------------------------------------------- 1 | #How many reindeers? kata 2 | #https://www.codewars.com/kata/52ad1db4b2651f744d000394 3 | 4 | import math 5 | def reindeer(presents): 6 | total = 2 7 | total += math.ceil(presents/30) 8 | if total <= 8: 9 | return total 10 | else: 11 | raise ValueError('Santa needs too many reindeers') -------------------------------------------------------------------------------- /plus_one_array.py: -------------------------------------------------------------------------------- 1 | #+1 Array kata 2 | #https://www.codewars.com/kata/5514e5b77e6b2f38e0000ca9 3 | 4 | def up_array(arr): 5 | cond = list(filter(lambda x: x < 0 or x//10 >= 1, arr)) != [] 6 | if cond == False and arr != []: 7 | arr = list(map(str, arr)) 8 | num = int(''.join(arr)) + 1 9 | return list(map(int,str(num))) -------------------------------------------------------------------------------- /round_by_0.5_steps.py: -------------------------------------------------------------------------------- 1 | #Round by 0.5 steps kata 2 | #https://www.codewars.com/kata/51f1342c76b586046800002a 3 | 4 | import math 5 | def solution(n): 6 | flr = math.floor(n) 7 | ceil = math.ceil(n) 8 | if n - flr < 0.25: 9 | return flr 10 | elif n - (flr + 0.5) >= 0.25: 11 | return ceil 12 | return flr+0.5 -------------------------------------------------------------------------------- /string_array_duplicates.py: -------------------------------------------------------------------------------- 1 | #string array duplicates kata 2 | #https://www.codewars.com/kata/59f08f89a5e129c543000069 3 | 4 | import re 5 | def dup(arry): 6 | output = [] 7 | for arr in arry: 8 | letters = re.findall("([\\w\\d])\\1*", arr) 9 | output.append(''.join(letters)) 10 | return output 11 | 12 | -------------------------------------------------------------------------------- /sum_of_odd_cubed_numbers.py: -------------------------------------------------------------------------------- 1 | #sum of odd cubed numbers kata 2 | #https://www.codewars.com/kata/580dda86c40fa6c45f00028a 3 | 4 | 5 | def cube_odd(arr): 6 | total = 0 7 | for num in arr: 8 | if (type(num) != int): 9 | return None 10 | if num % 2 != 0: 11 | total += num**3 12 | return total -------------------------------------------------------------------------------- /duplicate_sandwich.py: -------------------------------------------------------------------------------- 1 | #duplicate sandwich kata 2 | #https://www.codewars.com/kata/5f8a15c06dbd530016be0c19 3 | 4 | def duplicate_sandwich(arr): 5 | appeared = [] 6 | for i, item in enumerate(arr): 7 | if item not in appeared: 8 | appeared.append(item) 9 | else: 10 | return arr[arr.index(item)+1:i] -------------------------------------------------------------------------------- /grouped_by_commas.py: -------------------------------------------------------------------------------- 1 | #Grouped by commas kata 2 | #https://www.codewars.com/kata/5274e122fc75c0943d000148 3 | 4 | 5 | def group_by_commas(n): 6 | n = str(n)[::-1] 7 | output = '' 8 | for i, num in enumerate(n): 9 | if (i) % 3 == 0 and i != 0: 10 | output += ',' 11 | output += num 12 | return output[::-1] -------------------------------------------------------------------------------- /help-the-fruit-guy.py: -------------------------------------------------------------------------------- 1 | ## Help the Fruit Guy kata 2 | ## https://www.codewars.com/kata/557af4c6169ac832300000ba 3 | 4 | def transformFruit(fruit): 5 | return fruit.replace('rotten','').lower() 6 | def remove_rotten(bag_of_fruits): 7 | if not bag_of_fruits: 8 | return [] 9 | return list(map(transformFruit, bag_of_fruits)) 10 | -------------------------------------------------------------------------------- /how_much_hex_is_the_fish.py: -------------------------------------------------------------------------------- 1 | # how much hex is the fish kata 2 | # https://www.codewars.com/kata/5714eb80e1bf814e53000c06 3 | 4 | def fish_hex(name): 5 | name = name.lower() 6 | bitwise_or = 0 7 | for char in name: 8 | if char in "abcdef": 9 | bitwise_or = bitwise_or ^ int(char, 16) 10 | return bitwise_or 11 | -------------------------------------------------------------------------------- /maximum-triplet-sum.py: -------------------------------------------------------------------------------- 1 | ###Maximum Triplet Sum - codewars kata 2 | ###https://www.codewars.com/users/ellismckenzielee/completed_solutions 3 | 4 | def max_tri_sum(numbers): 5 | '''Returns the maximum value that can be produced from the summation 6 | of unique values in numbers''' 7 | 8 | return sum(sorted(set(numbers),reverse = True)[0:3]) -------------------------------------------------------------------------------- /simple_fun_136_missing_values.py: -------------------------------------------------------------------------------- 1 | #Simple Fun #136: Missing Values kata 2 | #https://www.codewars.com/kata/58a66c208b88b2de660000c3 3 | 4 | from collections import Counter 5 | def missing_values(seq): 6 | counts = Counter(seq) 7 | vals = [item for item, count in sorted(counts.items(), key=lambda x: x[1])] 8 | return vals[0] * vals[0] * vals[1] -------------------------------------------------------------------------------- /squash_the_bugs.py: -------------------------------------------------------------------------------- 1 | #squash the bugs kata 2 | #https://www.codewars.com/kata/56f173a35b91399a05000cb7 3 | 4 | def find_longest(string): 5 | spl = string.split(" ") 6 | longest, i = 0, 0 7 | 8 | while (i < len(spl)): 9 | if len(spl[i]) > longest: 10 | longest = len(spl[i]) 11 | i += 1 12 | return longest -------------------------------------------------------------------------------- /alphabetical_addition.py: -------------------------------------------------------------------------------- 1 | #alphabetical addition kata 2 | #https://www.codewars.com/kata/5d50e3914861a500121e1958 3 | 4 | def add_letters(*letters): 5 | letter_list = list('abcdefghijklmnopqrstuvwxyz') 6 | new_index = 0 7 | for letter in letters: 8 | new_index += (letter_list.index(letter)+1) 9 | return letter_list[(new_index -1) % 26] -------------------------------------------------------------------------------- /emotional_sort.py: -------------------------------------------------------------------------------- 1 | # Emotional Sort kata 2 | # https://www.codewars.com/kata/5a86073fb17101e453000258/train/python 3 | 4 | def sort_by_face(face): 5 | faces = [ ':D', ':)', ':|', ':(', 'T_T' ] 6 | return faces.index(face) 7 | 8 | def sort_emotions(arr, order): 9 | arr.sort(key = sort_by_face, reverse = not order) 10 | return arr 11 | -------------------------------------------------------------------------------- /simple_missing_sum.py: -------------------------------------------------------------------------------- 1 | #simple missing sum kata 2 | #https://www.codewars.com/kata/5a941f3a4a6b34edf900006f 3 | 4 | def solve(arr): 5 | arr = sorted(arr) 6 | num = 1 7 | for i in arr: 8 | if i <= num: 9 | num += i 10 | else: 11 | break 12 | return num 13 | 14 | 15 | -------------------------------------------------------------------------------- /array_exchange.py: -------------------------------------------------------------------------------- 1 | #array exchange kata 2 | #https://www.codewars.com/kata/5353212e5ee40d4694001114 3 | 4 | def exchange_with(a, b): 5 | a_len = len(a) 6 | b_len = len(b) 7 | a_plc = a.copy() 8 | b_plc = b.copy() 9 | 10 | a.extend(b_plc[::-1]) 11 | del a[0:a_len] 12 | b.extend(a_plc[::-1]) 13 | del b[0:b_len] 14 | -------------------------------------------------------------------------------- /collatz.py: -------------------------------------------------------------------------------- 1 | ##Collatz Kata 2 | ##https://www.codewars.com/kata/5286b2e162056fd0cb000c20/train/python 3 | 4 | def collatz(n): 5 | sequence = [str(n)] 6 | while n != 1: 7 | if n % 2 == 0: 8 | n = n / 2 9 | else: 10 | n = 3*n + 1 11 | sequence.append(str(int(n))) 12 | return '->'.join(sequence) 13 | -------------------------------------------------------------------------------- /keystroking.py: -------------------------------------------------------------------------------- 1 | #keystroking kata 2 | #https://www.codewars.com/kata/5be085e418bcfd260b000028 3 | 4 | def num_key_strokes(text): 5 | total = 0 6 | singles = "1234567890-=qwertyuiop[]\\asdfghjkl;'zxcvbnm,./ `" 7 | for letter in text: 8 | total += 1 9 | if letter not in singles: 10 | total += 1 11 | return total -------------------------------------------------------------------------------- /largest_5_digit_number_in_a_series.py: -------------------------------------------------------------------------------- 1 | #Largest 5 digit number in a series kata 2 | #https://www.codewars.com/kata/51675d17e0c1bed195000001 3 | 4 | def solution(digits): 5 | max_num = 0 6 | for i in range(len(digits)-4): 7 | number = int(digits[i:i+5]) 8 | if number > max_num: 9 | max_num = number 10 | return max_num -------------------------------------------------------------------------------- /simple_fun_79_delete_a_digit.py: -------------------------------------------------------------------------------- 1 | #simple Fun #79: Delete a Digit kata 2 | #https://www.codewars.com/kata/5894318275f2c75695000146 3 | 4 | def delete_digit(n): 5 | n = list(str(n)) 6 | max = 0 7 | for i, num in enumerate(n): 8 | res = int(''.join(n[0:i] + n[i+1:])) 9 | if res > max: 10 | max = res 11 | return max -------------------------------------------------------------------------------- /sum-digits-digital-root.py: -------------------------------------------------------------------------------- 1 | ##SUM OF DIGITS/DIGITAL ROOT KATA 2 | ##Function finds the recursive sum of numbers in number 'n' 3 | ##For example, if n = 16, ==> total = 1 + 6 4 | 5 | def digital_root(n): 6 | n = str(n) 7 | if len(n) == 1: 8 | return int(n) 9 | numbers = list(map(int, list(n))) 10 | return digital_root(sum(numbers)) -------------------------------------------------------------------------------- /ticker.py: -------------------------------------------------------------------------------- 1 | #ticker kata 2 | #https://www.codewars.com/kata/5a959662373c2e761d000183 3 | 4 | def ticker(text, width, tick): 5 | text = ' '*width + text 6 | text = list(text) 7 | output_text = '' 8 | for num in range(tick, tick+width): 9 | index = num % len(text) 10 | output_text += text[index] 11 | return output_text 12 | -------------------------------------------------------------------------------- /traffic_count.py: -------------------------------------------------------------------------------- 1 | # Traffic Count During Peak Hours kata 2 | # https://www.codewars.com/kata/586ed2dbaa0428f791000885/train/python 3 | 4 | def traffic_count(array): 5 | hours = [('4:00pm', 0), ('5:00pm', 1), ('6:00pm', 2), ('7:00pm', 3)] 6 | traffic = [(hour, max(array[hour_indx*6:(hour_indx*6)+6])) for hour, hour_indx in hours] 7 | return traffic 8 | -------------------------------------------------------------------------------- /very_even_numbers.py: -------------------------------------------------------------------------------- 1 | #very even numbers kata 2 | #https://www.codewars.com/kata/58c9322bedb4235468000019 3 | 4 | import numpy as np 5 | def is_very_even_number(n): 6 | n = np.array(list(map(int, list(str(n))))) 7 | total = np.sum(n) 8 | if len(n) <2 : 9 | return total % 2 == 0 10 | else: 11 | return is_very_even_number(total) -------------------------------------------------------------------------------- /double_sort.py: -------------------------------------------------------------------------------- 1 | #double sort kata 2 | #https://www.codewars.com/kata/57cc79ec484cf991c900018d 3 | 4 | def db_sort(arr): 5 | ints = [] 6 | strs = [] 7 | for char in arr: 8 | if type(char) == int: 9 | ints.append(char) 10 | else: 11 | strs.append(char) 12 | return sorted(ints) + sorted(strs) 13 | -------------------------------------------------------------------------------- /loose_change.py: -------------------------------------------------------------------------------- 1 | #loose change! kata 2 | #https://www.codewars.com/kata/57e1857d333d8e0f76002169 3 | 4 | money = { 5 | 'penny': 0.01, 6 | 'nickel': 0.05, 7 | 'dime': 0.1, 8 | 'quarter': 0.25, 9 | 'dollar': 1 10 | } 11 | 12 | def change_count(change): 13 | return "${:.2f}".format((sum([money[value] for value in change.split(' ')]))) -------------------------------------------------------------------------------- /simple_fun_23_square_digits_sequence.py: -------------------------------------------------------------------------------- 1 | #simple fun #23: square digits sequence kata 2 | #https://www.codewars.com/kata/5886d65e427c27afeb0000c1/solutions/python 3 | 4 | def square_digits_sequence(n): 5 | nums = [] 6 | while n not in nums: 7 | nums.append(n) 8 | n = sum(list(map(lambda x: int(x)**2, list(str(n))))) 9 | return len(nums) + 1 -------------------------------------------------------------------------------- /stones_on_the_table.py: -------------------------------------------------------------------------------- 1 | #stones on the table kata 2 | #https://www.codewars.com/kata/5f70e4cce10f9e0001c8995a 3 | 4 | import re 5 | def solution(stones): 6 | output = 0 7 | for letter in 'RGB': 8 | matches = re.findall(rf'{letter}+', stones) 9 | for match in matches: 10 | output += len(match)-1 11 | return output 12 | -------------------------------------------------------------------------------- /sum_of_array_singles.py: -------------------------------------------------------------------------------- 1 | #sum of array singles kata 2 | #https://www.codewars.com/kata/59f11118a5e129e591000134 3 | 4 | from collections import Counter 5 | def repeats(arr): 6 | counts = Counter(arr) 7 | print(counts) 8 | total = 0 9 | for key, count in counts.items(): 10 | if count == 1: 11 | total += key 12 | return total -------------------------------------------------------------------------------- /thinking_and_testing_a_times_b.py: -------------------------------------------------------------------------------- 1 | #Thinking & Testing: A * B kata 2 | #https://www.codewars.com/kata/5a90c9ecb171012b47000077 3 | 4 | def test_it(a, b): 5 | a = list(map(int, list(str(a)))) 6 | b = list(map(int, list(str(b)))) 7 | total = 0 8 | for numa in a: 9 | for numb in b: 10 | total += numa*numb 11 | return total -------------------------------------------------------------------------------- /dashatize_it.py: -------------------------------------------------------------------------------- 1 | #dashatize it kata 2 | #https://www.codewars.com/kata/58223370aef9fc03fd000071 3 | 4 | def dashatize(num): 5 | output = '' 6 | for num in str(num): 7 | if num.isnumeric() and int(num) % 2 !=0: 8 | output += '-' + num + '-' 9 | else: 10 | output += num 11 | return output.replace('--', '-').strip('-') -------------------------------------------------------------------------------- /find-screen-size.py: -------------------------------------------------------------------------------- 1 | ###Find Screen Size - codewars kata 2 | ###https://www.codewars.com/kata/5bbd279c8f8bbd5ee500000f 3 | 4 | def find_screen_height(width, ratio): 5 | '''Finds and returns screen height based on AR and 6 | width''' 7 | lhs, rhs = list(map(int, ratio.split(':'))) 8 | height = int(width * rhs/lhs) 9 | return str(width) + 'x' + str(height) -------------------------------------------------------------------------------- /greatest_common_factor_of_an_array.py: -------------------------------------------------------------------------------- 1 | #Greatest Common Factor of an Array kata 2 | #https://www.codewars.com/kata/5849169a6512c5964000016e 3 | 4 | def greatest_common_factor(seq): 5 | seq = sorted(seq) 6 | for num in list((range(1, seq[0]+1)))[::-1]: 7 | divisible = list(map(lambda x: x%num == 0, seq)) 8 | if all(divisible): 9 | return num -------------------------------------------------------------------------------- /prime-number.py: -------------------------------------------------------------------------------- 1 | def is_prime(num): 2 | '''Finds whether a number is prime''' 3 | if num == 0 or num == 1 or num < 0: 4 | return False 5 | else: 6 | for i in range(2, num+1): 7 | if (num % i == 0 and num != i): 8 | return False 9 | elif (num % i == 0) and (num == i): 10 | return True -------------------------------------------------------------------------------- /conver_pascalcase_into_snakecase.py: -------------------------------------------------------------------------------- 1 | #Convert PascalCase into snake_case kata 2 | #https://www.codewars.com/kata/529b418d533b76924600085d 3 | 4 | def char_replacer(chr): 5 | if chr.isupper(): 6 | return '_' + chr.lower() 7 | return chr 8 | 9 | def to_underscore(string): 10 | return ''.join(list(map(char_replacer, str(string)))).strip('_') 11 | -------------------------------------------------------------------------------- /integrate.py: -------------------------------------------------------------------------------- 1 | def integrate(coefficient, exponent): 2 | '''Finds the coefficient and exponent of the integral of the input expression''' 3 | new_exponent = exponent + 1 4 | new_coeff = coefficient/(new_exponent) 5 | if new_coeff.is_integer(): 6 | return str(int(new_coeff)) + 'x^' + str(new_exponent) 7 | return str(new_coeff) + 'x^' + str(new_exponent) -------------------------------------------------------------------------------- /person_class_bug.py: -------------------------------------------------------------------------------- 1 | # Person Class Bug kata 2 | # https://www.codewars.com/kata/513f887e484edf3eb3000001/train/python 3 | 4 | class Person(): 5 | 6 | def __init__(self, first_name, last_name, age): 7 | self.first_name = first_name 8 | self.last_name = last_name 9 | self.age = age 10 | self.full_name = f'{first_name} {last_name}' 11 | -------------------------------------------------------------------------------- /row-weights.py: -------------------------------------------------------------------------------- 1 | ###Row Weights - codewars kata 2 | ###https://www.codewars.com/kata/5abd66a5ccfd1130b30000a9/python 3 | 4 | def row_weights(array): 5 | '''Return the weights each team, according to problem challenge''' 6 | team1 = array[0::2] 7 | if len(array) == 1: 8 | team2 = [0] 9 | team2 = array[1::2] 10 | return (sum(team1), sum(team2)) -------------------------------------------------------------------------------- /ahh-grabscrab.py: -------------------------------------------------------------------------------- 1 | ###Ahh, grabscrab! - codewars kata 2 | ###https://www.codewars.com/kata/52b305bec65ea40fe90007a7 3 | 4 | def grabscrab(word, possible_words): 5 | '''Returns all the words in possible words that the pirate 6 | might have meant, based upon word''' 7 | word_sorted = sorted(word) 8 | return [word for word in possible_words if sorted(word) == word_sorted] -------------------------------------------------------------------------------- /odder-than-the-rest.py: -------------------------------------------------------------------------------- 1 | ###Odder Than the Rest - codewars kata 2 | ###https://www.codewars.com/kata/5983cba828b2f1fd55000114 3 | 4 | def odd_one(arr): 5 | '''Returns the index of the sole odd value in arr''' 6 | odds = list(map(lambda x: (x % 2 == 0 and x != 0), arr)) 7 | print(odds) 8 | if False in odds: 9 | return odds.index(False) 10 | return -1 -------------------------------------------------------------------------------- /redacted.py: -------------------------------------------------------------------------------- 1 | #Redacted! kata 2 | #https://www.codewars.com/kata/5b662d286d0db722bd000013 3 | 4 | def redacted(doc1, doc2): 5 | if len(doc1) != len(doc2): 6 | return False 7 | for i, char in enumerate(doc1): 8 | if (char != doc2[i] and char != 'X') or (char == 'X' and doc2[i] == '\n'): 9 | return False 10 | return True 11 | -------------------------------------------------------------------------------- /difference-of-two.py: -------------------------------------------------------------------------------- 1 | ###Difference of Two - codewars kata 2 | ###https://www.codewars.com/kata/5340298112fa30e786000688 3 | 4 | def twos_difference(lst): 5 | '''Returns pairs of integers in list that have a difference of two''' 6 | output = [] 7 | for num in sorted(lst): 8 | if num + 2 in lst: 9 | output.append((num, num+2)) 10 | return output -------------------------------------------------------------------------------- /disarium_number_special_numbers_series_3.py: -------------------------------------------------------------------------------- 1 | #disarium number (special numbers series #3) kata 2 | #https://www.codewars.com/kata/5a53a17bfd56cb9c14000003 3 | 4 | def disarium_number(number): 5 | number_string = str(number) 6 | total = 0 7 | for i, num in enumerate(number_string): 8 | total += int(num)**(i+1) 9 | return 'Disarium !!' if total == number else 'Not !!' -------------------------------------------------------------------------------- /english_beggars.py: -------------------------------------------------------------------------------- 1 | #english beggars kata 2 | #https://www.codewars.com/kata/59590976838112bfea0000fa 3 | 4 | def beggars(values, n): 5 | output = [] 6 | for i in range(n): 7 | indeces = list(range(i,len(values), n)) 8 | total = 0 9 | for index in indeces: 10 | total += values[index] 11 | output.append(total) 12 | return output -------------------------------------------------------------------------------- /lambdas_as_a_mechanism_for_open_and_closed.py: -------------------------------------------------------------------------------- 1 | # Lambda as a Mechanism for Open and Closed kata 2 | # https://www.codewars.com/kata/53574972e727385ad10002ca/train/python 3 | 4 | spoken = lambda greeting: greeting.title() + '.' 5 | shouted = lambda greeting: greeting.upper() + '!' 6 | whispered = lambda greeting: greeting.lower() + '.' 7 | 8 | greet = lambda style, msg: style(msg) 9 | -------------------------------------------------------------------------------- /number-of-trailing-zeros.py: -------------------------------------------------------------------------------- 1 | ###Codewars Kata - Number of trailing zeros of a factorial 2 | 3 | def zeros(n): 4 | '''Zeros calculates the number of trailing zeroes by looking at the number of prime 5 | factor fives''' 6 | 7 | total = 0 8 | i = 1 9 | while (n > 0) and (n/(5**i) >= 1): 10 | total += int(n/(5**i)) 11 | i += 1 12 | return total -------------------------------------------------------------------------------- /sum_of_roots_of_quadratic.py: -------------------------------------------------------------------------------- 1 | # Find the sum of roots of a quadratic equation 2 | # https://www.codewars.com/kata/57d448c6ba30875437000138 3 | 4 | import math 5 | def roots(a,b,c): 6 | try: 7 | one = (-b + math.sqrt(b**2 - 4*a*c))/(2*a) 8 | two = (-b - math.sqrt(b**2 - 4*a*c))/(2*a) 9 | return round(one + two, 2) 10 | except: 11 | None 12 | -------------------------------------------------------------------------------- /points.py: -------------------------------------------------------------------------------- 1 | def points(games): 2 | '''Count the number of points achieved in a season based on individual game scores''' 3 | points = 0 4 | for game in games: 5 | result = int(game[0]) - int(game[2]) 6 | if result > 0: 7 | points = points + 3 8 | elif result == 0: 9 | points = points + 1 10 | 11 | return points -------------------------------------------------------------------------------- /remove_consecutive_duplicate_words.py: -------------------------------------------------------------------------------- 1 | #remove consecutive duplicate words kata 2 | #https://www.codewars.com/kata/5b39e91ee7a2c103300018b3 3 | 4 | def remove_consecutive_duplicates(s): 5 | s = s.split(' ') 6 | output = [0] 7 | for word in s: 8 | print(word) 9 | if word != output[-1]: 10 | output.append(word) 11 | return ' '.join(output[1:]) -------------------------------------------------------------------------------- /simple_fun_110_array_operations.py: -------------------------------------------------------------------------------- 1 | # Simple Fun #110: Array Operations 2 | # https://www.codewars.com/kata/589aca25fef1a81a10000057/train/python/652d7e547e92f3209537cb05 3 | 4 | def array_operations(a, k): 5 | k = 1 if k % 2 else 2 6 | while k > 0: 7 | maximum = max(a) 8 | a = list(map(lambda elem: maximum - elem, a)) 9 | k -=1 10 | return a 11 | -------------------------------------------------------------------------------- /simple_fun_247_to_and_from.py: -------------------------------------------------------------------------------- 1 | ## simple fun #247: to and from kata 2 | ## https://www.codewars.com/kata/590c3173cd3b99c467000a26 3 | 4 | def to_and_from(a, b, t): 5 | distance = abs(a-b) 6 | modifier = 1 7 | if a-b > 0: 8 | modifier = -1 9 | if (t // distance)%2 == 0: 10 | return a + (t % distance*modifier) 11 | return b - (t % distance * modifier) -------------------------------------------------------------------------------- /unique_string_characters.py: -------------------------------------------------------------------------------- 1 | #unique string characters kata 2 | #https://www.codewars.com/kata/5a262cfb8f27f217f700000b 3 | 4 | def solve(a,b): 5 | output = '' 6 | for letter in a: 7 | if letter not in b: 8 | output += letter 9 | for letter in b: 10 | if letter not in a: 11 | output += letter 12 | 13 | return output -------------------------------------------------------------------------------- /valid_parantheses.py: -------------------------------------------------------------------------------- 1 | #Valid parantheses kata 2 | #https://www.codewars.com/kata/52774a314c2333f0a7000688 3 | 4 | def valid_parentheses(string): 5 | count = 0 6 | for char in string: 7 | if char == '(': 8 | count += 1 9 | elif char == ')': 10 | count -= 1 11 | if count < 0: 12 | return False 13 | return count == 0 -------------------------------------------------------------------------------- /your_order_please.py: -------------------------------------------------------------------------------- 1 | #Your order, please kata 2 | #https://www.codewars.com/kata/55c45be3b2079eccff00010f 3 | 4 | def order(sentence): 5 | words = sentence.split(' ') 6 | output = ['' for word in words] 7 | for word in words: 8 | for char in word: 9 | if char in '123456789': 10 | output[int(char)-1] = word 11 | return ' '.join(output) -------------------------------------------------------------------------------- /count-the-digit.py: -------------------------------------------------------------------------------- 1 | def nb_dig(n, d): 2 | '''Takes an integer n, calculates the square of each number from one to n, and returns 3 | how many times d appears''' 4 | 5 | values_list = list(range(0, n+1)) 6 | list_squared = list(map(lambda x: str(x**2), values_list)) 7 | str_list_squared = ''.join(list_squared) 8 | print(str(d)) 9 | return str_list_squared.count(str(d)) -------------------------------------------------------------------------------- /find-all-occurrences.py: -------------------------------------------------------------------------------- 1 | ###Find All Occurrences of an Element in an array - codewars kata 2 | ###https://www.codewars.com/kata/59a9919107157a45220000e1 3 | 4 | def find_all(array, n): 5 | '''Returns the number of times that n appears in array''' 6 | indeces = [] 7 | for i, num in enumerate(array): 8 | if num == n: 9 | indeces.append(i) 10 | return indeces -------------------------------------------------------------------------------- /generic-algorithm-series#3.py: -------------------------------------------------------------------------------- 1 | ###Generic Algorithm Series - #3 Crossover - codewars kata 2 | ###https://www.codewars.com/kata/567d71b93f8a50f461000019/solutions/python 3 | 4 | def crossover(chromosome1, chromosome2, index): 5 | '''Simulates a genetic crossover of chromosomes 1&2 at point index''' 6 | return [chromosome1[:index] + chromosome2[index:], chromosome2[:index] + chromosome1[index:]] -------------------------------------------------------------------------------- /genetic-algorithm-series#3.py: -------------------------------------------------------------------------------- 1 | ###Genetic Algorithm Series - #3 Crossover - codewars kata 2 | ###https://www.codewars.com/kata/567d71b93f8a50f461000019/solutions/python 3 | 4 | def crossover(chromosome1, chromosome2, index): 5 | '''Simulates a genetic crossover of chromosomes 1&2 at point index''' 6 | return [chromosome1[:index] + chromosome2[index:], chromosome2[:index] + chromosome1[index:]] -------------------------------------------------------------------------------- /maximum_subarray_sum.py: -------------------------------------------------------------------------------- 1 | #maximum subarray sum kata 2 | #https://www.codewars.com/kata/54521e9ec8e60bc4de000d6c 3 | 4 | def max_sequence(arr): 5 | mx = 0 6 | substr =[] 7 | for i in range(0, len(arr)): 8 | for j in range(0, len(arr) + 1 - i): 9 | total = sum(arr[j:j+i+1]) 10 | if total > mx: 11 | mx = total 12 | return mx 13 | -------------------------------------------------------------------------------- /small-enough.py: -------------------------------------------------------------------------------- 1 | ###No Loops 1 - Small Enough? - codewars kata 2 | ###https://www.codewars.com/kata/57cc4853fa9fc57a6a0002c2 3 | 4 | def small_enough(a, limit): 5 | '''Returns True if every element in a is smaller than 6 | limit''' 7 | return False if False in list(map(lambda elem: elem <= limit, a)) else True 8 | 9 | def small_enough(a, limit): 10 | return max(a) <= limit -------------------------------------------------------------------------------- /suitcase.py: -------------------------------------------------------------------------------- 1 | def fit_in(a,b,m,n): 2 | '''See if two squares fit in a suitcase based on dimensions''' 3 | print(a,b,m,n) 4 | check_1 = (a + b) <= m 5 | check_2 = (a+b) <=n 6 | check_3 = (a <= m) and (a <= n) and (b <= m) and (b <= n) 7 | 8 | if (check_1 == True or check_2 == True) and (check_3 == True): 9 | return True 10 | 11 | return False -------------------------------------------------------------------------------- /sum_square_even_root_odd.py: -------------------------------------------------------------------------------- 1 | #sum - square even, root odd kata 2 | #https://www.codewars.com/kata/5a4b16435f08299c7000274f 3 | 4 | def sum_square_even_root_odd(nums): 5 | output = [] 6 | for num in nums: 7 | if num % 2 == 0: 8 | total = num**2 9 | else: 10 | total = num**0.5 11 | output.append(total) 12 | return round(sum(output),2) -------------------------------------------------------------------------------- /evening_up_a_workload.py: -------------------------------------------------------------------------------- 1 | #evening up a workload kata 2 | #https://www.codewars.com/kata/56431c04ed1454a35d00003b 3 | 4 | def split_workload(workload): 5 | if workload == []: 6 | return (None, None) 7 | difference = [abs(sum(workload[i:])-sum(workload[0:i])) for i in range(0,len(workload))] 8 | location = difference.index(min(difference)) 9 | return (location, difference[location]) -------------------------------------------------------------------------------- /hofstadter_q.py: -------------------------------------------------------------------------------- 1 | # Hofstadter Q 2 | # https://www.codewars.com/kata/5897cdc26551af891c000124/train/python 3 | 4 | from functools import cache 5 | import sys 6 | 7 | sys.setrecursionlimit(10000) 8 | 9 | @cache 10 | def hofstadter_Q(n): 11 | if n in [1,2]: 12 | return 1 13 | else: 14 | return hofstadter_Q(n - hofstadter_Q(n-1)) + hofstadter_Q(n - hofstadter_Q(n-2)) 15 | -------------------------------------------------------------------------------- /jumping_number_special_number_series_4.py: -------------------------------------------------------------------------------- 1 | #jumping number (special numbers series #4) kata 2 | #https://www.codewars.com/kata/5a54e796b3bfa8932c0000ed 3 | 4 | def jumping_number(number): 5 | number = list(str(number)) 6 | for i in range(0, len(number)-1): 7 | if abs(int(number[i+1])-int(number[i])) != 1: 8 | return 'Not!!' 9 | return 'Jumping!!' 10 | -------------------------------------------------------------------------------- /number_of_measurements_to_spot_the_counterfeit_coin.py: -------------------------------------------------------------------------------- 1 | #number of measurements to spot the counterfeit coin kata 2 | #https://www.codewars.com/kata/59530d2401d6039f8600001f 3 | 4 | import numpy as np 5 | def how_many_measurements(n): 6 | if n <= 3: 7 | if n == 1: 8 | return 0 9 | return 1 10 | 11 | num = (np.log((n*3))/np.log(3)) 12 | return int(num) -------------------------------------------------------------------------------- /pete-the-baker.py: -------------------------------------------------------------------------------- 1 | def cakes(recipe, available): 2 | '''Function returns the maximum number of cakes that pete can bake based on the recipe and ingredients''' 3 | if len(recipe) > len(available): 4 | return 0 5 | else: 6 | ratio = [] 7 | for ingredient in recipe: 8 | ratio.append(int(available[ingredient]/recipe[ingredient])) 9 | return min(ratio) -------------------------------------------------------------------------------- /alphabet_symmetry.py: -------------------------------------------------------------------------------- 1 | #Alphabet Symmetry kata 2 | #https://www.codewars.com/kata/59d9ff9f7905dfeed50000b0 3 | 4 | def solve(arr): 5 | output = [] 6 | for str in arr: 7 | str = list(map(lambda x: ord(x.lower())-96, list(str))) 8 | str = list(map(lambda x: x[0] == x[1], zip(str, range(1,len(str)+1)))) 9 | output.append(str.count(True)) 10 | return output 11 | -------------------------------------------------------------------------------- /calculate_number_of_inversions_in_array.py: -------------------------------------------------------------------------------- 1 | #calculate number of inversions in array kata 2 | #https://www.codewars.com/kata/537529f42993de0e0b00181f 3 | 4 | import numpy as np 5 | def count_inversions(array): 6 | array = np.array(array) 7 | total = 0 8 | for i in range(len(array)): 9 | num = array[i] 10 | total += np.sum(array[i+1:] < num) 11 | return total 12 | -------------------------------------------------------------------------------- /fill-hdd.py: -------------------------------------------------------------------------------- 1 | ###Fill the HDD - codewars kata 2 | ###https://www.codewars.com/kata/5d49c93d089c6e000ff8428c 3 | 4 | def save(sizes, hd): 5 | '''Returns number of files that can be copied to HDD 6 | based on file and HDD sizes''' 7 | total = 0 8 | for i in range(len(sizes)): 9 | total += sizes[i] 10 | if total > hd: 11 | return i 12 | return len(sizes) -------------------------------------------------------------------------------- /string_letter_counting.py: -------------------------------------------------------------------------------- 1 | #String letter counting kata 2 | #https://www.codewars.com/kata/59e19a747905df23cb000024 3 | 4 | def string_letter_count(s): 5 | output = '' 6 | for letter in 'abcdefghijklmnopqrstuvwxyz': 7 | total = s.count(letter.upper()) + s.count(letter.lower()) 8 | if total > 0: 9 | output += str(total)+ letter 10 | return output 11 | -------------------------------------------------------------------------------- /validate_credit_card_number.py: -------------------------------------------------------------------------------- 1 | #Validate Credit Card Number kata 2 | #https://www.codewars.com/kata/5418a1dd6d8216e18a0012b2 3 | 4 | def validate(n): 5 | n = list(map(int, str(n))) 6 | start_num = [0,1][len(n) % 2] 7 | n = [x*2 if (i+start_num)%2 == 0 else x for i, x in enumerate(n)] 8 | n = [x-9 if x > 9 else x for i, x in enumerate(n)] 9 | return sum(n) % 10 == 0 10 | -------------------------------------------------------------------------------- /get_planet_name_by_ID.py: -------------------------------------------------------------------------------- 1 | #Get planet name by ID kata 2 | #https://www.codewars.com/kata/515e188a311df01cba000003 3 | 4 | def get_planet_name(id): 5 | return { 6 | 1: "Mercury", 7 | 2: "Venus", 8 | 3: "Earth", 9 | 4: "Mars", 10 | 5: "Jupiter", 11 | 6: "Saturn", 12 | 7: "Uranus" , 13 | 8: "Neptune", 14 | }[id] 15 | -------------------------------------------------------------------------------- /sum_of_odd_numbers.py: -------------------------------------------------------------------------------- 1 | #sum of odd numbers kata 2 | #https://www.codewars.com/kata/55fd2d567d94ac3bc9000064 3 | 4 | def row_sum_odd_numbers(n): 5 | powers = list(range(2, n)) 6 | start_point = 1 7 | if n ==1: 8 | return 1 9 | for power in powers: 10 | start_point += 2*power 11 | total = list(range(start_point + 2, start_point + ((n+1)*2), 2)) 12 | return sum(total) -------------------------------------------------------------------------------- /sums_of_parts.py: -------------------------------------------------------------------------------- 1 | #sums of parts kata 2 | #https://www.codewars.com/kata/5ce399e0047a45001c853c2b 3 | 4 | import numpy as np 5 | def parts_sums(ls): 6 | reduction = np.cumsum(ls) 7 | if reduction.size == 0: 8 | return [0] 9 | reduction = np.insert(reduction, 0, 0, axis=0) 10 | total = np.ones(len(ls)+1)*reduction[-1] 11 | final = (total - reduction) 12 | return final.tolist() -------------------------------------------------------------------------------- /consecutive_differences.py: -------------------------------------------------------------------------------- 1 | #consecutive differences kata 2 | #https://www.codewars.com/kata/5ff22b6e833a9300180bb953 3 | 4 | def differences(lst): 5 | output = [0] 6 | while len(lst) >= 1: 7 | if len(lst) != 1: 8 | lst = list(map(lambda x: abs(x[0] - x[1]), list(zip(lst[1:], lst[0:-1])))) 9 | else: 10 | output = lst 11 | break 12 | return output[0] -------------------------------------------------------------------------------- /count_the_divisors_of_a_number.py: -------------------------------------------------------------------------------- 1 | #count the divisors of a number kata 2 | #https://www.codewars.com/kata/542c0f198e077084c0000c2e 3 | 4 | import math 5 | def divisors(n): 6 | divisor_list = set() 7 | i = 1 8 | while i < math.sqrt(n) + 1: 9 | if n % i == 0: 10 | divisor_list.add(i) 11 | divisor_list.add(n/i) 12 | i += 1 13 | return len(divisor_list) -------------------------------------------------------------------------------- /even-odd-pattern#1.py: -------------------------------------------------------------------------------- 1 | ###Even Odd Pattern #1 2 | ###https://www.codewars.com/kata/559e708e72d342b0c900007b 3 | 4 | def even_odd(arr): 5 | '''Returns a total based on a formula that I had to work out''' 6 | total = 0 7 | for i, num in enumerate(arr): 8 | print(i%2) 9 | if i % 2 != 0: 10 | total *= num 11 | else: 12 | total += num 13 | return total -------------------------------------------------------------------------------- /stray-number.py: -------------------------------------------------------------------------------- 1 | def stray(arr): 2 | '''Finds the stray number in an array''' 3 | first_num = arr[0] 4 | second_num = arr[1] 5 | if first_num != second_num: 6 | third_num = arr[2] 7 | if third_num == second_num: 8 | return first_num 9 | else: 10 | return second_num 11 | for num in arr: 12 | if num != first_num: 13 | return num -------------------------------------------------------------------------------- /counting_duplicates.py: -------------------------------------------------------------------------------- 1 | #Counting duplicates kata 2 | #https://www.codewars.com/kata/54bf1c2cd5b56cc47f0007a1 3 | 4 | from collections import Counter 5 | 6 | def duplicate_count(text): 7 | text = list(map(lambda x: x.lower(), text)) 8 | result = Counter(text) 9 | total = 0 10 | for key, value in result.items(): 11 | if value > 1: 12 | total += 1 13 | return total 14 | -------------------------------------------------------------------------------- /find_the_unique_number.py: -------------------------------------------------------------------------------- 1 | #find the unique number kata 2 | #https://www.codewars.com/kata/585d7d5adb20cf33cb000235 3 | 4 | def find_uniq(arr): 5 | unique = set(arr) 6 | for num in unique: 7 | new_arr = arr.copy() 8 | index = new_arr.index(num) 9 | new_arr.pop(index) 10 | if num in new_arr: 11 | continue 12 | else: 13 | return num 14 | -------------------------------------------------------------------------------- /noisy_cell_counts.py: -------------------------------------------------------------------------------- 1 | # Noisy Cell Counts kata 2 | # https://www.codewars.com/kata/63ebadc7879f2500315fa07e/train/python 3 | 4 | def cleaned_counts(data): 5 | adjusted_data = [data[0]] 6 | for point in data[1:]: 7 | if point < adjusted_data[-1]: 8 | adjusted_data.append(adjusted_data[-1]) 9 | else: 10 | adjusted_data.append(point) 11 | return adjusted_data 12 | -------------------------------------------------------------------------------- /adjacent_repeated_words_in_a_string.py: -------------------------------------------------------------------------------- 1 | #adjacent repeated words in a string kata 2 | #https://www.codewars.com/kata/5245a9138ca049e9a10007b8 3 | 4 | from itertools import groupby 5 | def count_adjacent_pairs(st): 6 | lst = list(map(lambda x: x.lower(), st.split(" "))) 7 | total = 0 8 | for _, g in groupby(lst): 9 | if len([group for group in g]) > 1: 10 | total +=1 11 | return total -------------------------------------------------------------------------------- /count_IP_addresses.py: -------------------------------------------------------------------------------- 1 | #Count IP Addresses kata 2 | #https://www.codewars.com/kata/526989a41034285187000de4 3 | 4 | def ips_between(start, end): 5 | start = list(map(int, start.split('.'))) 6 | end = list(map(int, end.split('.'))) 7 | difference = list(map(lambda x: x[1] - x[0], zip(start,end))) 8 | totals = list(map(lambda x: x[1] * x[0], zip(difference,[256**3, 256**2,256, 1]))) 9 | return sum(totals) -------------------------------------------------------------------------------- /find_the_index_of_the_second_occurance.py: -------------------------------------------------------------------------------- 1 | # Find the index of the second occurance of a letter in a string kata 2 | # https://www.codewars.com/kata/63f96036b15a210058300ca9/train/python 3 | 4 | def second_symbol(s, symbol, count=0): 5 | for index, char in enumerate(s): 6 | if char == symbol: 7 | count += 1 8 | if count == 2: 9 | return index 10 | return -1 11 | -------------------------------------------------------------------------------- /hells_kitchen.py: -------------------------------------------------------------------------------- 1 | #Hells Kitchen kata 2 | #https://www.codewars.com/kata/57d1f36705c186d018000813 3 | 4 | def gordon(a): 5 | a = ' '.join(list(map(lambda x: x.upper()+'!!!!', a.split(' ')))) 6 | for letter in 'AEIOU': 7 | if letter == 'A': 8 | replacement = '@' 9 | else: 10 | replacement = '*' 11 | a = a.replace(letter, replacement) 12 | return a 13 | 14 | -------------------------------------------------------------------------------- /remove_duplicate_words.py: -------------------------------------------------------------------------------- 1 | #remove duplicate words kata 2 | #https://www.codewars.com/kata/5b39e3772ae7545f650000fc 3 | 4 | def remove_duplicate_words(s): 5 | s = s.split(' ') 6 | words_used = set() 7 | output = [] 8 | for word in s: 9 | print(word) 10 | if word not in words_used: 11 | output.append(word) 12 | words_used.add(word) 13 | return ' '.join(output) -------------------------------------------------------------------------------- /status_arrays.py: -------------------------------------------------------------------------------- 1 | #Status arrays kata 2 | #https://www.codewars.com/kata/601c18c1d92283000ec86f2b 3 | 4 | def status(nums): 5 | nums_with_position = [] 6 | for i, num in enumerate(nums): 7 | previous_smaller = len(list(filter(lambda x: x < num, nums))) 8 | nums_with_position.append([previous_smaller + i + 1, i, num]) 9 | return list(map(lambda x: x[2], sorted(nums_with_position, key=lambda x: (x[0])))) -------------------------------------------------------------------------------- /magnet-particules.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from numpy import inf 3 | def doubles(maxk, maxn): 4 | '''Calculates the force of a box of magnets. See Magnet particules in boxes 5 | for more details''' 6 | total_force = 0 7 | for k in range(1, maxk+1): 8 | total = (1/(k*np.arange(2, maxn+2)**(2*k))) 9 | total[total == inf] = 0 10 | total_force += np.sum(total) 11 | return total_force -------------------------------------------------------------------------------- /the_@_operator.py: -------------------------------------------------------------------------------- 1 | # The @ Operator kata 2 | # https://www.codewars.com/kata/631f0c3a0b9cb0de6ded0529/train/python 3 | def evaluate(equation): 4 | nums = list(map(int, equation.split(' @ '))) 5 | total = nums[0] 6 | for num in nums[1:]: 7 | try: 8 | total = ((total + num) + (total - num) + (total * num) + (total // num)) 9 | except: 10 | return None 11 | return total 12 | -------------------------------------------------------------------------------- /cryptanalysis_word_patterns.py: -------------------------------------------------------------------------------- 1 | #crypanalysis word patterns kata 2 | #https://www.codewars.com/kata/5f3142b3a28d9b002ef58f5e 3 | 4 | def word_pattern(word): 5 | output = '' 6 | conversion = [] 7 | word = word.lower() 8 | for letter in word: 9 | if letter not in conversion: 10 | conversion.append(letter) 11 | output += str(conversion.index(letter)) +'.' 12 | return output[:-1] -------------------------------------------------------------------------------- /going-to-the-cinema.py: -------------------------------------------------------------------------------- 1 | ###Going to the Cinema - codewars kata 2 | ###https://www.codewars.com/kata/562f91ff6a8b77dfe900006e 3 | 4 | import math 5 | def movie(card, ticket, perc): 6 | total_card = card 7 | total_tickets = 0 8 | i = 1 9 | while math.ceil(total_card) >= total_tickets: 10 | total_card += ticket *(perc**i) 11 | total_tickets += ticket 12 | i += 1 13 | return i - 1 14 | -------------------------------------------------------------------------------- /regexp-eight-bit-unsigned.py: -------------------------------------------------------------------------------- 1 | ###Regexp Basics - Codewars kata 2 | ###https://www.codewars.com/users/ellismckenzielee/completed_solutions 3 | 4 | def eight_bit_number(n): 5 | '''Returns True if n is an 8-bit unsigned number, else False''' 6 | if not n.isalnum(): 7 | return False 8 | n_int = int(n) 9 | return True if (len(str(n_int)) == len(n) and n_int > -1 and n_int < 256) else False 10 | 11 | -------------------------------------------------------------------------------- /ultimate-array-reverser.py: -------------------------------------------------------------------------------- 1 | ##ULTIMATE ARRAY REVERSER KATA 2 | ##Reverse an array in such a way, that their string stay the same lengths 3 | 4 | def reverse(a): 5 | start_point = 0 6 | output = [] 7 | a_string = ''.join(a)[::-1] 8 | for item in a: 9 | end_point = start_point + len(item) 10 | output.append(a_string[start_point:end_point]) 11 | start_point = end_point 12 | return output -------------------------------------------------------------------------------- /crack_the_pin.py: -------------------------------------------------------------------------------- 1 | #crack the pin kata 2 | #https://www.codewars.com/kata/5efae11e2d12df00331f91a6 3 | 4 | import hashlib, itertools 5 | def crack(hash): 6 | result = hashlib.md5('00078'.encode()) 7 | for pin in itertools.product(range(10), repeat=5): 8 | pin = ''.join(list(map(str, pin))) 9 | result = hashlib.md5(pin.encode()).hexdigest() 10 | 11 | if result == hash: 12 | return pin 13 | -------------------------------------------------------------------------------- /exes-and-ohs.py: -------------------------------------------------------------------------------- 1 | def xo(s): 2 | '''Checks if a string has the same amount of x and o's''' 3 | x_count = 0 4 | o_count = 0 5 | for i in s: 6 | if (i == 'x' or i == 'X'): 7 | x_count+=1 8 | elif (i == 'o' or i == 'O'): 9 | o_count+=1 10 | 11 | if ((x_count == o_count) or ((x_count and o_count) == 0)): 12 | return True 13 | else: 14 | return False -------------------------------------------------------------------------------- /half-life.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime, timedelta 2 | def half_life(person1, person2): 3 | year, month, day = list(map(int, person1.split('-'))) 4 | person1 = datetime(year,month,day) 5 | 6 | year, month, day = list(map(int, person2.split('-'))) 7 | person2 = datetime(year,month,day) 8 | 9 | ans = (max(person1, person2) + timedelta(days=abs(person2-person1).days)) 10 | return ans.strftime('%Y-%m-%d') -------------------------------------------------------------------------------- /next-happy-year.py: -------------------------------------------------------------------------------- 1 | ###See You Next Happy Year - codewars kata 2 | ###https://www.codewars.com/kata/5ae7e3f068e6445bc8000046 3 | 4 | def next_happy_year(year): 5 | '''Returns the next year after 'year' in which each digit is unique''' 6 | happy_year = False 7 | while happy_year == False: 8 | year += 1 9 | if len(set(list(str(year)))) == 4: 10 | happy_year = True 11 | 12 | return year -------------------------------------------------------------------------------- /break-camelcase.py: -------------------------------------------------------------------------------- 1 | ###Solution codewars kata 2 | ###Takes a string as input and replaces any camelcase letters with a space and lowercase letter 3 | 4 | def solution(s): 5 | '''Solution returns the formatted string''' 6 | return ''.join(list(map(upper, list(s)))) 7 | 8 | def upper(letter): 9 | '''Converts capital letters to a space and the lower case letter''' 10 | return ' ' + letter if letter.isupper() else letter -------------------------------------------------------------------------------- /fizzbuzz_backwards.py: -------------------------------------------------------------------------------- 1 | #Fizzbuzz Backwards kata 2 | #https://www.codewars.com/kata/59ad13d5589d2a1d84000020 3 | 4 | def reverse_fizz_buzz(array): 5 | if 'Fizz' in array: 6 | fizz = array.index('Fizz') 7 | else: 8 | fizz = array.index('FizzBuzz') 9 | if 'Buzz' in array: 10 | buzz = array.index('Buzz') 11 | else: 12 | buzz = array.index('FizzBuzz') 13 | 14 | return (fizz + 1, buzz +1 ) -------------------------------------------------------------------------------- /maximum-length-difference.py: -------------------------------------------------------------------------------- 1 | def mxdiflg(a1, a2): 2 | '''Find the largest difference between the length of two strings from a1 and a2''' 3 | if a1 == [] or a2 == []: 4 | return -1 5 | x = len(min(a1, key=len)) 6 | y = len(max(a2, key=len)) 7 | result1 = abs(x-y) 8 | x = len(max(a1, key=len)) 9 | y = len(min(a2, key=len)) 10 | result2 = abs(y-x) 11 | return result1 if result1 >= result2 else result2 -------------------------------------------------------------------------------- /simple_letter_removal.py: -------------------------------------------------------------------------------- 1 | #simple letter removal kata 2 | #https://www.codewars.com/kata/5b728f801db5cec7320000c7 3 | 4 | def solve(st,k): 5 | num, removed = 0, 0 6 | while removed < k and st: 7 | if chr(num+97) in st: 8 | indx = st.index(chr(num+97)) 9 | st = st[0:indx] + st[indx+1:] 10 | removed += 1 11 | else: 12 | num += 1 13 | return st 14 | 15 | -------------------------------------------------------------------------------- /word_values.py: -------------------------------------------------------------------------------- 1 | #word values kata 2 | #https://www.codewars.com/kata/598d91785d4ce3ec4f000018 3 | 4 | def name_value(my_list): 5 | letters = 'abcdefghijklmnopqrstuvwxyz' 6 | output = [] 7 | for i, chars in enumerate(my_list): 8 | total = 0 9 | for char in chars: 10 | if char in letters: 11 | total += letters.index(char) + 1 12 | output.append(total*(i+1)) 13 | return output -------------------------------------------------------------------------------- /are_we_alternate.py: -------------------------------------------------------------------------------- 1 | # are we alternate? kata 2 | # https://www.codewars.com/kata/59325dc15dbb44b2440000af 3 | 4 | def is_alt(s): 5 | vowels = "aeiou" 6 | previous_letter_is_vowel = not s[0] in vowels 7 | for letter in s: 8 | is_vowel = letter in vowels 9 | if is_vowel == previous_letter_is_vowel: 10 | return False 11 | previous_letter_is_vowel = is_vowel 12 | return True 13 | 14 | -------------------------------------------------------------------------------- /exercise_in_summing.py: -------------------------------------------------------------------------------- 1 | #exercise in summing kata 2 | #https://www.codewars.com/kata/52cd0d600707d0abcd0003eb 3 | 4 | def minimum_sum(values, n): 5 | '''sum the n smallest integers in the array values (not necessarily ordered)''' 6 | 7 | return sum(sorted(values)[:n]) 8 | 9 | def maximum_sum(values, n): 10 | '''sum the n largest integers in the array values (not necessarily ordered)''' 11 | return sum(sorted(values, reverse=True)[:n]) -------------------------------------------------------------------------------- /longest_alphabetical_substring.py: -------------------------------------------------------------------------------- 1 | #longest alphabetic substring kata 2 | #https://www.codewars.com/kata/5a7f58c00025e917f30000f1 3 | 4 | import re 5 | def longest(s): 6 | matches = re.findall('a*b*c*d*e*f*g*h*i*j*k*l*m*n*o*p*q*r*s*t*u*v*w*x*y*z*', s) 7 | current_longest = matches[0] 8 | for match in matches: 9 | if len(match) > len(current_longest): 10 | current_longest = match 11 | return current_longest -------------------------------------------------------------------------------- /lottery_machine.py: -------------------------------------------------------------------------------- 1 | #lottery machine kata 2 | #https://www.codewars.com/kata/5832db03d5bafb7d96000107 3 | 4 | import re 5 | def lottery(s): 6 | matches = re.findall('[0-9]', s) 7 | used_nums, output = set(), [] 8 | if not matches: 9 | return 'One more run!' 10 | for num in matches: 11 | if num not in used_nums: 12 | output.append(num) 13 | used_nums.add(num) 14 | return ''.join(output) -------------------------------------------------------------------------------- /most_sales.py: -------------------------------------------------------------------------------- 1 | #most sales kata 2 | #https://www.codewars.com/kata/5e16ffb7297fe00001114824 3 | 4 | def top3(products, amounts, prices): 5 | totals = list(map(lambda x: x[0]*x[1], zip(amounts,prices))) 6 | ordered_products = [] 7 | 8 | for i in range(0,3): 9 | max_index = totals.index(max(totals)) 10 | ordered_products.append(products[max_index]) 11 | totals[max_index] = -1 12 | return ordered_products -------------------------------------------------------------------------------- /sort_the_vowels.py: -------------------------------------------------------------------------------- 1 | #sort the vowels kata 2 | #https://www.codewars.com/kata/59e49b2afc3c494d5d00002a 3 | 4 | def sort_vowels(s): 5 | if type(s) == int or s == None: 6 | return '' 7 | 8 | output = '' 9 | for letter in s: 10 | if letter.lower() in 'aeiou': 11 | letter = '|' + letter 12 | else: 13 | letter += '|' 14 | output += letter +'\n' 15 | return output.strip('\n') -------------------------------------------------------------------------------- /briefcase_lock.py: -------------------------------------------------------------------------------- 1 | # Briefcase Lock kata 2 | # https://www.codewars.com/kata/64ef24b0679cdc004d08169e/train/python 3 | 4 | def min_turns(current, target): 5 | total = 0 6 | for i in range(4): 7 | current_num = int(current[i]) + 1 8 | target_num = int(target[i]) + 1 9 | diff = abs(target_num - current_num) 10 | if diff > 5: 11 | diff = 10 - diff 12 | total += diff 13 | return total 14 | -------------------------------------------------------------------------------- /find_the_capitals.py: -------------------------------------------------------------------------------- 1 | #find the capitals kata 2 | #https://www.codewars.com/kata/53573877d5493b4d6e00050c 3 | 4 | def capital(capitals): 5 | sentences = [] 6 | for capital in capitals: 7 | if 'state' in capital.keys(): 8 | type = 'state' 9 | else: 10 | type = 'country' 11 | sentences.append('The capital of {} is {}'.format(capital[type], capital['capital'])) 12 | 13 | return sentences -------------------------------------------------------------------------------- /fix_string_case.py: -------------------------------------------------------------------------------- 1 | #fix string case kata 2 | #https://www.codewars.com/kata/5b180e9fedaa564a7000009a 3 | 4 | def solve(s): 5 | upper = 0 6 | lower = 0 7 | for letter in s: 8 | if letter.isupper(): 9 | upper += 1 10 | else: 11 | lower += 1 12 | if upper == lower: 13 | return s.lower() 14 | elif upper > lower: 15 | return s.upper() 16 | else: 17 | return s.lower() -------------------------------------------------------------------------------- /reduce-pyramid.py: -------------------------------------------------------------------------------- 1 | ##REDUCING A PYRAMID KATA 2 | ##Given the first row of a number pyramid, the code below finds the 3 | ##value stored in the last row 4 | 5 | def reduce_pyramid(base): 6 | pascals = pascal(len(base)-1) 7 | totals = [x*y for x,y in zip(pascals, base)] 8 | return sum(totals) 9 | 10 | def pascal(n): 11 | line = [1] 12 | for k in range(n): 13 | line.append(line[k] * (n-k) // (k+1)) 14 | return line -------------------------------------------------------------------------------- /scaling_squared_strings.py: -------------------------------------------------------------------------------- 1 | #scaling squared strings kata 2 | #https://www.codewars.com/kata/56ed20a2c4e5d69155000301 3 | 4 | def scale(strng, k, v): 5 | output = '' 6 | substrings = strng.split('\n') 7 | for sub in substrings: 8 | temp = '' 9 | for char in sub: 10 | temp += char * k 11 | print(temp) 12 | output += (temp +'\n') * v 13 | temp = '' 14 | return output.strip('\n') -------------------------------------------------------------------------------- /strong_number_special_numbers_series_2.py: -------------------------------------------------------------------------------- 1 | #Strong Number (Special Number Series #2) kata 2 | #https://www.codewars.com/kata/5a4d303f880385399b000001 3 | 4 | def strong_num(number): 5 | total = 0 6 | for num in list(map(int, str(number))): 7 | total2 = 1 8 | for x in range(1, num+1): 9 | total2 *= x 10 | total += total2 11 | return 'STRONG!!!!' if total == number else 'Not Strong !!' 12 | 13 | -------------------------------------------------------------------------------- /ball_upwards.py: -------------------------------------------------------------------------------- 1 | #ball upwards kata 2 | #https://www.codewars.com/kata/566be96bb3174e155300001b 3 | 4 | def max_ball(v0): 5 | previous_max = 0 6 | current = 1 7 | t = 0 8 | while current >= previous_max: 9 | t+=1 10 | current = (v0*t/(3.6*10)) - (0.5*9.81*(t/10)**2) 11 | if current > previous_max: 12 | previous_max = current 13 | else: 14 | print(t) 15 | return int(t-1) -------------------------------------------------------------------------------- /create_string_for_array_of_objects.py: -------------------------------------------------------------------------------- 1 | # Creating a string for an array of objects from a set of words kata 2 | # https://www.codewars.com/kata/5877786688976801ad000100 3 | 4 | import re 5 | def words_to_object(s): 6 | matches = re.findall(r"[^ ]+ [^ ]+", s) 7 | dicts = [] 8 | for mtch in matches: 9 | name, id = mtch.split(" ") 10 | dicts.append(f"{{name : '{name}', id : '{id}'}}") 11 | return f"[{', '.join(dicts)}]" 12 | -------------------------------------------------------------------------------- /fun-with-lists-length.py: -------------------------------------------------------------------------------- 1 | ###Fun with lists: length - codewars kata 2 | ###https://www.codewars.com/kata/581e476d5f59408553000a4b 3 | 4 | 5 | def length(head): 6 | '''Returns the length of linked list''' 7 | if head == None: 8 | return 0 9 | 10 | elif head: 11 | number = 1 12 | 13 | while head.next: 14 | head = head.next 15 | number += 1 16 | return number 17 | -------------------------------------------------------------------------------- /mispelled_word.py: -------------------------------------------------------------------------------- 1 | #mispelled word kata 2 | #https://www.codewars.com/kata/5892595f190ca40ad0000095 3 | 4 | import difflib 5 | def mispelled(word1,word2): 6 | if word1 == '' and word2 == '': 7 | return True 8 | output_list = [li for li in difflib.ndiff(word2, word1) if li[0] != ' '] 9 | if len(output_list) <= 2 and (word1 == '' or word2 == ''): 10 | return False 11 | return True if len(output_list) <= 2 else False 12 | -------------------------------------------------------------------------------- /n_smallest_elements_in_original_order.py: -------------------------------------------------------------------------------- 1 | #N smallest elements in original order 2 | #https://www.codewars.com/kata/5aec1ed7de4c7f3517000079 3 | 4 | def first_n_smallest(arr, n): 5 | ordered = sorted(arr) 6 | smallest = ordered[:n] 7 | print(smallest) 8 | output = [] 9 | for num in arr: 10 | if num in smallest and len(output) = value: 12 | return i -------------------------------------------------------------------------------- /sixteen_plus_eighteen_equals_214.py: -------------------------------------------------------------------------------- 1 | #16+18=214 kata 2 | #https://www.codewars.com/kata/5effa412233ac3002a9e471d 3 | 4 | def add(num1, num2): 5 | str_1, str_2 = str(num1), str(num2) 6 | max_length = max(len(str_1), len(str_2)) 7 | str_1 = '0'*(max_length - len(str_1)) + str_1 8 | str_2 = '0'*(max_length - len(str_2)) + str_2 9 | result = list(map(lambda x: str(int(x[0]) + int(x[1])), list(zip(str_1, str_2)))) 10 | return int(''.join(result)) -------------------------------------------------------------------------------- /counting_duplicates_across_multiple_lists.py: -------------------------------------------------------------------------------- 1 | ## counting duplicates across multiple lists 2 | ## https://www.codewars.com/kata/6113c2dc3069b1001b8fdd05/ 3 | 4 | def count_duplicates(name,age,height): 5 | prev = [] 6 | duplicates = 0 7 | for i, n in enumerate(name): 8 | profile = [n, age[i], height[i]] 9 | if profile in prev: 10 | duplicates += 1 11 | else: 12 | prev.append(profile) 13 | return duplicates -------------------------------------------------------------------------------- /how_many_unique_consonants.py: -------------------------------------------------------------------------------- 1 | # How many unique consonants kata 2 | # https://www.codewars.com/kata/5a19226646d843de9000007d/solutions/python 3 | 4 | def count_consonants(text): 5 | consonants = [] 6 | for letter in text: 7 | lowercase_letter = letter.lower() 8 | if lowercase_letter not in consonants + ['a','e', 'i', 'o', 'u'] and lowercase_letter.isalpha(): 9 | consonants.append(lowercase_letter) 10 | return len(consonants) 11 | -------------------------------------------------------------------------------- /reach_me_and_sum_my_digits.py: -------------------------------------------------------------------------------- 1 | # reach me and sum my digits kata 2 | # https://www.codewars.com/kata/55ffb44050558fdb200000a4 3 | 4 | def sum_dig_nth_term(init_val, pattern_l, nth_term): 5 | current_term, current_val, counter = 1, init_val, 0 6 | while current_term < nth_term: 7 | current_val += pattern_l[counter % len(pattern_l)] 8 | counter += 1 9 | current_term += 1 10 | return sum(int(digit) for digit in str(current_val)) 11 | -------------------------------------------------------------------------------- /create-phone-number.py: -------------------------------------------------------------------------------- 1 | def create_phone_number(n): 2 | '''Converts phone number digits into a phone number format''' 3 | phone_number = '(' 4 | for i, num in enumerate(n): 5 | if i < 3: 6 | phone_number += str(num) 7 | if i == 2: 8 | phone_number += ') ' 9 | elif i <= 13: 10 | phone_number += str(num) 11 | if i == 5: 12 | phone_number += '-' 13 | return phone_number -------------------------------------------------------------------------------- /decode_the_morse_code.py: -------------------------------------------------------------------------------- 1 | #decode the morse code kata 2 | #https://www.codewars.com/kata/54b724efac3d5402db00065e 3 | 4 | def decodeMorse(morse_code): 5 | morse_code = morse_code.lstrip().rstrip() 6 | morse_code = morse_code.split(' ') 7 | output = [] 8 | 9 | for code in morse_code: 10 | output.append(''.join(list(map(lambda x: MORSE_CODE[x], code.split(' '))))) 11 | output = ' '.join(output) 12 | 13 | return output 14 | 15 | -------------------------------------------------------------------------------- /interview_question_easy.py: -------------------------------------------------------------------------------- 1 | #interview question (easy) kata 2 | #https://www.codewars.com/kata/5b358a1e228d316283001892 3 | 4 | def get_strings(city): 5 | city = city.lower() 6 | output = '' 7 | letters_considered = set() 8 | for letter in city: 9 | if letter not in letters_considered and letter.isalnum(): 10 | output += letter + ':' + '*'*city.count(letter) +',' 11 | letters_considered.add(letter) 12 | return output[:-1] -------------------------------------------------------------------------------- /sort_the_odd.py: -------------------------------------------------------------------------------- 1 | #sort the odd kata 2 | #https://www.codewars.com/kata/578aa45ee9fd15ff4600090d 3 | 4 | def sort_array(source_array): 5 | odds = [] 6 | for i, num in enumerate(source_array): 7 | if num % 2 != 0: 8 | odds.append(num) 9 | source_array[i] = None 10 | output = [] 11 | for num in sorted(odds): 12 | index = source_array.index(None) 13 | source_array[index] = num 14 | return source_array 15 | -------------------------------------------------------------------------------- /responsible-drinking.py: -------------------------------------------------------------------------------- 1 | ###Responsible Drinking - codewars kata 2 | ###https://www.codewars.com/kata/5aee86c5783bb432cd000018 3 | 4 | import re 5 | def hydrate(drink_string): 6 | '''Returns number of waters to balance alcoholic drinks found 7 | in drink string''' 8 | drink_total = sum(list(map(int,re.findall('[\d]+', drink_string)))) 9 | 10 | glasses = ('glass' if drink_total == 1 else 'glasses') 11 | return '{} {} of water'.format(drink_total, glasses) -------------------------------------------------------------------------------- /weight_for_weight.py: -------------------------------------------------------------------------------- 1 | #weight for weight kata 2 | #https://www.codewars.com/kata/55c6126177c9441a570000cc 3 | 4 | def calc_weights(weight): 5 | total = 0 6 | for digit in weight: 7 | digit = int(digit) 8 | total += digit 9 | return total 10 | 11 | def order_weight(strng): 12 | weights = strng.split(' ') 13 | weights_converted = list(map(calc_weights, weights)) 14 | return ' '.join([x for _, x in sorted(zip(weights_converted, weights))]) -------------------------------------------------------------------------------- /which-section-did-you-scroll-to.py: -------------------------------------------------------------------------------- 1 | ###Which section did you scroll to? - codewars kata 2 | ###https://www.codewars.com/kata/5cb05eee03c3ff002153d4ef/train/python 3 | 4 | def get_section_id(scroll, sizes): 5 | '''Returns the size, from sizes (and area on the screen), which has been scrolled to''' 6 | total_pixels = 0 7 | for i, num in enumerate(sizes): 8 | total_pixels += num 9 | if total_pixels > scroll: 10 | return i 11 | return -1 -------------------------------------------------------------------------------- /yoga-class.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | def yoga(classroom, poses): 3 | '''Return amount of poses a yoga class can perform based on given criteria''' 4 | if classroom == [] or poses == []: 5 | return 0 6 | classroom = np.array(classroom) 7 | total_poses = 0 8 | for row in classroom: 9 | row_total = sum(row) 10 | row += row_total 11 | for pose in poses: 12 | total_poses += np.sum([pose <= row]) 13 | return total_poses -------------------------------------------------------------------------------- /IQ_test.py: -------------------------------------------------------------------------------- 1 | #IQ Test kata 2 | #https://www.codewars.com/kata/552c028c030765286c00007d 3 | 4 | def iq_test(numbers): 5 | numbers = list(map(int, numbers.split(' '))) 6 | evens, edx = 0, 0 7 | odds, odx = 0, 0 8 | for i, num in enumerate(numbers): 9 | if num % 2 == 0: 10 | evens += 1 11 | edx = i 12 | else: 13 | odds += 1 14 | odx = i 15 | return [edx, odx][[evens, odds].index(min(evens, odds))] + 1 16 | -------------------------------------------------------------------------------- /are-same-squared.py: -------------------------------------------------------------------------------- 1 | 2 | #ARE THEY THE "SAME" KATA 3 | ##Checks whether the elements in b are the elements in a squared, 4 | ##regardless of the order 5 | 6 | def comp(array1, array2): 7 | if array1 == None or array2 == None: 8 | return False 9 | square_values = [x**2 for x in array1] 10 | for num in array2: 11 | if num not in square_values: 12 | return False 13 | else: 14 | square_values.remove(num) 15 | return True -------------------------------------------------------------------------------- /poet-and-pendulum.py: -------------------------------------------------------------------------------- 1 | ###The Poet and The Pendulum - codewars kata 2 | ###https://www.codewars.com/kata/5bd776533a7e2720c40000e5 3 | 4 | def pendulum(values): 5 | '''Returns values sorted, with smallest value at centre of the list and the 6 | remaining sorted incrmentally left then right''' 7 | sorted_values = sorted(values) 8 | mid = [sorted_values [0]] 9 | right = sorted_values[1::2] 10 | left = sorted_values[2::2] 11 | return left[::-1] + mid + right -------------------------------------------------------------------------------- /consecutive_strings.py: -------------------------------------------------------------------------------- 1 | #consecutive strinngs kata 2 | #https://www.codewars.com/kata/56a5d994ac971f1ac500003e 3 | 4 | def longest_consec(strarr, k): 5 | concat, longest, output = [],0,'' 6 | if k > 0 and k <= len(strarr): 7 | for i in range(len(strarr[:])): 8 | concat.append(''.join(strarr[i:i+k])) 9 | if len(concat[-1]) > longest: 10 | output = concat[-1] 11 | longest = len(concat[-1]) 12 | return output 13 | -------------------------------------------------------------------------------- /numericals_of_a_string.py: -------------------------------------------------------------------------------- 1 | #numericals of a string kata 2 | #https://www.codewars.com/kata/5b4070144d7d8bbfe7000001 3 | 4 | def numericals(s): 5 | dict = { 6 | } 7 | output_list = [] 8 | for letter in s: 9 | if letter not in dict.keys(): 10 | dict[letter] = 0 11 | output_list.append(1) 12 | else: 13 | dict[letter] += 1 14 | output_list.append(dict[letter]+1) 15 | return ''.join(map(str, output_list)) -------------------------------------------------------------------------------- /ski_jump.py: -------------------------------------------------------------------------------- 1 | #ski jump kata 2 | #https://www.codewars.com/kata/57ed7214f670e99f7a000c73 3 | 4 | def ski_jump(mountain): 5 | height = len(mountain) 6 | jump = (height * (height * 1.5) * 9)/10 7 | if jump < 10: 8 | sentence = 'He\'s crap!' 9 | elif jump < 25: 10 | sentence = 'He\'s ok!' 11 | elif jump < 50: 12 | sentence = 'He\'s flying!' 13 | else: 14 | sentence = 'Gold!!' 15 | return '{0:.2f}'.format(jump) + ' metres: ' + sentence -------------------------------------------------------------------------------- /square-up-array.py: -------------------------------------------------------------------------------- 1 | def square_up(n): 2 | '''Return a list depending on the value of nu 3 | for example: n = 2 ==> [0,1,2,1]. n = 3 ==> [0, 0, 0, 0, 2, 1, 3, 2, 1] ''' 4 | arr_to_n = list(range(1,n+1)) 5 | arr_to_n.sort(reverse=True) 6 | output_list = [] 7 | previous_list = [0]*n 8 | for i in range(1, n+1): 9 | previous_list[-i] = arr_to_n[-i] 10 | output_list.extend(previous_list) 11 | return [num if num >= 0 else 0 for num in output_list] -------------------------------------------------------------------------------- /swap_case_using_N.py: -------------------------------------------------------------------------------- 1 | #swap case using N kata 2 | #https://www.codewars.com/kata/5f3afc40b24f090028233490 3 | 4 | def swap(s,n): 5 | s = list(s) 6 | n = list(bin(n).split('b')[1]) 7 | count = 0 8 | output = [] 9 | for letter in s: 10 | if n[count%len(n)] == '1': 11 | output.append(letter.swapcase()) 12 | else: 13 | output.append(letter) 14 | if letter.isalnum(): 15 | count += 1 16 | return ''.join(output) -------------------------------------------------------------------------------- /ten-minute-walk.py: -------------------------------------------------------------------------------- 1 | ###Take a Ten Minute Walk - codewars kata 2 | ###https://www.codewars.com/kata/54da539698b8a2ad76000228/train/python 3 | 4 | def is_valid_walk(walk): 5 | '''Returns whether a walk is equal to 10 minuts based on directions travelled 6 | and number of increments''' 7 | north_south = walk.count('n') == walk.count('s') 8 | east_west = walk.count('e') == walk.count('w') 9 | length = len(walk) == 10 10 | return north_south and east_west and length -------------------------------------------------------------------------------- /van_ecks_sequence.py: -------------------------------------------------------------------------------- 1 | # Van Ecks Sequence kata 2 | # https://www.codewars.com/kata/62e4df54323f44005c54424c/train/python 3 | 4 | def seq(n): 5 | sequence, head = [0], 0 6 | while len(sequence) < n: 7 | head = sequence[0] 8 | if head not in sequence[1:]: 9 | sequence = [0] + sequence 10 | else: 11 | distance = sequence[1:].index(head) + 1 12 | sequence = [distance] + sequence 13 | return sequence[0] 14 | 15 | -------------------------------------------------------------------------------- /message_validator.py: -------------------------------------------------------------------------------- 1 | #Message Validator kata 2 | #https://www.codewars.com/kata/5fc7d2d2682ff3000e1a3fbc 3 | 4 | import re 5 | def is_a_valid_message(message): 6 | if message == "": 7 | return True 8 | elif message == [] or not message[0].isnumeric(): 9 | return False 10 | 11 | matches = re.findall(r"([0-9]+)([a-zA-Z]+|$)", message) 12 | for match in matches: 13 | if len(match[1]) != int(match[0]): 14 | return False 15 | return True 16 | -------------------------------------------------------------------------------- /pillow_on_the_fridge.py: -------------------------------------------------------------------------------- 1 | #pillow on the fridge kata 2 | #https://www.codewars.com/kata/57d147bcc98a521016000320 3 | 4 | def pillow(s): 5 | fridge = 'n' in s[0] 6 | pillow = 'B' in s[1] 7 | 8 | if (pillow == False) or (fridge == False): 9 | return False 10 | fridge_index = [i for i, x in enumerate(s[0]) if x == "n"][0] 11 | pillow_index = [i for i, x in enumerate(s[1]) if x == "B"][-1] 12 | 13 | return fridge_index <= pillow_index 14 | 15 | 16 | -------------------------------------------------------------------------------- /reverse_every_other_word_in_the_string.py: -------------------------------------------------------------------------------- 1 | #reverse every other word in the string 2 | #https://www.codewars.com/kata/58d76854024c72c3e20000de 3 | 4 | def reverse_alternate(string): 5 | words = string.split(' ') 6 | words = list(filter(lambda a: a != '', words)) 7 | output = '' 8 | for i, word in enumerate(words): 9 | if i % 2 == 1: 10 | output += word[::-1] + ' ' 11 | else: 12 | output += word + ' ' 13 | return output.strip() 14 | -------------------------------------------------------------------------------- /sort_only_integers_in_nested_list.py: -------------------------------------------------------------------------------- 1 | #sort only integers in nested list kata 2 | #https://www.codewars.com/kata/5a4bdd73d8e145f17d000035 3 | 4 | def sort_nested_list(A): 5 | vals = [] 6 | for sub_lst in A: 7 | for lst in sub_lst: 8 | vals += lst 9 | vals = sorted(vals) 10 | for i, sub_lst in enumerate(A): 11 | for j, lst in enumerate(sub_lst): 12 | for k in range(len(lst)): 13 | A[i][j][k] = vals.pop(0) 14 | return A -------------------------------------------------------------------------------- /how_much_coffee_do_you_need.py: -------------------------------------------------------------------------------- 1 | #how much coffee do you need? kata 2 | #https://www.codewars.com/kata/57de78848a8b8df8f10005b1 3 | 4 | def how_much_coffee(events): 5 | output = 0 6 | possible_events = ['cw', 'cat', 'dog', 'movie'] 7 | for event in events: 8 | if event in possible_events: 9 | output += 1 10 | elif event.lower() in possible_events: 11 | output += 2 12 | 13 | return output if output < 4 else 'You need extra sleep' 14 | -------------------------------------------------------------------------------- /lets_recycle.py: -------------------------------------------------------------------------------- 1 | #let's recycle! kata 2 | #https://www.codewars.com/kata/5b6db1acb118141f6b000060 3 | 4 | def recycle(a): 5 | bin_indeces = ['paper', 'glass', 'organic', 'plastic'] 6 | bin_contents = ([],[],[],[]) 7 | 8 | for item in a: 9 | bin_contents[bin_indeces.index(item['material'])].append(item['type']) 10 | if 'secondMaterial' in item.keys(): 11 | bin_contents[bin_indeces.index(item['secondMaterial'])].append(item['type']) 12 | return (bin_contents) -------------------------------------------------------------------------------- /search_for_letters.py: -------------------------------------------------------------------------------- 1 | #Search for letters kata 2 | #https://www.codewars.com/kata/52dbae61ca039685460001ae 3 | 4 | def change(st): 5 | output = [0 for i in range(0, 26)] 6 | for letter in st: 7 | condition1, condition2 = [(65 <= ord(letter)), (ord(letter) <= 90)], [(97 <= ord(letter)), (ord(letter) <= 122)] 8 | if all(condition1) or all(condition2): 9 | letter = ord(letter.lower()) 10 | output[letter-97] = 1 11 | return ''.join(list(map(str, output))) -------------------------------------------------------------------------------- /tortoise-racing.py: -------------------------------------------------------------------------------- 1 | import math 2 | def race(v1, v2, g): 3 | '''Calculates the time required for a tortoise to catch another, 4 | depending on speed and starting delay''' 5 | if v2 <= v1: 6 | return None 7 | speed_difference = v2 - v1 8 | time_required = (g/speed_difference)*3600 9 | hours = int(time_required/3600) 10 | minutes = int((time_required - hours*3600)/60) 11 | seconds = int(time_required - hours*3600 - minutes*60) 12 | return [hours, minutes, seconds] -------------------------------------------------------------------------------- /largest-product-in-a-series.py: -------------------------------------------------------------------------------- 1 | ###Largest Product in a Series - codewars kata 2 | ###https://www.codewars.com/kata/529872bdd0f550a06b00026e/solutions/python 3 | 4 | import numpy as np 5 | def greatest_product(n): 6 | '''Returns the greatest product of five consecutive numbers in 7 | n''' 8 | n = np.array(list(map(int, n))) 9 | roll_array = np.copy(n) 10 | for num in range(4): 11 | roll_array = np.roll(roll_array, -1) 12 | n = n*roll_array 13 | return np.max(n[0:-4]) -------------------------------------------------------------------------------- /thinking_and_testing_something_capitalized.py: -------------------------------------------------------------------------------- 1 | #thinking & testing: something capitalized kata 2 | #https://www.codewars.com/kata/56d93f249c844788bc000002 3 | 4 | def testit(s): 5 | if s == '': 6 | return '' 7 | s = s.split(' ') 8 | output_string = '' 9 | for string in s: 10 | letters = list(string) 11 | letters[-1] = letters[-1].title() 12 | string = ''.join(letters) 13 | output_string += string + ' ' 14 | return ''.join(list(output_string)[:-1]) -------------------------------------------------------------------------------- /yes-no-yes-no.py: -------------------------------------------------------------------------------- 1 | ###Yes No Yes No - codewars kata 2 | ### https://www.codewars.com/kata/573c84bf0addf9568d001299/train/python 3 | 4 | def yes_no(arr): 5 | if not arr: 6 | return [] 7 | output = [arr[0]] 8 | arr = arr[1:] 9 | 10 | while len(arr) > 1: 11 | output.append(arr[1]) 12 | del arr[1] 13 | arr.append(arr[0]) 14 | del arr[0] 15 | if arr: 16 | output.append(arr[0]) 17 | return output 18 | 19 | 20 | -------------------------------------------------------------------------------- /cyclops-number.py: -------------------------------------------------------------------------------- 1 | ###Cyclops Numbers - codewars kata 2 | ###https://www.codewars.com/kata/56b0bc0826814364a800005a 3 | 4 | 5 | def cyclops (n): 6 | '''Returns True or False depending on whether a number 7 | is a cyclops number. See link''' 8 | bin_n = bin(n).split('b')[1] 9 | cond_1 = (len(bin_n) % 2 == 1) 10 | if '0' in bin_n: 11 | cond_2 = (bin_n.index('0') + 1 == 1 + len(bin_n) // 2) 12 | else: 13 | cond_2 = False 14 | return True if cond_1 and cond_2 else False -------------------------------------------------------------------------------- /evenly_distribute_values_in_array.py: -------------------------------------------------------------------------------- 1 | #evenly distribute values in array kata 2 | #https://www.codewars.com/kata/5bb50eb68f8bbdb4b300021d 3 | 4 | def distribute_evenly(lst): 5 | itms = [] 6 | output = [] 7 | for itm in lst: 8 | if itm not in itms: 9 | itms.append(itm) 10 | 11 | while len(lst) > 0: 12 | for itm in itms: 13 | if itm in lst: 14 | del lst[lst.index(itm)] 15 | output.append(itm) 16 | return output -------------------------------------------------------------------------------- /thue-morse-sequence.py: -------------------------------------------------------------------------------- 1 | # Thue-Morse Sequence kata 2 | # https://www.codewars.com/kata/591aa1752afcb02fa300002a/train/python 3 | 4 | def thue_morse(n,seq ='0'): 5 | if len(seq) >= n: 6 | return seq[0:n] 7 | else: 8 | return thue_morse(n, seq + complementary(seq)) 9 | 10 | def complementary(str): 11 | complement = '' 12 | for b in str: 13 | if b == "1": 14 | complement += '0' 15 | else: 16 | complement += '1' 17 | return complement 18 | -------------------------------------------------------------------------------- /bobs-reversing-obfuscator.py: -------------------------------------------------------------------------------- 1 | ###Bob's reversing obfuscator - kata 2 | ###https://www.codewars.com/kata/559ee79ab98119dd0100001d 3 | 4 | def decoder(encoded, marker): 5 | '''Returns decoded string''' 6 | encoded = encoded.replace(marker, '#') 7 | marker = '#' 8 | encoded = encoded[::-1] 9 | output= '' 10 | for letter in encoded: 11 | if letter != marker: 12 | output += letter 13 | if letter == marker: 14 | output = output[::-1] 15 | return output[::-1] -------------------------------------------------------------------------------- /find_the_nth_occurrence_of_a_word_in_a_string.py: -------------------------------------------------------------------------------- 1 | #find the nth occurrence of a word in a string! kata 2 | #https://www.codewars.com/kata/5b1d1812b6989d61bd00004f 3 | 4 | def find_nth_occurrence(substring, string, occurrence=0): 5 | count = 0 6 | for i, char in enumerate(string): 7 | captured_string = string[i: i+len(substring)] 8 | if captured_string == substring: 9 | count +=1 10 | if count == occurrence: 11 | return i 12 | return -1 13 | -------------------------------------------------------------------------------- /making-change.py: -------------------------------------------------------------------------------- 1 | ###Making Change - codewars kata 2 | ###Return the coins which makes up the change that achieves the minimum number of coins 3 | 4 | def make_change(amount): 5 | '''Returns a dictionary of minimum coins required to reach amount''' 6 | coins = [50, 25, 10, 5, 1] 7 | names = ['H','Q','D','N','P'] 8 | output = {} 9 | for i, coin in enumerate(coins): 10 | if amount // coin > 0: 11 | output[names[i]] = amount // coin 12 | amount %= coin 13 | return output -------------------------------------------------------------------------------- /simple_fun_305_typist.py: -------------------------------------------------------------------------------- 1 | #simple fun #305: typist kata 2 | #https://www.codewars.com/kata/592645498270ccd7950000b4/solutions/python 3 | 4 | 5 | def check_case(char): 6 | if char.isupper(): 7 | return True 8 | return False 9 | 10 | def typist(s): 11 | upper, output = False, 0 12 | for char in s: 13 | output += 1 14 | new_case = check_case(char) 15 | if new_case != upper: 16 | upper = new_case 17 | output += 1 18 | return output 19 | -------------------------------------------------------------------------------- /sum-numbers-0-n.py: -------------------------------------------------------------------------------- 1 | ###Sum of numbers from 0 to N - codewars kata 2 | ###https://www.codewars.com/kata/56e9e4f516bcaa8d4f001763/python 3 | 4 | def show_sequence(n): 5 | '''Returns a string showing the summation of n to the total''' 6 | if n < 0: 7 | strng = '{}<0'.format(n) 8 | elif n == 0: 9 | strng = '{}=0'.format(n) 10 | else: 11 | total = sum(list(range(n+1))) 12 | strng = '+'.join(list(map(str, list(range(n+1))))) + ' = {}'.format(str(total)) 13 | return strng -------------------------------------------------------------------------------- /complete-the-pattern#2.py: -------------------------------------------------------------------------------- 1 | ###Complete the patter #2 - codewars kata 2 | ###https://www.codewars.com/users/ellismckenzielee/completed_solutions 3 | 4 | def pattern(n): 5 | '''Produces pattern based on n, as specified in the kata''' 6 | if n <= 0: 7 | return '' 8 | str_n = str(n) 9 | liste_int = list(range(0,n+1))[::-1] 10 | liste_str = list(map(str, liste_int)) 11 | output = '' 12 | for i in liste_int[:-2]: 13 | output += ''.join(liste_str[:i]) + '\n' 14 | return output + str_n -------------------------------------------------------------------------------- /pairs_of_bears.py: -------------------------------------------------------------------------------- 1 | #Pairs of Bears kata 2 | #https://www.codewars.com/kata/57d165ad95497ea150000020 3 | 4 | def bears(x,s): 5 | output = "" 6 | previous = False 7 | counts = 0 8 | for i in range(0, len(s) -1): 9 | letters = s[i] + s[i+1] 10 | if (letters == 'B8' or letters == '8B') and previous == False: 11 | output += letters 12 | previous = True 13 | counts += 1 14 | else: 15 | previous = False 16 | return [output, counts >= x] -------------------------------------------------------------------------------- /simple_equation_reversal.py: -------------------------------------------------------------------------------- 1 | #simple equation reversal kata 2 | #https://www.codewars.com/kata/5aa3af22ba1bb5209f000037 3 | 4 | def solve(eq): 5 | output = "" 6 | numbers = "" 7 | for char in list(eq[::-1]): 8 | if char not in ['0','1','2','3','4','5','6','7','8','9']: 9 | output += ''.join(list(numbers)[::-1]) 10 | output += (char) 11 | numbers = "" 12 | else: 13 | numbers += char 14 | output += numbers[::-1] 15 | return output 16 | -------------------------------------------------------------------------------- /string_prefix_and_suffix.py: -------------------------------------------------------------------------------- 1 | #string prefix and suffix kata 2 | #https://www.codewars.com/kata/5ce969ab07d4b7002dcaa7a1 3 | 4 | def solve(st): 5 | part_1 = st[:int(len(st)/2)] 6 | part_2 = st[int(len(st)/2):] 7 | if len(part_2) > len(part_1): 8 | part_2 = part_2[1:] 9 | for i, letter in enumerate(part_1): 10 | if part_1 != part_2: 11 | part_1 = part_1[:-1] 12 | part_2 = part_2[1:] 13 | else: 14 | return len(part_1) 15 | return 0 16 | -------------------------------------------------------------------------------- /title_case.py: -------------------------------------------------------------------------------- 1 | #Title Case kata 2 | #https://www.codewars.com/kata/5202ef17a402dd033c000009 3 | 4 | def title_case(title, minor_words=''): 5 | title = title.split(' ') 6 | minor_words = minor_words.split(' ') 7 | minor_words = list(map(lambda x: x.lower(), minor_words)) 8 | output = title[0].title() 9 | for word in title[1:]: 10 | if word.lower() not in minor_words: 11 | output += ' ' + word.title() 12 | else: 13 | output += ' ' + word.lower() 14 | return output -------------------------------------------------------------------------------- /find-all-non-consecutive-numbers.py: -------------------------------------------------------------------------------- 1 | ###Find all non-consecutive numbers - codewars kata 2 | ###https://www.codewars.com/kata/58f8b35fda19c0c79400020f 3 | 4 | def all_non_consecutive(arr): 5 | '''Returns value and index of all non-consecutive numbers. 6 | A consecutive number is larger than the number at the previous 7 | index by 1''' 8 | output = [] 9 | for i, num in enumerate(arr[1:]): 10 | if num != (arr[i]+1): 11 | output.append({'n': num, 'i': i+1}) 12 | return output 13 | -------------------------------------------------------------------------------- /next-number-same-1-bits.py: -------------------------------------------------------------------------------- 1 | ###Basics 08: Find next higher number with same Bits (1's) - codewars kata 2 | ###https://www.codewars.com/kata/56bdd0aec5dc03d7780010a5 3 | 4 | def next_higher(value): 5 | '''Returns next number with same number of 1 bits''' 6 | initial = bin(value).split('b')[1].count('1') 7 | current_num = value+1 8 | while True: 9 | number_1s = bin(current_num).split('b')[1].count('1') 10 | if number_1s == initial: 11 | return current_num 12 | current_num += 1 -------------------------------------------------------------------------------- /alternate-capitalisation.py: -------------------------------------------------------------------------------- 1 | ###Alternate capitalisation - codewars kata 2 | ###https://www.codewars.com/kata/59cfc000aeb2844d16000075 3 | 4 | def capitalize(s): 5 | '''Returns two strings based on s. In one case, numbers at an 6 | even index are capitalised, and in the second case, the opposite is true''' 7 | even = ''.join([letter.capitalize() if i % 2 == 0 else letter for i, letter in enumerate(s)]) 8 | odd = ''.join([letter.capitalize() if i % 2 == 1 else letter for i, letter in enumerate(s)]) 9 | return [even, odd] -------------------------------------------------------------------------------- /bouncing-ball.py: -------------------------------------------------------------------------------- 1 | ###Bouncing Balls - codewars kata 2 | ###https://www.codewars.com/kata/5544c7a5cb454edb3c000047 3 | 4 | def bouncingBall(h, bounce, window): 5 | '''Returns how many times a person in a window could see a bouncing 6 | ball dropped from a height above''' 7 | bounces = 0 8 | if (bounce >= 1) or (bounce <=0) or (h <0) or (window<0) or (window==h): 9 | return -1 10 | while h > window: 11 | h = bounce*h 12 | if h > window: 13 | bounces += 2 14 | return bounces + 1 -------------------------------------------------------------------------------- /integer-to-whitespace.py: -------------------------------------------------------------------------------- 1 | ###Convert integer to whitespce format - codewars kata 2 | ###https://www.codewars.com/kata/55b350026cc02ac1a7000032 3 | 4 | def whitespace_number(n): 5 | '''Converts number n into whitespace format''' 6 | binary_format = str(bin(n).split('b')[1]) 7 | print(binary_format) 8 | output = '' 9 | if n> 0: 10 | output += ' ' 11 | elif n < 0: 12 | output += '\t' 13 | 14 | output += binary_format.replace('1', '\t').replace('0', ' ') 15 | return output + '\n' -------------------------------------------------------------------------------- /pandemia.py: -------------------------------------------------------------------------------- 1 | ###Pandemia - codewars kata 2 | ###https://www.codewars.com/kata/5e2596a9ad937f002e510435 3 | 4 | def infected(s): 5 | '''Returns the percentage of infected regions, depending on the geography''' 6 | islands = s.split('X') 7 | infected = 0 8 | safe = 0 9 | for island in islands: 10 | if '1' in island: 11 | infected += len(island) 12 | else: 13 | safe += len(island) 14 | if infected + safe == 0: 15 | return 0 16 | return infected/(infected+safe)*100 -------------------------------------------------------------------------------- /rule-of-divisibility-13.py: -------------------------------------------------------------------------------- 1 | ###Rule of Divisibility by 13 - codewars kata 2 | ###https://www.codewars.com/kata/564057bc348c7200bd0000ff 3 | 4 | def thirt(n): 5 | '''See codewars challenge''' 6 | multipliers = [1, 10, 9, 12, 3, 4] 7 | old_num = 0 8 | new_num = -1000 9 | while old_num != new_num: 10 | old_num = new_num 11 | new_num = 0 12 | for i, num in enumerate(list(str(n))[::-1]): 13 | new_num += (int(num) * (multipliers[i%6])) 14 | n = new_num 15 | return new_num -------------------------------------------------------------------------------- /count_the_smiley_faces.py: -------------------------------------------------------------------------------- 1 | #Count the smiley faces! kata 2 | #https://www.codewars.com/kata/583203e6eb35d7980400002a 3 | 4 | def count_smileys(arr): 5 | total = 0 6 | for face in arr: 7 | template = [[':',';'], ['-','~'], [')','D']] 8 | if len(face) == 2: 9 | template = template[0::2] 10 | elif len(face) != 3: 11 | continue 12 | face = list(zip(face, template)) 13 | face = list(map(lambda x: x[0] in x[1], face)) 14 | total += int(all(face)) 15 | return total -------------------------------------------------------------------------------- /duplicates_duplicates_everywhere.py: -------------------------------------------------------------------------------- 1 | #duplicates, duplicates everywhere kata 2 | #https://www.codewars.com/kata/5e8dd197c122f6001a8637ca/solutions/python 3 | 4 | def remove_duplicate_ids(obj): 5 | letters_used = set() 6 | for key, lst in sorted(obj.items(), key=lambda x: -int(x[0])): 7 | new_lst = [] 8 | for letter in lst: 9 | if letter not in letters_used: 10 | new_lst.append(letter) 11 | letters_used.add(letter) 12 | obj[key] = new_lst 13 | return obj 14 | -------------------------------------------------------------------------------- /josephus-surviror.py: -------------------------------------------------------------------------------- 1 | ###Josephus Survivor - codewars kata 2 | ###https://www.codewars.com/kata/555624b601231dc7a400017a 3 | 4 | def josephus_survivor(n,k): 5 | '''Returns the last person standing in a circle of n people, 6 | when eliminated in steps of k''' 7 | n_list = list(range(1,n +1)) 8 | index = (k - 1) 9 | while len(n_list) > 1: 10 | while index >= len(n_list): 11 | index = index - len(n_list) 12 | del n_list[index % n] 13 | index += k - 1 14 | return n_list[0] 15 | -------------------------------------------------------------------------------- /oring_arrays.py: -------------------------------------------------------------------------------- 1 | ## ORing Arrays kata 2 | ## https://www.codewars.com/kata/5ac5e9aa3853da25d9000102 3 | 4 | def or_arrays(arr1, arr2, default=0): 5 | binary_or = [] 6 | for i in range(max(len(arr1), len(arr2))): 7 | if i < len(arr1): 8 | elem_1 = arr1[i] 9 | else: 10 | elem_1 = default 11 | 12 | if i < len(arr2): 13 | elem_2 = arr2[i] 14 | else: 15 | elem_2 = default 16 | binary_or.append(elem_1 | elem_2) 17 | return binary_or 18 | -------------------------------------------------------------------------------- /product-array.py: -------------------------------------------------------------------------------- 1 | ###Product Array - codewars kata 2 | ###https://www.codewars.com/kata/5a905c2157c562994900009d 3 | 4 | def product_array(numbers): 5 | '''Returns an array based on numbers input. At index 6 | i, the output contains the product of all elements in numbers, 7 | excluding the element at position i''' 8 | output = [] 9 | total = numbers[0] 10 | 11 | for num in numbers[1:]: 12 | total *= num 13 | 14 | for num in numbers: 15 | output.append(total/num) 16 | return output 17 | -------------------------------------------------------------------------------- /simple_fun_160_cut_the_ropes.py: -------------------------------------------------------------------------------- 1 | #simple fun #160: cut the ropes kata 2 | #https://www.codewars.com/kata/58ad388555bf4c80e800001e 3 | 4 | def cut_the_ropes(arr): 5 | remaining_list = [len(arr)] 6 | 7 | for num in arr: 8 | minimum = min(arr) 9 | arr = list(map(lambda x: x-minimum, arr)) 10 | remaining = len(arr) - arr.count(0) 11 | arr = list(filter(lambda x: x != 0, arr)) 12 | if remaining == 0: 13 | return remaining_list 14 | remaining_list.append(remaining) 15 | -------------------------------------------------------------------------------- /delta_generators.py: -------------------------------------------------------------------------------- 1 | # Delta Generators kata 2 | # https://www.codewars.com/kata/6040b781e50db7000ab35125 3 | def delta(values, n): 4 | values = iter(values) 5 | if (n == 0): 6 | return values 7 | else: 8 | return delta(diff(values),n-1) 9 | 10 | def diff(iterable): 11 | one = next(iterable) 12 | while True: 13 | try: 14 | two = next(iterable) 15 | yield two.__sub__(one) 16 | one = two 17 | except StopIteration: 18 | return 19 | 20 | -------------------------------------------------------------------------------- /cartesian-plane-function.py: -------------------------------------------------------------------------------- 1 | #Functions below return the output of functions f (sumin), g (sumax) and h (sumsum) 2 | #See kata 'Functions of Integers on Cartesian Plane' for more information 3 | def sumin(n): 4 | total = 0 5 | for i in range (1,n): 6 | total += ((i*(n+1-i)) + (i*(n-i))) 7 | return total + n 8 | 9 | def sumax(n): 10 | total = 0 11 | for i in range (1, n): 12 | total += ((n+1-i)*(n+1-i)) + ((n+1-i)*(n-i)) 13 | return total + 1 14 | 15 | def sumsum(n): 16 | return sumin(n) + sumax(n) -------------------------------------------------------------------------------- /life_path_number.py: -------------------------------------------------------------------------------- 1 | #Life path number kata 2 | #https://www.codewars.com/kata/5a1a76c8a7ad6aa26a0007a0 3 | 4 | def life_path_number(birthdate): 5 | if type(birthdate[0]) != int: 6 | num = list(filter(lambda x: x in '0123456789', list(birthdate))) 7 | num = list(map(int, num)) 8 | return life_path_number(num) 9 | 10 | elif len(birthdate)> 1: 11 | total = sum(birthdate) 12 | total = list(map(int, str(total))) 13 | return life_path_number(total) 14 | else: 15 | return birthdate[0] -------------------------------------------------------------------------------- /string_doubles.py: -------------------------------------------------------------------------------- 1 | #string doubles kata 2 | #https://www.codewars.com/kata/5a145ab08ba9148dd6000094 3 | 4 | def doubles(s): 5 | previous, counter, s = '', 0, list(s) 6 | while True: 7 | for i in range(len(s)-1): 8 | if s[i] == s[i+1]: 9 | s[i], s[i+1] = '0', '0' 10 | 11 | output = ''.join(list(filter(lambda x: x != '0', s))) 12 | if output == previous: 13 | return output 14 | else: 15 | previous = output 16 | s = list(output) 17 | -------------------------------------------------------------------------------- /the_speed_of_letters.py: -------------------------------------------------------------------------------- 1 | #the speed of letters kata 2 | #https://www.codewars.com/kata/5fc7caa854783c002196f2cb 3 | 4 | def speedify(st): 5 | if st: 6 | st = list(st) 7 | alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 8 | spaces = max([i + alphabet.index(letter) for i, letter in enumerate(st)]) + 1 9 | output = [' ' for space in range(spaces)] 10 | for i, letter in enumerate(st): 11 | output[i + alphabet.index(letter)] = letter 12 | return ''.join(output) 13 | return st 14 | 15 | -------------------------------------------------------------------------------- /simple_string_expansion.py: -------------------------------------------------------------------------------- 1 | #simple string expansion kata 2 | #https://www.codewars.com/kata/5a793fdbfd8c06d07f0000d5 3 | 4 | def solve(st): 5 | i, st = 0, st[::-1] 6 | while i < len(st): 7 | if st[i] == ')': 8 | output = '' 9 | elif st[i] == '(': 10 | if st[i+1] in '0123456789': 11 | output *= int(st[i+1]) 12 | else: 13 | output += st[i+1] 14 | i += 1 15 | else: 16 | output += st[i] 17 | i += 1 18 | return output[::-1] -------------------------------------------------------------------------------- /sms_lottery_bet_validator.py: -------------------------------------------------------------------------------- 1 | # SMS lottery bet validator 2 | # https://www.codewars.com/kata/59a3e2897ac7fd05f800005f 3 | 4 | import re 5 | def validate_bet(game, text): 6 | raw_numbers = list(map(int, re.findall(r'[0-9]+(?![;\'\.0-9])', text))) 7 | numbers = [] 8 | for number in raw_numbers: 9 | if number in numbers: 10 | return None 11 | numbers.append(number) 12 | 13 | n, m = game 14 | if len(numbers) == n and all(map(lambda num: 0 < num <= m, numbers)): 15 | return sorted(numbers) 16 | -------------------------------------------------------------------------------- /the_lamp.py: -------------------------------------------------------------------------------- 1 | #the lamp: revisited kata 2 | #https://www.codewars.com/kata/570e6e32de4dc8a8340016dd 3 | 4 | class Lamp: 5 | def __init__(self, color='red', on=False): 6 | self.color = color 7 | self.on = on 8 | 9 | def toggle_switch(self): 10 | if self.on == True: 11 | self.on = False 12 | else: 13 | self.on = True 14 | 15 | def state(self): 16 | if self.on == True: 17 | return 'The lamp is on.' 18 | else: 19 | return 'The lamp is off.' -------------------------------------------------------------------------------- /simple_fun_250_prefix_to_suffix.py: -------------------------------------------------------------------------------- 1 | # Simple Fun #250: Prefix Sums to Suffix Sums kata 2 | # https://www.codewars.com/kata/590c4c342ad5cd6a8700005c/train/python/64413d15abc98500651861fc 3 | 4 | def prefix_sums_to_suffix_sums(prefix_sums): 5 | initial = [] 6 | prev = 0 7 | for prefix in prefix_sums: 8 | initial.append(prefix - prev) 9 | prev = prefix 10 | prev = sum(initial) 11 | suffixes = [prev] 12 | for num in initial[0:-1]: 13 | suffixes.append(prev-num) 14 | prev = prev-num 15 | return suffixes 16 | -------------------------------------------------------------------------------- /the_vowel_code.py: -------------------------------------------------------------------------------- 1 | #the vowel code kata 2 | #https://www.codewars.com/kata/53697be005f803751e0015aa 3 | 4 | def switcher(char): 5 | dict1 = {'a':'1','e':'2','i':'3','o':'4','u':'5'} 6 | dict2 = {'1':'a','2':'e','3':'i','4':'o','5':'u'} 7 | 8 | if char in dict1.keys(): 9 | return dict1[char] 10 | elif char in dict2.keys(): 11 | return dict2[char] 12 | return char 13 | 14 | def encode(st): 15 | return ''.join(list(map(switcher, list(st)))) 16 | 17 | def decode(st): 18 | return ''.join(list(map(switcher, list(st)))) -------------------------------------------------------------------------------- /who_has_the_most_money.py: -------------------------------------------------------------------------------- 1 | #who has the most money kata 2 | #https://www.codewars.com/kata/528d36d7cc451cd7e4000339 3 | 4 | def most_money(students): 5 | names = [] 6 | totals = [] 7 | for student in students: 8 | names.append(student.name) 9 | totals.append(student.fives*5 + student.tens*10 + student.twenties*20) 10 | maximum = max(totals) 11 | if sum(totals) == len(totals)*maximum and len(names) > 1: 12 | return 'all' 13 | else: 14 | index = totals.index(maximum) 15 | return names[index] 16 | -------------------------------------------------------------------------------- /the_5_love_languages.py: -------------------------------------------------------------------------------- 1 | #the 5 love languages kata 2 | #https://www.codewars.com/kata/5aa7a581fd8c06b552000177 3 | 4 | def love_language(partner, weeks): 5 | attempts = weeks * 7 6 | attempts_split = attempts // 5 7 | totals = [0,0,0,0,0] 8 | for i, language in enumerate(LOVE_LANGUAGES): 9 | for attempt in range(attempts_split): 10 | response = partner.response(language) 11 | if response == 'positive': 12 | totals[i] += 1 13 | 14 | return LOVE_LANGUAGES[totals.index(max(totals))] -------------------------------------------------------------------------------- /character_with_longest_consecutive_repetition.py: -------------------------------------------------------------------------------- 1 | #character with longest consecutive repetition kata 2 | #https://www.codewars.com/kata/586d6cefbcc21eed7a001155 3 | 4 | from itertools import groupby 5 | def longest_repetition(chars): 6 | maximum = 0 7 | letter = '' 8 | split_string = ["".join(g) for k, g in groupby(chars)] 9 | print(split_string) 10 | for section in split_string: 11 | length = len(section) 12 | if length > maximum: 13 | letter = section[0] 14 | maximum = length 15 | return (letter, maximum) -------------------------------------------------------------------------------- /make_a_window.py: -------------------------------------------------------------------------------- 1 | #Make a window kata 2 | #https://www.codewars.com/kata/59c03f175fb13337df00002e 3 | 4 | def make_a_window(num): 5 | output = '' 6 | for i in range(5): 7 | if i in (0,4): 8 | edge, middle, type = '-', '-', '-' 9 | n = 1 10 | elif i == 2: 11 | edge, middle, type = '|', '+', '-' 12 | n = 1 13 | else: 14 | edge, middle, type = '|', '|', '.' 15 | n=num 16 | output += (n*(edge + type*num + middle + type*num + edge +'\n')) 17 | return output[:-1] -------------------------------------------------------------------------------- /sort_the_number_sequence.py: -------------------------------------------------------------------------------- 1 | #sort the number sequence kata 2 | #https://www.codewars.com/kata/5816b76988ca9613cc00024f 3 | 4 | def sort_sequence(sequence): 5 | output, temp = [], [] 6 | for num in sequence: 7 | if num != 0: 8 | temp.append(num) 9 | else: 10 | output.append([sum(temp), sorted(temp)+[0]]) 11 | temp = [] 12 | output = sorted(output, key=lambda x: x[0]) 13 | output = list(map(lambda x: x[1], output)) 14 | return [item for sublst in output for item in sublst] 15 | 16 | -------------------------------------------------------------------------------- /find_the_parity_outlier.py: -------------------------------------------------------------------------------- 1 | #find the parity outlier kata 2 | #https://www.codewars.com/kata/5526fc09a1bbd946250002dc 3 | 4 | def add_one(x): 5 | return x + 1 6 | 7 | def modulo_by_two(x): 8 | return x % 2 9 | 10 | def find_outlier(integers): 11 | original_integers = integers 12 | integers = list(map(add_one, integers)) 13 | integers = list(map(modulo_by_two, integers)) 14 | 15 | if sum(integers) != 1: 16 | return original_integers[integers.index(0)] 17 | else: 18 | return original_integers[integers.index(1)] 19 | -------------------------------------------------------------------------------- /speed_limit.py: -------------------------------------------------------------------------------- 1 | # Speed Limit kata 2 | # https://www.codewars.com/kata/635a7827bafe03708e3e1db6/train/python 3 | 4 | def speed_limit(speed, signals): 5 | total_fine = 0 6 | for signal in signals: 7 | total_fine = total_fine + calculate_fine(speed, signal) 8 | return total_fine 9 | 10 | def calculate_fine(speed, speed_limit): 11 | fine = 0 12 | if speed - speed_limit >= 30: 13 | fine = 500 14 | elif speed - speed_limit >= 20: 15 | fine = 250 16 | elif speed - speed_limit >= 10: 17 | fine = 100 18 | return fine 19 | -------------------------------------------------------------------------------- /tetris_series_1_scoring_system.py: -------------------------------------------------------------------------------- 1 | #tetris series #1 - scoring system kata 2 | #https://www.codewars.com/kata/5da9af1142d7910001815d32 3 | 4 | import numpy as np 5 | def get_score(arr) -> int: 6 | points = np.array([40, 100, 300, 1200]) 7 | line_score = 0 8 | total = 0 9 | for line in arr: 10 | if line != 0: 11 | line_score += line 12 | total += points[line-1] 13 | if line_score >= 10: 14 | points = points + np.array([40, 100, 300, 1200]) 15 | line_score -= 10 16 | return total 17 | -------------------------------------------------------------------------------- /who_likes_it.py: -------------------------------------------------------------------------------- 1 | #Who likes it? kata 2 | #https://www.codewars.com/kata/5266876b8f4bf2da9b000362 3 | 4 | def likes(names): 5 | if names == []: 6 | return 'no one likes this' 7 | elif len(names) == 1: 8 | return names[0] + ' likes this' 9 | elif len(names) == 2: 10 | return names[0] + ' and ' + names[1] + ' like this' 11 | elif len(names) == 3: 12 | return names[0] + ', ' + names[1] + ' and ' + names[2] + ' like this' 13 | else: 14 | return names[0] + ', ' + names[1] + ' and {} others like this'.format(len(names)-2) -------------------------------------------------------------------------------- /the_alphabet_product.py: -------------------------------------------------------------------------------- 1 | ## The alphabet product 2 | ## https://www.codewars.com/kata/63b06ea0c9e1ce000f1e2407/train/python 3 | 4 | def alphabet(ns): 5 | products = [] 6 | nums = [] 7 | for index, current in enumerate(sorted(ns)): 8 | print(index, current) 9 | if current in products: 10 | index = products.index(current) 11 | products.pop(index) 12 | else: 13 | for num in nums: 14 | products.append(num * current) 15 | nums.append(current) 16 | 17 | return nums[-1] 18 | -------------------------------------------------------------------------------- /minimum_number_of_taxis.py: -------------------------------------------------------------------------------- 1 | #minimum number of taxis kata 2 | #https://www.codewars.com/kata/5e1b37bcc5772a0028c50c5d 3 | 4 | import numpy as np 5 | def min_num_taxis(requests): 6 | start_times = [time[0] for time in requests] 7 | end_times = [time[1] for time in requests] 8 | earliest_time = min(start_times) 9 | latest_time = max(end_times) 10 | 11 | taxis = np.zeros(latest_time-earliest_time) 12 | for i, start_time in enumerate(start_times): 13 | taxis[start_time-earliest_time:end_times[i]-earliest_time+1] += 1 14 | return np.max(taxis) -------------------------------------------------------------------------------- /remove_the_parantheses.py: -------------------------------------------------------------------------------- 1 | #remove the parantheses kata 2 | #https://www.codewars.com/kata/5f7c38eb54307c002a2b8cc8 3 | 4 | def remove_parentheses(s): 5 | output = '' 6 | current_level = 0 7 | for char in s: 8 | print(char) 9 | if char not in '()': 10 | if current_level == 0: 11 | output += char 12 | else: 13 | if char == '(': 14 | print(True) 15 | current_level +=1 16 | elif char == ')': 17 | current_level -= 1 18 | return output 19 | -------------------------------------------------------------------------------- /simple_fun_112_array_erasing.py: -------------------------------------------------------------------------------- 1 | #simple fun #112: array erasing kata 2 | #https://www.codewars.com/kata/589d1c08cc2e997caf0000e5 3 | 4 | from itertools import groupby, chain 5 | def array_erasing(lst): 6 | runs = 0 7 | while lst: 8 | groups = [list(g) for _, g in groupby(lst)] 9 | candidates = [i for i, g in enumerate(groups) if len(g) > 1] 10 | i = min(candidates, key=lambda k:abs(len(groups)/2-k)) if candidates else len(groups)//2 11 | lst = list(chain.from_iterable(groups[:i] + groups[i+1:])) 12 | runs += 1 13 | return runs 14 | -------------------------------------------------------------------------------- /tracking_sums_in_a_process.py: -------------------------------------------------------------------------------- 1 | #Tracking Sumns in a Process kata 2 | #https://www.codewars.com/kata/56dbb6603e5dd6543c00098d 3 | 4 | def unique_filter(arr): 5 | seen = set() 6 | return [x for x in arr if not (x in seen or seen.add(x))] 7 | 8 | def track_sum(arr): 9 | sums = [] 10 | unique = unique_filter(arr) 11 | srted = sorted(unique,reverse=True) 12 | subtracted = list(map(lambda x: x[0] - x[1], zip(srted[:-1], srted[1:]))) 13 | unique2 = unique_filter(subtracted) 14 | return [[sum(arr), sum(unique), sum(subtracted), sum(unique2)], unique2] 15 | -------------------------------------------------------------------------------- /help_the_bookseller.py: -------------------------------------------------------------------------------- 1 | #help the bookseller! kata 2 | #https://www.codewars.com/kata/54dc6f5a224c26032800005c 3 | 4 | def stock_list(listOfArt, listOfCat): 5 | listOfArt =list(map(lambda x: (x.split(' ')[0][0], int(x.split(' ')[1])), listOfArt)) 6 | totals = dict.fromkeys(listOfCat, 0) 7 | flag = True 8 | for lst in listOfArt: 9 | if lst[0] in listOfCat: 10 | totals[lst[0]] += lst[1] 11 | flag = False 12 | if flag == True: 13 | return "" 14 | return ' - '.join([f"({key} : {value})" for key, value in totals.items()]) 15 | 16 | -------------------------------------------------------------------------------- /naughty_or_nice.py: -------------------------------------------------------------------------------- 1 | #naughty or nice? kata 2 | #https://www.codewars.com/kata/52a6b34e43c2484ac10000cd 3 | 4 | def return_names(people,nice=True): 5 | output = [] 6 | for person in people: 7 | if (person['was_nice'] == True) and (nice==True): 8 | output.append(person['name']) 9 | elif (person['was_nice'] == False) and (nice==False): 10 | output.append(person['name']) 11 | return output 12 | def get_nice_names(people): 13 | return return_names(people) 14 | 15 | def get_naughty_names(people): 16 | return return_names(people, False) -------------------------------------------------------------------------------- /primordial_of_a_number.py: -------------------------------------------------------------------------------- 1 | #primordial of a number kata 2 | #https://www.codewars.com/kata/5a99a03e4a6b34bb3c000124 3 | 4 | import numpy as np 5 | 6 | def num_primorial(n): 7 | total = 1 8 | prime_number_count = 0 9 | number = 2 10 | while prime_number_count < n: 11 | if is_prime(number) == True: 12 | total *= number 13 | prime_number_count += 1 14 | number += 1 15 | 16 | return total 17 | 18 | def is_prime(num): 19 | remainders =num % np.arange(1, num+1) 20 | return len(remainders[remainders == 0]) == 2 21 | -------------------------------------------------------------------------------- /simple_fun_74_growing_plant.py: -------------------------------------------------------------------------------- 1 | #simple fun #74: growing plant kata 2 | #https://www.codewars.com/kata/58941fec8afa3618c9000184 3 | 4 | import math 5 | def growing_plant(upSpeed, downSpeed, desiredHeight): 6 | total_height = 0 7 | counter = 1 8 | days = 1 9 | 10 | while total_height < desiredHeight: 11 | if counter == 1: 12 | total_height += upSpeed 13 | counter = 2 14 | else: 15 | total_height -= downSpeed 16 | counter = 1 17 | 18 | days += 1 19 | 20 | return math.ceil(days /2) -------------------------------------------------------------------------------- /simpsons-rule.py: -------------------------------------------------------------------------------- 1 | ##SIMPSONS RULS - APPROXIMATE INTEGRATION KATA 2 | ##Given n, use simpsons rule to integrate between 0 and pi 3 | ##The function is 3/2 * sin^3x 4 | 5 | import numpy as np 6 | import math 7 | def simpson(n): 8 | fa = function(0) 9 | fb = function(math.pi) 10 | h = math.pi/n 11 | first_term_i = ((2*np.arange(1,(n/2)+1))-1)*h 12 | second_term_i = (2*np.arange(1, n/2)*h) 13 | return (fa + fb + (4*np.sum(function(first_term_i))) + 2*np.sum(function(second_term_i)))*(math.pi/(3*n)) 14 | 15 | def function(arr): 16 | return (3/2)*(np.sin(arr))**3 -------------------------------------------------------------------------------- /find-next-higher-number-with-same-1s.py: -------------------------------------------------------------------------------- 1 | ###Basics 08: Find next higher number with same Bits (1's) - codewars kata 2 | ###https://www.codewars.com/kata/56bdd0aec5dc03d7780010a5 3 | 4 | def next_higher(value): 5 | '''Returns the next number above value which has the same 6 | number of ones when displayed in binary''' 7 | initial = bin(value).split('b')[1].count('1') 8 | current_num = value+1 9 | while True: 10 | number_1s = bin(current_num).split('b')[1].count('1') 11 | if number_1s == initial: 12 | return current_num 13 | current_num += 1 -------------------------------------------------------------------------------- /flatten.py: -------------------------------------------------------------------------------- 1 | #flatten() kata 2 | #https://www.codewars.com/kata/513fa1d75e4297ba38000003 3 | 4 | def list_sorter(lst): 5 | output = [] 6 | for elem in lst: 7 | if type(elem) == list: 8 | output += list_sorter(elem) 9 | else: 10 | output.append(elem) 11 | return output 12 | 13 | def flatten(*args): 14 | output = [] 15 | for arg in [*args]: 16 | if type(arg) == list: 17 | print('list', arg) 18 | output += list_sorter(arg) 19 | else: 20 | output.append(arg) 21 | return output 22 | -------------------------------------------------------------------------------- /ip-validation.py: -------------------------------------------------------------------------------- 1 | def is_valid_IP(strng): 2 | '''Function checks the validity of IP address''' 3 | list = strng.split('.') 4 | print(list) 5 | if len(list) == 4: 6 | for item in list: 7 | if item[0] == '0' and len(item) > 1: 8 | return False 9 | elif not item.isalnum(): 10 | return False 11 | elif not item.isnumeric(): 12 | return False 13 | elif int(item) < 0 or int(item) > 255: 14 | return False 15 | return True 16 | else: 17 | return False -------------------------------------------------------------------------------- /simple_frequency_sort.py: -------------------------------------------------------------------------------- 1 | #simple frequency sort kata 2 | #https://www.codewars.com/kata/5a8d2bf60025e9163c0000bc 3 | 4 | def solve(arr): 5 | nums = set(arr) 6 | frequencies = {} 7 | for num in nums: 8 | if arr.count(num) in frequencies: 9 | frequencies[arr.count(num)].append(num) 10 | else: 11 | frequencies[arr.count(num)] = [num] 12 | output = [] 13 | for count in sorted(frequencies.keys(), reverse=True): 14 | for num in sorted(frequencies[count]): 15 | output.extend([num for y in range(count)]) 16 | return output -------------------------------------------------------------------------------- /simple_fun_162.py: -------------------------------------------------------------------------------- 1 | # Simple Fun # 162: Pairwise kata 2 | # https://www.codewars.com/kata/58afa8185eb02ea2a7000094/train/python 3 | 4 | def pairwise(arr, n): 5 | total = 0 6 | for index, num in enumerate(arr): 7 | if not isinstance(num, int): 8 | continue 9 | pair = n - num 10 | if pair in arr: 11 | pair_index = arr.index(pair) 12 | if pair_index == index: 13 | continue 14 | arr[index] = 'x' 15 | arr[pair_index] = 'x' 16 | total += (pair_index + index) 17 | return total 18 | -------------------------------------------------------------------------------- /split_and_then_add_both_sides_of_an_array_together.py: -------------------------------------------------------------------------------- 1 | #split and then add both sides of an array together kata 2 | #https://www.codewars.com/kata/5946a0a64a2c5b596500019a 3 | 4 | def split_and_add(numbers, n): 5 | while n > 0: 6 | split_index = int(len(numbers)/2) 7 | lhs_list = numbers[:split_index] 8 | rhs_list = numbers[split_index:] 9 | if len(lhs_list) < len(rhs_list): 10 | lhs_list.insert(0, 0) 11 | zipped_list = list(zip(lhs_list, rhs_list)) 12 | numbers = list(map(sum, zipped_list)) 13 | n -= 1 14 | return numbers -------------------------------------------------------------------------------- /consonant-value.py: -------------------------------------------------------------------------------- 1 | ###Consonant Value - codewars kata 2 | ###https://www.codewars.com/kata/59c633e7dcc4053512000073/python 3 | 4 | import re 5 | def solve(s): 6 | '''Returns the maximum numeric value of consonant substring in 7 | s''' 8 | s = re.sub('[aeiou]+', ' ', s) 9 | s = s.split(' ') 10 | maximum = 0 11 | alphabet = '-abcdefghijklmnopqrstuvwxyz' 12 | for group in s: 13 | total = 0 14 | for letter in group: 15 | total += alphabet.index(letter) 16 | if total > maximum: 17 | maximum = total 18 | return maximum -------------------------------------------------------------------------------- /make-the-deadfish-swim.py: -------------------------------------------------------------------------------- 1 | ###Make the Deadfish Swim - codewars kata 2 | ###https://www.codewars.com/kata/51e0007c1f9378fa810002a9/python 3 | 4 | def parse(data): 5 | '''Returns a list according to the data input''' 6 | output = 0 7 | output_array = [] 8 | for letter in data: 9 | if letter == 'i': 10 | output += 1 11 | elif letter == 'd': 12 | output -= 1 13 | elif letter == 's': 14 | output *= output 15 | elif letter == 'o': 16 | output_array.append(output) 17 | return output_array 18 | -------------------------------------------------------------------------------- /roman_numerals_decoder.py: -------------------------------------------------------------------------------- 1 | #Roman numercals decoder kata 2 | #https://www.codewars.com/kata/51b6249c4612257ac0000005 3 | 4 | def solution(roman): 5 | total = 0 6 | roman = list(roman)[::-1] 7 | dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C':100, 'D': 500, 'M': 1000} 8 | previous_value = 0 9 | for letter in roman: 10 | if dict[letter] < previous_value: 11 | total -= dict[letter] 12 | previous_value = dict[letter] 13 | else: 14 | total += dict[letter] 15 | previous_value = dict[letter] 16 | return total -------------------------------------------------------------------------------- /simple_max_digit_sum.py: -------------------------------------------------------------------------------- 1 | #simple max digit sum kata 2 | #https://www.codewars.com/kata/5b162ed4c8c47ea2f5000023 3 | 4 | def digit_sum(num): 5 | tot = 0 6 | while num > 0: 7 | tot += (num % 10) 8 | num = int(num /10) 9 | return tot 10 | 11 | def solve(n): 12 | total = digit_sum(n) 13 | largest = n 14 | print(n) 15 | i = 1 16 | while n > 0: 17 | n = n - (n % (10)**i) -1 18 | new_total = digit_sum(n) 19 | i += 1 20 | if new_total > total: 21 | total = new_total 22 | largest = n 23 | return largest -------------------------------------------------------------------------------- /cats_and_shelves.py: -------------------------------------------------------------------------------- 1 | # Cats and Shelves kata 2 | # https://www.codewars.com/kata/62c93765cef6f10030dfa92b 3 | 4 | # def solution(start, finish): 5 | # current_level, jumps = start, 0 6 | # while current_level < finish: 7 | # step = 1 8 | # if finish - current_level >= 3: 9 | # step = 3 10 | # current_level += step 11 | # jumps += 1 12 | 13 | # return jumps 14 | 15 | def solution(start, finish): 16 | steps_of_three = (finish - start) // 3 17 | steps_of_one = (finish - start) - steps_of_three*3 18 | return steps_of_three + steps_of_one 19 | -------------------------------------------------------------------------------- /last-digit-powers.py: -------------------------------------------------------------------------------- 1 | ##LAST DIGIT TO APPEAR IN SEQUENCE OF POWERS KATA 2 | ##Code below returns the last digit to appear in a 3 | ##sequence of powers (n) 4 | 5 | def LDTA(n): 6 | num_set = set() 7 | power = 1 8 | counter = 0 9 | while counter < 100: 10 | total = n**power 11 | ints = list(map(int, list(str(total)))) 12 | for num in ints: 13 | if num not in num_set: 14 | if len(num_set) == 9: 15 | return num 16 | else: 17 | num_set.add(num) 18 | counter += 1 19 | power += 1 -------------------------------------------------------------------------------- /ordered-count.py: -------------------------------------------------------------------------------- 1 | def ordered_count(input): 2 | '''Counts the number of occurences of each character and returns in tuple format''' 3 | characters = '' 4 | counts = [] 5 | 6 | for letter in input: 7 | if letter in characters: 8 | location = characters.find(letter) 9 | counts[location] = counts[location] + 1 10 | else: 11 | characters += letter 12 | counts.append(1) 13 | 14 | output = [] 15 | for i in range(0, len(characters)): 16 | output.append((characters[i], counts[i])) 17 | 18 | return output -------------------------------------------------------------------------------- /sort_and_transform.py: -------------------------------------------------------------------------------- 1 | #sort and transform kata 2 | #https://www.codewars.com/kata/57cc847e58a06b1492000264 3 | 4 | def sort_transform(arr): 5 | output_string = '' 6 | for command in ['a','b','c','d']: 7 | output_string += string_appender(output_string, arr, command) 8 | 9 | return output_string[:-1] 10 | 11 | def string_appender(strg, arr, command): 12 | if command in ('b', 'd'): 13 | arr = sorted(arr) 14 | elif command == 'c': 15 | arr = sorted(arr)[::-1] 16 | return str(chr(arr[0])) + str(chr(arr[1])) + str(chr(arr[-2])) + str(chr(arr[-1])) + '-' 17 | --------------------------------------------------------------------------------