├── .gitignore ├── 4KYU ├── next_bigger │ ├── main.py │ └── test.py └── permutations │ ├── main.py │ └── test.py ├── 5KYU ├── alphanumeric │ ├── main.py │ └── test.py ├── anagrams │ ├── main.py │ └── test.py ├── domain_name │ ├── main.py │ └── test.py ├── first_non_repeating_letter │ ├── main.py │ └── test.py ├── flatten │ ├── main.py │ └── test.py ├── generate_hashtag │ ├── main.py │ └── test.py ├── hex_string_to_RGB │ ├── main.py │ └── test.py ├── make_readable │ ├── main.py │ └── test.py ├── move_zeros │ ├── main.py │ └── test.py ├── perimeter │ ├── main.py │ └── test.py ├── pig_it │ ├── main.py │ └── test.py ├── rgb │ ├── main.py │ └── test.py ├── solution │ ├── main.py │ └── test.py ├── to_underscore │ ├── main.py │ └── test.py └── valid_ISBN10 │ ├── main.py │ └── test.py ├── 6KYU ├── alphabet_position.py ├── array_diff.py ├── binary_to_string.py ├── bowling_pins.py ├── break_camel_case.py ├── camel_case.py ├── count_bits.py ├── count_characters.py ├── count_inversions.py ├── count_smileys.py ├── digital_root.py ├── duplicate_arguments.py ├── duplicate_count.py ├── duplicate_encode.py ├── encrypt_this.py ├── fibonacci.py ├── find_it.py ├── find_missing.py ├── find_missing_letter.py ├── find_odd_names.py ├── find_outlier.py ├── find_senior.py ├── find_uniq.py ├── format_words.py ├── generate_color_rgb.py ├── gr33k_l33t.py ├── group_by_commas.py ├── hanoi.py ├── high.py ├── highest_rank.py ├── in_array.py ├── is_age_diverse.py ├── is_pangram.py ├── is_prime.py ├── is_valid_IP.py ├── is_valid_walk.py ├── kebabize.py ├── likes.py ├── longest_consec.py ├── matrix_addition.py ├── min_permutation.py ├── more_zeros.py ├── mul_table.py ├── multiplication_table.py ├── namelist.py ├── order.py ├── pascal.py ├── pascals_triangle.py ├── pyramid.py ├── remove_parentheses.py ├── solution_multiples.py ├── song_decoder.py ├── sort_array.py ├── sortme.py ├── spin_words.py ├── split_strings.py ├── sum_arrangements.py ├── sum_arrays.py ├── sum_fracts.py ├── title_case.py ├── to_camel_case.py ├── to_weird_case.py ├── tower_builder.py ├── two_sum.py ├── uncollapse.py ├── unique_in_order.py ├── up_array.py ├── valid_phone_number.py ├── vowel_code.py ├── wave.py └── what_century.py ├── 7KYU ├── accum.py ├── add.py ├── add_arrays.py ├── add_binary.py ├── add_v2.py ├── add_v3.py ├── add_v4.py ├── adjacent_element_product.py ├── all_non_consecutive.py ├── alphabet_war.py ├── alphabetic.py ├── alternate.py ├── alternate_case.py ├── annulus_area.py ├── applize.py ├── are_coprime.py ├── are_equally_strong.py ├── area_rectangle.py ├── args_count.py ├── arithmetic.py ├── arithmetic_sequence_elements.py ├── arr2bin.py ├── arr_adder.py ├── arrange.py ├── arrow_area.py ├── ascii_encrypt_decrypt.py ├── average.py ├── average_scores.py ├── averages.py ├── balanced_num.py ├── band_name_generator.py ├── battle.py ├── between_extremes.py ├── binary_array_to_number.py ├── binary_cleaner.py ├── bingo.py ├── bits_battle.py ├── boredom.py ├── broken.py ├── bumps.py ├── calc.py ├── calc_type.py ├── calculate.py ├── calculate_ratio.py ├── calculating.py ├── calculator.py ├── capitalize.py ├── capitalize_v2.py ├── capitals.py ├── case_sensitive.py ├── cat_mouse.py ├── char_concat.py ├── char_to_ascii.py ├── check_coupon.py ├── check_three_and_two.py ├── circle_area.py ├── closest_multiple_10.py ├── collision.py ├── colour_association.py ├── comes_after.py ├── compare.py ├── compare_digit_number.py ├── compress.py ├── connotation.py ├── consecutive.py ├── consecutive_letters.py ├── consonant_count.py ├── contain_all_rots.py ├── convert_hash_to_array.py ├── cool_string.py ├── count_correct_characters.py ├── count_developers.py ├── count_divisors.py ├── count_duplicates.py ├── count_languages.py ├── count_name.py ├── counter.py ├── create_dict.py ├── cube_odd.py ├── cube_sum.py ├── cyclops.py ├── day_of_week.py ├── db_sort.py ├── decode_pass.py ├── determine_sequence.py ├── diff.py ├── digitize.py ├── div_con.py ├── divisors.py ├── dominator.py ├── dont_give_me_five.py ├── double_every_other.py ├── duplicates.py ├── elevator_distance.py ├── equable_triangle.py ├── esrever.py ├── esthetic.py ├── evaporator.py ├── even_and_odd.py ├── even_chars.py ├── even_last.py ├── even_numbers.py ├── even_odd_disparity.py ├── even_or_odd.py ├── explode.py ├── expression_out.py ├── factorial.py ├── filter_list.py ├── filter_long_words.py ├── find_admin.py ├── find_array.py ├── find_deleted_number.py ├── find_digit.py ├── find_factorial.py ├── find_longest.py ├── find_page_number.py ├── find_screen_height.py ├── find_short.py ├── find_smallest.py ├── find_squares.py ├── find_sum.py ├── find_sum_v2.py ├── find_the_capitals.py ├── find_the_missing_tree.py ├── first_non_repeated.py ├── fix.py ├── fix_string_case.py ├── fizzbuzz.py ├── formatted_string.py ├── frame.py ├── freq_seq.py ├── friend.py ├── generate_pairs.py ├── generate_pairs_v2.py ├── geometric_sequence_elements.py ├── get_ages.py ├── get_average.py ├── get_count.py ├── get_decimal.py ├── get_even_numbers.py ├── get_factorial.py ├── get_larger_numbers.py ├── get_middle.py ├── get_missing_element.py ├── get_next_square.py ├── get_sum.py ├── get_sum_of_digits.py ├── get_villain_name.py ├── gimme.py ├── gimme_the_letters.py ├── gordon.py ├── gps.py ├── greet.py ├── greet_developers.py ├── halving_sum.py ├── hamming_weight.py ├── has_unique_chars.py ├── head_tail_init_last.py ├── heron.py ├── hex_hash.py ├── high_and_low.py ├── highest_value.py ├── how_many_years.py ├── incrementer.py ├── infected.py ├── initials.py ├── insert_dash.py ├── insurance.py ├── int_diff.py ├── interactive_dictionary.py ├── invite_more_women.py ├── isLeapYear.py ├── is_all_possibilities.py ├── is_anagram.py ├── is_isogram.py ├── is_it_a_num.py ├── is_it_letter.py ├── is_letter.py ├── is_narcissistic.py ├── is_negative_zero.py ├── is_perfect.py ├── is_prime.py ├── is_ruby_coming.py ├── is_same_language.py ├── is_sorted_and_how.py ├── is_square.py ├── is_triangle.py ├── is_vowel.py ├── keywords.py ├── kooka_counter.py ├── largest.py ├── largest_number.py ├── largest_pair_sum.py ├── last.py ├── least_larger.py ├── length.py ├── like_or_dislike.py ├── limit_string_length.py ├── line_numbering.py ├── longest.py ├── majority.py ├── make_backronym.py ├── make_password.py ├── maskify.py ├── max_diff.py ├── max_number.py ├── max_product.py ├── max_product_v2.py ├── max_redigit.py ├── max_sum_between_two_negatives.py ├── max_tri_sum.py ├── median.py ├── meeting.py ├── middle_me.py ├── min_max.py ├── min_min_max.py ├── min_value.py ├── mispelled.py ├── missing_no.py ├── mobile_keyboard.py ├── modify_multiply.py ├── most_frequent_item_count.py ├── move_ten.py ├── move_vowels.py ├── multiply_and_filter.py ├── mxdiflg.py ├── mygcd.py ├── mystery.py ├── nb_dig.py ├── next_prime.py ├── nickname_generator.py ├── no_ifs_no_buts.py ├── no_odds.py ├── noonerize.py ├── not_visible_cubes.py ├── nth_char.py ├── number_joy.py ├── number_of_occurrences.py ├── number_star_ladder.py ├── numbers.py ├── odd_or_even.py ├── olympic_ring.py ├── ones_complement.py ├── ones_counter.py ├── open_or_senior.py ├── order_food.py ├── ordered_count.py ├── outed.py ├── over_the_road.py ├── pairs.py ├── palindrome.py ├── pass_hash.py ├── pass_the_door_man.py ├── paul.py ├── pentagonal.py ├── person_class_bug.py ├── person_greet.py ├── power_of_two.py ├── predict_age.py ├── premier_league_standings.py ├── presents.py ├── prev_mult_of_three.py ├── product.py ├── quotable.py ├── race_podium.py ├── range_bit_count.py ├── remove.py ├── remove_.py ├── remove_chars.py ├── remove_consecutive_duplicates.py ├── remove_duplicate_words.py ├── remove_smallest.py ├── remove_url_anchor.py ├── remove_v2.py ├── remove_v3.py ├── remove_vowels.py ├── repeats.py ├── reverse.py ├── reverse_bits.py ├── reverse_letter.py ├── reverse_list.py ├── reverse_number.py ├── reverse_v1.py ├── reverse_words.py ├── roots.py ├── row_sum_odd_numbers.py ├── save.py ├── sc.py ├── score_test.py ├── second_symbol.py ├── sequence_sum.py ├── series_sum.py ├── seven_ate9.py ├── sexy_name.py ├── shades_of_grey.py ├── shorter_reverse_longer.py ├── shortest_distance.py ├── show_sequence.py ├── small_enough.py ├── smallest.py ├── smallest_product.py ├── socket_client.py ├── solution.py ├── solution_idx.py ├── solution_last_digits.py ├── solution_v2.py ├── solve.py ├── solve_remove_duplicates.py ├── solve_v2.py ├── solve_v3.py ├── sort_by_length.py ├── sort_by_value_and_index.py ├── sort_dict.py ├── sort_gift_code.py ├── sort_my_string.py ├── sort_numbers.py ├── sort_reindeer.py ├── sort_vowels.py ├── sortme.py ├── spacey.py ├── spacify.py ├── spam.py ├── special_number.py ├── split_in_parts.py ├── spoonerize.py ├── square_digits.py ├── squares.py ├── stanton_measure.py ├── sticky_calc.py ├── stray.py ├── string_hash.py ├── string_merge.py ├── strings_from_a_hash.py ├── strong_num.py ├── sum.py ├── sum_cubes.py ├── sum_digits.py ├── sum_even_numbers.py ├── sum_from_string.py ├── sum_no_duplicates.py ├── sum_of_all_arguments.py ├── sum_of_digits.py ├── sum_of_integers_in_string.py ├── sum_of_minimums.py ├── sum_or_product.py ├── sum_ppg.py ├── sum_square_even_root_odd.py ├── sum_triangular_numbers.py ├── sum_two_smallest_numbers.py ├── summy.py ├── swap.py ├── swap_v2.py ├── swap_vowel_case.py ├── switch_dict.py ├── switcher.py ├── switcheroo.py ├── t_area.py ├── task.py ├── task_trim.py ├── testit.py ├── textin.py ├── thin_or_fat.py ├── tidyNumber.py ├── time_for_milk_and_cookies.py ├── to24hourtime.py ├── to_12_hour_time.py ├── to_acronym.py ├── to_float_array.py ├── to_time.py ├── transform.py ├── triangle.py ├── trouble.py ├── two_oldest_ages.py ├── type_of_triangle.py ├── unique.py ├── unscramble_eggs.py ├── unused_digits.py ├── valid_number.py ├── valid_spacing.py ├── validate_pin.py ├── validate_word.py ├── vaporcode.py ├── vector_length.py ├── vert_and_hor_mirror.py ├── vowel_change.py ├── vowel_indices.py ├── vowel_one.py ├── vowel_to_index.py ├── well.py ├── without_last.py ├── word_splitter.py ├── word_to_bin.py ├── words_to_marks.py ├── words_to_sentence.py └── wrap.py ├── 8KYU ├── abbrev_name.py ├── add_length.py ├── approx_equals.py ├── areYouPlayingBanjo.py ├── area_or_perimeter.py ├── array_madness.py ├── arrays_merge.py ├── authenticate.py ├── ball.py ├── basic_op.py ├── better_than_average.py ├── between.py ├── bmi.py ├── bonus_time.py ├── build_string.py ├── century.py ├── check_exam.py ├── class_cat.py ├── class_ghost.py ├── classic_hello_world.py ├── close_compare.py ├── combine_names.py ├── contamination.py ├── count_by.py ├── count_positives_sum_negatives.py ├── count_sheep.py ├── cube_checker.py ├── dating_range.py ├── difference_in_ages.py ├── digitize.py ├── distance_between_points.py ├── divide_numbers.py ├── divisible_by.py ├── double_integer.py ├── each_cons.py ├── enough.py ├── ensure_question.py ├── eval_object.py ├── excluding_vat_price.py ├── fake_bin.py ├── find_difference.py ├── find_index.py ├── find_longest.py ├── find_multiples.py ├── find_needle.py ├── first.py ├── first_non_consecutive.py ├── fix_the_meerkat.py ├── format_money.py ├── generate_link.py ├── generate_range.py ├── get_planet_name.py ├── get_real_floor.py ├── get_size.py ├── get_status.py ├── goose_filter.py ├── grader.py ├── greet.py ├── greet_language.py ├── grow.py ├── include.py ├── index.py ├── invert.py ├── isDigit.py ├── is_digit.py ├── is_divisible.py ├── is_today.py ├── is_uppercase.py ├── is_vow.py ├── job_matching.py ├── litres.py ├── logical_calc.py ├── logs.py ├── lovefunc.py ├── mag_number.py ├── make_upper_case.py ├── mango.py ├── maps.py ├── merge_arrays.py ├── min_max.py ├── mouth_size.py ├── mul_by_n.py ├── multi_table.py ├── multiple_of_index.py ├── name_shuffler.py ├── name_your_python.py ├── nba_extrap.py ├── nearest_sq.py ├── next_id.py ├── no_boring_zeros.py ├── nth_even.py ├── number_to_pwr.py ├── other_angle.py ├── parse_float.py ├── past.py ├── people_with_age_drink.py ├── period_is_late.py ├── pipe_fix.py ├── points.py ├── position.py ├── powers_of_two.py ├── problem.py ├── pythagorean_triple.py ├── quarter_of.py ├── remainder.py ├── remove.py ├── remove_char.py ├── remove_every_other.py ├── remove_exclamation_marks.py ├── reverse_list.py ├── reverse_words.py ├── same_case.py ├── say_hello.py ├── shortcut.py ├── shorten_to_date.py ├── sorter.py ├── sp_eng.py ├── square.py ├── square_area.py ├── square_or_square_root.py ├── square_sum.py ├── str_count.py ├── string_to_array.py ├── stringy.py ├── sum_array.py ├── sum_mix.py ├── sum_of_differences.py ├── swap_values.py ├── switch_it_up.py ├── take.py ├── temple_strings.py ├── to_alternating_case.py ├── to_binary.py ├── to_csv_text.py ├── triple_trouble.py ├── twice_as_old.py ├── type_validation.py ├── unusual_five.py ├── update_light.py ├── validate_hello.py ├── validate_usr.py ├── warn_the_sheep.py ├── weather_info.py ├── well.py └── zero_fuel.py ├── LICENSE ├── README.md └── SQL ├── 5KYU ├── min_median_max.sql └── running_total.sql ├── 6KYU ├── calculating_batting_average.sql ├── conditional_count.sql ├── simple_exists.sql ├── simple_having.sql ├── simple_in.sql ├── simple_join_and_rank.sql ├── simple_union_all.sql ├── simple_with.sql └── top_10_customers_by_total_payments_amount.sql ├── 7KYU ├── absolute_value_and_log_to_base.sql ├── ascii_converter.sql ├── best_selling_books.sql ├── bit_length.sql ├── bytes_in_string_from_ints.sql ├── concatenating_columns.sql ├── counting_and_grouping.sql ├── countries_capitals_for_trivia_night.sql ├── create_a_function.sql ├── cube_root_and_natural_log.sql ├── easy_regex_extraction.sql ├── first_and_last_IP_in_a_network.sql ├── hello_sql_world.sql ├── inventory.sql ├── length_based_select_with_like.sql ├── maths_with_string_manipulations.sql ├── moving_values.sql ├── raise_to_the_power.sql ├── real_price.sql ├── regex_replace.sql ├── repeat_and_reverse.sql ├── right_and_left.sql ├── simple_group_by.sql ├── simple_join.sql ├── simple_join_with_count.sql ├── sql_basics_position.sql ├── sql_disorder.sql ├── sum_of_angles.sql ├── sum_of_odd_numbers.sql ├── sum_of_triangular_numbers.sql ├── support_local_products.sql ├── total_wins.sql ├── trimming_the_field.sql ├── truncating.sql ├── up_and_down.sql └── vowel_count.sql ├── 8KYU ├── adults_only.sql ├── booltoword.sql ├── century_from_year.sql ├── check_for_factor.sql ├── collect_tuition.sql ├── convert_to_hexadecimal.sql ├── easy_sql_ordering.sql ├── even_or_odd.sql ├── find_all_active_students.sql ├── grasshopper_messi_goals_function.sql ├── is_it_a_palindrome.sql ├── lowercase.sql ├── make_upper_case.sql ├── n_divisible_by_x_and_y.sql ├── number_of_cubes_with_paint.sql ├── on_the_canadian_border.sql ├── opposite_number.sql ├── quarter_of_the_year.sql ├── register_for_the_party.sql ├── remove_exclamation_marks.sql ├── remove_string_spaces.sql ├── returning_strings.sql ├── reversed_strings.sql ├── rounding_decimals.sql ├── select_columns.sql ├── simple_distinct.sql ├── simple_min_max.sql ├── simple_multiplication.sql ├── simple_sum.sql ├── simple_where_and_order_by.sql ├── sql_basics_mod.sql ├── square_root_and_log.sql ├── squaring_an_argument.sql ├── string_repeat.sql ├── summation.sql ├── terminal_game_move_function.sql └── third_angle_of_a_triangle.sql └── README.md /4KYU/permutations/main.py: -------------------------------------------------------------------------------- 1 | from itertools import permutations as pm 2 | from typing import List 3 | 4 | 5 | def permutations(string: str) -> List[str]: 6 | return sorted([''.join(i) for i in set(pm(string))]) 7 | -------------------------------------------------------------------------------- /5KYU/alphanumeric/main.py: -------------------------------------------------------------------------------- 1 | from string import ascii_lowercase 2 | 3 | 4 | def alphanumeric(password: str) -> bool: 5 | if not password: 6 | return False 7 | for i in password: 8 | if (i.lower() in ascii_lowercase) or (i in '0123456789'): 9 | continue 10 | else: 11 | return False 12 | return True 13 | -------------------------------------------------------------------------------- /5KYU/anagrams/main.py: -------------------------------------------------------------------------------- 1 | from itertools import permutations 2 | from typing import List 3 | 4 | 5 | def anagrams(word: str, words: List[str]) -> List[str]: 6 | list_of_permutations: list = list({''.join(map(str, i)) for i in set(list(permutations(word)))}) 7 | return [i for i in words if i in list_of_permutations] 8 | -------------------------------------------------------------------------------- /5KYU/domain_name/main.py: -------------------------------------------------------------------------------- 1 | def domain_name(url: str) -> str: 2 | return url.split("www.")[-1].split("//")[-1].split(".")[0] 3 | -------------------------------------------------------------------------------- /5KYU/first_non_repeating_letter/main.py: -------------------------------------------------------------------------------- 1 | def first_non_repeating_letter(s: str) -> str: 2 | if s: 3 | non_repeating = [i for i in s if s.lower().count(i.lower()) == 1] 4 | return non_repeating[0] if len(non_repeating) >= 1 else '' 5 | return '' 6 | -------------------------------------------------------------------------------- /5KYU/flatten/main.py: -------------------------------------------------------------------------------- 1 | def flatten(*args): 2 | to_flatten = lambda *n: (e for a in n for e in (to_flatten(*a) if isinstance(a, (tuple, list)) else (a,))) 3 | return list(to_flatten(*args)) 4 | -------------------------------------------------------------------------------- /5KYU/generate_hashtag/main.py: -------------------------------------------------------------------------------- 1 | def generate_hashtag(s: str): 2 | if s: 3 | hashtag = ''.join([i.title() for i in s.split()]) 4 | return f'#{hashtag}' if len(hashtag) < 140 else False 5 | return False 6 | -------------------------------------------------------------------------------- /5KYU/hex_string_to_RGB/main.py: -------------------------------------------------------------------------------- 1 | def hex_string_to_RGB(hex_string: str) -> dict: 2 | try: 3 | dict_rgb: dict = {} 4 | dict_rgb['r'] = int(hex_string[1:3], 16) 5 | dict_rgb['g'] = int(hex_string[3:5], 16) 6 | dict_rgb['b'] = int(hex_string[5:7], 16) 7 | return dict_rgb 8 | except: 9 | return {} 10 | -------------------------------------------------------------------------------- /5KYU/make_readable/main.py: -------------------------------------------------------------------------------- 1 | def make_readable(seconds): 2 | hour = seconds // 3600 3 | minutes = (seconds - hour * 3600) // 60 4 | sec = seconds - hour * 3600 - minutes * 60 5 | return ("%02d:%02d:%02d" % (hour, minutes, sec)) 6 | -------------------------------------------------------------------------------- /5KYU/move_zeros/main.py: -------------------------------------------------------------------------------- 1 | def move_zeros(array): 2 | zero = 0 3 | new_array = [] 4 | for i in array: 5 | if i == 0 and type(i) == int or type(i) == float: 6 | zero += 1 7 | else: 8 | new_array.append(i) 9 | new_array.extend([0] * zero) 10 | return new_array -------------------------------------------------------------------------------- /5KYU/move_zeros/test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import main 3 | 4 | 5 | class TestMoveZeros(unittest.TestCase): 6 | def test_one(self): 7 | """ Should moves all of the zeros to the end, preserving the order of the other elements """ 8 | self.assertEqual([1, 1, 2, 1, 3, 0, 0], main.move_zeros([1, 0, 1, 2, 0, 1, 3])) 9 | 10 | 11 | if __name__ == '__main__': 12 | unittest.main() 13 | -------------------------------------------------------------------------------- /5KYU/perimeter/main.py: -------------------------------------------------------------------------------- 1 | def perimeter(n: int) -> int: 2 | if n <= 0: 3 | return [] 4 | elif n == 1: 5 | return [0] 6 | elif n == 2: 7 | return [0, 1] 8 | D = {0: 0} 9 | result = [0, 1] 10 | for i in range(1, n + 2): 11 | result.append(result[-1] + result[-2]) 12 | D[i] = result[i] 13 | return sum(list(D.values())) * 4 14 | 15 | -------------------------------------------------------------------------------- /5KYU/perimeter/test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import main 3 | 4 | 5 | class TestPerimeter(unittest.TestCase): 6 | def test_one(self): 7 | """ Should returns perimeter of squares in a rectangle """ 8 | self.assertEqual(80, main.perimeter(5)) 9 | self.assertEqual(216, main.perimeter(7)) 10 | 11 | if __name__ == '__main__': 12 | unittest.main() 13 | -------------------------------------------------------------------------------- /5KYU/pig_it/main.py: -------------------------------------------------------------------------------- 1 | def change_word(s: str) -> str: 2 | """ Moves the first letter of each word to the end of it. """ 3 | return f'{s[1:]}{s[0]}' 4 | 5 | def pig_it(s: str) -> str: 6 | pig_text = [] 7 | for i in s.split(): 8 | if i not in ('!?'): 9 | pig_text.append(f'{change_word(i)}ay') 10 | else: pig_text.append(i) 11 | return ' '.join(pig_text) 12 | -------------------------------------------------------------------------------- /5KYU/solution/main.py: -------------------------------------------------------------------------------- 1 | def solution(array_a: list, array_b: list) -> float: 2 | if array_a == array_b: 3 | return 0.0 4 | squares_of_array_diff = [(i - j) ** 2 for i, j in zip(array_a, array_b)] 5 | return sum(squares_of_array_diff) / len(array_a) 6 | -------------------------------------------------------------------------------- /5KYU/to_underscore/main.py: -------------------------------------------------------------------------------- 1 | def to_underscore(string: str) -> str: 2 | if type(string) != str: 3 | return str(string) 4 | else: 5 | my_snake_case = '' 6 | for i in string: 7 | if i.isupper(): 8 | my_snake_case += f'_{i.lower()}' 9 | else: 10 | my_snake_case += f'{i.lower()}' 11 | return my_snake_case[1:] -------------------------------------------------------------------------------- /5KYU/valid_ISBN10/main.py: -------------------------------------------------------------------------------- 1 | def valid_ISBN10(isbn: str) -> bool: 2 | try: 3 | if (len(isbn) != 10) or ("X" in isbn and isbn[-1].isdigit()) or (isbn.isalpha()): 4 | return False 5 | return not sum([i * (10 if k == 'X' else int(k)) for i, k in enumerate(isbn, start=1)]) % 11 6 | except Exception: 7 | return False -------------------------------------------------------------------------------- /6KYU/alphabet_position.py: -------------------------------------------------------------------------------- 1 | import string 2 | 3 | 4 | def alphabet_position(s: str) -> str: 5 | """ 6 | This function return string with replace every letter with its position in the alphabet. 7 | """ 8 | dict_of_letters: dict = {letter: str(idx) for idx, letter in enumerate(string.ascii_lowercase, start=1)} 9 | return ' '.join([dict_of_letters[i] for i in s.lower() if i in dict_of_letters]) 10 | -------------------------------------------------------------------------------- /6KYU/array_diff.py: -------------------------------------------------------------------------------- 1 | def array_diff(a: list, b: list) -> list: 2 | return [i for i in a if i not in b] 3 | -------------------------------------------------------------------------------- /6KYU/binary_to_string.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/5583d268479559400d000064/ 2 | 3 | def binary_to_string(binary: str) -> str: 4 | return ''.join(chr(int(binary[i:i + 8], 2)) for i in range(0, len(binary), 8)) 5 | -------------------------------------------------------------------------------- /6KYU/break_camel_case.py: -------------------------------------------------------------------------------- 1 | def solution(s: str) -> str: 2 | if all(i.islower() for i in s): 3 | return s 4 | return ''.join(' ' + i if i.isupper() else i for i in s) 5 | -------------------------------------------------------------------------------- /6KYU/camel_case.py: -------------------------------------------------------------------------------- 1 | def camel_case(string): 2 | letter_title = string.title() 3 | total_string = letter_title.split() 4 | total_string = ''.join(total_string) 5 | return total_string -------------------------------------------------------------------------------- /6KYU/count_bits.py: -------------------------------------------------------------------------------- 1 | def count_bits(n): 2 | n_bin = bin(n) 3 | for _ in range(len(n_bin)): 4 | count = n_bin.count('1') 5 | return count -------------------------------------------------------------------------------- /6KYU/count_characters.py: -------------------------------------------------------------------------------- 1 | def count(string: str) -> dict: 2 | dict_of_letter = {} 3 | for i in string: 4 | if i not in dict_of_letter: 5 | dict_of_letter[i] = 1 6 | else: 7 | dict_of_letter[i] += 1 8 | return dict_of_letter 9 | -------------------------------------------------------------------------------- /6KYU/count_smileys.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | 4 | def count_smileys(arr: list) -> int: 5 | """ 6 | This function returns the total number of smiling faces. 7 | """ 8 | return len(re.findall('[:;][-~]?[)D]', ' '.join(arr))) 9 | -------------------------------------------------------------------------------- /6KYU/digital_root.py: -------------------------------------------------------------------------------- 1 | def digital_root(n: int) -> int: 2 | """ This function returns recursive sum of all the digits in a number. """ 3 | if n < 10: 4 | return n 5 | return (digital_root(sum(map(int, str(n))))) -------------------------------------------------------------------------------- /6KYU/duplicate_arguments.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/520d9c27e9940532eb00018e/ 2 | 3 | from collections import Counter 4 | 5 | 6 | def solution(*args) -> bool: 7 | if not args: 8 | return False 9 | counter = Counter(args) 10 | return max(list(counter.values())) > 1 11 | -------------------------------------------------------------------------------- /6KYU/duplicate_encode.py: -------------------------------------------------------------------------------- 1 | def duplicate_encode(s: str) -> str: 2 | return f'{"".join("(" if s.lower().count(i.lower()) == 1 else ")" for i in s)}' 3 | -------------------------------------------------------------------------------- /6KYU/encrypt_this.py: -------------------------------------------------------------------------------- 1 | def encrypt_this(text): 2 | myStr = text.split() 3 | for i, letter in enumerate(myStr): 4 | if len(letter) == 1: 5 | myStr[i] = str(ord(letter)) 6 | elif len(letter) == 2: 7 | myStr[i] = str(ord(letter[0]))+letter[1] 8 | else: 9 | myStr[i] = str(ord(letter[0])) + letter[-1] + letter[2:-1] + letter[1] 10 | return ' '.join(myStr) -------------------------------------------------------------------------------- /6KYU/fibonacci.py: -------------------------------------------------------------------------------- 1 | def fibonacci(n: int) -> list: 2 | if n <= 0: 3 | return [] 4 | elif n == 1: 5 | return [0] 6 | elif n == 2: 7 | return [0, 1] 8 | D = {0: 0} 9 | result = [0, 1] 10 | for i in range(1, n): 11 | result.append(result[-1] + result[-2]) 12 | D[i] = result[i] 13 | return list(D.values()) 14 | 15 | fibonacci(6) 16 | -------------------------------------------------------------------------------- /6KYU/find_it.py: -------------------------------------------------------------------------------- 1 | def find_it(x: list) -> int: 2 | dict_num = {} 3 | for item in x: 4 | if item in dict_num: 5 | dict_num[item] += 1 6 | else: 7 | dict_num[item] = 1 8 | for el in dict_num: 9 | if dict_num[el] % 2 != 0: 10 | return el -------------------------------------------------------------------------------- /6KYU/find_missing.py: -------------------------------------------------------------------------------- 1 | def find_missing(sequence: list) -> int: 2 | d = (sequence[-1] - sequence[0]) // len(sequence) 3 | for i in range(len(sequence) - 1): 4 | if sequence[i + 1] - sequence[i] != d: 5 | return sequence[i] + d 6 | -------------------------------------------------------------------------------- /6KYU/find_odd_names.py: -------------------------------------------------------------------------------- 1 | def is_odd(name: str) -> bool: 2 | return True if sum(ord(i) for i in name) % 2 else False 3 | 4 | def find_odd_names(lst: list) -> list: 5 | return [i for i in lst if is_odd(i['firstName'])] 6 | -------------------------------------------------------------------------------- /6KYU/find_outlier.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | def find_outlier(integers: List[int]) -> int: 5 | odd, even = [i for i in integers if not i % 2], [i for i in integers if i % 2] 6 | if len(odd) > len(even): 7 | return int(''.join(map(str, even))) 8 | else: 9 | return int(''.join(map(str, odd))) 10 | -------------------------------------------------------------------------------- /6KYU/find_senior.py: -------------------------------------------------------------------------------- 1 | def find_senior(lst: list) -> list: 2 | return ([i for i in lst if i['age'] == max([i['age'] for i in lst])]) 3 | -------------------------------------------------------------------------------- /6KYU/find_uniq.py: -------------------------------------------------------------------------------- 1 | def find_uniq(arr: list) -> int: 2 | """ This function returns the unique number from 'arr'. """ 3 | count_min = arr.count(min(arr)) 4 | count_max = arr.count(max(arr)) 5 | if count_min == 1: 6 | return min(arr) 7 | return max(arr) -------------------------------------------------------------------------------- /6KYU/group_by_commas.py: -------------------------------------------------------------------------------- 1 | def group_by_commas(n: int) -> str: 2 | """ This function returns a string that is the decimal representation 3 | of the number grouped by commas after every 3 digits """ 4 | return f'{n:,}' -------------------------------------------------------------------------------- /6KYU/hanoi.py: -------------------------------------------------------------------------------- 1 | def hanoi(disks: int) -> int: 2 | """ 3 | The minimum number of moves to complete a Tower of Hanoi is known as a Mersenne Number. 4 | """ 5 | return 2 ** disks - 1 6 | -------------------------------------------------------------------------------- /6KYU/high.py: -------------------------------------------------------------------------------- 1 | from string import ascii_lowercase 2 | 3 | 4 | def get_sum_value_letter(word: str) -> int: 5 | eng_lowercase: dict = {v:k for k, v in enumerate(ascii_lowercase, start=1)} 6 | return sum(eng_lowercase[letter] for letter in word) 7 | 8 | 9 | def high(string: str) -> str: 10 | """ This function returns highest scoring word. """ 11 | return max(string.split(), key=get_sum_value_letter) 12 | -------------------------------------------------------------------------------- /6KYU/in_array.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/550554fd08b86f84fe000a58/ 2 | 3 | def in_array(array1: list, array2: list) -> list: 4 | words: list = [] 5 | for i in array1: 6 | for j in array2: 7 | if (i in j) and (i not in words): 8 | words.append(i) 9 | return sorted(words) 10 | -------------------------------------------------------------------------------- /6KYU/is_pangram.py: -------------------------------------------------------------------------------- 1 | def is_pangram(s: str) -> bool: 2 | letter_from_s: dict = {} 3 | for i in s.lower(): 4 | if i not in letter_from_s: 5 | if i.isalpha(): 6 | letter_from_s[i] = 1 7 | else: 8 | letter_from_s[i] += 1 9 | return len(letter_from_s) == 26 10 | -------------------------------------------------------------------------------- /6KYU/is_prime.py: -------------------------------------------------------------------------------- 1 | def is_prime(num): 2 | if num <= 1: 3 | return False 4 | d = 2 5 | while d * d <= num and num % d != 0: 6 | d += 1 7 | return d * d > num -------------------------------------------------------------------------------- /6KYU/is_valid_IP.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | 4 | def is_valid_IP(string: str) -> bool: 5 | valid_ip = re.match(r"^(25[0-5]|2[0-4][0-9]|[1]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[1]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[1]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[1]?[0-9][0-9]?)$", string) 6 | return True if valid_ip else False 7 | -------------------------------------------------------------------------------- /6KYU/is_valid_walk.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | def is_valid_walk(walk: List[str]) -> bool: 5 | if len(walk) != 10: 6 | return False 7 | string_of_my_walk_rout = ''.join(walk) 8 | if string_of_my_walk_rout.count('n') == string_of_my_walk_rout.count('s') and string_of_my_walk_rout.count('e') == string_of_my_walk_rout.count('w'): 9 | return True 10 | return False 11 | -------------------------------------------------------------------------------- /6KYU/kebabize.py: -------------------------------------------------------------------------------- 1 | def kebabize(string): 2 | myString = '' 3 | for letter in string: 4 | if not letter.isdigit(): 5 | myString += letter 6 | for letter_myString in myString: 7 | if letter_myString.istitle(): 8 | myString = myString.replace(letter_myString, '-' + letter_myString.lower()) 9 | if myString.startswith('-'): 10 | return myString[1:] 11 | return myString -------------------------------------------------------------------------------- /6KYU/longest_consec.py: -------------------------------------------------------------------------------- 1 | def longest_consec(arr: list, k: int) -> str: 2 | if not arr or k > len(arr) or k <= 0: 3 | return '' 4 | consecutive_strings: list = [] 5 | for i in range(len(arr) - k + 1): 6 | consecutive_strings.append(f'{"".join(arr[i:k+i])}') 7 | return max(consecutive_strings, key=len) 8 | -------------------------------------------------------------------------------- /6KYU/more_zeros.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/5d41e16d8bad42002208fe1a/ 2 | 3 | def more_zeros(s: str) -> list: 4 | bin_value: list = [] 5 | for i in s: 6 | binary_ord = bin(ord(i))[2:] 7 | if binary_ord not in bin_value and binary_ord.count('0') > binary_ord.count('1'): 8 | bin_value.append(binary_ord) 9 | return [chr(int(i, 2)) for i in bin_value] 10 | -------------------------------------------------------------------------------- /6KYU/multiplication_table.py: -------------------------------------------------------------------------------- 1 | def multiplication_table(size: int) -> list: 2 | result = [] 3 | for i in range(1, size + 1): 4 | row = [] 5 | for j in range(1, size + 1): 6 | row.append(i * j) 7 | result.append(row) 8 | return result 9 | -------------------------------------------------------------------------------- /6KYU/order.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/55c45be3b2079eccff00010f/ 2 | 3 | import re 4 | 5 | def order(sentence: str) -> str: 6 | order_and_word: dict = {} 7 | for word in sentence.split(): 8 | order = int(re.search(r'\d', word).group()) 9 | order_and_word[order] = word 10 | return ' '.join([v for k, v in sorted(order_and_word.items())]) 11 | -------------------------------------------------------------------------------- /6KYU/pascal.py: -------------------------------------------------------------------------------- 1 | from math import factorial 2 | 3 | 4 | def pascal(n: int) -> list: 5 | triangle = [] 6 | for i in range(n): 7 | row = [] 8 | for j in range(i + 1): 9 | row.append(factorial(i)//(factorial(j)*factorial(i - j))) 10 | triangle.append(row) 11 | return triangle 12 | -------------------------------------------------------------------------------- /6KYU/pascals_triangle.py: -------------------------------------------------------------------------------- 1 | from math import factorial 2 | 3 | 4 | def pascals_triangle(n: int) -> list: 5 | triangle = [] 6 | for i in range(n): 7 | for j in range(i + 1): 8 | triangle.append(factorial(i)//(factorial(j)*factorial(i - j))) 9 | return triangle 10 | -------------------------------------------------------------------------------- /6KYU/pyramid.py: -------------------------------------------------------------------------------- 1 | def pyramid(n: int) -> list: 2 | if n < 1: 3 | return [] 4 | my_pyramid: list = [] 5 | for i in range(1, n+1): 6 | my_pyramid.append([1]*i) 7 | return my_pyramid 8 | -------------------------------------------------------------------------------- /6KYU/remove_parentheses.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/5f7c38eb54307c002a2b8cc8/ 2 | 3 | from re import findall, sub 4 | 5 | 6 | def remove_parentheses(s: str) -> str: 7 | while findall(r"\([^()]*\)", s): 8 | s = sub(r"\([^()]*\)", "", s) 9 | return s 10 | -------------------------------------------------------------------------------- /6KYU/solution_multiples.py: -------------------------------------------------------------------------------- 1 | def solution(number: int) -> int: 2 | return sum([i for i in range (2, number) if not i % 3 or not i % 5]) 3 | -------------------------------------------------------------------------------- /6KYU/song_decoder.py: -------------------------------------------------------------------------------- 1 | def song_decoder(song: str) -> str: 2 | return ' '.join(song.replace("WUB", ' ').split()) 3 | -------------------------------------------------------------------------------- /6KYU/sortme.py: -------------------------------------------------------------------------------- 1 | def sortme(words: list) -> list: 2 | return sorted(words, key=lambda x: x.lower()) 3 | -------------------------------------------------------------------------------- /6KYU/spin_words.py: -------------------------------------------------------------------------------- 1 | def spin_words(sentence: str) -> str: 2 | list_of_words = [] 3 | for i in sentence.split(): 4 | if len(i) >= 5: 5 | list_of_words.append(i[::-1]) 6 | else: 7 | list_of_words.append(i) 8 | return ' '.join(list_of_words) 9 | -------------------------------------------------------------------------------- /6KYU/split_strings.py: -------------------------------------------------------------------------------- 1 | def solution(s: str) -> list: 2 | if len(s) % 2: 3 | s += "_" 4 | every_two_characters: list = [] 5 | while s: 6 | every_two_characters.append(s[:2]) 7 | s = s[2:] 8 | return every_two_characters 9 | -------------------------------------------------------------------------------- /6KYU/to_weird_case.py: -------------------------------------------------------------------------------- 1 | def swapcase_letter(string: str) -> str: 2 | return ''.join([l.lower() if i % 2 else l.upper() for i, l in enumerate(string)]) 3 | 4 | def to_weird_case(string: str) -> str: 5 | return ' '.join(swapcase_letter(word) for word in string.split()) 6 | -------------------------------------------------------------------------------- /6KYU/tower_builder.py: -------------------------------------------------------------------------------- 1 | def tower_builder(n_floors: int) -> list: 2 | tower: list = [] 3 | level: str = '' 4 | for i in range(n_floors): 5 | star = "*" * (i*2+1) 6 | space = " " * (n_floors-i-1) 7 | level = space + star + space 8 | tower.append(level) 9 | return tower 10 | -------------------------------------------------------------------------------- /6KYU/uncollapse.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | 4 | def uncollapse(digits: str) -> str: 5 | result = re.findall(r'(zero)|(one)|(two)|(three)|(four)|(five)|(six)|(seven)|(eight)|(nine)|(ten)', digits) 6 | return ' '.join([j for i in result for j in i if j]) 7 | -------------------------------------------------------------------------------- /6KYU/unique_in_order.py: -------------------------------------------------------------------------------- 1 | def unique_in_order(iterable): 2 | unique = [] 3 | current_letter = None 4 | for i in iterable: 5 | if i != current_letter: 6 | unique.append(i) 7 | current_letter = i 8 | return (unique) -------------------------------------------------------------------------------- /6KYU/valid_phone_number.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | 4 | def validPhoneNumber(phoneNumber: str) -> bool: 5 | result = re.findall(r"^\(\d{3}\)\s\d{3}-\d{4}$", phoneNumber) 6 | return len(result) >= 1 -------------------------------------------------------------------------------- /6KYU/wave.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/58f5c63f1e26ecda7e000029/ 2 | 3 | def wave(people: str) -> list: 4 | """ This function turns a string into a Mexican Wave """ 5 | wave: list = [] 6 | for i in range(len(people)): 7 | if people[i].isalpha(): 8 | wave.append(people[:i] + people[i].upper() + people[i+1:]) 9 | return wave 10 | -------------------------------------------------------------------------------- /7KYU/accum.py: -------------------------------------------------------------------------------- 1 | def accum(s: str) -> str: 2 | list_letter: list = [] 3 | for i, k in enumerate(range(len(s)), start=1): 4 | list_letter.append(s[i-1]*i) 5 | my_str = ' '.join(list_letter) 6 | return '-'.join(w.capitalize() for w in my_str.split()) 7 | -------------------------------------------------------------------------------- /7KYU/add.py: -------------------------------------------------------------------------------- 1 | def add(a): 2 | def add2(b): 3 | return a + b 4 | return add2 5 | -------------------------------------------------------------------------------- /7KYU/add_arrays.py: -------------------------------------------------------------------------------- 1 | def add_arrays(array1: list, array2: list) -> list: 2 | if len(array1) == len(array2): 3 | return [i + j for i, j in zip(array1, array2)] 4 | raise Exception("Input arguments are not of equal length") 5 | -------------------------------------------------------------------------------- /7KYU/add_binary.py: -------------------------------------------------------------------------------- 1 | def add_binary(a: int, b: int) -> str: 2 | """ 3 | This function: add binary. 4 | """ 5 | return (bin(a + b))[2:] 6 | -------------------------------------------------------------------------------- /7KYU/add_v2.py: -------------------------------------------------------------------------------- 1 | add = lambda a: lambda b: a + b 2 | -------------------------------------------------------------------------------- /7KYU/add_v3.py: -------------------------------------------------------------------------------- 1 | def add(num1: int, num2: int) -> int: 2 | num1: str = str(num1) 3 | num2: str = str(num2) 4 | if len(num1) < len(num2): 5 | num1 = num1.zfill(len(num2)) 6 | else: 7 | num2 = num2.zfill(len(num1)) 8 | my_sum: str = '' 9 | for i in zip(num1, num2): 10 | my_sum += str(sum(int(j) for j in i)) 11 | return int(my_sum) -------------------------------------------------------------------------------- /7KYU/add_v4.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/555de49a04b7d1c13c00000e/ 2 | 3 | def add(*args) -> int: 4 | return round(sum(k / i for i, k in enumerate(args, 1))) 5 | -------------------------------------------------------------------------------- /7KYU/adjacent_element_product.py: -------------------------------------------------------------------------------- 1 | def adjacent_element_product(array: list) -> int: 2 | return max([array[i] * array[i + 1] for i in range(len(array) - 1)]) -------------------------------------------------------------------------------- /7KYU/alphabetic.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/5a8059b1fd577709860000f6/ 2 | 3 | 4 | def alphabetic(s: str) -> bool: 5 | """ This function takes an input string of lowercase letters and returns true/false depending on whether the string is in alphabetical order or not. """ 6 | return s == ''.join(sorted([i for i in s], key=str.lower)) 7 | -------------------------------------------------------------------------------- /7KYU/alternate.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/62a611067274990047f431a8/ 2 | 3 | def alternate(n: int, first_value, second_value) -> list: 4 | final_list: list = [] 5 | 6 | while len(final_list) < n: 7 | final_list.append(first_value) 8 | if len(final_list) < n: 9 | final_list.append(second_value) 10 | 11 | return final_list 12 | -------------------------------------------------------------------------------- /7KYU/alternate_case.py: -------------------------------------------------------------------------------- 1 | def alternate_case(s: str) -> str: 2 | alternate_s = '' 3 | for i in s: 4 | if i.islower(): 5 | alternate_s += i.upper() 6 | else: 7 | alternate_s += i.lower() 8 | return alternate_s 9 | -------------------------------------------------------------------------------- /7KYU/annulus_area.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | 4 | def annulus_area(r: int) -> float: 5 | return round(math.pi * ((r / 2) ** 2), 2) -------------------------------------------------------------------------------- /7KYU/applize.py: -------------------------------------------------------------------------------- 1 | def i(word: str) -> str: 2 | VOWELS = 'AaEeIiOoUu' 3 | if len(word) == 0 or word.startswith('I') or word[0].islower(): 4 | return 'Invalid word' 5 | count_vowels = len([i for i in word if i in VOWELS]) 6 | if count_vowels >= len(word) - count_vowels: 7 | return 'Invalid word' 8 | return f'{"i" + word}' 9 | -------------------------------------------------------------------------------- /7KYU/are_coprime.py: -------------------------------------------------------------------------------- 1 | def are_coprime(n: int, m: int) -> bool: 2 | factors_n: set = set(i for i in range(1, n+1) if not n % i) 3 | factors_m: set = set(i for i in range(1, m+1) if not m % i) 4 | return True if len(factors_n & factors_m) == 1 else False 5 | -------------------------------------------------------------------------------- /7KYU/are_equally_strong.py: -------------------------------------------------------------------------------- 1 | def are_equally_strong(your_left: int, your_right: int, friends_left: int, friends_right: int) -> bool: 2 | return (your_left == friends_left or your_left == friends_right) and (your_right == friends_right or your_right == friends_left) -------------------------------------------------------------------------------- /7KYU/area_rectangle.py: -------------------------------------------------------------------------------- 1 | from typing import Union 2 | 3 | 4 | def area(diagonal: int, side_a: int) -> Union[int, float]: 5 | if diagonal <= side_a: 6 | return "Not a rectangle" 7 | side_b = (diagonal ** 2 - side_a ** 2) ** 0.5 8 | area_rectangle = side_a * side_b 9 | return round(area_rectangle, 2) 10 | -------------------------------------------------------------------------------- /7KYU/args_count.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/5c44b0b200ce187106452139/ 2 | 3 | """ returns the count of passed arguments """ 4 | args_count = lambda *args, **kwargs: len(args) + len(kwargs) -------------------------------------------------------------------------------- /7KYU/arithmetic.py: -------------------------------------------------------------------------------- 1 | def arithmetic(a, b, operator): 2 | op: dict = {'add': '+', 3 | 'subtract': '-', 4 | 'multiply': '*', 5 | 'divide': '/'} 6 | return eval(f'{a}{op.get(operator)}{b}') 7 | -------------------------------------------------------------------------------- /7KYU/arithmetic_sequence_elements.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/55caf1fd8063ddfa8e000018/ 2 | 3 | 4 | def arithmetic_sequence_elements(a, d, n) -> str: 5 | return ', '.join(map(str, [a + d * (i - 1) for i in range(1, n + 1)])) 6 | -------------------------------------------------------------------------------- /7KYU/arr2bin.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/559576d984d6962f8c00003c/ 2 | 3 | def arr2bin(arr: list) -> str or bool: 4 | if not arr: 5 | return '0' 6 | if any(type(i) != int for i in arr): 7 | return False 8 | else: 9 | return bin(sum(arr))[2:] 10 | -------------------------------------------------------------------------------- /7KYU/arr_adder.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/59778cb1b061e877c50000cc/ 2 | 3 | def arr_adder(arr: list) -> str: 4 | return ' '.join(''.join(i) for i in zip(*arr)) 5 | -------------------------------------------------------------------------------- /7KYU/arrow_area.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/589478160c0f8a40870000bc/ 2 | 3 | from math import sqrt 4 | 5 | 6 | def arrow_area(a: int, b: int): 7 | triangle_side = sqrt(pow(a, 2) + pow(b, 2)) / 2 8 | return round(b / 4 * sqrt(4 * pow(triangle_side, 2) - pow(b, 2)), 2) 9 | -------------------------------------------------------------------------------- /7KYU/ascii_encrypt_decrypt.py: -------------------------------------------------------------------------------- 1 | # https://www.codewars.com/kata/56e9ac87c3e7d512bc001363/ 2 | 3 | def ascii_encrypt(plaintext: str) -> str: 4 | plaintext_encrypt: str = ''.join(chr(ord(k)+i) for i, k in enumerate(plaintext)) 5 | return plaintext_encrypt 6 | 7 | def ascii_decrypt(plaintext: str) -> str: 8 | plaintext_decrypt: str = ''.join(chr(ord(k)-i) for i, k in enumerate(plaintext)) 9 | return plaintext_decrypt -------------------------------------------------------------------------------- /7KYU/average.py: -------------------------------------------------------------------------------- 1 | from numpy import average as np_average 2 | 3 | class Calculator: 4 | @staticmethod 5 | def average(*args): 6 | return np_average(args) if args else 0 -------------------------------------------------------------------------------- /7KYU/average_scores.py: -------------------------------------------------------------------------------- 1 | def average(array: list) -> int: 2 | return round(sum(array)/len(array)) 3 | -------------------------------------------------------------------------------- /7KYU/averages.py: -------------------------------------------------------------------------------- 1 | def averages(arr: list) -> list: 2 | if arr is None: 3 | return [] 4 | my_avg = [] 5 | for i in range(len(arr) - 1): 6 | my_avg.append((arr[i] + arr[i + 1]) / 2) 7 | return my_avg -------------------------------------------------------------------------------- /7KYU/band_name_generator.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/59727ff285281a44e3000011/ 2 | 3 | def band_name_generator(name: str) -> str: 4 | if name[0].lower() != name[-1].lower(): 5 | return f"The {name.capitalize()}" 6 | else: 7 | return f"{name.capitalize()}{name[1:]}" 8 | -------------------------------------------------------------------------------- /7KYU/between_extremes.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/56d19b2ac05aed1a20000430/ 2 | 3 | def between_extremes(numbers: list) -> int: 4 | """ 5 | This function returns the difference between the largest and smallest values. 6 | """ 7 | return max(numbers) - min(numbers) 8 | -------------------------------------------------------------------------------- /7KYU/binary_array_to_number.py: -------------------------------------------------------------------------------- 1 | def binary_array_to_number(arr): 2 | string_number = "".join(str(x) for x in arr) 3 | result = int("".join(str(i) for i in string_number), 2) 4 | return result -------------------------------------------------------------------------------- /7KYU/binary_cleaner.py: -------------------------------------------------------------------------------- 1 | def binary_cleaner(seq: list) -> tuple: 2 | list_with_zero_and_one = [] 3 | list_with_idx_element_greater_one = [] 4 | for i, k in enumerate(seq): 5 | if k <= 1: 6 | list_with_zero_and_one.append(k) 7 | else: 8 | list_with_idx_element_greater_one.append(i) 9 | return list_with_zero_and_one, list_with_idx_element_greater_one 10 | -------------------------------------------------------------------------------- /7KYU/bingo.py: -------------------------------------------------------------------------------- 1 | # https://www.codewars.com/kata/5a1ee4dfffe75f0fcb000145/ 2 | 3 | 4 | def bingo(array: list) -> str: 5 | return 'WIN' if {2,7,9,14,15}.issubset(set(array)) else 'LOSE' 6 | -------------------------------------------------------------------------------- /7KYU/bits_battle.py: -------------------------------------------------------------------------------- 1 | def bits_battle(num: list) -> str: 2 | count_one = sum([bin(i)[2:].count('1') for i in num if i % 2]) 3 | count_zero = sum([bin(i)[2:].count('0') for i in num if not i % 2]) 4 | if count_one > count_zero: 5 | return 'odds win' 6 | elif count_one < count_zero: 7 | return 'evens win' 8 | else: 9 | return 'tie' -------------------------------------------------------------------------------- /7KYU/broken.py: -------------------------------------------------------------------------------- 1 | def broken(inp: str) -> str: 2 | my_str = '' 3 | for i in inp: 4 | if i == '0': 5 | my_str += '1' 6 | elif i == '1': 7 | my_str += '0' 8 | return my_str 9 | -------------------------------------------------------------------------------- /7KYU/bumps.py: -------------------------------------------------------------------------------- 1 | def bumps(road: str) -> str: 2 | return "Woohoo!" if road.count('n') <= 15 else "Car Dead" 3 | -------------------------------------------------------------------------------- /7KYU/calc.py: -------------------------------------------------------------------------------- 1 | def calc(s: str) -> int: 2 | total1 = '' 3 | for i in s: 4 | total1 += str(ord(i)) 5 | total2 = '' 6 | for k in total1: 7 | if k == str(7): 8 | total2 += str(1) 9 | else: 10 | total2 += k 11 | return sum([int(i) for i in total1]) - sum([int(i) for i in total2]) 12 | -------------------------------------------------------------------------------- /7KYU/calc_type.py: -------------------------------------------------------------------------------- 1 | from operator import add, sub, mul, truediv 2 | 3 | 4 | def calc_type(a, b, res) -> str: 5 | operations: dict = {'addition': add, 6 | 'subtraction': sub, 7 | 'multiplication': mul, 8 | 'division': truediv 9 | } 10 | return ', '.join([k for k, v in operations.items() if v(a, b) == res]) 11 | -------------------------------------------------------------------------------- /7KYU/calculating.py: -------------------------------------------------------------------------------- 1 | def calculate(s: str) -> str: 2 | math_str = s.replace('plus', '+').replace('minus', '-') 3 | return str(eval(math_str)) 4 | -------------------------------------------------------------------------------- /7KYU/capitalize.py: -------------------------------------------------------------------------------- 1 | def capitalize(s: str) -> list: 2 | string_one: str = '' 3 | string_two: str = '' 4 | for i, k in enumerate(s): 5 | if not i % 2: 6 | string_one += k.upper() 7 | string_two += k 8 | else: 9 | string_one += k 10 | string_two += k.upper() 11 | return [string_one, string_two] 12 | -------------------------------------------------------------------------------- /7KYU/capitalize_v2.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/59cfc09a86a6fdf6df0000f1/ 2 | 3 | def capitalize(s: str, ind: list) -> str: 4 | return ''.join(k.upper() if i in ind else k for i, k in enumerate(s)) 5 | -------------------------------------------------------------------------------- /7KYU/capitals.py: -------------------------------------------------------------------------------- 1 | def capitals(word: str) -> list: 2 | return [i for i, k in enumerate(word) if k.isupper()] 3 | -------------------------------------------------------------------------------- /7KYU/case_sensitive.py: -------------------------------------------------------------------------------- 1 | def case_sensitive(s: str) -> list: 2 | upper_letter = [i for i in s if i.isupper()] 3 | if len(upper_letter) < 1: 4 | return [True, []] 5 | return [False, upper_letter] 6 | -------------------------------------------------------------------------------- /7KYU/cat_mouse.py: -------------------------------------------------------------------------------- 1 | def cat_mouse(x: str) -> str: 2 | return 'Escaped!' if x.count('.') >= 4 else 'Caught!' 3 | -------------------------------------------------------------------------------- /7KYU/char_concat.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/55147ff29cd40b43c600058b/ 2 | 3 | def char_concat(word: str) -> str: 4 | result = str() 5 | for i in range(1, len(word) // 2 + 1): 6 | result += word[i - 1] 7 | result += word[len(word) - i] 8 | result += str(i) 9 | return result 10 | -------------------------------------------------------------------------------- /7KYU/check_three_and_two.py: -------------------------------------------------------------------------------- 1 | import collections 2 | 3 | 4 | def check_three_and_two(array: list) -> bool: 5 | count_letter = collections.Counter() 6 | for letter in array: 7 | count_letter[letter] += 1 8 | if max(count_letter.values()) == 3 and min(count_letter.values()) == 2: 9 | return True 10 | return False 11 | -------------------------------------------------------------------------------- /7KYU/circle_area.py: -------------------------------------------------------------------------------- 1 | from math import pi 2 | 3 | def circle_area(r): 4 | try: 5 | if r < 0: 6 | return False 7 | return round(pi * pow(r, 2), 2) 8 | except TypeError: 9 | return False -------------------------------------------------------------------------------- /7KYU/closest_multiple_10.py: -------------------------------------------------------------------------------- 1 | # https://www.codewars.com/kata/58249d08b81f70a2fc0001a4/ 2 | 3 | def closest_multiple_10(i: int) -> int: 4 | return round(i/10) * 10 -------------------------------------------------------------------------------- /7KYU/collision.py: -------------------------------------------------------------------------------- 1 | def collision(x1, y1, radius1, x2, y2, radius2) -> bool: 2 | if ((x1 - x2) ** 2 + (y1 - y2) ** 2) <= (radius1 + radius2) ** 2: 3 | return True 4 | return False 5 | -------------------------------------------------------------------------------- /7KYU/colour_association.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/56d6b7e43e8186c228000637/ 2 | 3 | 4 | def colour_association(arr: list) -> list: 5 | return [{i[0]: i[1]} for i in arr] 6 | -------------------------------------------------------------------------------- /7KYU/comes_after.py: -------------------------------------------------------------------------------- 1 | def comes_after(st: str, l: str) -> str: 2 | s: str = '' 3 | for i in range(len(st)-1): 4 | if st[i].lower() == l.lower() and st[i+1].isalpha(): 5 | s += st[i+1] 6 | return s -------------------------------------------------------------------------------- /7KYU/compare.py: -------------------------------------------------------------------------------- 1 | def compare(s1: str, s2: str) -> bool: 2 | def get_sum(s): 3 | return sum(ord(c) for c in s.upper()) if s and s.isalpha() else None 4 | return get_sum(s1) == get_sum(s2) -------------------------------------------------------------------------------- /7KYU/compare_digit_number.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/63f3c61dd27f3c07cc7978de/ 2 | 3 | def compare(a: int, b: int) -> str: 4 | len_intersection: int = len(set(str(a)) & set(str(b))) 5 | if (len_intersection == 2) or (a == b): 6 | return '100%' 7 | elif len_intersection == 1: 8 | return '50%' 9 | else: 10 | return '0%' -------------------------------------------------------------------------------- /7KYU/compress.py: -------------------------------------------------------------------------------- 1 | def compress(sentence: str) -> str: 2 | word: list = [] 3 | for i in sentence.lower().split(): 4 | if i not in word: 5 | word.append(i) 6 | return ''.join([str(word.index(i)) for i in sentence.lower().split()]) 7 | -------------------------------------------------------------------------------- /7KYU/connotation.py: -------------------------------------------------------------------------------- 1 | from string import ascii_lowercase 2 | 3 | 4 | def connotation(strng: str) -> bool: 5 | FIRST_HALF = len([i for i in strng.split() if i[0].lower() in ascii_lowercase[:13]]) 6 | SECOND_HALF = len([i for i in strng.split() if i[0].lower() in ascii_lowercase[13:]]) 7 | return True if FIRST_HALF >= SECOND_HALF else False 8 | -------------------------------------------------------------------------------- /7KYU/consecutive.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/559cc2d2b802a5c94700000c/ 2 | 3 | 4 | from typing import List 5 | 6 | 7 | def consecutive(arr: List[int]) -> int: 8 | if arr: 9 | return len(set(range(min(arr), max(arr) + 1)) - set(arr)) 10 | return 0 11 | -------------------------------------------------------------------------------- /7KYU/consecutive_letters.py: -------------------------------------------------------------------------------- 1 | from string import ascii_lowercase 2 | 3 | 4 | def solve(st: str) -> bool: 5 | return ''.join(sorted(st)) in ascii_lowercase 6 | -------------------------------------------------------------------------------- /7KYU/consonant_count.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/564e7fc20f0b53eb02000106/ 2 | 3 | from re import findall 4 | 5 | 6 | def consonant_count(s: str) -> int: 7 | return len(findall(r'[^(\W)(0-9)(aeiou)(_)]', s.lower())) 8 | -------------------------------------------------------------------------------- /7KYU/contain_all_rots.py: -------------------------------------------------------------------------------- 1 | def contain_all_rots(strng: str, arr: list) -> bool: 2 | if not strng: 3 | return True 4 | rotation: set = set([strng[i:] + strng[:i] for i in range(len(strng)+1)]) 5 | return (rotation.intersection(set(arr)) == rotation) 6 | -------------------------------------------------------------------------------- /7KYU/convert_hash_to_array.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/59557b2a6e595316ab000046/train/python 2 | 3 | def convert_hash_to_array(hash: dict) -> list: 4 | """ Convert a hash into an array. """ 5 | return sorted(list([k, v] for k, v in hash.items())) 6 | -------------------------------------------------------------------------------- /7KYU/count_developers.py: -------------------------------------------------------------------------------- 1 | def count_developers(lst) -> int: 2 | return len([i for i in lst if i['continent'] == 'Europe' and i['language'] == 'JavaScript']) 3 | -------------------------------------------------------------------------------- /7KYU/count_duplicates.py: -------------------------------------------------------------------------------- 1 | def count_duplicates(name: list, age: list, height: list) -> int: 2 | a: list = [list(i) for i in zip(name, age, height)] 3 | not_duplicates: list = [] 4 | count_duplicates: int = 0 5 | for i in a: 6 | if i not in not_duplicates: 7 | not_duplicates.append(i) 8 | else: 9 | count_duplicates += 1 10 | return count_duplicates 11 | -------------------------------------------------------------------------------- /7KYU/count_languages.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | 4 | def count_languages(lst: list) -> dict: 5 | return Counter([i['language'] for i in lst]) 6 | -------------------------------------------------------------------------------- /7KYU/count_name.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | def count_name(arr: List[str], name: str) -> int: 5 | return arr.count(name) 6 | -------------------------------------------------------------------------------- /7KYU/counter.py: -------------------------------------------------------------------------------- 1 | # https://www.codewars.com/kata/60edafd71dad1800563cf933/ 2 | 3 | def counter(): 4 | count: int = 0 5 | def inc(): 6 | nonlocal count 7 | count += 1 8 | return count 9 | return inc -------------------------------------------------------------------------------- /7KYU/create_dict.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/5533c2a50c4fea6832000101/ 2 | 3 | from itertools import zip_longest 4 | 5 | 6 | def create_dict(keys: list, values: list) -> dict: 7 | """ This function makes dictionary from two lists """ 8 | return dict(zip_longest(keys, values)) if len(keys) >= len(values) else dict(zip(keys, values)) 9 | -------------------------------------------------------------------------------- /7KYU/cube_odd.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | 4 | def cube_odd(arr: list) -> Optional[int]: 5 | try: 6 | if all(type(i) == int for i in arr): 7 | return(sum([i ** 3 for i in arr if i % 2])) 8 | except TypeError: 9 | return None 10 | -------------------------------------------------------------------------------- /7KYU/cube_sum.py: -------------------------------------------------------------------------------- 1 | def cube_sum(n: int, m: int) -> int: 2 | if n > m: 3 | n, m = m, n 4 | return sum(list(i ** 3 for i in range(n+1, m+1))) 5 | -------------------------------------------------------------------------------- /7KYU/cyclops.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/56b0bc0826814364a800005a/ 2 | 3 | def cyclops(n: int) -> bool: 4 | """ A cyclops number is a number in binary that is made up of all 1's, with one 0 in the exact middle. """ 5 | split_bin: list = bin(n)[2:].split('0') 6 | return len(split_bin[0]) == len(split_bin[1]) if len(split_bin) == 2 else False 7 | -------------------------------------------------------------------------------- /7KYU/day_of_week.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/5885b5d2b632089dc30000cc/ 2 | 3 | from datetime import datetime 4 | 5 | 6 | def day_of_week(date: str) -> str: 7 | """ This function takes an date in format d/m/Y(String) and return what day of the week it was(String) """ 8 | return datetime.strptime(date, '%d/%m/%Y').strftime('%A') 9 | -------------------------------------------------------------------------------- /7KYU/decode_pass.py: -------------------------------------------------------------------------------- 1 | def decode_pass(pass_list: list, bits: str): 2 | bits_to_str: str = ''.join(chr(int(i, 2)) for i in bits.split()) 3 | return bits_to_str if bits_to_str in pass_list else False 4 | -------------------------------------------------------------------------------- /7KYU/diff.py: -------------------------------------------------------------------------------- 1 | # return a sorted set with the difference 2 | def diff(a: list, b: list) -> list: 3 | if a is b: 4 | return [] 5 | return sorted(list(set(a) ^ set(b))) 6 | -------------------------------------------------------------------------------- /7KYU/digitize.py: -------------------------------------------------------------------------------- 1 | def digitize(num: int) -> list: 2 | if num == 0: 3 | return [0] 4 | my_digitize = [] 5 | while num != 0: 6 | l = num % 10 7 | my_digitize.append(l) 8 | num = (num - l) // 10 9 | return list(reversed(my_digitize)) 10 | -------------------------------------------------------------------------------- /7KYU/div_con.py: -------------------------------------------------------------------------------- 1 | def div_con(x): 2 | sum_for_int, sum_for_str = sum([i for i in x if type(i) == int]), sum([int(i) for i in x if type(i) == str]) 3 | return sum_for_int - sum_for_str 4 | 5 | div_con([9, 3, '7', '3']) 6 | -------------------------------------------------------------------------------- /7KYU/divisors.py: -------------------------------------------------------------------------------- 1 | def divisors(integer): 2 | array_divisors = [] 3 | for i in range(integer-1, 1, -1): 4 | if integer % i == 0: 5 | array_divisors.append(i) 6 | 7 | if len(array_divisors) == 0: 8 | return (f'{integer} is prime') 9 | 10 | return sorted(array_divisors) -------------------------------------------------------------------------------- /7KYU/dominator.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/559e10e2e162b69f750000b4/ 2 | 3 | from collections import Counter 4 | 5 | 6 | def dominator(arr: list) -> int: 7 | if arr: 8 | num, count = Counter(arr).most_common(1)[0] 9 | if count > len(arr) // 2: 10 | return num 11 | else: return -1 12 | else: return -1 13 | -------------------------------------------------------------------------------- /7KYU/dont_give_me_five.py: -------------------------------------------------------------------------------- 1 | def dont_give_me_five(start: int, end: int) -> int: 2 | """This function returns the count of all numbers except numbers with a 5.""" 3 | count = 0 4 | for item in range(start, end+1): 5 | if '5' not in str(item): 6 | #print (item) 7 | count += 1 8 | return count -------------------------------------------------------------------------------- /7KYU/double_every_other.py: -------------------------------------------------------------------------------- 1 | def double_every_other(lst: list) -> list: 2 | lst_double: list = [j * 2 if not i % 2 else j for i, j in enumerate(lst, 1)] 3 | return lst_double -------------------------------------------------------------------------------- /7KYU/duplicates.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/5558cc216a7a231ac9000022/ 2 | 3 | from collections import Counter 4 | 5 | 6 | def duplicates(arr: list) -> list: 7 | result = [] 8 | counter = Counter() 9 | for i in arr: 10 | counter[i] += 1 11 | if counter[i] == 2: 12 | result.append(i) 13 | return result 14 | -------------------------------------------------------------------------------- /7KYU/elevator_distance.py: -------------------------------------------------------------------------------- 1 | def elevator_distance(array: list) -> int: 2 | return sum([abs(array[i] - array[i+1]) for i in range(len(array)-1)]) -------------------------------------------------------------------------------- /7KYU/equable_triangle.py: -------------------------------------------------------------------------------- 1 | def equable_triangle(a: int, b: int, c: int) -> bool: 2 | perimeter = a + b + c 3 | semi_perimeter = perimeter // 2 4 | area = (semi_perimeter * (semi_perimeter - a) * (semi_perimeter - b) * (semi_perimeter - c)) ** 0.5 5 | return True if perimeter == area else False 6 | -------------------------------------------------------------------------------- /7KYU/esrever.py: -------------------------------------------------------------------------------- 1 | def esrever(s: str) -> str: 2 | if len(s) < 2: 3 | return s 4 | return s[:-1][::-1] + s[-1] 5 | -------------------------------------------------------------------------------- /7KYU/evaporator.py: -------------------------------------------------------------------------------- 1 | def evaporator(content: int, evap_per_day: int, threshold: int) -> int: 2 | full = 100 3 | day = 0 4 | while full >= threshold: 5 | full -= full * (evap_per_day / 100) 6 | day += 1 7 | return day 8 | -------------------------------------------------------------------------------- /7KYU/even_chars.py: -------------------------------------------------------------------------------- 1 | def even_chars(st: str) -> list: 2 | """ This function returns a sequence (index begins with 1) of all the even characters from a string. """ 3 | if len(st) < 2 or len(st) > 100: 4 | return 'invalid string' 5 | even = [] 6 | for i, k in enumerate(range(len(st))): 7 | if i % 2 != 0: 8 | even.append(st[i]) 9 | return even -------------------------------------------------------------------------------- /7KYU/even_last.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | 4 | def even_last(numbers: Optional[int]) -> int: 5 | if len(numbers) == 0: 6 | return 0 7 | sum_even = sum([numbers[i] for i, k in enumerate(range(len(numbers))) if not k % 2]) 8 | return sum_even * numbers[-1] 9 | -------------------------------------------------------------------------------- /7KYU/even_numbers.py: -------------------------------------------------------------------------------- 1 | def even_numbers(arr: list, n: int) -> list: 2 | even_from_arr: list = [i for i in arr if not i % 2] 3 | return even_from_arr[len(even_from_arr) - n:] 4 | -------------------------------------------------------------------------------- /7KYU/explode.py: -------------------------------------------------------------------------------- 1 | def explode(s: str) -> str: 2 | return ''.join(int(i)*i for i in s) -------------------------------------------------------------------------------- /7KYU/factorial.py: -------------------------------------------------------------------------------- 1 | # from math import factorial as fact 2 | 3 | def factorial(n: int) -> int: 4 | # Using recursion 5 | if 0 <= n <= 1: 6 | return 1 7 | elif n < 0: 8 | return None 9 | return n * factorial(n - 1) 10 | # Using math-library 11 | # return fact(n) if n > 0 else None -------------------------------------------------------------------------------- /7KYU/filter_list.py: -------------------------------------------------------------------------------- 1 | def filter_list(arr: list) -> list: 2 | """This function returns a new list with the strings filtered out.""" 3 | my_list = [] 4 | for item in arr: 5 | if str(item).isdigit() and type(item) != str: 6 | my_list.append(item) 7 | return my_list -------------------------------------------------------------------------------- /7KYU/filter_long_words.py: -------------------------------------------------------------------------------- 1 | def filter_long_words(sentence: str, n: int) -> list: 2 | return [i for i in sentence.split() if len(i) > n] 3 | -------------------------------------------------------------------------------- /7KYU/find_admin.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | def find_admin(lst: List[dict], lang: str) -> List[dict]: 5 | return [i for i in lst if i['language'] == lang and i['githubAdmin'] == 'yes'] 6 | -------------------------------------------------------------------------------- /7KYU/find_array.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/59a2a3ba5eb5d4e609000055/ 2 | 3 | def find_array(arr1: list, arr2: list) -> list: 4 | 5 | new_arr = list() 6 | 7 | for i in arr2: 8 | if i < len(arr1): 9 | new_arr.append(arr1[i]) 10 | 11 | return new_arr 12 | -------------------------------------------------------------------------------- /7KYU/find_deleted_number.py: -------------------------------------------------------------------------------- 1 | def find_deleted_number(arr: list, mixed_arr: list) -> int: 2 | if arr == sorted(mixed_arr): 3 | return 0 4 | return int(''.join(map(str, (set(arr) - set(mixed_arr))))) -------------------------------------------------------------------------------- /7KYU/find_digit.py: -------------------------------------------------------------------------------- 1 | # https://www.codewars.com/kata/577b9960df78c19bca00007e/ 2 | 3 | def find_digit(num: int, nth: int) -> int: 4 | if nth <= 0: 5 | return -1 6 | else: 7 | num: str = str(abs(num)).zfill(nth)[::-1] 8 | return [int(k) for i, k in enumerate(num, 1) if i == nth][0] -------------------------------------------------------------------------------- /7KYU/find_factorial.py: -------------------------------------------------------------------------------- 1 | def factorial(n: int): 2 | if n == 0 or n == 1: 3 | return 1 4 | elif 2 <= n < 13: 5 | return n * factorial(n - 1) 6 | else: 7 | raise ValueError('Value Error') 8 | -------------------------------------------------------------------------------- /7KYU/find_longest.py: -------------------------------------------------------------------------------- 1 | # https://www.codewars.com/kata/58daa7617332e59593000006/ 2 | 3 | def find_longest(arr: list) -> int: 4 | return sorted(arr, key=lambda x: len(str(x)), reverse=True)[0] -------------------------------------------------------------------------------- /7KYU/find_screen_height.py: -------------------------------------------------------------------------------- 1 | def find_screen_height(width: int, ratio: str) -> str: 2 | k_ratio = [] 3 | for i in ratio.split(':'): 4 | k_ratio.append(int(i)) 5 | height = (width * k_ratio[1]) // k_ratio[0] 6 | return f'{width}x{height}' -------------------------------------------------------------------------------- /7KYU/find_short.py: -------------------------------------------------------------------------------- 1 | def find_short(s): 2 | split_str = s.split() 3 | split_str.sort(key=len) 4 | return (len(split_str[0])) -------------------------------------------------------------------------------- /7KYU/find_smallest.py: -------------------------------------------------------------------------------- 1 | def find_smallest(numbers: list, to_return: str) -> int: 2 | if to_return == "value": 3 | return min(numbers) 4 | return numbers.index(min(numbers)) 5 | -------------------------------------------------------------------------------- /7KYU/find_squares.py: -------------------------------------------------------------------------------- 1 | def find_squares(n: int) -> str: 2 | k = (n - 1) // 2 # because n = 2k + 1 3 | return f'{(k + 1) ** 2}-{k ** 2}' 4 | -------------------------------------------------------------------------------- /7KYU/find_sum.py: -------------------------------------------------------------------------------- 1 | def find(n: int) -> int: 2 | """ 3 | This function return the sum of all multiples of 3 and 5. 4 | """ 5 | return sum([i for i in range(2, n + 1) if not i % 3 or not i % 5]) 6 | -------------------------------------------------------------------------------- /7KYU/find_sum_v2.py: -------------------------------------------------------------------------------- 1 | # https://www.codewars.com/kata/55c5b03f8c28da9a51000045/ 2 | 3 | def find_sum(*args) -> int: 4 | return sum(args) if all(i>=0 for i in args) else -1 -------------------------------------------------------------------------------- /7KYU/find_the_missing_tree.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/58aa8698ae929e1c830001c7/ 2 | 3 | from collections import Counter 4 | 5 | 6 | def find_the_missing_tree(trees: list) -> int: 7 | counter = Counter(trees) 8 | return min(counter, key=counter.get) 9 | -------------------------------------------------------------------------------- /7KYU/first_non_repeated.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/570f6436b29c708a32000826 2 | 3 | def first_non_repeated(s: str) -> str or None: 4 | try: return [i for i in s if s.count(i) == 1][0] 5 | except IndexError: return None 6 | -------------------------------------------------------------------------------- /7KYU/fix.py: -------------------------------------------------------------------------------- 1 | def fix(s: str) -> str: 2 | """ This function capitalise the first letter of the first word of each sentence. """ 3 | my_s = [i.capitalize() for i in s.split('. ')] 4 | return '. '.join(map(str, my_s)) -------------------------------------------------------------------------------- /7KYU/fix_string_case.py: -------------------------------------------------------------------------------- 1 | def solve(s: str) -> str: 2 | count_lower: int = 0 3 | count_upper: int = 0 4 | for i in s: 5 | if i.islower(): 6 | count_lower += 1 7 | else: 8 | count_upper += 1 9 | if count_lower >= count_upper: 10 | return s.lower() 11 | return s.upper() 12 | -------------------------------------------------------------------------------- /7KYU/formatted_string.py: -------------------------------------------------------------------------------- 1 | def solution(c: int) -> str: 2 | """ This function returns a formatted string. """ 3 | return 'Value is ' + ('0000' + str(c))[-5:] -------------------------------------------------------------------------------- /7KYU/frame.py: -------------------------------------------------------------------------------- 1 | def frame(phrase='', ch='*') -> str: 2 | if not phrase: 3 | return f'{ch * 4}\n{ch + " " + ch}\n{ch + " " + ch}\n{ch * 4}' 4 | else: 5 | first_line = f"{ch}{ch * (len(phrase)+2)}{ch}" 6 | second_line = f"{ch}{' ' * (len(phrase)+2)}{ch}" 7 | third_line = f"{ch} {phrase} {ch}" 8 | return f'{first_line}\n{second_line}\n{third_line}\n{second_line}\n{first_line}' 9 | -------------------------------------------------------------------------------- /7KYU/freq_seq.py: -------------------------------------------------------------------------------- 1 | def freq_seq(s: str, sep: str) -> str: 2 | return sep.join(str(s.count(i)) for i in s) -------------------------------------------------------------------------------- /7KYU/friend.py: -------------------------------------------------------------------------------- 1 | def friend(x:list): 2 | my_frend = [] 3 | for item in x: 4 | if len(item) == 4: 5 | my_frend.append(item) 6 | return (my_frend) -------------------------------------------------------------------------------- /7KYU/generate_pairs.py: -------------------------------------------------------------------------------- 1 | from itertools import combinations_with_replacement 2 | 3 | 4 | def generate_pairs(n: int) -> list: 5 | return [list(i) for i in combinations_with_replacement(range(n+1), 2)] 6 | -------------------------------------------------------------------------------- /7KYU/generate_pairs_v2.py: -------------------------------------------------------------------------------- 1 | from itertools import combinations_with_replacement 2 | 3 | 4 | def generate_pairs(m: int, n: int) -> list: 5 | # First way 6 | # pairs: list = [] 7 | # for i in range(m, n+1): 8 | # for j in range(i, n+1): 9 | # pairs.append((i,j)) 10 | # return pairs 11 | # 12 | # Second way 13 | return [i for i in combinations_with_replacement(range(m, n+1), 2)] 14 | -------------------------------------------------------------------------------- /7KYU/geometric_sequence_elements.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/55caef80d691f65cb6000040/ 2 | 3 | def geometric_sequence_elements(a: int, r: int, n: int) -> str: 4 | """ This function print first 'n' elements of the sequence with the given constant 'r' and first element 'a'. """ 5 | return ', '.join(map(str, [a * pow(r, i) for i in range(n)])) 6 | -------------------------------------------------------------------------------- /7KYU/get_ages.py: -------------------------------------------------------------------------------- 1 | def get_ages(sum_, difference): 2 | if sum_ < 0 or difference < 0 or sum_ - difference < 0: 3 | return None 4 | return ((difference + round(sum_ - difference) / 2 ), round(sum_ - difference) / 2) 5 | -------------------------------------------------------------------------------- /7KYU/get_average.py: -------------------------------------------------------------------------------- 1 | from numpy import average 2 | 3 | 4 | def get_average(lst: list) -> int: 5 | return round(average([i['age'] for i in lst])) -------------------------------------------------------------------------------- /7KYU/get_count.py: -------------------------------------------------------------------------------- 1 | def get_count(input_str:str): 2 | vowel = ['a', 'e', 'i', 'o', 'u'] 3 | myStr = [] 4 | for el in input_str: 5 | if el in vowel: 6 | myStr.append(el) 7 | return len(myStr) -------------------------------------------------------------------------------- /7KYU/get_decimal.py: -------------------------------------------------------------------------------- 1 | from math import modf 2 | 3 | 4 | def get_decimal(n): 5 | fractional, whole = modf(n) 6 | return round(abs(fractional), 50) -------------------------------------------------------------------------------- /7KYU/get_even_numbers.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | def get_even_numbers(arr: List[int]) -> List[int]: 5 | if len(arr) < 1: 6 | return [] 7 | return list(filter(lambda i: not(i % 2), arr)) 8 | -------------------------------------------------------------------------------- /7KYU/get_factorial.py: -------------------------------------------------------------------------------- 1 | # from math import factorial as fact 2 | 3 | 4 | def factorial(n: int) -> int: 5 | return 1 if n <= 1 else n * factorial(n - 1) 6 | # return fact(n) -------------------------------------------------------------------------------- /7KYU/get_larger_numbers.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/563b1f55a5f2079dc100008a/ 2 | 3 | def get_larger_numbers(a: list, b: list) -> list: 4 | return [max(i, j) for i, j in zip(a, b)] 5 | -------------------------------------------------------------------------------- /7KYU/get_middle.py: -------------------------------------------------------------------------------- 1 | def get_middle(s: str) -> str: 2 | if len(s) < 3: 3 | return s 4 | for i, k in enumerate(range(len(s)-1)): 5 | needed_idx = len(s) // 2 6 | if len(s) % 2 == 0: 7 | return s[needed_idx - 1] + s[needed_idx] 8 | else: 9 | return s[needed_idx] 10 | -------------------------------------------------------------------------------- /7KYU/get_missing_element.py: -------------------------------------------------------------------------------- 1 | def get_missing_element(seq: list) -> int: 2 | return int(''.join(map(str,(set([i for i in range(10)]) - set(seq))))) -------------------------------------------------------------------------------- /7KYU/get_next_square.py: -------------------------------------------------------------------------------- 1 | def is_perfect_square(n: int) -> bool: 2 | if n ** 0.5 != int(n ** 0.5): 3 | return False 4 | return True 5 | 6 | 7 | def find_next_square(n: int) -> int: 8 | if is_perfect_square(n) is False: 9 | return -1 10 | n += 1 11 | while not is_perfect_square(n): 12 | n += 1 13 | return n 14 | -------------------------------------------------------------------------------- /7KYU/get_sum.py: -------------------------------------------------------------------------------- 1 | def get_sum(a,b): 2 | if a == b: 3 | return (a) 4 | n = [] 5 | if a > b: 6 | for i in range(b, a+1): 7 | n.append(i) 8 | return sum(n) 9 | 10 | else: 11 | for i in range(a, b+1): 12 | n.append(i) 13 | return sum(n) -------------------------------------------------------------------------------- /7KYU/get_sum_of_digits.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/563d59dd8e47a5ed220000ba 2 | 3 | 4 | def get_sum_of_digits(num: int) -> int: 5 | return sum([int(i) for i in str(num)]) 6 | -------------------------------------------------------------------------------- /7KYU/gimme.py: -------------------------------------------------------------------------------- 1 | def gimme(input_array: list) -> int: 2 | middle_element = sorted(input_array)[1] 3 | return input_array.index(middle_element) 4 | -------------------------------------------------------------------------------- /7KYU/gps.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | from math import floor 3 | 4 | 5 | def gps(s: int, x: List[float]) -> int: 6 | average_hourly_speed = [3600 * (x[i + 1] - x[i]) / s for i in range(len(x) - 1)] 7 | return floor(max(average_hourly_speed)) if len(x) > 1 else 0 8 | -------------------------------------------------------------------------------- /7KYU/greet.py: -------------------------------------------------------------------------------- 1 | def greet(name: str) -> str: 2 | return f'Hello {name.capitalize()}!' -------------------------------------------------------------------------------- /7KYU/greet_developers.py: -------------------------------------------------------------------------------- 1 | def greet_developers(lst: list) -> list: 2 | for i in lst: 3 | i.update({'greeting': f'Hi {i["firstName"]}, what do you like the most about {i["language"]}?'}) 4 | return lst 5 | -------------------------------------------------------------------------------- /7KYU/halving_sum.py: -------------------------------------------------------------------------------- 1 | def halving_sum(n: int) -> int: 2 | halv_sum: int = n 3 | while n != 1: 4 | n //= 2 5 | halv_sum += n 6 | return halv_sum 7 | -------------------------------------------------------------------------------- /7KYU/hamming_weight.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/5519e930cd82ff8a9a000216/ 2 | 3 | def hamming_weight(x: int) -> int: 4 | return x.bit_count() 5 | -------------------------------------------------------------------------------- /7KYU/has_unique_chars.py: -------------------------------------------------------------------------------- 1 | def has_unique_chars(string: str) -> bool: 2 | if len(string) == 1: 3 | return True 4 | unique = [] 5 | for item in string: 6 | if item not in unique: 7 | unique.append(item) 8 | else: 9 | return False 10 | return True -------------------------------------------------------------------------------- /7KYU/head_tail_init_last.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/54592a5052756d5c5d0009c3/ 2 | 3 | head = lambda x: x[0] 4 | tail = lambda x: x[1:] if len(x) > 1 else [] 5 | init = lambda x: x[:-1] if len(x) > 1 else [] 6 | last = lambda x: x[-1] -------------------------------------------------------------------------------- /7KYU/heron.py: -------------------------------------------------------------------------------- 1 | from math import sqrt 2 | 3 | 4 | def heron(a, b, c): 5 | s = (a + b + c) / 2 6 | return round(sqrt(s * (s - a) * (s - b) * (s - c)), 2) -------------------------------------------------------------------------------- /7KYU/hex_hash.py: -------------------------------------------------------------------------------- 1 | def hex_hash(code: str) -> int: 2 | my_string_with_hex_ord = '' 3 | list_of_num = [] 4 | for letter in code: 5 | my_string_with_hex_ord += hex(ord(letter))[2:] 6 | for symbol in my_string_with_hex_ord: 7 | if symbol.isdigit(): 8 | list_of_num.append(int(symbol)) 9 | return sum(list_of_num) -------------------------------------------------------------------------------- /7KYU/high_and_low.py: -------------------------------------------------------------------------------- 1 | def high_and_low(string: str) -> str: 2 | """This function returns the highest and lowest number.""" 3 | my_num = [] 4 | for item in string.split(): 5 | my_num.append(int(item)) 6 | high = max(my_num) 7 | low = min(my_num) 8 | return ''.join(map(str, str(high)+' '+str(low))) -------------------------------------------------------------------------------- /7KYU/highest_value.py: -------------------------------------------------------------------------------- 1 | def highest_value(a: str, b: str) -> str: 2 | return a if sum(ord(i) for i in a) >= sum(ord(i) for i in b) else b 3 | -------------------------------------------------------------------------------- /7KYU/how_many_years.py: -------------------------------------------------------------------------------- 1 | def how_many_years(date1: str, date2: str) -> int: 2 | return abs(int(date1.split('/')[0]) - int(date2.split('/')[0])) 3 | -------------------------------------------------------------------------------- /7KYU/incrementer.py: -------------------------------------------------------------------------------- 1 | # https://www.codewars.com/kata/590e03aef55cab099a0002e8/ 2 | 3 | 4 | def incrementer(nums: list) -> list: 5 | return [int(str(i+k)[-1]) for i, k in enumerate(nums, 1)] 6 | -------------------------------------------------------------------------------- /7KYU/infected.py: -------------------------------------------------------------------------------- 1 | def infected(s: str): 2 | try: 3 | map: list = [] 4 | for i in s.split('X'): 5 | if '1' in i: 6 | map.append(len(i) * '1') 7 | else: 8 | map.append(i) 9 | final_map = ''.join(map) 10 | return 100 * final_map.count('1') / len(final_map) 11 | except ZeroDivisionError: 12 | return 0 13 | -------------------------------------------------------------------------------- /7KYU/initials.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/55968ab32cf633c3f8000008/ 2 | 3 | def initials(name: str) -> str: 4 | 5 | split_name: list = name.split() 6 | 7 | return f"{'.'.join(i[0].upper() for i in split_name[:-1])}.{split_name[-1].title()}" -------------------------------------------------------------------------------- /7KYU/int_diff.py: -------------------------------------------------------------------------------- 1 | from itertools import combinations 2 | 3 | 4 | def int_diff(lst: list, n: int) -> int: 5 | return sum([1 for i in list(combinations(lst, 2)) if abs(i[0]-i[1]) == n]) 6 | -------------------------------------------------------------------------------- /7KYU/invite_more_women.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/58acfe4ae0201e1708000075/ 2 | 3 | def invite_more_women(arr: list) -> bool: 4 | return arr.count(-1) < arr.count(1) 5 | -------------------------------------------------------------------------------- /7KYU/isLeapYear.py: -------------------------------------------------------------------------------- 1 | from calendar import isleap 2 | 3 | def isLeapYear(year: int) -> bool: 4 | return isleap(year) -------------------------------------------------------------------------------- /7KYU/is_all_possibilities.py: -------------------------------------------------------------------------------- 1 | def is_all_possibilities(arr: list) -> bool: 2 | if arr: 3 | return sorted(arr) == [i for i in range(0, len(arr))] 4 | return False -------------------------------------------------------------------------------- /7KYU/is_anagram.py: -------------------------------------------------------------------------------- 1 | # write the function is_anagram 2 | def is_anagram(test: str, original: str) -> bool: 3 | letters_from_test: list = sorted([i.lower() for i in test]) 4 | letters_from_original: list = sorted([i.lower() for i in original]) 5 | return letters_from_test == letters_from_original -------------------------------------------------------------------------------- /7KYU/is_it_a_num.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/596343a24489a8b2a00000a2/ 2 | 3 | import re 4 | 5 | 6 | def is_it_a_num(s: str) -> str: 7 | num: str = ''.join(re.findall(r'\d', s)) 8 | if len(num) == 11 and num.startswith('0'): 9 | return num 10 | else: 11 | return "Not a phone number" 12 | -------------------------------------------------------------------------------- /7KYU/is_it_letter.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/57a06b07cf1fa58b2b000252/ 2 | 3 | from string import ascii_letters 4 | 5 | 6 | def is_it_letter(s: str) -> bool: 7 | return s in ascii_letters 8 | -------------------------------------------------------------------------------- /7KYU/is_letter.py: -------------------------------------------------------------------------------- 1 | def is_letter(s:str): 2 | if len(s) == 1 and s.isalpha(): 3 | return True 4 | return False -------------------------------------------------------------------------------- /7KYU/is_narcissistic.py: -------------------------------------------------------------------------------- 1 | # https://www.codewars.com/kata/56b22765e1007b79f2000079/ 2 | 3 | 4 | def is_narcissistic(n: int) -> bool: 5 | """ A Narcissistic Number is a number of length s in which the sum of its digits 6 | to the power of s is equal to the original number """ 7 | return sum([pow(int(i), len(str(n))) for i in str(n)]) == n -------------------------------------------------------------------------------- /7KYU/is_negative_zero.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/5c5086287bc6600001c7589a/ 2 | 3 | 4 | from re import match 5 | 6 | 7 | def is_negative_zero(n: float) -> bool: 8 | """ This function returns true if the input number is -0 and false otherwise. """ 9 | return bool(match(r'-0.0', str(n))) 10 | -------------------------------------------------------------------------------- /7KYU/is_perfect.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/56a28c30d7eb6acef700004d/ 2 | 3 | def is_perfect(n: int) -> bool: 4 | divisors: list = [1] 5 | for i in range(2, int(n ** 0.5) + 1): 6 | if not n % i: 7 | divisors.append(i) 8 | divisors.append(n // i) 9 | return sum(divisors) == n if n != 1 else False 10 | -------------------------------------------------------------------------------- /7KYU/is_prime.py: -------------------------------------------------------------------------------- 1 | def is_prime(n: int) -> bool: 2 | ''' 3 | This function returns True if n is a prime number otherwise return False. 4 | ''' 5 | if n <= 1: 6 | return False 7 | d = 2 8 | while d * d <= n and n % d != 0: 9 | d += 1 10 | return d * d > n 11 | -------------------------------------------------------------------------------- /7KYU/is_ruby_coming.py: -------------------------------------------------------------------------------- 1 | def is_ruby_coming(lst: list) -> bool: 2 | return True if any([i['language'].lower() == 'ruby' for i in lst]) else False 3 | -------------------------------------------------------------------------------- /7KYU/is_same_language.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | def is_same_language(lst: List[dict]) -> bool: 5 | return True if len(set([i['language'] for i in lst])) == 1 else False 6 | -------------------------------------------------------------------------------- /7KYU/is_sorted_and_how.py: -------------------------------------------------------------------------------- 1 | def is_sorted_and_how(arr: list) -> str: 2 | if arr == sorted(arr): 3 | return "yes, ascending" 4 | elif arr == sorted(arr, reverse=True): 5 | return "yes, descending" 6 | else: 7 | return "no" -------------------------------------------------------------------------------- /7KYU/is_square.py: -------------------------------------------------------------------------------- 1 | from math import sqrt 2 | 3 | 4 | def is_square(arr: list): 5 | if arr: 6 | return all(sqrt(i) == int(i ** 0.5) for i in arr) 7 | return None 8 | -------------------------------------------------------------------------------- /7KYU/is_triangle.py: -------------------------------------------------------------------------------- 1 | def is_triangle(a:float, b:float, c:float): 2 | if (a < c + b) and (b < a + c) and (c < a + b): #длина каждого отрезка меньше суммы длин двух остальных отрезков 3 | return True 4 | else: 5 | return False -------------------------------------------------------------------------------- /7KYU/is_vowel.py: -------------------------------------------------------------------------------- 1 | def is_vowel(s: str) -> bool: 2 | if len(s) == 0 or len(s) > 1: 3 | return False 4 | vowel = ["a", "e", "i", "o", "u"] 5 | for item in s: 6 | if item.lower() in vowel: 7 | return True 8 | return False -------------------------------------------------------------------------------- /7KYU/keywords.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/634ac4e77611b9f57dff456d/ 2 | 3 | import keyword 4 | 5 | keywords: set = {str(i) for i in keyword.kwlist} 6 | -------------------------------------------------------------------------------- /7KYU/kooka_counter.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/58e8cad9fd89ea0c6c000258/ 2 | 3 | def kooka_counter(laughing: str) -> int: 4 | male: int = len([i for i in laughing.split('ha') if i]) 5 | female: int = len([i for i in laughing.split('Ha') if i]) 6 | return male + female 7 | -------------------------------------------------------------------------------- /7KYU/largest.py: -------------------------------------------------------------------------------- 1 | def largest(n: int, xs: list) -> list: 2 | return sorted(xs)[-n:] -------------------------------------------------------------------------------- /7KYU/largest_number.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | 4 | def solve(s: str) -> int: 5 | """ 6 | This function returns the largest number from string. 7 | """ 8 | num = re.findall(r'\d+', s) 9 | int_num = [] 10 | for i in num: 11 | int_num.append(int(i)) 12 | return max(int_num) -------------------------------------------------------------------------------- /7KYU/largest_pair_sum.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | def largest_pair_sum(numbers: List[int]) -> int: 5 | return sum(sorted(numbers, reverse=True)[:2]) 6 | -------------------------------------------------------------------------------- /7KYU/last.py: -------------------------------------------------------------------------------- 1 | def last(s: str) -> list: 2 | return sorted(list(s.split()), key=lambda i: i[-1]) -------------------------------------------------------------------------------- /7KYU/least_larger.py: -------------------------------------------------------------------------------- 1 | def least_larger(arr: list, idx: int) -> int: 2 | """ This function returns the index of the least number larger than the element at the given index, or -1 if there is no such index. """ 3 | if len(arr) < 0: 4 | return -1 5 | my_element = [i for i in arr if i > arr[idx]] 6 | if len(my_element) > 0: 7 | return arr.index(min(my_element)) 8 | return -1 -------------------------------------------------------------------------------- /7KYU/length.py: -------------------------------------------------------------------------------- 1 | # https://www.codewars.com/kata/581e476d5f59408553000a4b/ 2 | 3 | def length(head) -> int: 4 | if head: 5 | return 1 + length(head.next) 6 | return 0 -------------------------------------------------------------------------------- /7KYU/limit_string_length.py: -------------------------------------------------------------------------------- 1 | def solution(st: str, limit: int) -> str: 2 | if len(st) <= limit: 3 | return st 4 | for i in range(len(st)): 5 | return st[i:limit]+'...' -------------------------------------------------------------------------------- /7KYU/line_numbering.py: -------------------------------------------------------------------------------- 1 | def number(lines: list) -> list: 2 | if len(lines) < 1: 3 | return [] 4 | line_numbering = [f'{i}: {k}' for i, k in enumerate(lines, start=1)] 5 | return line_numbering 6 | -------------------------------------------------------------------------------- /7KYU/longest.py: -------------------------------------------------------------------------------- 1 | def longest(a1: str, a2: str) -> str: 2 | if a1 is a2: 3 | return ''.join(sorted(set(a1))) 4 | return ''.join(sorted(set(a1 + a2))) 5 | -------------------------------------------------------------------------------- /7KYU/majority.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | 4 | def majority(arr: list): 5 | if arr: 6 | count: dict = Counter(arr) 7 | max_values: int = max(count.values()) 8 | key_for_max_values: list = [k for k, v in count.items() if v == max_values] 9 | return key_for_max_values[0] if len(key_for_max_values) == 1 else None 10 | return None 11 | -------------------------------------------------------------------------------- /7KYU/make_backronym.py: -------------------------------------------------------------------------------- 1 | # https://www.codewars.com/kata/55805ab490c73741b7000064/ 2 | 3 | def make_backronym(acronym: str) -> str: 4 | return ' '.join(dictionary.get(i.upper()) for i in acronym) -------------------------------------------------------------------------------- /7KYU/make_password.py: -------------------------------------------------------------------------------- 1 | def make_password(phrase: str) -> str: 2 | return ''.join(i[0] for i in phrase.split()).translate(str.maketrans({'O': '0', 'o': '0', 'I': '1', 'i': '1', 'S': '5', 's': '5'})) -------------------------------------------------------------------------------- /7KYU/maskify.py: -------------------------------------------------------------------------------- 1 | def maskify(cc): 2 | if len(cc) <= 4: 3 | return cc 4 | my_str = "" 5 | for i in cc: 6 | my_str += str(i) 7 | str_maskify = "#"*len(my_str[:-4])+my_str[-4:] 8 | return str_maskify -------------------------------------------------------------------------------- /7KYU/max_diff.py: -------------------------------------------------------------------------------- 1 | def max_diff(lst: list) -> int: 2 | """ Function returns the difference between the largest and the smallest value. """ 3 | return max(lst) - min(lst) if lst else 0 4 | -------------------------------------------------------------------------------- /7KYU/max_number.py: -------------------------------------------------------------------------------- 1 | def max_number(n: int) -> int: 2 | ''' This function returns the maximum number could be formed from the digits of the number given (n). ''' 3 | my_arr = [] 4 | for i in str(n): 5 | my_arr.append(int(i)) 6 | return int(''.join(map(str, sorted(my_arr, reverse=True)))) -------------------------------------------------------------------------------- /7KYU/max_product.py: -------------------------------------------------------------------------------- 1 | from functools import reduce 2 | from operator import mul 3 | 4 | 5 | def max_product(lst: list, n_largest_elements: int) -> int: 6 | largest_elements = sorted(lst)[-n_largest_elements:] 7 | return reduce(mul, largest_elements) 8 | -------------------------------------------------------------------------------- /7KYU/max_product_v2.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/5784c89be5553370e000061b/ 2 | 3 | import heapq 4 | 5 | 6 | def max_product(a: list) -> int: 7 | first, second = heapq.nlargest(2, a) 8 | return first * second 9 | -------------------------------------------------------------------------------- /7KYU/max_redigit.py: -------------------------------------------------------------------------------- 1 | def max_redigit(num: int) -> int: 2 | """ This function takes one positive three digit integer and rearranges its digits to get maximum possible number. """ 3 | if len(str(num)) != 3 or not str(num).isdigit(): 4 | return None 5 | digit = [] 6 | for i in str(num): 7 | digit.append(int(i)) 8 | return int(''.join(map(str, sorted(digit, reverse = True)))) -------------------------------------------------------------------------------- /7KYU/max_tri_sum.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/5aa1bcda373c2eb596000112/ 2 | 3 | 4 | def max_tri_sum(numbers: list) -> int: 5 | return sum(sorted(set(numbers), reverse=True)[:3]) 6 | -------------------------------------------------------------------------------- /7KYU/meeting.py: -------------------------------------------------------------------------------- 1 | from typing import List, Union 2 | 3 | 4 | def meeting(rooms: List[str]) -> Union[int, str]: 5 | if 'O' not in rooms: 6 | return 'None available!' 7 | return rooms.index('O') 8 | 9 | -------------------------------------------------------------------------------- /7KYU/middle_me.py: -------------------------------------------------------------------------------- 1 | def middle_me(N: int, X: str, Y: str) -> str: 2 | """ This function takes a key of X and place it in the middle of Y repeated N times. """ 3 | string = N * Y 4 | if len(string) % 2: 5 | return X 6 | else: 7 | id_x = len(string) // 2 8 | return f'{string[:id_x]}{X}{string[id_x:]}' -------------------------------------------------------------------------------- /7KYU/min_max.py: -------------------------------------------------------------------------------- 1 | def min_max(lst): 2 | min_number = min(lst) 3 | max_number = max(lst) 4 | return [min_number, max_number] -------------------------------------------------------------------------------- /7KYU/min_value.py: -------------------------------------------------------------------------------- 1 | def min_value(digits: list) -> int: 2 | """"This function returns the smallest number that could be formed from these digits, using the digits only once (ignore duplicates).""" 3 | my_arr = [] 4 | for item in digits: 5 | if item not in my_arr: 6 | my_arr.append(item) 7 | return int(''.join(map(str, sorted(my_arr)))) -------------------------------------------------------------------------------- /7KYU/missing_no.py: -------------------------------------------------------------------------------- 1 | def missing_no(nums: list) -> int: 2 | """ This function finds the missing number """ 3 | return list(set(nums) ^ set(range(0, 101)))[0] 4 | -------------------------------------------------------------------------------- /7KYU/mobile_keyboard.py: -------------------------------------------------------------------------------- 1 | def mobile_keyboard(s: str) -> int: 2 | keyboard: dict = {1: '0123456789*#', 3 | 2: 'adgjmptw', 4 | 3: 'behknqux', 5 | 4: 'cfilorvy', 6 | 5: 'sz' 7 | } 8 | return sum(k for k, v in keyboard.items() for i in s if i in v) 9 | -------------------------------------------------------------------------------- /7KYU/modify_multiply.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/5ace2d9f307eb29430000092/ 2 | 3 | def modify_multiply(st: str, loc: int, num: int) -> str: 4 | modify_word: str = ((st.split()[loc] + '-') * num)[:-1] 5 | return modify_word 6 | -------------------------------------------------------------------------------- /7KYU/most_frequent_item_count.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/56582133c932d8239900002e/ 2 | 3 | from collections import Counter 4 | 5 | 6 | def most_frequent_item_count(collection: list) -> int: 7 | """ Function to find the count of the most frequent item of an array. """ 8 | return max(Counter(collection).values()) if collection else 0 9 | -------------------------------------------------------------------------------- /7KYU/move_ten.py: -------------------------------------------------------------------------------- 1 | def move_ten(st: str) -> str: 2 | new_str: str = '' 3 | for i in range(len(st)): 4 | val = ord(st[i]) + 10 5 | if val > 122: 6 | new_str += chr(val - 26) 7 | else: 8 | new_str += chr(val) 9 | return new_str 10 | -------------------------------------------------------------------------------- /7KYU/move_vowels.py: -------------------------------------------------------------------------------- 1 | def move_vowels(string: str) -> str: 2 | if len(string) <= 1: 3 | return string 4 | vowels_from_string = '' 5 | consonants_from_string = '' 6 | for i in string: 7 | if i in 'aeiou': 8 | vowels_from_string += i 9 | else: consonants_from_string += i 10 | return f'{consonants_from_string}{vowels_from_string}' -------------------------------------------------------------------------------- /7KYU/multiply_and_filter.py: -------------------------------------------------------------------------------- 1 | from typing import Union 2 | 3 | 4 | def multiply_and_filter(seq: list, multiplier: Union[int, float]) -> list: 5 | return [i * multiplier for i in seq if type(i) == int or type(i) == float] 6 | -------------------------------------------------------------------------------- /7KYU/mxdiflg.py: -------------------------------------------------------------------------------- 1 | def mxdiflg(a1: list, a2: list) -> int: 2 | if not a1 or not a2: 3 | return -1 4 | return max(abs(len(min(a1, key=len)) - len(max(a2, key=len))), abs(len(max(a1, key=len))) - len(min(a2, key=len))) 5 | -------------------------------------------------------------------------------- /7KYU/mygcd.py: -------------------------------------------------------------------------------- 1 | from math import gcd 2 | 3 | 4 | def mygcd(x: int, y: int) -> int: 5 | return gcd(x, y) 6 | -------------------------------------------------------------------------------- /7KYU/mystery.py: -------------------------------------------------------------------------------- 1 | def mystery(s: str, n: int) -> str: 2 | if n == 0: 3 | return '' 4 | return ''.join(i for i, k in zip(s, bin(n)[2:]) if k == '1') 5 | -------------------------------------------------------------------------------- /7KYU/nb_dig.py: -------------------------------------------------------------------------------- 1 | def nb_dig(n: int, d: int) -> int: 2 | square = [i ** 2 for i in range(n + 1)] 3 | count_digit = ' '.join(map(str, square)).count(str(d)) 4 | return count_digit -------------------------------------------------------------------------------- /7KYU/nickname_generator.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/593b1909e68ff627c9000186/ 2 | 3 | def nickname_generator(name: str) -> str: 4 | vowels: str = 'aeiou' 5 | if len(name) < 4: 6 | return "Error: Name too short" 7 | if name[2] in vowels: 8 | return name[:4] 9 | else: 10 | return name[:3] 11 | -------------------------------------------------------------------------------- /7KYU/no_odds.py: -------------------------------------------------------------------------------- 1 | def no_odds(values: list) -> list: 2 | return [i for i in values if i % 2 == 0] -------------------------------------------------------------------------------- /7KYU/noonerize.py: -------------------------------------------------------------------------------- 1 | def noonerize(numbers: list) -> int or str: 2 | if not all(type(i) == int for i in numbers): 3 | return "invalid array" 4 | else: 5 | first_num: int = int(str(numbers[1])[0] + str(numbers[0])[1:]) 6 | second_num: int = int(str(numbers[0])[0] + str(numbers[1])[1:]) 7 | return abs(first_num-second_num) 8 | -------------------------------------------------------------------------------- /7KYU/not_visible_cubes.py: -------------------------------------------------------------------------------- 1 | def not_visible_cubes(n: int) -> int: 2 | if n < 3: 3 | return 0 4 | return (n - 2) ** 3 5 | -------------------------------------------------------------------------------- /7KYU/nth_char.py: -------------------------------------------------------------------------------- 1 | def nth_char(words: list) -> str: 2 | return ''.join(words[i][k] for i, k in enumerate(range(len(words)))) -------------------------------------------------------------------------------- /7KYU/number_joy.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/570523c146edc287a50014b1/ 2 | 3 | def number_joy(n: int) -> bool: 4 | digit_sum: int = sum(int(i) for i in str(n)) 5 | return digit_sum * int(str(digit_sum)[::-1]) == n 6 | -------------------------------------------------------------------------------- /7KYU/number_of_occurrences.py: -------------------------------------------------------------------------------- 1 | def number_of_occurrences(element: int, sample: list) -> int: 2 | return sample.count(element) -------------------------------------------------------------------------------- /7KYU/number_star_ladder.py: -------------------------------------------------------------------------------- 1 | # https://www.codewars.com/kata/5631213916d70a0979000066/ 2 | 3 | def pattern(n: int) -> str: 4 | row = '1\n' 5 | for i in range(2, n+1): 6 | row += f"1{'*'*(i-1)}{i}\n" 7 | return row[:-1] -------------------------------------------------------------------------------- /7KYU/numbers.py: -------------------------------------------------------------------------------- 1 | def numbers(*args) -> bool: 2 | return all([type(i) == int or type(i) == float for i in args]) -------------------------------------------------------------------------------- /7KYU/odd_or_even.py: -------------------------------------------------------------------------------- 1 | def odd_or_even(n:list): 2 | if len(n) == 0: 3 | return [0] 4 | elif sum(n) % 2 == 0: 5 | return "even" 6 | else: 7 | return "odd" -------------------------------------------------------------------------------- /7KYU/ones_complement.py: -------------------------------------------------------------------------------- 1 | def ones_complement(binary_number: str) -> str: 2 | return ''.join('1' if i == '0' else '0' for i in binary_number) -------------------------------------------------------------------------------- /7KYU/ones_counter.py: -------------------------------------------------------------------------------- 1 | def ones_counter(inp: list) -> list: 2 | if inp: 3 | if all(i == 1 for i in inp): 4 | return [len(inp)] 5 | if all(i == 0 for i in inp): 6 | return [] 7 | return [len(i) for i in ''.join(map(str, inp)).split('0') if len(i) > 0] 8 | return [] 9 | -------------------------------------------------------------------------------- /7KYU/open_or_senior.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | def open_or_senior(data: List[int]) -> List[str]: 5 | categories_of_membership: list = [] 6 | for i in data: 7 | if i[0] >= 55 and i[1] > 7: 8 | categories_of_membership.append('Senior') 9 | else: 10 | categories_of_membership.append('Open') 11 | return categories_of_membership 12 | -------------------------------------------------------------------------------- /7KYU/order_food.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | def order_food(lst: List[dict]) -> dict: 5 | meals = {} 6 | for i in lst: 7 | if i['meal'] not in meals: 8 | meals[i['meal']] = 1 9 | else: 10 | meals[i['meal']] += 1 11 | return meals 12 | -------------------------------------------------------------------------------- /7KYU/ordered_count.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/57a6633153ba33189e000074/ 2 | 3 | from collections import Counter 4 | 5 | 6 | def ordered_count(inp: str) -> list: 7 | return [(k, v) for k, v in Counter(inp).items()] 8 | -------------------------------------------------------------------------------- /7KYU/outed.py: -------------------------------------------------------------------------------- 1 | def outed(meet: dict, boss: str) -> str: 2 | rating: int = 0 3 | for key, value in meet.items(): 4 | if key == boss: 5 | rating += 2 * value 6 | else: 7 | rating += value 8 | rating /= len(meet) 9 | return 'Get Out Now!' if rating <= 5 else 'Nice Work Champ!' 10 | -------------------------------------------------------------------------------- /7KYU/over_the_road.py: -------------------------------------------------------------------------------- 1 | def over_the_road(address: int, n: int) -> int: 2 | return ((2 * n) + 1) - address 3 | -------------------------------------------------------------------------------- /7KYU/pairs.py: -------------------------------------------------------------------------------- 1 | def pairs(array: list) -> int: 2 | """ This function returns the count of pairs that have consecutive numbers. """ 3 | pairs_from_array = list(zip(array[::2], array[1::2])) 4 | count = 0 5 | for i, j in pairs_from_array: 6 | if (i - j == 1) or (i - j == -1): 7 | count += 1 8 | return count 9 | -------------------------------------------------------------------------------- /7KYU/palindrome.py: -------------------------------------------------------------------------------- 1 | def palindrome(num): 2 | if isinstance(num, int) and num > 0: 3 | return True if str(num) == str(num)[::-1] else False 4 | return "Not valid" 5 | -------------------------------------------------------------------------------- /7KYU/pass_hash.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | 3 | 4 | def pass_hash(s: str) -> str: 5 | """ This function converts a given string into an md5 hash. """ 6 | hash_object = hashlib.md5(s.encode('UTF-8')) 7 | hex_dig = hash_object.hexdigest() 8 | return hex_dig 9 | -------------------------------------------------------------------------------- /7KYU/pentagonal.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/5fb856190d5230001d48d721/ 2 | 3 | def pentagonal(n: int) -> int: 4 | return (5 * n * (n - 1) + 2) // 2 if n > 0 else -1 5 | -------------------------------------------------------------------------------- /7KYU/person_class_bug.py: -------------------------------------------------------------------------------- 1 | class Person(): 2 | 3 | def __init__(self, first_name: str, last_name: str, age: int, full_name = None): 4 | self.first_name = first_name 5 | self.last_name = last_name 6 | self.full_name = "{} {}".format(first_name, last_name) 7 | self.age = age 8 | -------------------------------------------------------------------------------- /7KYU/person_greet.py: -------------------------------------------------------------------------------- 1 | # TODO: This method needs to be called multiple times for the same person (my_name). 2 | # It would be nice if we didnt have to always pass in my_name every time we needed to great someone. 3 | 4 | class Person(object): 5 | 6 | def __init__(self, name): 7 | self.name = name 8 | 9 | def greet(self, your_name): 10 | return f'Hello {your_name}, my name is {self.name}' 11 | -------------------------------------------------------------------------------- /7KYU/power_of_two.py: -------------------------------------------------------------------------------- 1 | from math import log2 2 | 3 | 4 | def power_of_two(x: int) -> bool: 5 | if x == 0: 6 | return False 7 | n = log2(x) 8 | if pow(2, int(n)) == x: 9 | return True 10 | return False 11 | -------------------------------------------------------------------------------- /7KYU/predict_age.py: -------------------------------------------------------------------------------- 1 | from math import sqrt 2 | 3 | 4 | def predict_age(*args): 5 | return sqrt(sum(i * i for i in args)) // 2 6 | -------------------------------------------------------------------------------- /7KYU/presents.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | def presents(arr: List[int]) -> List[int]: 5 | return list(map(lambda x: x + 1, [arr.index(i) for i, k in enumerate(arr, start=1)])) 6 | -------------------------------------------------------------------------------- /7KYU/prev_mult_of_three.py: -------------------------------------------------------------------------------- 1 | def prev_mult_of_three(n: int): 2 | if not n % 3: 3 | return n 4 | else: 5 | while n % 3: 6 | n //= 10 7 | return n or None 8 | -------------------------------------------------------------------------------- /7KYU/product.py: -------------------------------------------------------------------------------- 1 | def product(s: str) -> int: 2 | return s.count('!') * s.count('?') 3 | -------------------------------------------------------------------------------- /7KYU/quotable.py: -------------------------------------------------------------------------------- 1 | def quotable(name: str, quote: str) -> str: 2 | return f'{name} said: "{quote}"' 3 | -------------------------------------------------------------------------------- /7KYU/race_podium.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/62cecd4e5487c10028996e04/ 2 | 3 | from math import ceil 4 | 5 | 6 | def race_podium(blocks: int) -> tuple: 7 | first = ceil(blocks / 3) + 1 8 | second = first - 1 9 | third = blocks - (first + second) 10 | if not third: 11 | second -= 1 12 | third += 1 13 | return second, first, third 14 | -------------------------------------------------------------------------------- /7KYU/range_bit_count.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/58845748bd5733f1b300001f/ 2 | 3 | def range_bit_count(a: int, b: int) -> int: 4 | return sum([sum(map(int, format(i, 'b'))) for i in range(a, b + 1)]) 5 | -------------------------------------------------------------------------------- /7KYU/remove.py: -------------------------------------------------------------------------------- 1 | def remove(s: str) -> str: 2 | new_s: str = '' 3 | for i in s.split(): 4 | while i[-1] == '!': 5 | i = i[:-1] 6 | new_s += f'{i} ' 7 | return new_s[:-1] 8 | -------------------------------------------------------------------------------- /7KYU/remove_.py: -------------------------------------------------------------------------------- 1 | class List: 2 | def remove_(self, integer_list: list, values_list: list) -> list: 3 | return [i for i in integer_list if i not in values_list] 4 | -------------------------------------------------------------------------------- /7KYU/remove_chars.py: -------------------------------------------------------------------------------- 1 | from string import ascii_letters 2 | 3 | 4 | def remove_chars(s: str) -> str: 5 | return ''.join([i for i in s if i in ascii_letters or i == ' ']) 6 | -------------------------------------------------------------------------------- /7KYU/remove_consecutive_duplicates.py: -------------------------------------------------------------------------------- 1 | def remove_consecutive_duplicates(s: str) -> str: 2 | """ This function removes all consecutive duplicate words from string, leaving only first words entries. """ 3 | unique = [] 4 | current_word = None 5 | for i in s.split(' '): 6 | if i != current_word: 7 | unique.append(i) 8 | current_word = i 9 | return ' '.join(unique) 10 | -------------------------------------------------------------------------------- /7KYU/remove_duplicate_words.py: -------------------------------------------------------------------------------- 1 | def remove_duplicate_words(s: str) -> str: 2 | return ' '.join(dict.fromkeys([i for i in s.split()])) 3 | -------------------------------------------------------------------------------- /7KYU/remove_smallest.py: -------------------------------------------------------------------------------- 1 | def remove_smallest(numbers): 2 | if len(numbers) == 0: 3 | return ([]) 4 | new_list = list(numbers) 5 | my_min = min(new_list) 6 | del new_list[new_list.index(my_min)] 7 | return (new_list) 8 | -------------------------------------------------------------------------------- /7KYU/remove_url_anchor.py: -------------------------------------------------------------------------------- 1 | def remove_url_anchor(url: str) -> str: 2 | if '#' in url: 3 | return url[:url.index('#')] 4 | return url 5 | -------------------------------------------------------------------------------- /7KYU/remove_v2.py: -------------------------------------------------------------------------------- 1 | def remove(s: str) -> str: 2 | return ' '.join([i for i in s.split() if i.count('!') != 1]) 3 | -------------------------------------------------------------------------------- /7KYU/remove_v3.py: -------------------------------------------------------------------------------- 1 | def remove(s: str) -> str: 2 | last_letter_idx: int = s.rindex([i for i in s if i.isalpha()][-1]) 3 | count_mark: int = s[last_letter_idx+1:].count('!') 4 | return s.replace('!', '') + '!' * count_mark 5 | -------------------------------------------------------------------------------- /7KYU/remove_vowels.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | 4 | def remove_vowels(strng: str) -> str: 5 | strng = re.sub('[aeiou]', '', strng) 6 | return strng 7 | -------------------------------------------------------------------------------- /7KYU/repeats.py: -------------------------------------------------------------------------------- 1 | def repeats(arr: list) -> int: 2 | """ This function returns the sum of the numbers that occur only once. """ 3 | no_repeats = [] 4 | for i in sorted(arr): 5 | if arr.count(i) == 1: 6 | no_repeats.append(i) 7 | return (sum(no_repeats)) 8 | -------------------------------------------------------------------------------- /7KYU/reverse.py: -------------------------------------------------------------------------------- 1 | def reverse(n: int) -> int: 2 | """ This function takes in input 'n' and returns 'n' with all digits reversed. Assume positive 'n'. """ 3 | reversed_n = [] 4 | while n != 0: 5 | i = n % 10 6 | reversed_n.append(i) 7 | n = (n - i) // 10 8 | return int(''.join(map(str, reversed_n))) 9 | -------------------------------------------------------------------------------- /7KYU/reverse_bits.py: -------------------------------------------------------------------------------- 1 | def reverse_bits(n: int) -> int: 2 | """ 3 | This function reverses the bits in an integer. 4 | """ 5 | return int(''.join([str(bin(n)[2:])[::-1]]), 2) 6 | -------------------------------------------------------------------------------- /7KYU/reverse_letter.py: -------------------------------------------------------------------------------- 1 | def reverse_letter(string: str) -> str: 2 | """This function returns reversed string with alphabetic characters.""" 3 | my_string = '' 4 | for item in string: 5 | if item.isalpha(): 6 | my_string += item 7 | return ''.join(map(str, list(reversed(my_string)))) 8 | -------------------------------------------------------------------------------- /7KYU/reverse_list.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/57a04da9e298a7ee43000111/ 2 | 3 | def reverse_list(lst: list) -> list: 4 | """ This function simply reverses lists. """ 5 | 6 | return lst[::-1] 7 | -------------------------------------------------------------------------------- /7KYU/reverse_v1.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/5413759479ba273f8100003d/ 2 | 3 | def reverse(lst: list) -> list: 4 | empty_list: list = list() 5 | for i in lst: 6 | empty_list.insert(0, i) 7 | return empty_list 8 | -------------------------------------------------------------------------------- /7KYU/reverse_words.py: -------------------------------------------------------------------------------- 1 | def reverse_words(x:str): 2 | my_revers = [] 3 | for item in x.split(' '): 4 | my_revers.append(item[::-1]) 5 | return (' '.join(map(str, my_revers))) 6 | -------------------------------------------------------------------------------- /7KYU/roots.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/57d448c6ba30875437000138/ 2 | 3 | def roots(a, b, c): 4 | d = b ** 2 - 4 * a * c 5 | if d < 0: return None 6 | x1 = (-b + d ** 0.5) / (2 * a) 7 | x2 = (-b - d ** 0.5) / (2 * a) 8 | 9 | return round(x1 + x2, 2) 10 | -------------------------------------------------------------------------------- /7KYU/row_sum_odd_numbers.py: -------------------------------------------------------------------------------- 1 | def row_sum_odd_numbers(n: int) -> int: 2 | return n ** 3 3 | -------------------------------------------------------------------------------- /7KYU/save.py: -------------------------------------------------------------------------------- 1 | def save(sizes: list, hd: int) -> int: 2 | return sum([sum(sizes[:i+1]) <= hd for i in range(len(sizes))]) 3 | -------------------------------------------------------------------------------- /7KYU/sc.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/56fe97b3cc08ca00e4000dc9/ 2 | 3 | def sc(apple: list) -> list: 4 | for i in range(len(apple)): 5 | for j in range(len(apple[i])): 6 | if apple[i][j] == 'B': 7 | return [i, j] 8 | -------------------------------------------------------------------------------- /7KYU/score_test.py: -------------------------------------------------------------------------------- 1 | def score_test(tests: list, right: int, omit: int, wrong: int) -> int: 2 | ans = [tests.count(i) for i in range(3)] 3 | return ans[0]*right + ans[1]*omit - ans[2]*wrong 4 | -------------------------------------------------------------------------------- /7KYU/second_symbol.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/63f96036b15a210058300ca9/ 2 | 3 | def second_symbol(s: str, symbol: str) -> int: 4 | 5 | idx = list() 6 | 7 | for i, k in enumerate(s): 8 | if k == symbol and len(idx) != 2: 9 | idx.append(i) 10 | if len(idx) == 2: 11 | return idx[-1] 12 | else: 13 | return -1 14 | -------------------------------------------------------------------------------- /7KYU/sequence_sum.py: -------------------------------------------------------------------------------- 1 | def sequence_sum(begin_number: int, end_number: int, step: int) -> int: 2 | if begin_number > end_number: 3 | return 0 4 | return sum(range(begin_number, end_number + 1, step)) 5 | -------------------------------------------------------------------------------- /7KYU/series_sum.py: -------------------------------------------------------------------------------- 1 | def series_sum(n: int) -> str: 2 | """ 3 | This function returns the sum of following series upto nth term(parameter). 4 | Series: 1 + 1/4 + 1/7 + 1/10 + 1/13 + 1/16 + ... 5 | """ 6 | s = 0 7 | for i in range(n): 8 | s += 1 / (1 + (i * 3)) 9 | return "{:.2f}".format(s) -------------------------------------------------------------------------------- /7KYU/seven_ate9.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | 4 | def seven_ate9(string: str) -> str: 5 | while '797' in string: 6 | string = re.sub(r'797', r'77', string) 7 | return string 8 | -------------------------------------------------------------------------------- /7KYU/shades_of_grey.py: -------------------------------------------------------------------------------- 1 | def shades_of_grey(n: int) -> list: 2 | ''' This function returns n shades of grey in an array ''' 3 | if n <= 0: 4 | return [] 5 | elif 1 <= n <= 254: 6 | return ['#' + f'{i:02x}' * 3 for i in range(1, n + 1)] 7 | else: 8 | return ['#' + f'{i:02x}' * 3 for i in range(1, 255)] 9 | -------------------------------------------------------------------------------- /7KYU/shorter_reverse_longer.py: -------------------------------------------------------------------------------- 1 | def shorter_reverse_longer(a: str, b: str) -> str: 2 | if len(a) < len(b): 3 | return f'{a}{b[::-1]}{a}' 4 | return f'{b}{a[::-1]}{b}' 5 | -------------------------------------------------------------------------------- /7KYU/shortest_distance.py: -------------------------------------------------------------------------------- 1 | from math import sqrt 2 | from typing import Union 3 | 4 | 5 | def shortest_distance(a: Union[int, float], b: Union[int, float], c: Union[int, float]) -> Union[int, float]: 6 | A = [sqrt(pow(a, 2) + pow((b + c), 2))] 7 | B = [sqrt(pow(b, 2) + pow((a + c), 2))] 8 | C = [sqrt(pow(c, 2) + pow((a + b), 2))] 9 | return min(list(A + B + C)) -------------------------------------------------------------------------------- /7KYU/show_sequence.py: -------------------------------------------------------------------------------- 1 | def show_sequence(n: int) -> str: 2 | if n < 0: 3 | return f'{n}<0' 4 | elif n == 0: 5 | return f'{n}=0' 6 | else: 7 | series = '' 8 | for i in range(n + 1): 9 | series += str(i) + '+' 10 | return f'{series[:-1]} = {sum(i for i in range(n + 1))}' 11 | -------------------------------------------------------------------------------- /7KYU/small_enough.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | def small_enough(array: List[int], limit: int) -> bool: 5 | return all(i <= limit for i in array) 6 | -------------------------------------------------------------------------------- /7KYU/smallest.py: -------------------------------------------------------------------------------- 1 | from math import gcd 2 | 3 | 4 | def lcm(a: int, b: int) -> int: 5 | return a * b // gcd(a, b) 6 | 7 | def smallest(n: int) -> int: 8 | smallest_num = 1 9 | for i in range (1, n + 1): 10 | smallest_num = lcm(smallest_num, i) 11 | return smallest_num -------------------------------------------------------------------------------- /7KYU/smallest_product.py: -------------------------------------------------------------------------------- 1 | from numpy import prod 2 | 3 | 4 | def smallest_product(a: list) -> int: 5 | return min([prod(i) for i in a]) 6 | -------------------------------------------------------------------------------- /7KYU/solution.py: -------------------------------------------------------------------------------- 1 | def solution(string: str, ending: str) -> bool: 2 | return string.endswith(ending) -------------------------------------------------------------------------------- /7KYU/solution_idx.py: -------------------------------------------------------------------------------- 1 | def solution(items: list, index: int, default_value: str): 2 | try: 3 | return items[index] 4 | except IndexError: 5 | return default_value 6 | -------------------------------------------------------------------------------- /7KYU/solution_last_digits.py: -------------------------------------------------------------------------------- 1 | def solution(n: int, d: int) -> list: 2 | if d <= 0: 3 | return [] 4 | else: 5 | return [int(i) for i in str(n)[-d:]] 6 | -------------------------------------------------------------------------------- /7KYU/solution_v2.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/5168b125faced29f66000005/ 2 | 3 | from re import findall 4 | 5 | 6 | def solution(full_text: str, search_text: str) -> int: 7 | return len(findall(search_text, full_text)) 8 | -------------------------------------------------------------------------------- /7KYU/solve.py: -------------------------------------------------------------------------------- 1 | def solve(arr: list) -> int: 2 | """ This function returns one integer that is either only negative or only positive. """ 3 | for i in range(len(arr)): 4 | if -arr[i] not in arr: 5 | return arr[i] -------------------------------------------------------------------------------- /7KYU/solve_remove_duplicates.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | def solve(arr: List[int]) -> List[int]: 5 | if len(arr) < 2: 6 | return arr 7 | list_without_duplicates = [] 8 | for item in arr[::-1]: 9 | if item not in list_without_duplicates: 10 | list_without_duplicates.append(item) 11 | return list_without_duplicates[::-1] 12 | -------------------------------------------------------------------------------- /7KYU/solve_v2.py: -------------------------------------------------------------------------------- 1 | def solve(s: str) -> int: 2 | new_s: str = '' 3 | for i in s: 4 | if i not in 'aeiou': 5 | new_s += f'-{i}-' 6 | else: 7 | new_s += i 8 | return len(max(new_s.split('-'), key=len)) -------------------------------------------------------------------------------- /7KYU/solve_v3.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | 4 | def solve(s: str) -> str: 5 | return ''.join(reversed([i[::-1] if not i.isdigit() else i for i in re.split('(\d+)', s)])) -------------------------------------------------------------------------------- /7KYU/sort_by_length.py: -------------------------------------------------------------------------------- 1 | def sort_by_length(arr: list) -> list: 2 | return sorted(arr, key=len) 3 | -------------------------------------------------------------------------------- /7KYU/sort_dict.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/53da6a7e112bd15cbc000012/ 2 | 3 | def sort_dict(d: dict) -> list: 4 | """ This function returns a sorted list of tuples from the dictionary """ 5 | return sorted(d.items(), key=lambda item: item[1], reverse=True) 6 | -------------------------------------------------------------------------------- /7KYU/sort_gift_code.py: -------------------------------------------------------------------------------- 1 | def sort_gift_code(code: str) -> str: 2 | my_letter = [] 3 | for letter in code: 4 | my_letter.append(letter) 5 | return ''.join(sorted(my_letter)) -------------------------------------------------------------------------------- /7KYU/sort_my_string.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/580755730b5a77650500010c/ 2 | 3 | 4 | def sort_my_string(s: str) -> str: 5 | return f"{s[::2]} {s[1::2]}" 6 | -------------------------------------------------------------------------------- /7KYU/sort_numbers.py: -------------------------------------------------------------------------------- 1 | def solution(nums: list) -> list: 2 | """ This function sorts the passed in array of numbers. """ 3 | if nums is None: 4 | return [] 5 | return sorted(nums) -------------------------------------------------------------------------------- /7KYU/sort_reindeer.py: -------------------------------------------------------------------------------- 1 | def sort_reindeer(reindeer_names: list) -> list: 2 | """ Function returns a sequence with the Reindeer names sorted by their last names. """ 3 | return sorted(reindeer_names, key=lambda last_names: last_names.split()[1]) 4 | -------------------------------------------------------------------------------- /7KYU/spacey.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/56576f82ab83ee8268000059/ 2 | 3 | def spacey(array: list) -> list: 4 | return list(''.join(array[:i + 1]) for i in range(len(array))) 5 | -------------------------------------------------------------------------------- /7KYU/spacify.py: -------------------------------------------------------------------------------- 1 | def spacify(string: str) -> str: 2 | """ Returns the given string with spaces inserted between each character. """ 3 | return ' '.join(i for i in string) 4 | -------------------------------------------------------------------------------- /7KYU/spam.py: -------------------------------------------------------------------------------- 1 | def spam(number): 2 | return ''.join(['hue' for i in range(number)]) -------------------------------------------------------------------------------- /7KYU/special_number.py: -------------------------------------------------------------------------------- 1 | def special_number(number: int) -> str: 2 | return "Special!!" if all(int(i) < 6 for i in str(number)) else "NOT!!" -------------------------------------------------------------------------------- /7KYU/split_in_parts.py: -------------------------------------------------------------------------------- 1 | def split_in_parts(s: str, part_length: int) -> str: 2 | words: list = [] 3 | for i in range(0, len(s), part_length): 4 | words.append(s[i:i+part_length]) 5 | return ' '.join(words) 6 | -------------------------------------------------------------------------------- /7KYU/square_digits.py: -------------------------------------------------------------------------------- 1 | def square_digits(num: int) -> int: 2 | return int(''.join(map(str, [int(i) ** 2 for i in str(num)]))) -------------------------------------------------------------------------------- /7KYU/stanton_measure.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/59a1cdde9f922b83ee00003b/ 2 | 3 | 4 | def stanton_measure(arr: list) -> int: 5 | return sum(1 for i in arr if i == arr.count(1)) 6 | -------------------------------------------------------------------------------- /7KYU/stray.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | from typing import List 3 | 4 | 5 | def stray(arr: List[int]) -> int: 6 | counter_list = Counter(arr) 7 | for k, v in counter_list.items(): 8 | if v == 1: 9 | return k 10 | -------------------------------------------------------------------------------- /7KYU/string_hash.py: -------------------------------------------------------------------------------- 1 | def string_hash(s: str) -> int: 2 | ascii_values_from_s = [ord(i) for i in s] 3 | a, b = sum(ascii_values_from_s), sum([ascii_values_from_s[i + 1] - ascii_values_from_s[i] for i in range(len(ascii_values_from_s)-1)]) 4 | c = (a | b) & (~a << 2) 5 | d = c ^ (32 * (s.count(' ') + 1)) 6 | return d 7 | -------------------------------------------------------------------------------- /7KYU/string_merge.py: -------------------------------------------------------------------------------- 1 | # https://www.codewars.com/kata/597bb84522bc93b71e00007e/ 2 | 3 | 4 | def string_merge(string1: str, string2: str, letter: str) -> str: 5 | first_index: int = string1.index(letter) 6 | second_index: int = string2.index(letter) 7 | return string1[:first_index]+string2[second_index:] -------------------------------------------------------------------------------- /7KYU/strings_from_a_hash.py: -------------------------------------------------------------------------------- 1 | def solution(d: dict) -> str: 2 | my_list = [] 3 | for key in d: 4 | my_list.append(f'{key} = {d[key]}') 5 | my_list = sorted(my_list) 6 | return ','.join(my_list) -------------------------------------------------------------------------------- /7KYU/strong_num.py: -------------------------------------------------------------------------------- 1 | from math import factorial 2 | 3 | 4 | def strong_num(number: int) -> str: 5 | if sum(factorial(int(i)) for i in str(number)) == number: 6 | return "STRONG!!!!" 7 | return "Not Strong !!" 8 | -------------------------------------------------------------------------------- /7KYU/sum.py: -------------------------------------------------------------------------------- 1 | def sum(*args): 2 | res = 0 3 | for x in args: 4 | if type(x) == int: 5 | res += x 6 | return res -------------------------------------------------------------------------------- /7KYU/sum_cubes.py: -------------------------------------------------------------------------------- 1 | def sum_cubes(n): 2 | my_array = [n ** 3 for n in range(1, n+1)] 3 | return sum(my_array) -------------------------------------------------------------------------------- /7KYU/sum_digits.py: -------------------------------------------------------------------------------- 1 | def sum_digits(num: int) -> int: 2 | return sum([int(i) for i in str(abs(num))]) 3 | -------------------------------------------------------------------------------- /7KYU/sum_even_numbers.py: -------------------------------------------------------------------------------- 1 | def sum_even_numbers(seq: list) -> int: 2 | return 0 if len(seq) == 0 else sum([i for i in seq if not i % 2]) -------------------------------------------------------------------------------- /7KYU/sum_from_string.py: -------------------------------------------------------------------------------- 1 | # https://www.codewars.com/kata/55da6c52a94744b379000036/ 2 | 3 | from re import findall 4 | 5 | 6 | def sum_from_string(strng: str) -> int: 7 | return sum(map(int, findall(r'[0-9]+', strng))) -------------------------------------------------------------------------------- /7KYU/sum_no_duplicates.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/5993fb6c4f5d9f770c0000f2/ 2 | 3 | def sum_no_duplicates(l: list) -> int: 4 | return sum(i for i in l if l.count(i) == 1) 5 | -------------------------------------------------------------------------------- /7KYU/sum_of_all_arguments.py: -------------------------------------------------------------------------------- 1 | def sum_args(*args): 2 | return sum(args) 3 | 4 | # test.assert_equals(sum_args(0, 1, 2, 3), 6) 5 | -------------------------------------------------------------------------------- /7KYU/sum_of_digits.py: -------------------------------------------------------------------------------- 1 | def sum_of_digits(digits) -> str: 2 | if not str(digits).isdecimal(): 3 | return '' 4 | else: 5 | return f'{" + ".join([i for i in str(digits)])} = {sum([int(i) for i in str(digits)])}' 6 | -------------------------------------------------------------------------------- /7KYU/sum_of_integers_in_string.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | 4 | def sum_of_integers_in_string(s: str) -> int: 5 | """ This function calculates the sum of the integers inside a string """ 6 | return sum([int(i) for i in re.findall(r'\d+', s)]) -------------------------------------------------------------------------------- /7KYU/sum_of_minimums.py: -------------------------------------------------------------------------------- 1 | def sum_of_minimums(numbers: list) -> int: 2 | """ 3 | This function returns the sum of minimum value in each row. 4 | """ 5 | return sum([min(i) for i in numbers]) 6 | -------------------------------------------------------------------------------- /7KYU/sum_or_product.py: -------------------------------------------------------------------------------- 1 | from numpy import prod 2 | 3 | 4 | def sum_or_product(array: list, n: int) -> str: 5 | sorted_array = sorted(array) 6 | sum_high, prod_low = sum(sorted_array[::-1][:n]), prod(sorted_array[:n]) 7 | return 'sum' if sum_high > prod_low else 'product' if prod_low > sum_high else 'same' 8 | -------------------------------------------------------------------------------- /7KYU/sum_ppg.py: -------------------------------------------------------------------------------- 1 | from typing import Union 2 | 3 | 4 | def sum_ppg(playerOne: dict, playerTwo: dict) -> Union[int, float]: 5 | return playerOne['ppg'] + playerTwo['ppg'] 6 | 7 | -------------------------------------------------------------------------------- /7KYU/sum_square_even_root_odd.py: -------------------------------------------------------------------------------- 1 | from math import sqrt 2 | from typing import List, Union 3 | 4 | 5 | def sum_square_even_root_odd(nums: List[(Union[int, float])]) -> float: 6 | sum_nums = 0 7 | for i in nums: 8 | if i % 2 == 0: 9 | sum_nums += pow(i, 2) 10 | else: 11 | sum_nums += sqrt(i) 12 | return round(sum_nums, 2) -------------------------------------------------------------------------------- /7KYU/sum_triangular_numbers.py: -------------------------------------------------------------------------------- 1 | def sum_triangular_numbers(n: int) -> int: 2 | if n <= 0: 3 | return 0 4 | elif n == 1: 5 | return n 6 | sum_numbers = 0 7 | for i in range(1, n + 2): 8 | sum_numbers += (i * (i - 1)) // 2 9 | return sum_numbers 10 | -------------------------------------------------------------------------------- /7KYU/sum_two_smallest_numbers.py: -------------------------------------------------------------------------------- 1 | def sum_two_smallest_numbers(numbers): 2 | sort_numbers = sorted(numbers) 3 | return (sort_numbers[0]+sort_numbers[1]) -------------------------------------------------------------------------------- /7KYU/summy.py: -------------------------------------------------------------------------------- 1 | def summy(string_of_ints: str) -> int: 2 | return sum([int(i) for i in string_of_ints.split(' ')]) -------------------------------------------------------------------------------- /7KYU/swap.py: -------------------------------------------------------------------------------- 1 | def swap(string_: str) -> str: 2 | """ Swap the case for each of the letters. """ 3 | return string_.swapcase() 4 | -------------------------------------------------------------------------------- /7KYU/swap_v2.py: -------------------------------------------------------------------------------- 1 | def swap(st: str) -> str: 2 | return st.translate(str.maketrans('aeiou', 'AEIOU')) -------------------------------------------------------------------------------- /7KYU/swap_vowel_case.py: -------------------------------------------------------------------------------- 1 | def swap_vowel_case(st: str) -> str: 2 | return ''.join(i.swapcase() if i in 'aeouiAEOUI' else i for i in st) 3 | -------------------------------------------------------------------------------- /7KYU/switch_dict.py: -------------------------------------------------------------------------------- 1 | def switch_dict(d: dict): 2 | new_dict: dict = {} 3 | for key, value in d.items(): 4 | if value not in new_dict: 5 | new_dict[value] = [] 6 | new_dict[value].append(key) 7 | return new_dict 8 | -------------------------------------------------------------------------------- /7KYU/switcheroo.py: -------------------------------------------------------------------------------- 1 | def switcheroo(string: str) -> str: 2 | return string.replace('a', '-').replace('b', 'a').replace('-', 'b') 3 | -------------------------------------------------------------------------------- /7KYU/t_area.py: -------------------------------------------------------------------------------- 1 | def t_area(t_str: str) -> float: 2 | return (t_str.count("\n") - 2) ** 2 / 2 3 | -------------------------------------------------------------------------------- /7KYU/task_trim.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/563fb342f47611dae800003c/ 2 | 3 | def trim(phrase: str, size: int) -> str: 4 | len_phrase: int = len(phrase) 5 | if size >= len_phrase: 6 | return phrase 7 | elif size < 3: 8 | return f'{phrase[:size]}...' 9 | else: 10 | return f'{phrase[:size-3]}...' 11 | -------------------------------------------------------------------------------- /7KYU/testit.py: -------------------------------------------------------------------------------- 1 | def testit(a: int, b: int) -> int: 2 | return a | b 3 | -------------------------------------------------------------------------------- /7KYU/textin.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | 4 | def textin(s: str) -> str: 5 | return re.sub('two|too|to', '2', s, flags=re.IGNORECASE) -------------------------------------------------------------------------------- /7KYU/tidyNumber.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/5a87449ab1710171300000fd/ 2 | 3 | def tidyNumber(n: int) -> bool: 4 | str_num: str = str(n) 5 | return all(str_num[i] <= str_num[i + 1] for i in range(len(str_num) - 1)) 6 | -------------------------------------------------------------------------------- /7KYU/time_for_milk_and_cookies.py: -------------------------------------------------------------------------------- 1 | def time_for_milk_and_cookies(dt): 2 | if dt.month == 12 and dt.day == 24: 3 | return True 4 | return False -------------------------------------------------------------------------------- /7KYU/to24hourtime.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/59b0a6da44a4b7080300008a/ 2 | 3 | from datetime import datetime 4 | 5 | 6 | def to24hourtime(hour: int, minute: int, period: str) -> str: 7 | time = datetime.strptime(f"{hour}:{minute} {period}", "%I:%M %p") 8 | return time.strftime("%H%M") 9 | -------------------------------------------------------------------------------- /7KYU/to_12_hour_time.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/59b0ab12cf3395ef68000081/ 2 | 3 | from datetime import datetime 4 | 5 | 6 | def to_12_hour_time(time_string: str) -> str: 7 | time_string_datetime = datetime.strptime(time_string, "%H%M") 8 | return time_string_datetime.strftime("%-I:%M %p").lower() 9 | -------------------------------------------------------------------------------- /7KYU/to_acronym.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/57a60bad72292d3e93000a5a/ 2 | 3 | 4 | def to_acronym(inp: str) -> str: 5 | """ This function takes a string and make an acronym of it. """ 6 | return ''.join(i[0] for i in inp.split()).upper() 7 | -------------------------------------------------------------------------------- /7KYU/to_float_array.py: -------------------------------------------------------------------------------- 1 | def to_float_array(arr: list) -> list: 2 | return [float(i) for i in arr] 3 | -------------------------------------------------------------------------------- /7KYU/to_time.py: -------------------------------------------------------------------------------- 1 | def to_time(seconds: int) -> str: 2 | return f'{seconds // 3600} hour(s) and {(seconds // 60) % 60} minute(s)' 3 | -------------------------------------------------------------------------------- /7KYU/transform.py: -------------------------------------------------------------------------------- 1 | def transform(s: list) -> str: 2 | return ''.join(map(str, s)) -------------------------------------------------------------------------------- /7KYU/triangle.py: -------------------------------------------------------------------------------- 1 | triangle = lambda a,b,c: abs(a-c) list: 2 | result = [arr[0]] 3 | for i in range(1, len(arr)): 4 | if result[-1] + arr[i] == target: 5 | continue 6 | else: 7 | result.append(arr[i]) 8 | return result 9 | 10 | 11 | trouble([1, 2, 3, 4, 5], 3) 12 | -------------------------------------------------------------------------------- /7KYU/two_oldest_ages.py: -------------------------------------------------------------------------------- 1 | def two_oldest_ages(ages: list) -> list: 2 | """ This function returns the two highest numbers within the array. """ 3 | return sorted(ages)[-2:] -------------------------------------------------------------------------------- /7KYU/unique.py: -------------------------------------------------------------------------------- 1 | def unique(integers: list) -> list: 2 | if len(integers) == 0: 3 | return [] 4 | return list(dict.fromkeys(integers)) 5 | -------------------------------------------------------------------------------- /7KYU/unscramble_eggs.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/55ea5650fe9247a2ea0000a7/ 2 | 3 | from re import sub 4 | 5 | 6 | def unscramble_eggs(word: str) -> str: 7 | return sub('egg', '', word) 8 | -------------------------------------------------------------------------------- /7KYU/unused_digits.py: -------------------------------------------------------------------------------- 1 | def unused_digits(*args) -> str: 2 | """ Given a list of integers, return the digits that are not present in any of them. """ 3 | digit: set = set(''.join(map(str, [i for i in range(0, 10)]))) 4 | digit_from_args: set = set(''.join(map(str, [i for i in args]))) 5 | return ''.join(sorted(digit - digit_from_args)) 6 | -------------------------------------------------------------------------------- /7KYU/valid_number.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | 4 | def valid_number(n: str) -> bool: 5 | result = re.match(r'^(\+|\-)?(\d+)?\.(\d\d)$', n) 6 | return True if result else False 7 | -------------------------------------------------------------------------------- /7KYU/valid_spacing.py: -------------------------------------------------------------------------------- 1 | def valid_spacing(s: str) -> bool: 2 | if s != ' '.join([i for i in s.split()]): 3 | return False 4 | return True 5 | -------------------------------------------------------------------------------- /7KYU/validate_pin.py: -------------------------------------------------------------------------------- 1 | def validate_pin(pin): 2 | if len(pin) < 4 or len(pin) == 5 or len(pin) > 6 or not pin.isdecimal(): 3 | return False 4 | return True -------------------------------------------------------------------------------- /7KYU/validate_word.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | 4 | def validate_word(s: str) -> bool: 5 | count = Counter(s.lower()) 6 | return True if len(set(count.values())) < 2 else False 7 | -------------------------------------------------------------------------------- /7KYU/vaporcode.py: -------------------------------------------------------------------------------- 1 | def vaporcode(s: str) -> str: 2 | """ This function converts any sentence into a V A P O R W A V E sentence """ 3 | return ' '.join(i.upper() for i in s if i != ' ') 4 | -------------------------------------------------------------------------------- /7KYU/vector_length.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/554dc2b88fbafd2e95000125/ 2 | 3 | def vector_length(vector: list): 4 | """ This function returns the vector's length """ 5 | return sum([(k - i)**2 for i, k in zip(vector[0], vector[1])])**0.5 6 | -------------------------------------------------------------------------------- /7KYU/vert_and_hor_mirror.py: -------------------------------------------------------------------------------- 1 | def vert_mirror(s: str) -> str: 2 | return '\n'.join([''.join(list(reversed(i))) for i in s.split('\n')]) 3 | 4 | 5 | def hor_mirror(s: str) -> str: 6 | return '\n'.join(reversed([i for i in s.split('\n')])) 7 | 8 | 9 | def oper(fct, s): 10 | return fct(s) 11 | -------------------------------------------------------------------------------- /7KYU/vowel_change.py: -------------------------------------------------------------------------------- 1 | def vowel_change(txt: str, vow: str) -> str: 2 | return ''.join(i.replace(i, vow) if i in 'aeiou' else i for i in txt) 3 | -------------------------------------------------------------------------------- /7KYU/vowel_indices.py: -------------------------------------------------------------------------------- 1 | def vowel_indices(word: str) -> list: 2 | """ 3 | This function returns list with index of the vowels in a given string. 4 | """ 5 | return [i for i, k in enumerate(word, start=1) if k.lower() in 'aeiouy'] 6 | -------------------------------------------------------------------------------- /7KYU/vowel_one.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/580751a40b5a777a200000a1/ 2 | 3 | def vowel_one(s: str) -> str: 4 | return ''.join(['1' if i in 'aeiou' else '0' for i in s.lower()]) 5 | -------------------------------------------------------------------------------- /7KYU/vowel_to_index.py: -------------------------------------------------------------------------------- 1 | def vowel_2_index(s: str) -> str: 2 | vowel = ['a', 'e', 'i', 'o', 'u'] 3 | my_string = '' 4 | for i, k in enumerate(s, start = 1): 5 | if k.lower() not in vowel: 6 | my_string += k 7 | elif k.lower() in vowel: 8 | my_string += str(i) 9 | return my_string -------------------------------------------------------------------------------- /7KYU/without_last.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/5a4ff3c5fd56cbaf9800003e/ 2 | 3 | def without_last(lst: list) -> list: 4 | return lst[:-1] 5 | -------------------------------------------------------------------------------- /7KYU/word_splitter.py: -------------------------------------------------------------------------------- 1 | SEPARATOR: list = [':', ',', '*', ';', '#', '|', '+', '%', '>', '?', '&', '=', '!'] 2 | def word_splitter(string: str) -> list: 3 | for i in string: 4 | if i in SEPARATOR: 5 | string = string.replace(i, ' ') 6 | return string.split() 7 | -------------------------------------------------------------------------------- /7KYU/word_to_bin.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | def word_to_bin(word: str) -> List[str]: 5 | list_word_to_bin = [bin(ord(letter))[2:].zfill(8) for letter in word] 6 | return list_word_to_bin 7 | -------------------------------------------------------------------------------- /7KYU/words_to_marks.py: -------------------------------------------------------------------------------- 1 | from string import ascii_lowercase 2 | 3 | 4 | def words_to_marks(s: str) -> int: 5 | letter: dict = {v:k for k, v in enumerate(ascii_lowercase, 1)} 6 | return sum(letter.get(i) for i in s) 7 | -------------------------------------------------------------------------------- /7KYU/words_to_sentence.py: -------------------------------------------------------------------------------- 1 | def words_to_sentence(words: list) -> str: 2 | """ This function create a string from a list of strings, separated by space. """ 3 | return ' '.join(words) 4 | -------------------------------------------------------------------------------- /7KYU/wrap.py: -------------------------------------------------------------------------------- 1 | def wrap(height, width, length): 2 | min_val = min(height, width, length) 3 | if min_val == height: 4 | return (height * 4 + length * 2 + width * 2) + 20 5 | elif min_val == width: 6 | return (width * 4 + height * 2 + length * 2) + 20 7 | return (length * 4 + height * 2 + width * 2) + 20 8 | -------------------------------------------------------------------------------- /8KYU/abbrev_name.py: -------------------------------------------------------------------------------- 1 | def abbrev_name(name: str) -> str: 2 | """ This function converts a name into initials. """ 3 | my_abbrev = '' 4 | for i in name.split(' '): 5 | my_abbrev += i[0] 6 | return '.'.join(map(str, my_abbrev.upper())) -------------------------------------------------------------------------------- /8KYU/add_length.py: -------------------------------------------------------------------------------- 1 | def add_length(s: str) -> list: 2 | words_with_len = [] 3 | for i in s.split(): 4 | words_with_len.append(i + ' ' + str(len(i))) 5 | return words_with_len -------------------------------------------------------------------------------- /8KYU/approx_equals.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/5f9f43328a6bff002fa29eb8/ 2 | 3 | def approx_equals(a: float, b: float) -> bool: 4 | diff: float = 0.001 5 | return abs(a - b) < diff 6 | -------------------------------------------------------------------------------- /8KYU/areYouPlayingBanjo.py: -------------------------------------------------------------------------------- 1 | def areYouPlayingBanjo(name: str) -> str: 2 | if name.startswith('R') or name.startswith('r'): 3 | return f'{name} plays banjo' 4 | return f'{name} does not play banjo' -------------------------------------------------------------------------------- /8KYU/area_or_perimeter.py: -------------------------------------------------------------------------------- 1 | def area_or_perimeter(length: int, width: int) -> int: 2 | """ This function returns area for a square or perimeter for a rectangle. """ 3 | if length == width: 4 | return length * width 5 | return (2 * length) + (2 * width) -------------------------------------------------------------------------------- /8KYU/array_madness.py: -------------------------------------------------------------------------------- 1 | def array_madness(arr1: list, arr2: list) -> bool: 2 | """ This function returns True if the sum of the squares of each element in arr1 is strictly greater than the sum of the cubes of each element in arr2. """ 3 | if len(arr1) and len(arr2) >= 1: 4 | return True if sum([i**2 for i in arr1]) > sum([i**3 for i in arr2]) else False 5 | return False -------------------------------------------------------------------------------- /8KYU/arrays_merge.py: -------------------------------------------------------------------------------- 1 | def merge_arrays(arr1: list, arr2: list) -> list: 2 | return sorted(list(set(arr1) | set(arr2))) -------------------------------------------------------------------------------- /8KYU/authenticate.py: -------------------------------------------------------------------------------- 1 | class Sleigh(object): 2 | def authenticate(self, name, password): 3 | if name == 'Santa Claus' and password == 'Ho Ho Ho!': 4 | return True 5 | return False -------------------------------------------------------------------------------- /8KYU/ball.py: -------------------------------------------------------------------------------- 1 | class Ball(object): 2 | def __init__(self, ball_type: str = "regular"): 3 | self.ball_type = ball_type 4 | -------------------------------------------------------------------------------- /8KYU/basic_op.py: -------------------------------------------------------------------------------- 1 | def basic_op(operator, value1, value2): 2 | if operator == '+': 3 | return value1 + value2 4 | elif operator == '-': 5 | return value1 - value2 6 | elif operator == '*': 7 | return value1 * value2 8 | else: 9 | return value1 / value2 -------------------------------------------------------------------------------- /8KYU/better_than_average.py: -------------------------------------------------------------------------------- 1 | from numpy import average 2 | 3 | 4 | def better_than_average(class_points: list, your_points: int) -> bool: 5 | return your_points > average(class_points) -------------------------------------------------------------------------------- /8KYU/between.py: -------------------------------------------------------------------------------- 1 | def between(a: int, b: int) -> list: 2 | return [item for item in range(a, b + 1)] -------------------------------------------------------------------------------- /8KYU/bmi.py: -------------------------------------------------------------------------------- 1 | def bmi(weight, height) -> str: 2 | """ This function calculates body mass index. """ 3 | body_mass_index = weight / pow(height, 2) 4 | if body_mass_index <= 18.5: 5 | return "Underweight" 6 | elif body_mass_index <= 25.0: 7 | return "Normal" 8 | elif body_mass_index <= 30.0: 9 | return "Overweight" 10 | return "Obese" -------------------------------------------------------------------------------- /8KYU/bonus_time.py: -------------------------------------------------------------------------------- 1 | def bonus_time(salary:int, bonus:bool): 2 | if bonus is True: 3 | return ("$"+str(salary*10)) 4 | return ("$"+str(salary)) -------------------------------------------------------------------------------- /8KYU/build_string.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/55c90cad4b0fe31a7200001f/ 2 | 3 | 4 | def build_string(*args) -> str: 5 | return "I like {0}!".format(", ".join(args)) 6 | -------------------------------------------------------------------------------- /8KYU/century.py: -------------------------------------------------------------------------------- 1 | def century(year: int) -> int: 2 | """This function returns the century by year.""" 3 | if year % 100 == 0: 4 | year //= 100 5 | return year 6 | else: 7 | year //= 100 8 | return year + 1 -------------------------------------------------------------------------------- /8KYU/class_cat.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/55a14aa4817efe41c20000bc/ 2 | 3 | 4 | from preloaded import Animal 5 | 6 | 7 | class Cat(Animal): 8 | 9 | def speak(self): 10 | 11 | return f'{self.name} meows.' 12 | -------------------------------------------------------------------------------- /8KYU/class_ghost.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | 4 | class Ghost(object): 5 | def __init__(self): 6 | self.color = random.choice(["white", "yellow", "purple", "red"]) 7 | 8 | ghost = Ghost() -------------------------------------------------------------------------------- /8KYU/classic_hello_world.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/57036f007fd72e3b77000023/ 2 | 3 | 4 | class Solution: 5 | 6 | def main(self): 7 | print('Hello World!') 8 | -------------------------------------------------------------------------------- /8KYU/close_compare.py: -------------------------------------------------------------------------------- 1 | def close_compare(a, b, margin = 0) -> int: 2 | if margin == 0: 3 | if a > b: 4 | return 1 5 | elif a < b: 6 | return -1 7 | else: 8 | return 0 9 | else: 10 | if abs(a - b) <= margin: 11 | return 0 12 | elif a - b > margin: 13 | return 1 14 | else: 15 | return -1 16 | -------------------------------------------------------------------------------- /8KYU/combine_names.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://codewars.com/kata/55f73f66d160f1f1db000059/ 2 | 3 | def combine_names(*args) -> str: 4 | return f'{args[0]} {args[1]}' 5 | -------------------------------------------------------------------------------- /8KYU/contamination.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/596fba44963025c878000039/ 2 | 3 | from re import sub 4 | 5 | 6 | def contamination(text: str, char: str) -> str: 7 | return sub(r'\S', char, text) 8 | -------------------------------------------------------------------------------- /8KYU/count_by.py: -------------------------------------------------------------------------------- 1 | def count_by(x: int, n: int) -> list: 2 | """ This function returns a sequence of numbers counting by `x` `n` times. """ 3 | # first way 4 | seq = [] 5 | for i in range(1, n + 1): 6 | seq.append(i * x) 7 | return seq 8 | # second way 9 | # return [i * x for i in range(1, n+1)] -------------------------------------------------------------------------------- /8KYU/count_positives_sum_negatives.py: -------------------------------------------------------------------------------- 1 | def count_positives_sum_negatives(arr): 2 | if len(arr) == 0: 3 | return [] 4 | pos = [] 5 | neg = [] 6 | for i in arr: 7 | if i > 0: 8 | pos.append(i) 9 | else: 10 | neg.append(i) 11 | return [len(pos), sum(neg)] -------------------------------------------------------------------------------- /8KYU/count_sheep.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/5b077ebdaf15be5c7f000077/ 2 | 3 | def count_sheep(n: int) -> str: 4 | return ''.join(f'{i} sheep...' for i in range(1, n + 1)) 5 | -------------------------------------------------------------------------------- /8KYU/cube_checker.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/58d248c7012397a81800005c/ 2 | 3 | def cube_checker(volume: int, side: int) -> bool: 4 | return pow(side, 3) == volume if volume > 0 and side > 0 else False -------------------------------------------------------------------------------- /8KYU/dating_range.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/5803956ddb07c5c74200144e/ 2 | 3 | def dating_range(age: int) -> str: 4 | if age <= 14: 5 | min_age = int(age - 0.10 * age) 6 | max_age = int(age + 0.10 * age) 7 | else: 8 | min_age = (age // 2) + 7 9 | max_age = (age - 7) * 2 10 | return f"{min_age}-{max_age}" 11 | -------------------------------------------------------------------------------- /8KYU/difference_in_ages.py: -------------------------------------------------------------------------------- 1 | def difference_in_ages(ages: list) -> tuple: 2 | """ This function returns 'min', 'max' in ages and calculate the difference between them. """ 3 | return (min(ages), max(ages), max(ages) - min(ages)) -------------------------------------------------------------------------------- /8KYU/digitize.py: -------------------------------------------------------------------------------- 1 | def digitize(n: int) -> list: 2 | num = [] 3 | for el in str(n): 4 | num.append((int(el))) 5 | return list(reversed(num)) -------------------------------------------------------------------------------- /8KYU/distance_between_points.py: -------------------------------------------------------------------------------- 1 | from math import sqrt 2 | 3 | 4 | def distance_between_points(a, b): 5 | return round(sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2), 6) 6 | -------------------------------------------------------------------------------- /8KYU/divide_numbers.py: -------------------------------------------------------------------------------- 1 | def divide_numbers(x,y): 2 | try: 3 | return x / y 4 | except ZeroDivisionError: 5 | return 'Division by zero :-(' -------------------------------------------------------------------------------- /8KYU/divisible_by.py: -------------------------------------------------------------------------------- 1 | def divisible_by(numbers: list, divisor: int) -> list: 2 | """This function returns all numbers which are divisible by the given divisor.""" 3 | if numbers is None: 4 | return [] 5 | res = [] 6 | for item in numbers: 7 | if item % divisor == 0: 8 | res.append(item) 9 | return res -------------------------------------------------------------------------------- /8KYU/double_integer.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | 4 | def double_integer(i: int) -> int: 5 | if i >= 0: 6 | return round(2 * math.sqrt(i) * math.sqrt(i)) 7 | return 2 * i -------------------------------------------------------------------------------- /8KYU/each_cons.py: -------------------------------------------------------------------------------- 1 | def each_cons(arr: list, n: int) -> list: 2 | # First way 3 | result: list = [] 4 | i: int = 0 5 | while i < len(arr) - n + 1: 6 | result.append(arr[i:i+n]) 7 | i += 1 8 | return result 9 | 10 | # Second way 11 | # return [arr[i:i+n] for i in range(len(arr) - n + 1)] 12 | -------------------------------------------------------------------------------- /8KYU/enough.py: -------------------------------------------------------------------------------- 1 | def enough(cap: int, on: int, wait: int) -> int: 2 | return 0 if (cap >= on + wait) else abs(cap-(on+wait)) -------------------------------------------------------------------------------- /8KYU/ensure_question.py: -------------------------------------------------------------------------------- 1 | def ensure_question(s: str) -> str: 2 | return s if s.endswith('?') else s + '?' -------------------------------------------------------------------------------- /8KYU/excluding_vat_price.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/5890d8bc9f0f422cf200006b/ 2 | 3 | def excluding_vat_price(price): 4 | 5 | """ 6 | This function calculates the original product price, without VAT. 7 | """ 8 | 9 | return round(price / 1.15, 2) if price else -1 10 | -------------------------------------------------------------------------------- /8KYU/fake_bin.py: -------------------------------------------------------------------------------- 1 | def fake_bin(x:str): 2 | my_str = [] 3 | for num in x: 4 | if int(num) >= 5: 5 | num = 1 6 | my_str.append(num) 7 | else: 8 | num = 0 9 | my_str.append(num) 10 | return (''.join(map(str, my_str))) -------------------------------------------------------------------------------- /8KYU/find_difference.py: -------------------------------------------------------------------------------- 1 | from numpy import prod 2 | 3 | 4 | def find_difference(a: list, b: list) -> int: 5 | return abs(prod(a) - prod(b)) -------------------------------------------------------------------------------- /8KYU/find_index.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/5703c093022cd1aae90012c9/ 2 | 3 | def find(arr, el): 4 | try: return arr.index(el) 5 | except: return "Not found" -------------------------------------------------------------------------------- /8KYU/find_longest.py: -------------------------------------------------------------------------------- 1 | def find_longest(string: str) -> int: 2 | return max([len(i) for i in string.split()]) -------------------------------------------------------------------------------- /8KYU/find_multiples.py: -------------------------------------------------------------------------------- 1 | def find_multiples(integer: int, limit: int) -> list: 2 | return [i for i in range(integer, limit + 1) if i % integer == 0] -------------------------------------------------------------------------------- /8KYU/find_needle.py: -------------------------------------------------------------------------------- 1 | def find_needle(haystack): 2 | for i, el in enumerate(haystack): 3 | if el == 'needle': 4 | return (f"found the needle at position {i}".format(i)) -------------------------------------------------------------------------------- /8KYU/first.py: -------------------------------------------------------------------------------- 1 | def first(seq: list, n: int = 1) -> list: 2 | if n == 0: 3 | return [] 4 | return seq[:n] 5 | -------------------------------------------------------------------------------- /8KYU/fix_the_meerkat.py: -------------------------------------------------------------------------------- 1 | def fix_the_meerkat(arr: list) -> list: 2 | return arr[::-1] -------------------------------------------------------------------------------- /8KYU/format_money.py: -------------------------------------------------------------------------------- 1 | def format_money(amount) -> str: 2 | return f'${amount:.2f}' -------------------------------------------------------------------------------- /8KYU/generate_link.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/57037ed25a7263ac35000c80/ 2 | 3 | import urllib.parse 4 | 5 | 6 | def generate_link(user: str) -> str: 7 | return f"http://www.codewars.com/users/{urllib.parse.quote(user)}" 8 | -------------------------------------------------------------------------------- /8KYU/generate_range.py: -------------------------------------------------------------------------------- 1 | def generate_range(min: int, max: int, step: int) -> list: 2 | """ This function generates a range of integers from min to max, with the step. """ 3 | return [i for i in range(min, max + 1, step)] 4 | -------------------------------------------------------------------------------- /8KYU/get_real_floor.py: -------------------------------------------------------------------------------- 1 | def get_real_floor(n: int) -> int: 2 | if n < 0: 3 | return n 4 | elif abs(n) < 2: 5 | return 0 6 | elif n > 13: 7 | return n - 2 8 | return n - 1 9 | -------------------------------------------------------------------------------- /8KYU/get_size.py: -------------------------------------------------------------------------------- 1 | def get_size(w: int, h: int, d: int) -> list: 2 | return [2 * (w * h + h * d + w * d), w * h * d] -------------------------------------------------------------------------------- /8KYU/get_status.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/54fdaa4a50f167b5c000005f/ 2 | 3 | def get_status(is_busy: bool) -> dict: 4 | dict_with_status: dict = {'status': 'busy' if is_busy else 'available'} 5 | return dict_with_status 6 | -------------------------------------------------------------------------------- /8KYU/goose_filter.py: -------------------------------------------------------------------------------- 1 | geese = ["African", "Roman Tufted", "Toulouse", "Pilgrim", "Steinbacher"] 2 | def goose_filter(birds: list) -> list: 3 | return list(filter(lambda x: x not in geese, birds)) 4 | # return [i for i in birds if i not in geese] -------------------------------------------------------------------------------- /8KYU/grader.py: -------------------------------------------------------------------------------- 1 | def grader(score): 2 | if (score > 1) or (score < 0.6): 3 | return 'F' 4 | elif 0.8 < score <= 1: 5 | return 'A' 6 | elif 0.7 < score <= 0.8: 7 | return 'B' 8 | elif 0.6 < score <= 0.7: 9 | return 'C' 10 | elif score >= 0.6: 11 | return 'D' -------------------------------------------------------------------------------- /8KYU/greet.py: -------------------------------------------------------------------------------- 1 | def greet(name: str, owner: str) -> str: 2 | return "Hello boss" if name is owner else "Hello guest" -------------------------------------------------------------------------------- /8KYU/grow.py: -------------------------------------------------------------------------------- 1 | def grow(arr: list) -> int: 2 | """This function returns the result of multiplying the values.""" 3 | if len(arr) is None: 4 | return 0 5 | res = 1 6 | for item in arr: 7 | res *= item 8 | return res -------------------------------------------------------------------------------- /8KYU/include.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/545991b4cbae2a5fda000158/ 2 | 3 | def include(arr: list, item: int) -> bool: 4 | """ 5 | This function returns true if the item belongs to the list, otherwise false. 6 | """ 7 | return bool(arr.count(item)) 8 | -------------------------------------------------------------------------------- /8KYU/index.py: -------------------------------------------------------------------------------- 1 | def index(array: list, n: int) -> int: 2 | """ This function find the N-th power of the element in the array with the index N. """ 3 | for k, i in enumerate(range(len(array))): 4 | if i == n: 5 | return (array[i] ** n) 6 | return -1 -------------------------------------------------------------------------------- /8KYU/invert.py: -------------------------------------------------------------------------------- 1 | def invert(a:list): 2 | if len(a) is None: 3 | return [] 4 | my_invert = [] 5 | for item in a: 6 | if item > 0: 7 | item *= -1 8 | my_invert.append(item) 9 | else: 10 | item *= -1 11 | my_invert.append(item) 12 | return my_invert -------------------------------------------------------------------------------- /8KYU/isDigit.py: -------------------------------------------------------------------------------- 1 | def isDigit(s: str) -> bool: 2 | return s.lstrip('-').replace('.', '', 1).isdigit() 3 | -------------------------------------------------------------------------------- /8KYU/is_digit.py: -------------------------------------------------------------------------------- 1 | def is_digit(n) -> bool: 2 | if len(n) > 1: 3 | return False 4 | return n.isdigit() -------------------------------------------------------------------------------- /8KYU/is_divisible.py: -------------------------------------------------------------------------------- 1 | def is_divisible(n,x,y): 2 | if n % x == 0 and n % y == 0: 3 | return True 4 | return False -------------------------------------------------------------------------------- /8KYU/is_today.py: -------------------------------------------------------------------------------- 1 | # https://www.codewars.com/kata/563c13853b07a8f17c000022/ 2 | 3 | from datetime import datetime 4 | 5 | 6 | def is_today(date) -> bool: 7 | return date.date() == datetime.today().date() -------------------------------------------------------------------------------- /8KYU/is_uppercase.py: -------------------------------------------------------------------------------- 1 | def is_uppercase(inp: str) -> bool: 2 | """ This function returns True if string is ALL CAPS else False. """ 3 | for i in inp.split(): 4 | if i.isupper(): 5 | return True 6 | return False -------------------------------------------------------------------------------- /8KYU/is_vow.py: -------------------------------------------------------------------------------- 1 | def is_vow(inp: list) -> list: 2 | result: list = [] 3 | for i in inp: 4 | if chr(i) in 'aeiou': 5 | result.append(chr(i)) 6 | else: 7 | result.append(i) 8 | return result 9 | -------------------------------------------------------------------------------- /8KYU/job_matching.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/56c22c5ae8b139416c00175d/ 2 | 3 | def job_matching(candidate: dict, job: dict) -> bool: 4 | return candidate['min_salary'] - (candidate['min_salary'] * 0.1) <= job['max_salary'] 5 | -------------------------------------------------------------------------------- /8KYU/litres.py: -------------------------------------------------------------------------------- 1 | from math import floor 2 | 3 | 4 | def litres(time): 5 | return (floor(time * 0.5)) -------------------------------------------------------------------------------- /8KYU/logical_calc.py: -------------------------------------------------------------------------------- 1 | from functools import reduce 2 | 3 | 4 | def logical_calc(array: list, op: str) -> bool: 5 | if op == "AND": 6 | return all(array) 7 | elif op == "OR": 8 | return any(array) 9 | elif op == "XOR": 10 | return reduce(lambda x, y: x ^ y, array) -------------------------------------------------------------------------------- /8KYU/logs.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/5b68c7029756802aa2000176/ 2 | 3 | from math import log 4 | 5 | 6 | def logs(x, a, b): 7 | return log(a * b, x) 8 | -------------------------------------------------------------------------------- /8KYU/lovefunc.py: -------------------------------------------------------------------------------- 1 | def lovefunc(flower1: int, flower2: int) -> bool: 2 | return True if (flower1 + flower2) % 2 else False 3 | -------------------------------------------------------------------------------- /8KYU/make_upper_case.py: -------------------------------------------------------------------------------- 1 | def make_upper_case(s: str) -> str: 2 | return s.upper() 3 | -------------------------------------------------------------------------------- /8KYU/maps.py: -------------------------------------------------------------------------------- 1 | def maps(a): 2 | return [int(i) * 2 for i in a] -------------------------------------------------------------------------------- /8KYU/merge_arrays.py: -------------------------------------------------------------------------------- 1 | def merge_arrays(first: list, second: list) -> list: 2 | return sorted(list(set(first + second))) -------------------------------------------------------------------------------- /8KYU/min_max.py: -------------------------------------------------------------------------------- 1 | from typing import List, Union 2 | 3 | 4 | def minimum(arr: List[(Union[int, float])]) -> Union[int, float]: 5 | return min(arr) 6 | 7 | def maximum(arr: List[(Union[int, float])]) -> Union[int, float]: 8 | return max(arr) -------------------------------------------------------------------------------- /8KYU/mouth_size.py: -------------------------------------------------------------------------------- 1 | def mouth_size(animal: str) -> str: 2 | return 'small' if animal.lower() == 'alligator' else 'wide' -------------------------------------------------------------------------------- /8KYU/mul_by_n.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/644661194e259c035311ada7/ 2 | 3 | def mul_by_n(lst: list, n: int) -> list: 4 | return [i * n for i in lst] -------------------------------------------------------------------------------- /8KYU/multi_table.py: -------------------------------------------------------------------------------- 1 | def multi_table(number: int): 2 | """ This function returns multiplication table for 'number'. """ 3 | return '\n'.join(f'{i} * {number} = {i * number}' for i in range(1, 11)) -------------------------------------------------------------------------------- /8KYU/multiple_of_index.py: -------------------------------------------------------------------------------- 1 | def multiple_of_index(arr: list) -> list: 2 | return [arr[i] for i in range(1, len(arr)) if arr[i] % i == 0] -------------------------------------------------------------------------------- /8KYU/name_shuffler.py: -------------------------------------------------------------------------------- 1 | def name_shuffler(s: str): 2 | return ' '.join(reversed(list(s.split(' ')))) -------------------------------------------------------------------------------- /8KYU/name_your_python.py: -------------------------------------------------------------------------------- 1 | class Python(object): 2 | def __init__(self, name): 3 | self.name = name 4 | 5 | 6 | obj = Python('Bubba') -------------------------------------------------------------------------------- /8KYU/nba_extrap.py: -------------------------------------------------------------------------------- 1 | def nba_extrap(ppg, mpg) -> float: 2 | try: 3 | return round((48 * ppg) / mpg, 1) 4 | except ZeroDivisionError: 5 | return 0 -------------------------------------------------------------------------------- /8KYU/nearest_sq.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/5a805d8cafa10f8b930005ba/ 2 | 3 | 4 | def nearest_sq(n: int) -> int: 5 | return pow(round(n ** 0.5), 2) 6 | -------------------------------------------------------------------------------- /8KYU/no_boring_zeros.py: -------------------------------------------------------------------------------- 1 | from numpy import trim_zeros 2 | 3 | 4 | def no_boring_zeros(num: int) -> int: 5 | digit_num = [] 6 | for i in str(abs(num)): 7 | digit_num.append(int(i)) 8 | if num < 0: 9 | return int(f'-{"".join(map(str, trim_zeros(digit_num)))}') 10 | elif num == 0: 11 | return 0 12 | return int("".join(map(str, trim_zeros(digit_num)))) -------------------------------------------------------------------------------- /8KYU/nth_even.py: -------------------------------------------------------------------------------- 1 | def nth_even(n: int) -> int: 2 | return 2 * (n - 1) -------------------------------------------------------------------------------- /8KYU/number_to_pwr.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/562926c855ca9fdc4800005b/ 2 | 3 | def number_to_pwr(number: int, p: int) -> int: 4 | result = 1 5 | for _ in range(1, p + 1): 6 | result *= number 7 | return result -------------------------------------------------------------------------------- /8KYU/other_angle.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/5a023c426975981341000014/ 2 | 3 | from typing import Union 4 | 5 | 6 | def other_angle(a: Union[int, float], b: Union[int, float]) -> Union[int, float]: 7 | return 180 - (a + b) 8 | -------------------------------------------------------------------------------- /8KYU/parse_float.py: -------------------------------------------------------------------------------- 1 | def parse_float(string: str) -> float: 2 | if type(string) == list: 3 | return None 4 | try: 5 | return float(string) 6 | except ValueError: 7 | return None -------------------------------------------------------------------------------- /8KYU/past.py: -------------------------------------------------------------------------------- 1 | def past(h: int, m: int, s: int) -> int: 2 | """ This function returns time converted to milliseconds. """ 3 | return (h * 3600 + m * 60 + s) * 1000 -------------------------------------------------------------------------------- /8KYU/people_with_age_drink.py: -------------------------------------------------------------------------------- 1 | def people_with_age_drink(age: int) -> str: 2 | drinks = ['toddy', 'coke', 'beer', 'whisky'] 3 | if age < 14: 4 | return f'drink {drinks[0]}' 5 | elif 14 <= age < 18: 6 | return f'drink {drinks[1]}' 7 | elif 18 <= age < 21: 8 | return f'drink {drinks[2]}' 9 | return f'drink {drinks[-1]}' -------------------------------------------------------------------------------- /8KYU/period_is_late.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/578a8a01e9fd1549e50001f1/ 2 | 3 | 4 | def period_is_late(last, today, cycle_length: int) -> bool: 5 | return (today-last).days > cycle_length 6 | -------------------------------------------------------------------------------- /8KYU/pipe_fix.py: -------------------------------------------------------------------------------- 1 | def pipe_fix(nums: list) -> list: 2 | return [n for n in range(nums[0], nums[-1] + 1)] -------------------------------------------------------------------------------- /8KYU/points.py: -------------------------------------------------------------------------------- 1 | def points(games: list) -> int: 2 | """ This function counts the points of our team in the championship. """ 3 | score = 0 4 | for item in range(len(games)): 5 | x = games[item][0] 6 | y = games[item][2] 7 | if x > y: 8 | score += 3 9 | elif x == y: 10 | score += 1 11 | return score -------------------------------------------------------------------------------- /8KYU/position.py: -------------------------------------------------------------------------------- 1 | from string import ascii_lowercase 2 | 3 | 4 | def position(alphabet: str): 5 | dict_letters = {letter: str(index) for index, letter in enumerate(ascii_lowercase, start=1)} 6 | if alphabet in dict_letters: 7 | return f'Position of alphabet: {dict_letters[alphabet]}' -------------------------------------------------------------------------------- /8KYU/powers_of_two.py: -------------------------------------------------------------------------------- 1 | def powers_of_two(n: int) -> list: 2 | return [2 ** i for i in range(n+1)] 3 | -------------------------------------------------------------------------------- /8KYU/problem.py: -------------------------------------------------------------------------------- 1 | def problem(a): 2 | if type(a) != str: 3 | return (a * 50) + 6 4 | return 'Error' -------------------------------------------------------------------------------- /8KYU/pythagorean_triple.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/5951d30ce99cf2467e000013/ 2 | 3 | 4 | def pythagorean_triple(integers: list) -> bool: 5 | integers = sorted(integers) 6 | return pow(integers[0], 2) + pow(integers[1], 2) == pow(integers[2], 2) -------------------------------------------------------------------------------- /8KYU/quarter_of.py: -------------------------------------------------------------------------------- 1 | def quarter_of(month: int) -> int: 2 | """ This function returns to which quarter of the year it belongs as an integer number. """ 3 | quartal = {1: [1, 2, 3], 4 | 2: [4, 5, 6], 5 | 3: [7, 8, 9], 6 | 4: [10, 11, 12]} 7 | for key, val in quartal.items(): 8 | for i in val: 9 | if i == month: 10 | return key -------------------------------------------------------------------------------- /8KYU/remainder.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/524f5125ad9c12894e00003f/ 2 | 3 | def remainder(a, b): 4 | """ 5 | This function returns the remainder of dividing the larger value by the smaller value. 6 | """ 7 | try: 8 | larger, smaller = max(a, b), min(a, b) 9 | return larger % smaller 10 | except ZeroDivisionError: 11 | return None 12 | -------------------------------------------------------------------------------- /8KYU/remove.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/57faf7275c991027af000679/ 2 | 3 | 4 | def remove(s: str, n: int) -> str: 5 | """ 6 | Remove n exclamation marks in the sentence from left to right. n is positive integer. 7 | """ 8 | return s.replace('!', '', n) 9 | -------------------------------------------------------------------------------- /8KYU/remove_char.py: -------------------------------------------------------------------------------- 1 | def remove_char(x: str) -> str: 2 | return (x[1:-1]) -------------------------------------------------------------------------------- /8KYU/remove_every_other.py: -------------------------------------------------------------------------------- 1 | def remove_every_other(my_list: list) -> list: 2 | """ This function removes every second element from the array. """ 3 | new_list = [] 4 | for i, k in enumerate(range(len(my_list))): 5 | if i % 2 == 0: 6 | new_list.append(my_list[i]) 7 | return new_list -------------------------------------------------------------------------------- /8KYU/remove_exclamation_marks.py: -------------------------------------------------------------------------------- 1 | def remove_exclamation_marks(s: str) -> str: 2 | return s.replace('!', '') -------------------------------------------------------------------------------- /8KYU/reverse_list.py: -------------------------------------------------------------------------------- 1 | def reverse_list(l): 2 | return [i for i in reversed(l)] -------------------------------------------------------------------------------- /8KYU/reverse_words.py: -------------------------------------------------------------------------------- 1 | def reverse_words(s: str) -> str: 2 | words_from_s = [] 3 | for i in s.split(' '): 4 | words_from_s.append(i) 5 | return ' '.join(reversed(words_from_s)) -------------------------------------------------------------------------------- /8KYU/same_case.py: -------------------------------------------------------------------------------- 1 | def same_case(a: str, b: str) -> int: 2 | if not a.isalpha() or not b.isalpha(): 3 | return -1 4 | return 1 if a.islower() and b.islower() or a.isupper() and b.isupper() else 0 5 | -------------------------------------------------------------------------------- /8KYU/say_hello.py: -------------------------------------------------------------------------------- 1 | def say_hello(name: list, city: str, state: str) -> str: 2 | return f'Hello, {" ".join(name)}! Welcome to {city}, {state}! -------------------------------------------------------------------------------- /8KYU/shortcut.py: -------------------------------------------------------------------------------- 1 | def shortcut(s: str) -> str: 2 | """ This function removes all the lowercase vowels in a given string. """ 3 | vowel = ['a', 'e', 'i', 'o', 'u'] 4 | str_without_vowel = '' 5 | for letter in s: 6 | if letter not in vowel: 7 | str_without_vowel += letter 8 | return str_without_vowel -------------------------------------------------------------------------------- /8KYU/shorten_to_date.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/56b0ff16d4aa33e5bb00008e/ 2 | 3 | def shorten_to_date(long_date: str) -> str: 4 | return long_date.split(',')[0] 5 | -------------------------------------------------------------------------------- /8KYU/sorter.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/5a07e5b7ffe75fd049000051/ 2 | 3 | def sorter(textbooks: list) -> list: 4 | return sorted(textbooks, key=str.casefold) 5 | -------------------------------------------------------------------------------- /8KYU/sp_eng.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | 4 | def sp_eng(sentence: str) -> bool: 5 | result = re.search(r'english', sentence, re.IGNORECASE) 6 | return True if result else False 7 | -------------------------------------------------------------------------------- /8KYU/square.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | def square(n: int) -> int: 4 | """ This function returns the square of 'n'. """ 5 | return math.pow(n, 2) -------------------------------------------------------------------------------- /8KYU/square_area.py: -------------------------------------------------------------------------------- 1 | from math import pi 2 | 3 | 4 | def square_area(A): 5 | radius = 2 * A / pi 6 | return round(radius ** 2, 2) -------------------------------------------------------------------------------- /8KYU/square_or_square_root.py: -------------------------------------------------------------------------------- 1 | from math import sqrt 2 | 3 | 4 | def square_or_square_root(arr: list) -> list: 5 | result = [] 6 | for i in arr: 7 | if int(sqrt(i)) != i ** 0.5: 8 | result.append(i ** 2) 9 | else: 10 | result.append(int(sqrt(i))) 11 | return result 12 | -------------------------------------------------------------------------------- /8KYU/square_sum.py: -------------------------------------------------------------------------------- 1 | def square_sum(numbers): 2 | """ This function returns the square sum. """ 3 | return sum([i ** 2 for i in numbers]) if len(numbers) > 0 else 0 -------------------------------------------------------------------------------- /8KYU/str_count.py: -------------------------------------------------------------------------------- 1 | def str_count(string: str, letter: str) -> int: 2 | """ This function returns an integer of the count of occurrences the 2nd argument is found in the first one. """ 3 | count_letter = 0 4 | for i in string: 5 | if i == letter: 6 | count_letter += 1 7 | return count_letter -------------------------------------------------------------------------------- /8KYU/string_to_array.py: -------------------------------------------------------------------------------- 1 | def string_to_array(s): 2 | return [i for i in s.split()] if len(s) >= 1 else [""] -------------------------------------------------------------------------------- /8KYU/stringy.py: -------------------------------------------------------------------------------- 1 | def stringy(size: int) -> str: 2 | if size % 2 == 0: 3 | return '10' * (size // 2) 4 | return '10' * (size // 2) + '1' -------------------------------------------------------------------------------- /8KYU/sum_array.py: -------------------------------------------------------------------------------- 1 | def sum_array(arr:list): 2 | if arr is None or len(arr) <= 2: 3 | return 0 4 | sorted_arr = sorted(arr) 5 | return sum(sorted_arr[1:-1]) -------------------------------------------------------------------------------- /8KYU/sum_mix.py: -------------------------------------------------------------------------------- 1 | def sum_mix(arr: list) -> int: 2 | return sum([int(i) for i in arr]) -------------------------------------------------------------------------------- /8KYU/sum_of_differences.py: -------------------------------------------------------------------------------- 1 | # https://www.codewars.com/kata/5b73fe9fb3d9776fbf00009e/ 2 | 3 | 4 | def sum_of_differences(arr: list) -> int: 5 | arr = sorted(arr, reverse=True) 6 | return sum(arr[i]-arr[i+1] for i in range(len(arr)-1)) 7 | -------------------------------------------------------------------------------- /8KYU/swap_values.py: -------------------------------------------------------------------------------- 1 | def swap_values(args): 2 | args[0], args[1] = args[1], args[0] -------------------------------------------------------------------------------- /8KYU/switch_it_up.py: -------------------------------------------------------------------------------- 1 | def switch_it_up(number: int) -> str: 2 | ''' This function returns number (0-9) in words. ''' 3 | dict_num = { 4 | 0: 'Zero', 5 | 1: 'One', 6 | 2: 'Two', 7 | 3: 'Three', 8 | 4: 'Four', 9 | 5: 'Five', 10 | 6: 'Six', 11 | 7: 'Seven', 12 | 8: 'Eight', 13 | 9: 'Nine' 14 | } 15 | return dict_num.get(number) -------------------------------------------------------------------------------- /8KYU/take.py: -------------------------------------------------------------------------------- 1 | def take(arr: list, n: int) -> list: 2 | return arr[:n] -------------------------------------------------------------------------------- /8KYU/temple_strings.py: -------------------------------------------------------------------------------- 1 | def temple_strings(obj: str, feature: str) -> str: 2 | return f'{obj} are {feature}' -------------------------------------------------------------------------------- /8KYU/to_alternating_case.py: -------------------------------------------------------------------------------- 1 | def to_alternating_case(s: str) -> str: 2 | my_str = '' 3 | for i in s: 4 | if i.islower(): 5 | my_str += i.upper() 6 | elif i.isupper(): 7 | my_str += i.lower() 8 | else: 9 | my_str += i 10 | return my_str -------------------------------------------------------------------------------- /8KYU/to_binary.py: -------------------------------------------------------------------------------- 1 | def to_binary(n: int) -> int: 2 | return int(str(bin(n))[2:]) -------------------------------------------------------------------------------- /8KYU/to_csv_text.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/5a34af40e1ce0eb1f5000036/ 2 | 3 | def to_csv_text(array: list) -> str: 4 | """ 5 | This function returns the CSV representation of a two-dimensional numeric array. 6 | """ 7 | csv: str = '' 8 | for i in array: 9 | csv += f"{','.join(map(str, i))}\n" 10 | return csv[:-1] 11 | -------------------------------------------------------------------------------- /8KYU/triple_trouble.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/5704aea738428f4d30000914/ 2 | 3 | def triple_trouble(one: str, two: str, three: str) -> str: 4 | return ''.join(''.join(i + j + k) for i, j, k in zip(one, two, three)) 5 | -------------------------------------------------------------------------------- /8KYU/twice_as_old.py: -------------------------------------------------------------------------------- 1 | def twice_as_old(dad_years_old: int, son_years_old: int) -> int: 2 | return abs(dad_years_old - (son_years_old * 2)) -------------------------------------------------------------------------------- /8KYU/type_validation.py: -------------------------------------------------------------------------------- 1 | # Solution for task: https://www.codewars.com/kata/59c1302ecb7fb48757000013/ 2 | 3 | 4 | def type_validation(variable, _type) -> bool: 5 | return _type in str(type(variable)) 6 | -------------------------------------------------------------------------------- /8KYU/unusual_five.py: -------------------------------------------------------------------------------- 1 | def unusual_five(): 2 | my_list = ["I", "am", "not", "a", "cheater!"] 3 | return len(my_list) -------------------------------------------------------------------------------- /8KYU/update_light.py: -------------------------------------------------------------------------------- 1 | def update_light(current: str) -> str: 2 | light = ['red', 'yellow', 'green'] 3 | if current == light[1]: 4 | return light[0] 5 | elif current == light[2]: 6 | return light[1] 7 | return light[2] 8 | -------------------------------------------------------------------------------- /8KYU/validate_hello.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | 4 | def validate_hello(greetings: str) -> bool: 5 | return True if re.search(r'hello|ciao|salut|hallo|hola|ahoj|czesc', greetings.lower()) else False -------------------------------------------------------------------------------- /8KYU/validate_usr.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | 4 | def validate_usr(username: str) -> bool: 5 | try: 6 | return re.match(r'[a-z0-9_]{4,16}', username).group(0) == username 7 | except AttributeError: 8 | return False 9 | -------------------------------------------------------------------------------- /8KYU/warn_the_sheep.py: -------------------------------------------------------------------------------- 1 | def warn_the_sheep(arr: list) -> str: 2 | my_arr = list(reversed(arr.copy())) 3 | for i in range(len(my_arr)): 4 | if my_arr[0] == "wolf": 5 | return 'Pls go away and stop eating my sheep' 6 | else: 7 | my_arr = [None] + my_arr 8 | return f'Oi! Sheep number {my_arr.index("wolf") - 1}! You are about to be eaten by a wolf!' -------------------------------------------------------------------------------- /8KYU/weather_info.py: -------------------------------------------------------------------------------- 1 | def weather_info(temp): 2 | c = convert_to_celsius(temp) 3 | if c < 0: 4 | return (str(c) + " is freezing temperature") 5 | return (str(c) + " is above freezing temperature") 6 | 7 | 8 | def convert_to_celsius(fahrenheit): 9 | celsius = (fahrenheit - 32) * (5/9) 10 | return celsius -------------------------------------------------------------------------------- /8KYU/well.py: -------------------------------------------------------------------------------- 1 | def well(x: list) -> str: 2 | good = x.count('good') 3 | if 1 <= good <= 2: 4 | return 'Publish!' 5 | elif good > 2: 6 | return 'I smell a series!' 7 | return 'Fail!' -------------------------------------------------------------------------------- /8KYU/zero_fuel.py: -------------------------------------------------------------------------------- 1 | def zero_fuel(distance_to_pump: int, mpg: int, fuel_left: int) -> bool: 2 | return True if mpg * fuel_left >= distance_to_pump else False 3 | -------------------------------------------------------------------------------- /SQL/5KYU/min_median_max.sql: -------------------------------------------------------------------------------- 1 | SELECT MIN(score) AS min, PERCENTILE_CONT(0.5) WITHIN GROUP(ORDER BY score) AS median, MAX(score) AS max 2 | FROM result; -------------------------------------------------------------------------------- /SQL/5KYU/running_total.sql: -------------------------------------------------------------------------------- 1 | SELECT CREATED_AT::DATE AS "date", COUNT(CREATED_AT) AS "count", SUM(COUNT(CREATED_AT::DATE)) OVER (ORDER BY CREATED_AT::DATE)::int as "total" 2 | FROM posts 3 | GROUP BY CREATED_AT::DATE -------------------------------------------------------------------------------- /SQL/6KYU/calculating_batting_average.sql: -------------------------------------------------------------------------------- 1 | SELECT player_name, games, round(hits/at_bats::decimal, 3)::text AS batting_average 2 | FROM yankees 3 | WHERE at_bats >= 100 4 | ORDER BY batting_average DESC -------------------------------------------------------------------------------- /SQL/6KYU/simple_exists.sql: -------------------------------------------------------------------------------- 1 | SELECT d.id, d.name 2 | FROM departments d 3 | WHERE EXISTS (SELECT * 4 | FROM sales s 5 | WHERE s.department_id = d.id AND s.price > 98) -------------------------------------------------------------------------------- /SQL/6KYU/simple_having.sql: -------------------------------------------------------------------------------- 1 | SELECT age, count(age) AS total_people 2 | FROM people 3 | GROUP BY age 4 | HAVING count(age) >= 10 -------------------------------------------------------------------------------- /SQL/6KYU/simple_in.sql: -------------------------------------------------------------------------------- 1 | SELECT d.id, d.name 2 | FROM departments d 3 | WHERE d.id IN (SELECT s.department_id FROM sales s WHERE s.price > 98.00); -------------------------------------------------------------------------------- /SQL/6KYU/simple_join_and_rank.sql: -------------------------------------------------------------------------------- 1 | SELECT p.*, count(s.sale) AS sale_count, RANK() OVER(PARTITION BY p.id ORDER BY p.id DESC) AS sale_rank 2 | FROM people p 3 | INNER JOIN sales s ON p.id = s.people_id 4 | GROUP BY p.id -------------------------------------------------------------------------------- /SQL/6KYU/simple_union_all.sql: -------------------------------------------------------------------------------- 1 | SELECT *, 'US' AS location 2 | FROM ussales 3 | WHERE price > 50 4 | UNION ALL 5 | SELECT *, 'EU' AS location 6 | FROM eusales 7 | WHERE price > 50 8 | ORDER BY location DESC, id -------------------------------------------------------------------------------- /SQL/6KYU/simple_with.sql: -------------------------------------------------------------------------------- 1 | WITH special_sales (id, name) 2 | AS 3 | ( 4 | SELECT DISTINCT d.id, d.name FROM departments d 5 | LEFT JOIN sales s ON d.id = s.department_id 6 | WHERE s.price > 90 7 | ) 8 | SELECT * FROM special_sales ORDER BY id -------------------------------------------------------------------------------- /SQL/6KYU/top_10_customers_by_total_payments_amount.sql: -------------------------------------------------------------------------------- 1 | SELECT c.customer_id, c.email, sum(cast(p.amount as float)) as total_amount, count(p.customer_id) as payments_count 2 | FROM customer c 3 | INNER JOIN payment p ON p.customer_id = c.customer_id GROUP BY c.customer_id 4 | ORDER BY total_amount DESC 5 | LIMIT 10 -------------------------------------------------------------------------------- /SQL/7KYU/absolute_value_and_log_to_base.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | ABS(d.number1) AS abs, 3 | LOG(64, d.number2) AS log 4 | FROM decimals d -------------------------------------------------------------------------------- /SQL/7KYU/ascii_converter.sql: -------------------------------------------------------------------------------- 1 | -- Solution for task: https://www.codewars.com/kata/594804a218e96caa8d00051b/ 2 | 3 | SELECT id, ASCII(LEFT(name, 1)) AS name, birthday, ASCII(LEFT(race, 1)) AS race 4 | FROM demographics; 5 | -------------------------------------------------------------------------------- /SQL/7KYU/best_selling_books.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM books ORDER BY copies_sold DESC LIMIT 5 -------------------------------------------------------------------------------- /SQL/7KYU/bit_length.sql: -------------------------------------------------------------------------------- 1 | SELECT id, BIT_LENGTH(name) as name, birthday, BIT_LENGTH(race) AS race 2 | FROM demographics -------------------------------------------------------------------------------- /SQL/7KYU/bytes_in_string_from_ints.sql: -------------------------------------------------------------------------------- 1 | -- Solution for task: https://www.codewars.com/kata/59491429952ac97ad9000106/ 2 | 3 | SELECT 4 | LENGTH(number1::TEXT) AS octnum1, 5 | LENGTH(number2::TEXT) AS octnum2, 6 | LENGTH(number3::TEXT) AS octnum3, 7 | LENGTH(number4::TEXT) AS octnum4, 8 | LENGTH(number5::TEXT) AS octnum5 9 | FROM numbers; -------------------------------------------------------------------------------- /SQL/7KYU/concatenating_columns.sql: -------------------------------------------------------------------------------- 1 | SELECT concat(prefix, ' ', first, ' ', last, ' ', suffix) AS title 2 | FROM names -------------------------------------------------------------------------------- /SQL/7KYU/counting_and_grouping.sql: -------------------------------------------------------------------------------- 1 | SELECT race, count(race) AS count 2 | FROM demographics 3 | GROUP BY race ORDER BY count DESC -------------------------------------------------------------------------------- /SQL/7KYU/countries_capitals_for_trivia_night.sql: -------------------------------------------------------------------------------- 1 | SELECT capital FROM countries 2 | WHERE continent in ('Africa', 'Afrika') and country LIKE 'E%' 3 | ORDER BY capital LIMIT 3 4 | -------------------------------------------------------------------------------- /SQL/7KYU/create_a_function.sql: -------------------------------------------------------------------------------- 1 | CREATE FUNCTION increment(age INTEGER) RETURNS INTEGER AS 2 | 'BEGIN 3 |   RETURN age + 1; 4 | END;' 5 | LANGUAGE plpgsql; -------------------------------------------------------------------------------- /SQL/7KYU/cube_root_and_natural_log.sql: -------------------------------------------------------------------------------- 1 | SELECT CBRT(number1) AS cuberoot, LN(number2) AS logarithm 2 | FROM decimals -------------------------------------------------------------------------------- /SQL/7KYU/easy_regex_extraction.sql: -------------------------------------------------------------------------------- 1 | SELECT name, greeting, (regexp_matches(greeting, '#(\d+)'))[1] AS user_id 2 | FROM greetings; -------------------------------------------------------------------------------- /SQL/7KYU/first_and_last_IP_in_a_network.sql: -------------------------------------------------------------------------------- 1 | SELECT id, NETWORK(ip_address) AS first_address, BROADCAST(ip_address) AS last_address 2 | FROM connections 3 | ORDER BY id -------------------------------------------------------------------------------- /SQL/7KYU/hello_sql_world.sql: -------------------------------------------------------------------------------- 1 | SELECT 'hello world!' AS "Greeting" -------------------------------------------------------------------------------- /SQL/7KYU/inventory.sql: -------------------------------------------------------------------------------- 1 | SELECT p.id, p.name, p.stock 2 | FROM products p 3 | WHERE p.stock <= 2 AND p.producent = 'CompanyA' 4 | ORDER BY p.id -------------------------------------------------------------------------------- /SQL/7KYU/length_based_select_with_like.sql: -------------------------------------------------------------------------------- 1 | select first_name, last_name 2 | from names 3 | where first_name like '______%' -------------------------------------------------------------------------------- /SQL/7KYU/maths_with_string_manipulations.sql: -------------------------------------------------------------------------------- 1 | SELECT (BIT_LENGTH(name) + LENGTH(race)) AS calculation 2 | FROM demographics -------------------------------------------------------------------------------- /SQL/7KYU/moving_values.sql: -------------------------------------------------------------------------------- 1 | SELECT  2 |   CHAR_LENGTH(name::text) AS id, 3 |   CHAR_LENGTH(legs::text) AS name, 4 |   CHAR_LENGTH(arms::text) AS legs, 5 |   CHAR_LENGTH(characteristics::text) AS arms, 6 |   CHAR_LENGTH(id::text) AS characteristics 7 | FROM monsters -------------------------------------------------------------------------------- /SQL/7KYU/raise_to_the_power.sql: -------------------------------------------------------------------------------- 1 | SELECT power(number1, number2) AS result 2 | FROM decimals -------------------------------------------------------------------------------- /SQL/7KYU/real_price.sql: -------------------------------------------------------------------------------- 1 | SELECT name, weight, price, ROUND(CAST(price / weight * 1000 AS NUMERIC), 2)::FLOAT AS price_per_kg 2 | FROM products 3 | ORDER BY price_per_kg, name ASC 4 | -------------------------------------------------------------------------------- /SQL/7KYU/regex_replace.sql: -------------------------------------------------------------------------------- 1 | -- Solution for task: https://www.codewars.com/kata/5942b066db68b6f35f000084/ 2 | 3 | SELECT project, commits, contributors, REGEXP_REPLACE(address, '[[:digit:]]', '!', 'g') AS address 4 | FROM repositories; 5 | -------------------------------------------------------------------------------- /SQL/7KYU/repeat_and_reverse.sql: -------------------------------------------------------------------------------- 1 | SELECT REPEAT(name, 3) AS name, REVERSE(characteristics) AS characteristics 2 | FROM monsters -------------------------------------------------------------------------------- /SQL/7KYU/right_and_left.sql: -------------------------------------------------------------------------------- 1 | -- Solution for task: https://www.codewars.com/kata/5943a58f95d5f72cb900006a/ 2 | 3 | SELECT LEFT(project, commits) AS project, RIGHT(address, contributors) AS address 4 | FROM repositories; 5 | -------------------------------------------------------------------------------- /SQL/7KYU/simple_group_by.sql: -------------------------------------------------------------------------------- 1 | SELECT COUNT(age) AS people_count, age FROM people GROUP BY age; 2 | -------------------------------------------------------------------------------- /SQL/7KYU/simple_join.sql: -------------------------------------------------------------------------------- 1 | SELECT p.id, p.name, p.isbn, p.company_id, p.price, c.name AS company_name 2 | FROM products p 3 | INNER JOIN companies c ON p.company_id = c.id -------------------------------------------------------------------------------- /SQL/7KYU/simple_join_with_count.sql: -------------------------------------------------------------------------------- 1 | SELECT p.*, count(t.id) AS toy_count 2 | FROM people p INNER JOIN toys t ON t.people_id = p.id 3 | GROUP BY p.id -------------------------------------------------------------------------------- /SQL/7KYU/sql_basics_position.sql: -------------------------------------------------------------------------------- 1 | SELECT id, name, POSITION(',' IN characteristics) AS comma 2 | FROM monsters 3 | ORDER BY comma -------------------------------------------------------------------------------- /SQL/7KYU/sql_disorder.sql: -------------------------------------------------------------------------------- 1 | SELECT number FROM numbers 2 | ORDER BY RANDOM() -------------------------------------------------------------------------------- /SQL/7KYU/sum_of_angles.sql: -------------------------------------------------------------------------------- 1 | -- Solution for task: https://www.codewars.com/kata/5a03b3f6a1c9040084001765/ 2 | 3 | SELECT 180*(n-2) AS res 4 | FROM angle; -------------------------------------------------------------------------------- /SQL/7KYU/sum_of_odd_numbers.sql: -------------------------------------------------------------------------------- 1 | -- Solution for task: https://www.codewars.com/kata/55fd2d567d94ac3bc9000064/ 2 | 3 | SELECT POWER(n, 3)::INT AS res 4 | FROM nums; -------------------------------------------------------------------------------- /SQL/7KYU/sum_of_triangular_numbers.sql: -------------------------------------------------------------------------------- 1 | -- Solution for task: https://www.codewars.com/kata/580878d5d27b84b64c000b51/ 2 | 3 | SELECT n, 4 | CASE 5 | WHEN n < 0 THEN 0 6 | ELSE (n*(n+1)*(n+2))/6 7 | END AS res 8 | FROM sumtriangular; -------------------------------------------------------------------------------- /SQL/7KYU/support_local_products.sql: -------------------------------------------------------------------------------- 1 | SELECT count(stock) AS products, country 2 | FROM products 3 | WHERE country IN ('United States of America', 'Canada') 4 | GROUP BY country ORDER BY products DESC -------------------------------------------------------------------------------- /SQL/7KYU/total_wins.sql: -------------------------------------------------------------------------------- 1 | SELECT name, SUM(won) AS won, SUM(lost) AS lost 2 | FROM fighters 3 | JOIN winning_moves ON winning_moves.id = fighters.move_id 4 | WHERE move NOT IN ('Hadoken', 'Shouoken', 'Kikoken') 5 | GROUP BY name 6 | ORDER BY won DESC LIMIT 6 7 | -------------------------------------------------------------------------------- /SQL/7KYU/trimming_the_field.sql: -------------------------------------------------------------------------------- 1 | SELECT m.id, m.name, split_part(m.characteristics, ',', 1) AS characteristic 2 | FROM monsters m 3 | ORDER BY id -------------------------------------------------------------------------------- /SQL/7KYU/truncating.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | TRUNC(d.number1 + d.number2) AS towardzero 3 | FROM decimals d -------------------------------------------------------------------------------- /SQL/7KYU/up_and_down.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | (CASE 3 | WHEN SUM(number1 % 2) <> 0 THEN MIN(number1) 4 | ELSE MAX(number1) 5 | END) as number1, 6 | (CASE 7 | WHEN SUM(number2 % 2) <> 0 THEN MIN(number2) 8 | ELSE MAX(number2) 9 | END) as number2 10 | FROM numbers -------------------------------------------------------------------------------- /SQL/7KYU/vowel_count.sql: -------------------------------------------------------------------------------- 1 | -- Solution for task: https://www.codewars.com/kata/54ff3102c1bad923760001f3/ 2 | 3 | SELECT str, (LENGTH(str) - LENGTH(TRANSLATE(LOWER(str), 'aeiou', '')))::INT AS res 4 | FROM getcount; -------------------------------------------------------------------------------- /SQL/8KYU/adults_only.sql: -------------------------------------------------------------------------------- 1 | SELECT name, age FROM users WHERE age >= 18; -------------------------------------------------------------------------------- /SQL/8KYU/booltoword.sql: -------------------------------------------------------------------------------- 1 | -- # Solution for task: https://www.codewars.com/kata/53369039d7ab3ac506000467/ 2 | -- # write your SQL statement here: you are given a table 'booltoword' with column 'bool', return a table with column 'bool' and your result in a column named 'res'. 3 | 4 | SELECT bool, 5 | CASE 6 | WHEN bool = true THEN 'Yes' 7 | WHEN bool = false THEN 'No' 8 | END AS res 9 | FROM booltoword; -------------------------------------------------------------------------------- /SQL/8KYU/century_from_year.sql: -------------------------------------------------------------------------------- 1 | --# Solution for task: https://www.codewars.com/kata/5a3fe3dde1ce0e8ed6000097/ 2 | 3 | SELECT 1+(yr-1)/100 AS century 4 | FROM years; -------------------------------------------------------------------------------- /SQL/8KYU/check_for_factor.sql: -------------------------------------------------------------------------------- 1 | -- you will be given a table 'kata' with columns 'id', 'base', and 'factor'.  2 | -- return the 'id' and your result in a column named 'res'. 3 | SELECT id, (base % factor = 0) as res 4 | FROM kata -------------------------------------------------------------------------------- /SQL/8KYU/collect_tuition.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM students WHERE tuition_received = false -------------------------------------------------------------------------------- /SQL/8KYU/convert_to_hexadecimal.sql: -------------------------------------------------------------------------------- 1 | SELECT TO_HEX(legs) AS legs, TO_HEX(arms) AS arms 2 | FROM monsters -------------------------------------------------------------------------------- /SQL/8KYU/easy_sql_ordering.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM companies 2 | ORDER BY employees DESC -------------------------------------------------------------------------------- /SQL/8KYU/even_or_odd.sql: -------------------------------------------------------------------------------- 1 | SELECT (CASE WHEN (number % 2) <> 0 THEN 'Odd' 2 | ELSE 'Even' END) is_even FROM numbers -------------------------------------------------------------------------------- /SQL/8KYU/find_all_active_students.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM students 2 | WHERE isactive = 1; -------------------------------------------------------------------------------- /SQL/8KYU/grasshopper_messi_goals_function.sql: -------------------------------------------------------------------------------- 1 | SELECT la_liga_goals + copa_del_rey_goals + champions_league_goals AS res FROM goals; -------------------------------------------------------------------------------- /SQL/8KYU/is_it_a_palindrome.sql: -------------------------------------------------------------------------------- 1 | -- Solution for task: https://www.codewars.com/kata/57a1fd2ce298a731b20006a4/ 2 | 3 | SELECT str, (LOWER(str) = REVERSE(LOWER(str)))::BOOL AS res 4 | FROM ispalindrome; 5 | -------------------------------------------------------------------------------- /SQL/8KYU/lowercase.sql: -------------------------------------------------------------------------------- 1 | SELECT id, name, birthday, LOWER(race) AS race 2 | FROM demographics -------------------------------------------------------------------------------- /SQL/8KYU/make_upper_case.sql: -------------------------------------------------------------------------------- 1 | -- Solution for task: https://www.codewars.com/kata/57a0556c7cb1f31ab3000ad7/ 2 | 3 | SELECT s, UPPER(s) AS res 4 | FROM makeuppercase; 5 | -------------------------------------------------------------------------------- /SQL/8KYU/n_divisible_by_x_and_y.sql: -------------------------------------------------------------------------------- 1 | -- Solution for task: https://www.codewars.com/kata/5545f109004975ea66000086/ 2 | 3 | SELECT id, (MOD(n, x) = 0 AND MOD(n, y) = 0)::BOOL AS res 4 | FROM kata; 5 | -------------------------------------------------------------------------------- /SQL/8KYU/number_of_cubes_with_paint.sql: -------------------------------------------------------------------------------- 1 | -- Solution for task: https://www.codewars.com/kata/5763bb0af716cad8fb000580/ 2 | 3 | SELECT n, 4 | CASE 5 | WHEN n = 0 THEN n + 1 6 | WHEN n > 0 THEN (6 * POWER(n, 2) + 2)::INTEGER 7 | END AS res 8 | FROM squares; 9 | -------------------------------------------------------------------------------- /SQL/8KYU/on_the_canadian_border.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM travelers WHERE country NOT IN ('Canada', 'Mexico', 'USA') -------------------------------------------------------------------------------- /SQL/8KYU/opposite_number.sql: -------------------------------------------------------------------------------- 1 | SELECT -number as res FROM opposite -------------------------------------------------------------------------------- /SQL/8KYU/register_for_the_party.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO participants VALUES ('Nick', 26, true); 2 | 3 | SELECT * FROM participants; -------------------------------------------------------------------------------- /SQL/8KYU/remove_exclamation_marks.sql: -------------------------------------------------------------------------------- 1 | --# Solution for task: https://www.codewars.com/kata/57a0885cbb9944e24c00008e/ 2 | 3 | --# write your SQL statement here: you are given a table 'removeexclamationmarks' with column 's', return a table with column 's' and your result in a column named 'res'. 4 | 5 | SELECT s, REPLACE(s, '!', '') AS res 6 | FROM removeexclamationmarks; -------------------------------------------------------------------------------- /SQL/8KYU/remove_string_spaces.sql: -------------------------------------------------------------------------------- 1 | SELECT x, REPLACE(x, ' ', '') AS res FROM nospace; -------------------------------------------------------------------------------- /SQL/8KYU/returning_strings.sql: -------------------------------------------------------------------------------- 1 | SELECT CONCAT('Hello, ', name, ' how are you doing today?') as greeting FROM person -------------------------------------------------------------------------------- /SQL/8KYU/reversed_strings.sql: -------------------------------------------------------------------------------- 1 | -- Solution for task: https://www.codewars.com/kata/5168bb5dfe9a00b126000018/ 2 | 3 | SELECT str, REVERSE(str)::TEXT AS res 4 | FROM solution; -------------------------------------------------------------------------------- /SQL/8KYU/rounding_decimals.sql: -------------------------------------------------------------------------------- 1 | SELECT FLOOR(number1) AS number1, CEIL(number2) AS number2 2 | FROM decimals -------------------------------------------------------------------------------- /SQL/8KYU/select_columns.sql: -------------------------------------------------------------------------------- 1 | SELECT custid, custname, custstate FROM customers; -------------------------------------------------------------------------------- /SQL/8KYU/simple_distinct.sql: -------------------------------------------------------------------------------- 1 | SELECT DISTINCT age FROM people -------------------------------------------------------------------------------- /SQL/8KYU/simple_min_max.sql: -------------------------------------------------------------------------------- 1 | SELECT MIN(age) AS age_min, MAX(age) AS age_max FROM people -------------------------------------------------------------------------------- /SQL/8KYU/simple_multiplication.sql: -------------------------------------------------------------------------------- 1 | -- Solution for task: https://www.codewars.com/kata/583710ccaa6717322c000105/ 2 | 3 | SELECT "number", 4 | CASE 5 | WHEN ("number" % 2)::BOOL THEN "number" * 9 6 | WHEN NOT ("number" % 2)::BOOL THEN "number" * 8 7 | END AS res 8 | FROM multiplication; -------------------------------------------------------------------------------- /SQL/8KYU/simple_sum.sql: -------------------------------------------------------------------------------- 1 | SELECT SUM(age) AS age_sum FROM people -------------------------------------------------------------------------------- /SQL/8KYU/simple_where_and_order_by.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM people WHERE age > 50 ORDER BY age DESC -------------------------------------------------------------------------------- /SQL/8KYU/sql_basics_mod.sql: -------------------------------------------------------------------------------- 1 | SELECT MOD(number1, number2) 2 | FROM decimals -------------------------------------------------------------------------------- /SQL/8KYU/square_root_and_log.sql: -------------------------------------------------------------------------------- 1 | SELECT SQRT(number1) as root, LOG(number2) as log 2 | FROM decimals -------------------------------------------------------------------------------- /SQL/8KYU/squaring_an_argument.sql: -------------------------------------------------------------------------------- 1 | --# Solution for task: https://www.codewars.com/kata/523b623152af8a30c6000027/ 2 | 3 | --# write your SQL statement here: 4 | -- you are given a table 'square' with column 'n' 5 | -- return a table with: 6 | -- this column and your result in a column named 'res' 7 | 8 | SELECT n, POWER(n, 2)::INT AS res 9 | FROM square; -------------------------------------------------------------------------------- /SQL/8KYU/string_repeat.sql: -------------------------------------------------------------------------------- 1 | --# Solution for task: https://www.codewars.com/kata/57a0e5c372292dd76d000d7e/ 2 | 3 | --# write your SQL statement here: you are given a table 'repeatstr' with columns 'n' and 's', return a table with all columns and your result in a column named 'res'. 4 | SELECT s, n, REPEAT(s, n) AS res 5 | FROM repeatstr; -------------------------------------------------------------------------------- /SQL/8KYU/summation.sql: -------------------------------------------------------------------------------- 1 | --# Solution for task: https://www.codewars.com/kata/55d24f55d7dd296eb9000030/ 2 | 3 | --# write your SQL statement here: you are given a table 'kata' with a column 'n', return a table with 'n' and your result stored in a column naed 'res'. 4 | SELECT n, n*(n+1)/2 AS res 5 | FROM kata; -------------------------------------------------------------------------------- /SQL/8KYU/terminal_game_move_function.sql: -------------------------------------------------------------------------------- 1 | --# write your statement here: you will be given a table 'moves' with columns 'position' and 'roll'. return a table with a column 'res'. #-- 2 | SELECT (2 * roll + position) AS res 3 | FROM moves -------------------------------------------------------------------------------- /SQL/8KYU/third_angle_of_a_triangle.sql: -------------------------------------------------------------------------------- 1 | -- Solution for task: https://www.codewars.com/kata/5a023c426975981341000014/ 2 | 3 | SELECT "a", "b", 180-"a"-"b" AS res 4 | FROM otherangle; --------------------------------------------------------------------------------