├── .0-positive_or_negative.py.swp ├── 0x00-python-hello_world ├── 0-run ├── 1-run_inline ├── 10-check_cycle.c ├── 100-write.py ├── 101-compile ├── 102-magic_calculation.py ├── 2-print.py ├── 3-print_number.py ├── 4-print_float.py ├── 5-print_string.py ├── 6-concat.py ├── 7-edges.py ├── 8-concat_edges.py ├── 9-easter_egg.py ├── README.md └── lists.h ├── 0x01-python-if_else_loops_functions ├── 0-positive_or_negative.py ├── 1-last_digit.py ├── 10-add.py ├── 10-main.py ├── 100-print_tebahpla.py ├── 101-main.py ├── 101-remove_char_at.py ├── 102-magic_calculation.py ├── 11-main.py ├── 11-pow.py ├── 12-fizzbuzz.py ├── 12-main.py ├── 13-insert_number.c ├── 2-print_alphabet.py ├── 3-print_alphabt.py ├── 4-print_hexa.py ├── 5-print_comb2.py ├── 6-print_comb3.py ├── 7-islower.py ├── 7-main.py ├── 8-main.py ├── 8-uppercase.py ├── 9-main.py ├── 9-print_last_digit.py ├── README.md └── lists.h ├── 0x02-python-import_modules ├── 0-add.py ├── 1-calculation.py ├── 100-my_calculator.py ├── 101-easy_print.py ├── 102-magic_calculation.py ├── 103-fast_alphabet.py ├── 2-args.py ├── 3-infinite_add.py ├── 4-hidden_discovery.py ├── 5-variable_load.py ├── README.md ├── add_0.py ├── calculator_1.py └── variable_load_5.py ├── 0x03-python-data_structures ├── 0-print_list_integer.py ├── 1-element_at.py ├── 10-divisible_by_2.py ├── 100-print_python_list_info.c ├── 100-test_lists.py ├── 11-delete_at.py ├── 12-switch.py ├── 13-is_palindrome.c ├── 2-replace_in_list.py ├── 3-print_reversed_list_integer.py ├── 4-new_in_list.py ├── 5-no_c.py ├── 6-print_matrix_integer.py ├── 7-add_tuple.py ├── 8-multiple_returns.py ├── 9-max_integer.py ├── README.md └── lists.h ├── 0x04-python-more_data_structures ├── 0-square_matrix_simple.py ├── 1-search_replace.py ├── 10-best_score.py ├── 100-weight_average.py ├── 101-square_matrix_map.py ├── 102-complex_delete.py ├── 103-python.c ├── 103-tests.py ├── 11-multiply_list_map.py ├── 12-roman_to_int.py ├── 2-uniq_add.py ├── 3-common_elements.py ├── 4-only_diff_elements.py ├── 5-number_keys.py ├── 6-print_sorted_dictionary.py ├── 7-update_dictionary.py ├── 8-simple_delete.py ├── 9-multiply_by_2.py ├── README.md └── tests │ ├── 0-main.py │ ├── 1-main.py │ ├── 10-main.py │ ├── 100-main.py │ ├── 101-main.py │ ├── 102-main.py │ ├── 11-main.py │ ├── 12-main.py │ ├── 2-main.py │ ├── 3-main.py │ ├── 4-main.py │ ├── 5-main.py │ ├── 6-main.py │ ├── 7-main.py │ ├── 8-main.py │ └── 9-main.py ├── 0x05-python-exceptions ├── 0-safe_print_list.py ├── 1-safe_print_integer.py ├── 100-safe_print_integer_err.py ├── 101-safe_function.py ├── 102-magic_calculation.py ├── 103-python.c ├── 2-safe_print_list_integers.py ├── 3-safe_print_division.py ├── 4-list_division.py ├── 5-raise_exception.py ├── 6-raise_exception_msg.py └── README.md ├── 0x06-python-classes ├── 0-square.py ├── 1-square.py ├── 100-singly_linked_list.py ├── 101-square.py ├── 102-square.py ├── 103-magic_class.py ├── 2-square.py ├── 3-square.py ├── 4-square.py ├── 5-square.py ├── 6-square.py ├── README.md └── tests │ ├── 0-main.py │ ├── 1-main.py │ ├── 100-main.py │ ├── 101-main.py │ ├── 102-main.py │ ├── 2-main.py │ ├── 3-main.py │ ├── 4-main.py │ ├── 5-main.py │ └── 6-main.py ├── 0x07-python-test_driven_development ├── 0-add_integer.py ├── 100-matrix_mul.py ├── 101-lazy_matrix_mul.py ├── 102-python.c ├── 2-matrix_divided.py ├── 3-say_my_name.py ├── 4-print_square.py ├── 5-text_indentation.py ├── 6-max_integer.py ├── README.md └── tests │ ├── 0-add_integer.txt │ ├── 0-main.py │ ├── 100-main.py │ ├── 100-matrix_mul.txt │ ├── 101-lazy_matrix_mul.txt │ ├── 101-main.py │ ├── 2-main.py │ ├── 2-matrix_divided.txt │ ├── 3-main.py │ ├── 3-say_my_name.txt │ ├── 4-main.py │ ├── 4-print_square.txt │ ├── 5-main.py │ ├── 5-text_indentation.txt │ └── 6-max_integer_test.py ├── 0x08-python-more_classes ├── 0-rectangle.py ├── 1-rectangle.py ├── 101-nqueens.py ├── 2-rectangle.py ├── 3-rectangle.py ├── 4-rectangle.py ├── 5-rectangle.py ├── 6-rectangle.py ├── 7-rectangle.py ├── 8-rectangle.py ├── 9-rectangle.py ├── README.md └── tests │ ├── 0-main.py │ ├── 1-main.py │ ├── 2-main.py │ ├── 3-main.py │ ├── 4-main.py │ ├── 5-main.py │ ├── 6-main.py │ ├── 7-main.py │ ├── 8-main.py │ └── 9-main.py ├── 0x09-python-everything_is_object ├── 0-answer.txt ├── 1-answer.txt ├── 10-answer.txt ├── 100-magic_string.py ├── 101-locked_class.py ├── 103-line1.txt ├── 103-line2.txt ├── 104-line1.txt ├── 104-line2.txt ├── 104-line3.txt ├── 104-line4.txt ├── 104-line5.txt ├── 105-line1.txt ├── 106-line1.txt ├── 106-line2.txt ├── 106-line3.txt ├── 106-line4.txt ├── 106-line5.txt ├── 11-answer.txt ├── 12-answer.txt ├── 13-answer.txt ├── 14-answer.txt ├── 15-answer.txt ├── 16-answer.txt ├── 17-answer.txt ├── 18-answer.txt ├── 19-copy_list.py ├── 2-answer.txt ├── 20-answer.txt ├── 21-answer.txt ├── 22-answer.txt ├── 23-answer.txt ├── 24-answer.txt ├── 25-answer.txt ├── 26-answer.txt ├── 27-answer.txt ├── 28-answer.txt ├── 3-answer.txt ├── 4-answer.txt ├── 5-answer.txt ├── 6-answer.txt ├── 7-answer.txt ├── 8-answer.txt ├── 9-answer.txt ├── README.md └── tests │ ├── 100-main.py │ ├── 101-main.py │ └── 19-main.py ├── 0x0A-python-inheritance ├── 0-lookup.py ├── 1-my_list.py ├── 10-square.py ├── 100-my_int.py ├── 101-add_attribute.py ├── 11-square.py ├── 2-is_same_class.py ├── 3-is_kind_of_class.py ├── 4-inherits_from.py ├── 5-base_geometry.py ├── 6-base_geometry.py ├── 7-base_geometry.py ├── 8-rectangle.py ├── 9-rectangle.py ├── README.md └── tests │ ├── 0-main.py │ ├── 1-main.py │ ├── 1-my_list.txt │ ├── 10-main.py │ ├── 100-main.py │ ├── 101-main.py │ ├── 11-main.py │ ├── 2-main.py │ ├── 3-main.py │ ├── 4-main.py │ ├── 5-main.py │ ├── 6-main.py │ ├── 7-base_geometry.txt │ ├── 7-main.py │ ├── 8-main.py │ └── 9-main.py ├── 0x0B-python-input_output ├── 0-read_file.py ├── 1-write_file.py ├── 10-student.py ├── 100-append_after.py ├── 101-stats.py ├── 11-student.py ├── 12-pascal_triangle.py ├── 2-append_write.py ├── 3-to_json_string.py ├── 4-from_json_string.py ├── 5-save_to_json_file.py ├── 6-load_from_json_file.py ├── 7-add_item.py ├── 8-class_to_json.py ├── 9-student.py └── README.md ├── 0x0C-python-almost_a_circle ├── README.md ├── models │ ├── __init__.py │ ├── base.py │ ├── rectangle.py │ └── square.py └── tests │ └── test_models │ ├── __init__.py │ ├── __pycache__ │ ├── __init__.cpython-310.pyc │ ├── test_base.cpython-310.pyc │ ├── test_rectangle.cpython-310.pyc │ └── test_square.cpython-310.pyc │ ├── test_base.py │ ├── test_rectangle.py │ └── test_square.py ├── 0x0D-SQL_introduction ├── 0-list_databases.sql ├── 1-create_database_if_missing.sql ├── 10-top_score.sql ├── 100-move_to_utf8.sql ├── 101-avg_temperatures.sql ├── 102-top_city.sql ├── 103-max_state.sql ├── 11-best_score.sql ├── 12-no_cheating.sql ├── 13-change_class.sql ├── 14-average.sql ├── 15-groups.sql ├── 16-no_link.sql ├── 2-remove_database.sql ├── 3-list_tables.sql ├── 4-first_table.sql ├── 5-full_table.sql ├── 6-list_values.sql ├── 7-insert_value.sql ├── 8-count_89.sql ├── 9-full_creation.sql ├── README.md └── temperatures.sql ├── 0x0E-SQL_more_queries ├── 0-privileges.sql ├── 1-create_user.sql ├── 10-genre_id_by_show.sql ├── 100-not_my_genres.sql ├── 101-not_a_comedy.sql ├── 102-rating_shows.sql ├── 103-rating_genres.sql ├── 11-genre_id_all_shows.sql ├── 12-no_genre.sql ├── 13-count_shows_by_genre.sql ├── 14-my_genres.sql ├── 15-comedy_only.sql ├── 16-shows_by_genre.sql ├── 2-create_read_user.sql ├── 3-force_name.sql ├── 4-never_empty.sql ├── 5-unique_id.sql ├── 6-states.sql ├── 7-cities.sql ├── 8-cities_of_california_subquery.sql ├── 9-cities_by_state_join.sql └── README.md ├── 0x0F-python-object_relational_mapping ├── 0-select_states.py ├── 1-filter_states.py ├── 10-model_state_my_get.py ├── 100-relationship_states_cities.py ├── 101-relationship_states_cities_list.py ├── 102-relationship_cities_states_list.py ├── 11-model_state_insert.py ├── 12-model_state_update_id_2.py ├── 13-model_state_delete_a.py ├── 14-model_city_fetch_by_state.py ├── 2-my_filter_states.py ├── 3-my_safe_filter_states.py ├── 4-cities_by_state.py ├── 5-filter_cities.py ├── 7-model_state_fetch_all.py ├── 8-model_state_fetch_first.py ├── 9-model_state_filter_a.py ├── README.md ├── model_city.py ├── model_state.py ├── relationship_city.py └── relationship_state.py ├── 0x10-python-network_0 ├── 0-body_size.sh ├── 1-body.sh ├── 100-status_code.sh ├── 101-post_json.sh ├── 102-catch_me.sh ├── 2-delete.sh ├── 3-methods.sh ├── 4-header.sh ├── 5-post_params.sh ├── 6-peak.py ├── 6-peak.txt └── README.md ├── 0x11-python-network_1 ├── 0-hbtn_status.py ├── 1-hbtn_header.py ├── 10-my_github.py ├── 100-github_commits.py ├── 2-post_email.py ├── 3-error_code.py ├── 4-hbtn_status.py ├── 5-hbtn_header.py ├── 6-post_email.py ├── 7-error_code.py ├── 8-json_api.py └── README.md ├── 0x12-javascript-warm_up ├── 0-javascript_is_amazing.js ├── 1-multi_languages.js ├── 10-factorial.js ├── 100-let_me_const.js ├── 101-call_me_moby.js ├── 102-add_me_maybe.js ├── 103-object_fct.js ├── 11-second_biggest.js ├── 12-object.js ├── 13-add.js ├── 2-arguments.js ├── 3-value_argument.js ├── 4-concat.js ├── 5-to_integer.js ├── 6-multi_languages_loop.js ├── 7-multi_c.js ├── 8-square.js ├── 9-add.js └── README.md ├── 0x13-javascript_objects_scopes_closures ├── 0-rectangle.js ├── 1-rectangle.js ├── 10-converter.js ├── 100-map.js ├── 101-sorted.js ├── 102-concat.js ├── 2-rectangle.js ├── 3-rectangle.js ├── 4-rectangle.js ├── 5-square.js ├── 6-square.js ├── 7-occurrences.js ├── 8-esrever.js ├── 9-logme.js └── README.md ├── 0x14-javascript-web_scraping ├── 0-readme.js ├── 1-writeme.js ├── 100-starwars_characters.js ├── 101-starwars_characters.js ├── 2-statuscode.js ├── 3-starwars_title.js ├── 4-starwars_count.js ├── 5-request_store.js ├── 6-completed_tasks.js └── README.md └── 0x15-javascript-web_jquery ├── 0-script.js ├── 1-script.js ├── 100-script.js ├── 101-script.js ├── 102-script.js ├── 103-script.js ├── 2-script.js ├── 3-script.js ├── 4-script.js ├── 5-script.js ├── 6-script.js ├── 7-script.js ├── 8-script.js ├── 9-script.js └── README.md /.0-positive_or_negative.py.swp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ElHakikAmina/alx-higher_level_programming/bb9364d7175e3c6d2f57eee964e1fb7683370bd6/.0-positive_or_negative.py.swp -------------------------------------------------------------------------------- /0x00-python-hello_world/0-run: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | python3 $PYFILE 3 | -------------------------------------------------------------------------------- /0x00-python-hello_world/1-run_inline: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | python3 <<< $PYCODE 3 | -------------------------------------------------------------------------------- /0x00-python-hello_world/10-check_cycle.c: -------------------------------------------------------------------------------- 1 | #include "lists.h" 2 | 3 | /** 4 | * check_cycle - checks if a linked list contains a cycle 5 | * @list: linked list to check 6 | * 7 | * Return: 1 if the list has a cycle, 0 if it doesn't 8 | */ 9 | int check_cycle(listint_t *list) 10 | { 11 | listint_t *slow = list; 12 | listint_t *fast = list; 13 | 14 | if (!list) 15 | return (0); 16 | 17 | while (slow && fast && fast->next) 18 | { 19 | slow = slow->next; 20 | fast = fast->next->next; 21 | if (slow == fast) 22 | return (1); 23 | } 24 | 25 | return (0); 26 | } 27 | -------------------------------------------------------------------------------- /0x00-python-hello_world/100-write.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import sys 3 | sys.stderr.write("and that piece of art is useful - Dora Korpar, 2015-10-19\n") 4 | sys.exit(1) 5 | -------------------------------------------------------------------------------- /0x00-python-hello_world/101-compile: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | python3 -m compileall -b $PYFILE i 3 | -------------------------------------------------------------------------------- /0x00-python-hello_world/102-magic_calculation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def magic_calculation(a, b): 3 | return (98 + a ** b) 4 | -------------------------------------------------------------------------------- /0x00-python-hello_world/2-print.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | print("\"Programming is like building a multilingual puzzle") 3 | -------------------------------------------------------------------------------- /0x00-python-hello_world/3-print_number.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | number = 98 3 | print(f"{number:d} Battery street") 4 | -------------------------------------------------------------------------------- /0x00-python-hello_world/4-print_float.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | number = 3.14159 3 | print(f"Float: {number:.2f}") 4 | -------------------------------------------------------------------------------- /0x00-python-hello_world/5-print_string.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | str = "Holberton School" 3 | print(3 * str) 4 | print(str[:9]) 5 | -------------------------------------------------------------------------------- /0x00-python-hello_world/6-concat.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | str1 = "Holberton" 3 | str2 = "School" 4 | str1 += " " + str2 5 | print("Welcome to {}!".format(str1)) 6 | -------------------------------------------------------------------------------- /0x00-python-hello_world/7-edges.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | word = "Holberton" 3 | word_first_3 = word[:3] 4 | word_last_2 = word[-2:] 5 | middle_word = word[1:-1] 6 | print("First 3 letters: {}".format(word_first_3)) 7 | print("Last 2 letters: {}".format(word_last_2)) 8 | print("Middle word: {}".format(middle_word)) 9 | -------------------------------------------------------------------------------- /0x00-python-hello_world/8-concat_edges.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | str = "Python is an interpreted, interactive, object-oriented programming\ 3 | language that combines remarkable power with very clear syntax" 4 | str = str[39:66] + str[106:112] + str[:6] 5 | print(str) 6 | -------------------------------------------------------------------------------- /0x00-python-hello_world/9-easter_egg.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import this 3 | -------------------------------------------------------------------------------- /0x00-python-hello_world/lists.h: -------------------------------------------------------------------------------- 1 | #ifndef LISTS_H 2 | #define LISTS_H 3 | 4 | #include 5 | 6 | 7 | typedef struct listint_s 8 | { 9 | int n; 10 | struct listint_s *next; 11 | } listint_t; 12 | 13 | size_t print_listint(const listint_t *h); 14 | listint_t *add_nodeint(listint_t **head, const int n); 15 | void free_listint(listint_t *head); 16 | int check_cycle(listint_t *list); 17 | 18 | #endif /* LISTS_H */ 19 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/0-positive_or_negative.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import random 3 | number = random.randint(-10, 10) 4 | if number > 0: 5 | print(f"{number:d} is positive") 6 | elif number == 0: 7 | print(f"{number:d} is zero") 8 | else: 9 | print(f"{number:d} is negative") 10 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/1-last_digit.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import random 3 | number = random.randint(-10000, 10000) 4 | digit = abs(number) % 10 5 | if number < 0: 6 | digit = -digit 7 | print(f"Last digit of {number:d} is {digit:d} and is ", end="") 8 | if digit > 5: 9 | print("greater than 5") 10 | elif digit == 0: 11 | print("0") 12 | else: 13 | print("less than 6 and not 0") 14 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/10-add.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Author - Bamidele Adefolaju 3 | def add(a, b): 4 | """Return the addition of a and b.""" 5 | return (a + b) 6 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/10-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | add = __import__('10-add').add 3 | 4 | print(add(1, 2)) 5 | print(add(98, 0)) 6 | print(add(100, -2)) 7 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/100-print_tebahpla.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Author -Bamidele Adefolaju 3 | 4 | i = 0 5 | for c in range(ord('z'), ord('a') - 1, -1): 6 | print("{}".format(chr(c - i)), end="") 7 | i = 32 if i == 0 else 0 8 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/101-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | remove_char_at = __import__('101-remove_char_at').remove_char_at 3 | 4 | print(remove_char_at("Best School", 3)) 5 | print(remove_char_at("Chicago", 2)) 6 | print(remove_char_at("C is fun!", 0)) 7 | print(remove_char_at("School", 10)) 8 | print(remove_char_at("Python", -2)) 9 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/101-remove_char_at.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Author - bamidele Adefolaju 3 | 4 | def remove_char_at(str, n): 5 | if n < 0: 6 | return (str) 7 | return (str[:n] + str[n+1:]) 8 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/102-magic_calculation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Author - Bamidele Adefolaju 3 | 4 | def magic_calculation(a, b, c): 5 | """Match bytecode provided by Holberton School.""" 6 | if a < b: 7 | return (c) 8 | if c > b: 9 | return (a + b) 10 | return (a*b - c) 11 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/11-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | pow = __import__('11-pow').pow 3 | 4 | print(pow(2, 2)) 5 | print(pow(98, 2)) 6 | print(pow(98, 0)) 7 | print(pow(100, -2)) 8 | print(pow(-4, 5)) 9 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/11-pow.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Author -Bamidele Adefolaju 3 | 4 | def pow(a, b): 5 | return (a ** b) 6 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/12-fizzbuzz.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Author - Bamidele Adefolaju 3 | """Print the numbers from 1 to 100 separated by a space. 4 | For multiples of three, print Fizz instead of the number 5 | For multiples of five, print Buzz instead of the number. 6 | For multiples of three and five, print FizzBuzz instead of the number. 7 | """ 8 | 9 | 10 | def fizzbuzz(): 11 | for number in range(1, 101): 12 | if number % 3 == 0 and number % 5 == 0: 13 | print("FizzBuzz ", end="") 14 | elif number % 3 == 0: 15 | print("Fizz ", end="") 16 | elif number % 5 == 0: 17 | print("Buzz ", end="") 18 | else: 19 | print("{} ".format(number), end="") 20 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/12-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | fizzbuzz = __import__('12-fizzbuzz').fizzbuzz 3 | 4 | fizzbuzz() 5 | print("") 6 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/13-insert_number.c: -------------------------------------------------------------------------------- 1 | #include "lists.h" 2 | 3 | /** 4 | * insert_node - Inserts a number into a sorted singly-linked list. 5 | * @head: A pointer the head of the linked list. 6 | * @number: The number to insert. 7 | * Author - Bamidele Adefolaju 8 | * Return: If the function fails - NULL. 9 | * Otherwise - a pointer to the new node. 10 | */ 11 | listint_t *insert_node(listint_t **head, int number) 12 | { 13 | listint_t *node = *head, *new; 14 | 15 | new = malloc(sizeof(listint_t)); 16 | if (new == NULL) 17 | return (NULL); 18 | new->n = number; 19 | 20 | if (node == NULL || node->n >= number) 21 | { 22 | new->next = node; 23 | *head = new; 24 | return (new); 25 | } 26 | 27 | while (node && node->next && node->next->n < number) 28 | node = node->next; 29 | 30 | new->next = node->next; 31 | node->next = new; 32 | 33 | return (new); 34 | } 35 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/2-print_alphabet.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Print the alphabet in lowercase, not followed by a new line.""" 3 | 4 | for letter in range(97, 123): 5 | print("{}".format(chr(letter)), end="") 6 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/3-print_alphabt.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Author - Bamidele Adefolaju 3 | for letter in range(97, 123): 4 | if chr(letter) != 'q' and chr(letter) != 'e': 5 | print("{}".format(chr(letter)), end="") 6 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/4-print_hexa.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Author - Bamidele Adefolaju 3 | 4 | """Print numbers 0 to 98 in decimal and hexadecimal.""" 5 | for number in range(0, 99): 6 | print("{} = {}".format(number, hex(number))) 7 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/5-print_comb2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for number in range(0, 100): 3 | if number == 99: 4 | print("{}".format(number)) 5 | else: 6 | print("{:02}".format(number), end=", ") 7 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/6-print_comb3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Author - Bamidele Adefolaju 3 | 4 | for digit1 in range(0, 10): 5 | for digit2 in range(digit1 + 1, 10): 6 | if digit1 == 8 and digit2 == 9: 7 | print("{}{}".format(digit1, digit2)) 8 | else: 9 | print("{}{}".format(digit1, digit2), end=", ") 10 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/7-islower.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Author - Bamidele Adefolaju 3 | 4 | def islower(c): 5 | """Function checks for lowercase characters.""" 6 | if ord(c) >= 97 and ord(c) <= 122: 7 | return True 8 | else: 9 | return False 10 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/7-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | islower = __import__('7-islower').islower 3 | 4 | print("a is {}".format("lower" if islower("a") else "upper")) 5 | print("H is {}".format("lower" if islower("H") else "upper")) 6 | print("A is {}".format("lower" if islower("A") else "upper")) 7 | print("3 is {}".format("lower" if islower("3") else "upper")) 8 | print("g is {}".format("lower" if islower("g") else "upper")) 9 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/8-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | uppercase = __import__('8-uppercase').uppercase 3 | 4 | uppercase("best") 5 | uppercase("Best School 98 Battery street") 6 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/8-uppercase.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Author - Bamidele Adefolaju 3 | 4 | def uppercase(str): 5 | """Print a string in uppercase.""" 6 | for c in str: 7 | if ord(c) >= 97 and ord(c) <= 122: 8 | c = chr(ord(c) - 32) 9 | print("{}".format(c), end="") 10 | print("") 11 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/9-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | print_last_digit = __import__('9-print_last_digit').print_last_digit 3 | 4 | print_last_digit(98) 5 | print_last_digit(0) 6 | r = print_last_digit(-1024) 7 | print(r) 8 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/9-print_last_digit.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Author - Bamidele Adefolaju 3 | 4 | def print_last_digit(number): 5 | print(abs(number) % 10, end="") 6 | return (abs(number) % 10) 7 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/lists.h: -------------------------------------------------------------------------------- 1 | #ifndef LISTS_H 2 | #define LISTS_H 3 | 4 | #include 5 | 6 | /** 7 | * struct listint_s - singly linked list 8 | * @n: integer 9 | * @next: points to the next node 10 | * 11 | * Description: singly linked list node structure 12 | */ 13 | typedef struct listint_s 14 | { 15 | int n; 16 | struct listint_s *next; 17 | } listint_t; 18 | 19 | size_t print_listint(const listint_t *h); 20 | listint_t *add_nodeint_end(listint_t **head, const int n); 21 | void free_listint(listint_t *head); 22 | listint_t *insert_node(listint_t **head, int number); 23 | 24 | #endif /* LISTS_H */ 25 | -------------------------------------------------------------------------------- /0x02-python-import_modules/0-add.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | if __name__ == "__main__": 4 | """Print the sum of 1 and 2.""" 5 | from add_0 import add 6 | 7 | a = 1 8 | b = 2 9 | print("{} + {} = {}".format(a, b, add(a, b))) 10 | -------------------------------------------------------------------------------- /0x02-python-import_modules/1-calculation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | if __name__ == "__main__": 4 | """Print the sum, difference, multiple and quotient of 10 and 5.""" 5 | from calculator_1 import add, sub, mul, div 6 | 7 | a = 10 8 | b = 5 9 | 10 | print("{} + {} = {}".format(a, b, add(a, b))) 11 | print("{} - {} = {}".format(a, b, sub(a, b))) 12 | print("{} * {} = {}".format(a, b, mul(a, b))) 13 | print("{} / {} = {}".format(a, b, div(a, b))) 14 | -------------------------------------------------------------------------------- /0x02-python-import_modules/100-my_calculator.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | if __name__ == "__main__": 4 | """Handle basic arithmetic operations.""" 5 | from calculator_1 import add, sub, mul, div 6 | import sys 7 | 8 | if len(sys.argv) - 1 != 3: 9 | print("Usage: ./100-my_calculator.py ") 10 | sys.exit(1) 11 | 12 | ops = {"+": add, "-": sub, "*": mul, "/": div} 13 | if sys.argv[2] not in list(ops.keys()): 14 | print("Unknown operator. Available operators: +, -, * and /") 15 | sys.exit(1) 16 | 17 | a = int(sys.argv[1]) 18 | b = int(sys.argv[3]) 19 | print("{} {} {} = {}".format(a, sys.argv[2], b, ops[sys.argv[2]](a, b))) 20 | -------------------------------------------------------------------------------- /0x02-python-import_modules/101-easy_print.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | __import__("os").write(1, "#pythoniscool\n".encode("UTF-8")) 3 | -------------------------------------------------------------------------------- /0x02-python-import_modules/102-magic_calculation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def magic_calculation(a, b): 4 | """Match bytecode provided by Holberton School.""" 5 | from magic_calculation_102 import add, sub 6 | 7 | if a < b: 8 | c = add(a, b) 9 | for i in range(4, 6): 10 | c = add(c, i) 11 | return (c) 12 | 13 | else: 14 | return(sub(a, b)) 15 | -------------------------------------------------------------------------------- /0x02-python-import_modules/103-fast_alphabet.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import string 3 | print(string.ascii_uppercase) 4 | -------------------------------------------------------------------------------- /0x02-python-import_modules/2-args.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | if __name__ == "__main__": 4 | """Print the number of and list of arguments.""" 5 | import sys 6 | 7 | count = len(sys.argv) - 1 8 | if count == 0: 9 | print("0 arguments.") 10 | elif count == 1: 11 | print("1 argument:") 12 | else: 13 | print("{} arguments:".format(count)) 14 | for i in range(count): 15 | print("{}: {}".format(i + 1, sys.argv[i + 1])) 16 | -------------------------------------------------------------------------------- /0x02-python-import_modules/3-infinite_add.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | if __name__ == "__main__": 4 | """Print the addition of all arguments.""" 5 | import sys 6 | 7 | total = 0 8 | for i in range(len(sys.argv) - 1): 9 | total += int(sys.argv[i + 1]) 10 | print("{}".format(total)) 11 | -------------------------------------------------------------------------------- /0x02-python-import_modules/4-hidden_discovery.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | if __name__ == "__main__": 4 | """Print all names defined by hidden_4 module.""" 5 | import hidden_4 6 | 7 | names = dir(hidden_4) 8 | for name in names: 9 | if name[:2] != "__": 10 | print(name) 11 | -------------------------------------------------------------------------------- /0x02-python-import_modules/5-variable_load.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | if __name__ == "__main__": 4 | """Print the value of variable a from variable_load_5.""" 5 | from variable_load_5 import a 6 | 7 | print(a) 8 | -------------------------------------------------------------------------------- /0x02-python-import_modules/add_0.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def add(a, b): 3 | """My addition function 4 | 5 | Args: 6 | a: first integer 7 | b: second integer 8 | 9 | Returns: 10 | The return value. a + b 11 | """ 12 | return (a + b) 13 | -------------------------------------------------------------------------------- /0x02-python-import_modules/calculator_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def add(a, b): 4 | """My addition function 5 | 6 | Args: 7 | a: first integer 8 | b: second integer 9 | 10 | Returns: 11 | The return value. a + b 12 | """ 13 | return (a + b) 14 | 15 | 16 | def sub(a, b): 17 | """My subtraction function 18 | 19 | Args: 20 | a: first integer 21 | b: second integer 22 | 23 | Returns: 24 | The return value. a - b 25 | """ 26 | return (a - b) 27 | 28 | 29 | def mul(a, b): 30 | """My multiplication function 31 | 32 | Args: 33 | a: first integer 34 | b: second integer 35 | 36 | Returns: 37 | The return value. a * b 38 | """ 39 | return (a * b) 40 | 41 | 42 | def div(a, b): 43 | """My division function 44 | 45 | Args: 46 | a: first integer 47 | b: second integer 48 | 49 | Returns: 50 | The return value. a / b 51 | """ 52 | return int(a / b) 53 | -------------------------------------------------------------------------------- /0x02-python-import_modules/variable_load_5.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | a = 98 3 | """Simple variable 4 | """ 5 | -------------------------------------------------------------------------------- /0x03-python-data_structures/0-print_list_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def print_list_integer(my_list=[]): 3 | for i in range(len(my_list)): 4 | print("{:d}".format(my_list[i])) 5 | -------------------------------------------------------------------------------- /0x03-python-data_structures/1-element_at.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def element_at(my_list, idx): 3 | if idx < 0 or idx > len(my_list) - 1: 4 | return 'None' 5 | else: 6 | return my_list[idx] 7 | -------------------------------------------------------------------------------- /0x03-python-data_structures/10-divisible_by_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def divisible_by_2(my_list=[]): 3 | new_list = [] 4 | for i in range(len(my_list)): 5 | if my_list[i] % 2 == 0: 6 | new_list.append(True) 7 | else: 8 | new_list.append(False) 9 | return new_list 10 | -------------------------------------------------------------------------------- /0x03-python-data_structures/100-print_python_list_info.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | void print_python_list_info(PyObject *p) 6 | { 7 | long int size = PyList_Size(p); 8 | int i; 9 | PyListObject *obj = (PyListObject *)p; 10 | 11 | printf("[*] Size of the Python List = %li\n", size); 12 | printf("[*] Allocated = %li\n", obj->allocated); 13 | for (i = 0; i < size; i++) 14 | printf("Element %i: %s\n", i, Py_TYPE(obj->ob_item[i])->tp_name); 15 | } 16 | -------------------------------------------------------------------------------- /0x03-python-data_structures/100-test_lists.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | 3 | lib = ctypes.CDLL('./libPyList.so') 4 | lib.print_python_list_info.argtypes = [ctypes.py_object] 5 | l = ['hello', 'World'] 6 | lib.print_python_list_info(l) 7 | del l[1] 8 | lib.print_python_list_info(l) 9 | l = l + [4, 5, 6.0, (9, 8), [9, 8, 1024], "Holberton"] 10 | lib.print_python_list_info(l) 11 | l = [] 12 | lib.print_python_list_info(l) 13 | l.append(0) 14 | lib.print_python_list_info(l) 15 | l.append(1) 16 | l.append(2) 17 | l.append(3) 18 | l.append(4) 19 | lib.print_python_list_info(l) 20 | l.pop() 21 | lib.print_python_list_info(l) 22 | -------------------------------------------------------------------------------- /0x03-python-data_structures/11-delete_at.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def delete_at(my_list=[], idx=0): 3 | if idx < 0 or idx > len(my_list) - 1: 4 | return my_list 5 | else: 6 | del my_list[idx] 7 | return my_list 8 | -------------------------------------------------------------------------------- /0x03-python-data_structures/12-switch.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | a = 89 3 | b = 10 4 | a, b = b, a 5 | print("a={:d} - b={:d}".format(a, b)) 6 | -------------------------------------------------------------------------------- /0x03-python-data_structures/13-is_palindrome.c: -------------------------------------------------------------------------------- 1 | #include "lists.h" 2 | 3 | /** 4 | * reverse_listint - reverses a linked list 5 | * @head: pointer to the first node in the list 6 | * 7 | * Return: pointer to the first node in the new list 8 | */ 9 | void reverse_listint(listint_t **head) 10 | { 11 | listint_t *prev = NULL; 12 | listint_t *current = *head; 13 | listint_t *next = NULL; 14 | 15 | while (current) 16 | { 17 | next = current->next; 18 | current->next = prev; 19 | prev = current; 20 | current = next; 21 | } 22 | 23 | *head = prev; 24 | } 25 | 26 | /** 27 | * is_palindrome - checks if a linked list is a palindrome 28 | * @head: double pointer to the linked list 29 | * 30 | * Return: 1 if it is, 0 if not 31 | */ 32 | int is_palindrome(listint_t **head) 33 | { 34 | listint_t *slow = *head, *fast = *head, *temp = *head, *dup = NULL; 35 | 36 | if (*head == NULL || (*head)->next == NULL) 37 | return (1); 38 | 39 | while (1) 40 | { 41 | fast = fast->next->next; 42 | if (!fast) 43 | { 44 | dup = slow->next; 45 | break; 46 | } 47 | if (!fast->next) 48 | { 49 | dup = slow->next->next; 50 | break; 51 | } 52 | slow = slow->next; 53 | } 54 | 55 | reverse_listint(&dup); 56 | 57 | while (dup && temp) 58 | { 59 | if (temp->n == dup->n) 60 | { 61 | dup = dup->next; 62 | temp = temp->next; 63 | } 64 | else 65 | return (0); 66 | } 67 | 68 | if (!dup) 69 | return (1); 70 | 71 | return (0); 72 | } 73 | -------------------------------------------------------------------------------- /0x03-python-data_structures/2-replace_in_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def replace_in_list(my_list, idx, element): 3 | if idx < 0 or idx > len(my_list) - 1: 4 | return my_list 5 | else: 6 | my_list[idx] = element 7 | return my_list 8 | -------------------------------------------------------------------------------- /0x03-python-data_structures/3-print_reversed_list_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def print_reversed_list_integer(my_list=[]): 3 | if my_list: 4 | my_list.reverse() 5 | for i in range(len(my_list)): 6 | print("{:d}".format(my_list[i])) 7 | -------------------------------------------------------------------------------- /0x03-python-data_structures/4-new_in_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def new_in_list(my_list, idx, element): 3 | copy = my_list.copy() 4 | if idx < 0 or idx > len(my_list) - 1: 5 | return my_list.copy() 6 | else: 7 | copy[idx] = element 8 | return copy 9 | -------------------------------------------------------------------------------- /0x03-python-data_structures/5-no_c.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def no_c(my_string): 3 | new_string = my_string.translate({ord(i): None for i in 'cC'}) 4 | return new_string 5 | -------------------------------------------------------------------------------- /0x03-python-data_structures/6-print_matrix_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def print_matrix_integer(matrix=[[]]): 3 | for row in matrix: 4 | for col in row: 5 | print("{:d}".format(col), end=" " if col != row[-1] else "") 6 | print() 7 | -------------------------------------------------------------------------------- /0x03-python-data_structures/7-add_tuple.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def add_tuple(tuple_a=(), tuple_b=()): 3 | new_tuple = () 4 | tuple_1 = tuple_a + (0, 0) 5 | tuple_2 = tuple_b + (0, 0) 6 | new_tuple = tuple_1[0] + tuple_2[0], tuple_1[1] + tuple_2[1] 7 | return new_tuple 8 | -------------------------------------------------------------------------------- /0x03-python-data_structures/8-multiple_returns.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def multiple_returns(sentence): 3 | my_tuple = () 4 | if len(sentence) == 0: 5 | my_tuple = 0, "None" 6 | else: 7 | my_tuple = len(sentence), sentence[0] 8 | return my_tuple 9 | -------------------------------------------------------------------------------- /0x03-python-data_structures/9-max_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def max_integer(my_list=[]): 3 | if len(my_list) == 0: 4 | return "None" 5 | else: 6 | max = my_list[0] 7 | for i in range(len(my_list)): 8 | if my_list[i] > max: 9 | max = my_list[i] 10 | return max 11 | -------------------------------------------------------------------------------- /0x03-python-data_structures/README.md: -------------------------------------------------------------------------------- 1 | # 0x03. Python - Data Structures: Lists, Tuples 2 | 3 | ## Table of contents 4 | Files | Description 5 | ----- | ----------- 6 | [0-print_list_integer.py](./0-print_list_integer.py) | Python function that prints all integers of a list 7 | [1-element_at.py](./1-element_at.py) | Python function that retrieves an element from a list like in C 8 | [2-replace_in_list.py](./2-replace_in_list.py) | Python function that replaces an element of a list at a specific position (like in C) 9 | [3-print_reversed_list_integer.py](./3-print_reversed_list_integer.py) | Python function that prints all integers of a list, in reverse order 10 | [4-new_in_list.py](./4-new_in_list.py) | Python function that replaces an element in a list at a specific position without modifying the original list (like in C) 11 | [5-no_c.py](./5-no_c.py) | Python function that removes all characters c and C from a string 12 | [6-print_matrix_integer.py](./6-print_matrix_integer.py) | Python function that prints a matrix of integers 13 | [7-add_tuple.py](./7-add_tuple.py) | Python function that adds 2 tuples 14 | [8-multiple_returns.py](./8-multiple_returns.py) | Python function that returns a tuple with the length of a string and its first character 15 | [9-max_integer.py](./9-max_integer.py) | Python function that finds the biggest integer of a list 16 | [10-divisible_by_2.py](./10-divisible_by_2.py) | Python function that finds all multiples of 2 in a list 17 | [11-delete_at.py](./11-delete_at.py) | Python function that deletes the item at a specific position in a list 18 | [12-switch.py](./12-switch.py) | Python program that completes source code in order to switch value of a and b 19 | [13-is_palindrome.c](./13-is_palindrome.c) | C program that checks if a singly linked list is a palindrome 20 | [lists.h](./lists.h) | Header file for the C program 21 | [100-print_python_list_info.c](./100-print_python_list_info.c) | C function to compile in a shared library that prints info on a Python list 22 | [100-test_lists.py](./100-test_lists.py) | Python script to test the C function above 23 | -------------------------------------------------------------------------------- /0x03-python-data_structures/lists.h: -------------------------------------------------------------------------------- 1 | #ifndef LISTS_H 2 | #define LISTS_H 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | /** 9 | * struct listint_s - singly linked list 10 | * @n: integer 11 | * @next: points to the next node 12 | * 13 | * Description: singly linked list node structure 14 | * for Holberton project 15 | */ 16 | typedef struct listint_s 17 | { 18 | int n; 19 | struct listint_s *next; 20 | } listint_t; 21 | 22 | size_t print_listint(const listint_t *h); 23 | listint_t *add_nodeint_end(listint_t **head, const int n); 24 | void free_listint(listint_t *head); 25 | 26 | void reverse_listint(listint_t **head); 27 | int is_palindrome(listint_t **head); 28 | 29 | #endif /* LISTS_H */ 30 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/0-square_matrix_simple.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def square_matrix_simple(matrix=[]): 3 | new_matrix = [[x ** 2 for x in row] for row in matrix] 4 | return new_matrix 5 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/1-search_replace.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def search_replace(my_list, search, replace): 3 | copy = [] 4 | for i in range(len(my_list)): 5 | if my_list[i] == search: 6 | copy.append(replace) 7 | else: 8 | copy.append(my_list[i]) 9 | return copy 10 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/10-best_score.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def best_score(a_dictionary): 4 | """Returns a key with the biggest integer value.""" 5 | if not isinstance(a_dictionary, dict) or len(a_dictionary) == 0: 6 | return None 7 | 8 | ret = list(a_dictionary.keys())[0] 9 | big = a_dictionary[ret] 10 | for k, v in a_dictionary.items(): 11 | if v > big: 12 | big = v 13 | ret = k 14 | return (ret) 15 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/100-weight_average.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def weight_average(my_list=[]): 3 | if not my_list: 4 | return 0 5 | average = 0 6 | div = 0 7 | for tup in my_list: 8 | average += tup[0] * tup[1] 9 | div += tup[1] 10 | return float(average / div) 11 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/101-square_matrix_map.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def square_matrix_map(matrix=[]): 3 | return list(map(lambda x: list(map(lambda i: i ** 2, x)), matrix)) 4 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/102-complex_delete.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def complex_delete(a_dictionary, value): 3 | for key in list(a_dictionary): 4 | if a_dictionary[key] == value: 5 | del a_dictionary[key] 6 | return a_dictionary 7 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/103-python.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | void print_python_bytes(PyObject *p) 7 | { 8 | long int size; 9 | int i; 10 | char *trying_str = NULL; 11 | 12 | printf("[.] bytes object info\n"); 13 | if (!PyBytes_Check(p)) 14 | { 15 | printf(" [ERROR] Invalid Bytes Object\n"); 16 | return; 17 | } 18 | 19 | PyBytes_AsStringAndSize(p, &trying_str, &size); 20 | 21 | printf(" size: %li\n", size); 22 | printf(" trying string: %s\n", trying_str); 23 | if (size < 10) 24 | printf(" first %li bytes:", size + 1); 25 | else 26 | printf(" first 10 bytes:"); 27 | for (i = 0; i <= size && i < 10; i++) 28 | printf(" %02hhx", trying_str[i]); 29 | printf("\n"); 30 | } 31 | 32 | void print_python_list(PyObject *p) 33 | { 34 | long int size = PyList_Size(p); 35 | int i; 36 | PyListObject *list = (PyListObject *)p; 37 | const char *type; 38 | 39 | printf("[*] Python list info\n"); 40 | printf("[*] Size of the Python List = %li\n", size); 41 | printf("[*] Allocated = %li\n", list->allocated); 42 | for (i = 0; i < size; i++) 43 | { 44 | type = (list->ob_item[i])->ob_type->tp_name; 45 | printf("Element %i: %s\n", i, type); 46 | if (!strcmp(type, "bytes")) 47 | print_python_bytes(list->ob_item[i]); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/103-tests.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | 3 | lib = ctypes.CDLL('./libPython.so') 4 | lib.print_python_list.argtypes = [ctypes.py_object] 5 | lib.print_python_bytes.argtypes = [ctypes.py_object] 6 | s = b"Hello" 7 | lib.print_python_bytes(s); 8 | b = b'\xff\xf8\x00\x00\x00\x00\x00\x00'; 9 | lib.print_python_bytes(b); 10 | b = b'What does the \'b\' character do in front of a string literal?'; 11 | lib.print_python_bytes(b); 12 | l = [b'Hello', b'World'] 13 | lib.print_python_list(l) 14 | del l[1] 15 | lib.print_python_list(l) 16 | l = l + [4, 5, 6.0, (9, 8), [9, 8, 1024], b"Holberton", "Betty"] 17 | lib.print_python_list(l) 18 | l = [] 19 | lib.print_python_list(l) 20 | l.append(0) 21 | lib.print_python_list(l) 22 | l.append(1) 23 | l.append(2) 24 | l.append(3) 25 | l.append(4) 26 | lib.print_python_list(l) 27 | l.pop() 28 | lib.print_python_list(l) 29 | l = ["Holberton"] 30 | lib.print_python_list(l) 31 | lib.print_python_bytes(l); 32 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/11-multiply_list_map.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def multiply_list_map(my_list=[], number=0): 3 | return (list(map((lambda i: i * number), my_list))) 4 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/12-roman_to_int.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def roman_to_int(roman_string): 3 | if not roman_string or type(roman_string) != str: 4 | return 0 5 | roman_d = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} 6 | roman_n = 0 7 | for j in range(len(roman_string)): 8 | if j > 0 and roman_d[roman_string[j]] > roman_d[roman_string[j - 1]]: 9 | roman_n += roman_d[roman_string[j]] - 2 * \ 10 | roman_d[roman_string[j - 1]] 11 | else: 12 | roman_n += roman_d[roman_string[j]] 13 | return roman_n 14 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/2-uniq_add.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def uniq_add(my_list=[]): 3 | new = set(my_list) 4 | res = 0 5 | for i in new: 6 | res += i 7 | return res 8 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/3-common_elements.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def common_elements(set_1, set_2): 3 | return set_1 & set_2 4 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/4-only_diff_elements.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def only_diff_elements(set_1, set_2): 3 | return set_1 ^ set_2 4 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/5-number_keys.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def number_keys(a_dictionary): 3 | return len(a_dictionary.keys()) 4 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/6-print_sorted_dictionary.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def print_sorted_dictionary(a_dictionary): 3 | for i in sorted(a_dictionary): 4 | print("{:s}: {}".format(i, a_dictionary[i])) 5 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/7-update_dictionary.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def update_dictionary(a_dictionary, key, value): 3 | if key not in a_dictionary: 4 | a_dictionary[key] = value 5 | else: 6 | for i in a_dictionary: 7 | if i == key: 8 | a_dictionary[i] = value 9 | return a_dictionary 10 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/8-simple_delete.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def simple_delete(a_dictionary, key=""): 3 | if key in a_dictionary: 4 | del a_dictionary[key] 5 | return a_dictionary 6 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/9-multiply_by_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def multiply_by_2(a_dictionary): 3 | new_d = {} 4 | for i in a_dictionary: 5 | new_d[i] = a_dictionary[i] * 2 6 | return new_d 7 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/tests/0-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | square_matrix_simple = __import__('0-square_matrix_simple').square_matrix_simple 3 | 4 | matrix = [ 5 | [1, 2, 3], 6 | [4, 5, 6], 7 | [7, 8, 9] 8 | ] 9 | 10 | new_matrix = square_matrix_simple(matrix) 11 | print(new_matrix) 12 | print(matrix) 13 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/tests/1-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | search_replace = __import__('1-search_replace').search_replace 3 | 4 | my_list = [1, 2, 3, 4, 5, 4, 2, 1, 1, 4, 89] 5 | new_list = search_replace(my_list, 2, 89) 6 | 7 | print(new_list) 8 | print(my_list) 9 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/tests/10-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | best_score = __import__('10-best_score').best_score 3 | 4 | a_dictionary = {'John': 12, 'Bob': 14, 'Mike': 14, 'Molly': 16, 'Adam': 10} 5 | best_key = best_score(a_dictionary) 6 | print("Best score: {}".format(best_key)) 7 | 8 | best_key = best_score(None) 9 | print("Best score: {}".format(best_key)) 10 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/tests/100-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | weight_average = __import__('100-weight_average').weight_average 3 | 4 | my_list = [(1, 2), (2, 1), (3, 10), (4, 2)] 5 | # = ((1 * 2) + (2 * 1) + (3 * 10) + (4 * 2)) / (2 + 1 + 10 + 2) 6 | result = weight_average(my_list) 7 | print("Average: {:0.2f}".format(result)) 8 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/tests/101-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | square_matrix_map = \ 3 | __import__('101-square_matrix_map').square_matrix_map 4 | 5 | matrix = [ 6 | [1, 2, 3], 7 | [4, 5, 6], 8 | [7, 8, 9] 9 | ] 10 | 11 | new_matrix = square_matrix_map(matrix) 12 | print(new_matrix) 13 | print(matrix) 14 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/tests/102-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | complex_delete = __import__('102-complex_delete').complex_delete 3 | print_sorted_dictionary = \ 4 | __import__('6-print_sorted_dictionary').print_sorted_dictionary 5 | 6 | a_dictionary = {'lang': "C", 'track': "Low", 'pref': "C", 'ids': [1, 2, 3]} 7 | new_dict = complex_delete(a_dictionary, 'C') 8 | print_sorted_dictionary(a_dictionary) 9 | print("--") 10 | print_sorted_dictionary(new_dict) 11 | 12 | print("--") 13 | print("--") 14 | new_dict = complex_delete(a_dictionary, 'c_is_fun') 15 | print_sorted_dictionary(a_dictionary) 16 | print("--") 17 | print_sorted_dictionary(new_dict) 18 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/tests/11-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | mutiply_list_map = __import__('11-mutiply_list_map').mutiply_list_map 3 | 4 | my_list = [1, 2, 3, 4, 6] 5 | new_list = mutiply_list_map(my_list, 4) 6 | print(new_list) 7 | print(my_list) 8 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/tests/12-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ Roman to Integer test file 3 | """ 4 | roman_to_int = __import__('12-roman_to_int').roman_to_int 5 | 6 | roman_number = "X" 7 | print("{} = {}".format(roman_number, roman_to_int(roman_number))) 8 | 9 | roman_number = "VII" 10 | print("{} = {}".format(roman_number, roman_to_int(roman_number))) 11 | 12 | roman_number = "IX" 13 | print("{} = {}".format(roman_number, roman_to_int(roman_number))) 14 | 15 | roman_number = "LXXXVII" 16 | print("{} = {}".format(roman_number, roman_to_int(roman_number))) 17 | 18 | roman_number = "DCCVII" 19 | print("{} = {}".format(roman_number, roman_to_int(roman_number))) 20 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/tests/2-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | uniq_add = __import__('2-uniq_add').uniq_add 3 | 4 | my_list = [1, 2, 3, 1, 4, 2, 5] 5 | result = uniq_add(my_list) 6 | print("Result: {:d}".format(result)) 7 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/tests/3-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | common_elements = __import__('3-common_elements').common_elements 3 | 4 | set_1 = { "Python", "C", "Javascript" } 5 | set_2 = { "Bash", "C", "Ruby", "Perl" } 6 | c_set = common_elements(set_1, set_2) 7 | print(sorted(list(c_set))) 8 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/tests/4-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | only_diff_elements = __import__('4-only_diff_elements').only_diff_elements 3 | 4 | set_1 = { "Python", "C", "Javascript" } 5 | set_2 = { "Bash", "C", "Ruby", "Perl" } 6 | od_set = only_diff_elements(set_1, set_2) 7 | print(sorted(list(od_set))) 8 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/tests/5-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | number_keys = __import__('5-number_keys').number_keys 3 | 4 | a_dictionary = { 'language': "C", 'number': 13, 'track': "Low level" } 5 | nb_keys = number_keys(a_dictionary) 6 | print("Number of keys: {:d}".format(nb_keys)) 7 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/tests/6-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | print_sorted_dictionary = __import__('6-print_sorted_dictionary').print_sorted_dictionary 3 | 4 | a_dictionary = { 'language': "C", 'Number': 89, 'track': "Low level", 'ids': [1, 2, 3] } 5 | print_sorted_dictionary(a_dictionary) 6 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/tests/7-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | update_dictionary = __import__('7-update_dictionary').update_dictionary 3 | print_sorted_dictionary = __import__('6-print_sorted_dictionary').print_sorted_dictionary 4 | 5 | a_dictionary = { 'language': "C", 'number': 89, 'track': "Low level" } 6 | new_dict = update_dictionary(a_dictionary, 'language', "Python") 7 | print_sorted_dictionary(new_dict) 8 | print("--") 9 | print_sorted_dictionary(a_dictionary) 10 | 11 | print("--") 12 | print("--") 13 | 14 | new_dict = update_dictionary(a_dictionary, 'city', "San Francisco") 15 | print_sorted_dictionary(new_dict) 16 | print("--") 17 | print_sorted_dictionary(a_dictionary) 18 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/tests/8-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | simple_delete = __import__('8-simple_delete').simple_delete 3 | print_sorted_dictionary = \ 4 | __import__('6-print_sorted_dictionary').print_sorted_dictionary 5 | 6 | a_dictionary = { 'language': "C", 'Number': 89, 'track': "Low", 'ids': [1, 2, 3] } 7 | new_dict = simple_delete(a_dictionary, 'track') 8 | print_sorted_dictionary(a_dictionary) 9 | print("--") 10 | print_sorted_dictionary(new_dict) 11 | 12 | print("--") 13 | print("--") 14 | new_dict = simple_delete(a_dictionary, 'c_is_fun') 15 | print_sorted_dictionary(a_dictionary) 16 | print("--") 17 | print_sorted_dictionary(new_dict) 18 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/tests/9-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | multiply_by_2 = __import__('9-multiply_by_2').multiply_by_2 3 | print_sorted_dictionary = \ 4 | __import__('6-print_sorted_dictionary').print_sorted_dictionary 5 | 6 | a_dictionary = {'John': 12, 'Alex': 8, 'Bob': 14, 'Mike': 14, 'Molly': 16} 7 | new_dict = multiply_by_2(a_dictionary) 8 | print_sorted_dictionary(a_dictionary) 9 | print("--") 10 | print_sorted_dictionary(new_dict) 11 | -------------------------------------------------------------------------------- /0x05-python-exceptions/0-safe_print_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def safe_print_list(my_list=[], x=0): 4 | """Print x elememts of a list. 5 | 6 | Args: 7 | my_list (list): The list to print elements from. 8 | x (int): The number of elements of my_list to print. 9 | 10 | Returns: 11 | The number of elements printed. 12 | """ 13 | ret = 0 14 | for i in range(x): 15 | try: 16 | print("{}".format(my_list[i]), end="") 17 | ret += 1 18 | except IndexError: 19 | break 20 | print("") 21 | return (ret) 22 | -------------------------------------------------------------------------------- /0x05-python-exceptions/1-safe_print_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def safe_print_integer(value): 4 | """Print an integer with "{:d}".format(). 5 | 6 | Args: 7 | value (int): The integer to print. 8 | 9 | Returns: 10 | If a TypeError or ValueError occurs - False. 11 | Otherwise - True. 12 | """ 13 | try: 14 | print("{:d}".format(value)) 15 | return (True) 16 | except (TypeError, ValueError): 17 | return (False) 18 | -------------------------------------------------------------------------------- /0x05-python-exceptions/100-safe_print_integer_err.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import sys 4 | 5 | 6 | def safe_print_integer_err(value): 7 | """Prints an integer with "{:d}".format(). 8 | 9 | If a ValueError message is caught, a corresponding 10 | message is printed to standard error. 11 | 12 | Args: 13 | value (int): The integer to print. 14 | 15 | Returns: 16 | If a TypeError or ValueError occurs - False. 17 | Otherwise - True. 18 | """ 19 | try: 20 | print("{:d}".format(value)) 21 | return (True) 22 | except (TypeError, ValueError): 23 | print("Exception: {}".format(sys.exc_info()[1]), file=sys.stderr) 24 | return (False) 25 | -------------------------------------------------------------------------------- /0x05-python-exceptions/101-safe_function.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | from __future__ import print_function 3 | import sys 4 | 5 | 6 | def safe_function(fct, *args): 7 | try: 8 | res = fct(*args) 9 | except Exception as e: 10 | print("Exception: {}".format(e), file=sys.stderr) 11 | return None 12 | else: 13 | return res 14 | -------------------------------------------------------------------------------- /0x05-python-exceptions/102-magic_calculation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def magic_calculation(a, b): 3 | result = 0 4 | for i in range(1, 3): 5 | try: 6 | if i > a: 7 | raise Exception('Too far') 8 | result += a ** b / i 9 | except Exception: 10 | result = b + a 11 | break 12 | return result 13 | -------------------------------------------------------------------------------- /0x05-python-exceptions/103-python.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | /** 4 | * print_python_float - gives data of the PyFloatObject 5 | * @p: the PyObject 6 | */ 7 | void print_python_float(PyObject *p) 8 | { 9 | double value = 0; 10 | char *string = NULL; 11 | 12 | fflush(stdout); 13 | printf("[.] float object info\n"); 14 | 15 | if (!PyFloat_CheckExact(p)) 16 | { 17 | printf(" [ERROR] Invalid Float Object\n"); 18 | return; 19 | } 20 | value = ((PyFloatObject *)p)->ob_fval; 21 | string = PyOS_double_to_string(value, 'r', 0, Py_DTSF_ADD_DOT_0, NULL); 22 | printf(" value: %s\n", string); 23 | } 24 | /** 25 | * print_python_bytes - gives data of the PyBytesObject 26 | * @p: the PyObject 27 | */ 28 | void print_python_bytes(PyObject *p) 29 | { 30 | Py_ssize_t size = 0, i = 0; 31 | char *string = NULL; 32 | 33 | fflush(stdout); 34 | printf("[.] bytes object info\n"); 35 | if (!PyBytes_CheckExact(p)) 36 | { 37 | printf(" [ERROR] Invalid Bytes Object\n"); 38 | return; 39 | } 40 | size = PyBytes_Size(p); 41 | printf(" size: %zd\n", size); 42 | string = (assert(PyBytes_Check(p)), (((PyBytesObject *)(p))->ob_sval)); 43 | printf(" trying string: %s\n", string); 44 | printf(" first %zd bytes:", size < 10 ? size + 1 : 10); 45 | while (i < size + 1 && i < 10) 46 | { 47 | printf(" %02hhx", string[i]); 48 | i++; 49 | } 50 | printf("\n"); 51 | } 52 | /** 53 | * print_python_list - gives data of the PyListObject 54 | * @p: the PyObject 55 | */ 56 | void print_python_list(PyObject *p) 57 | { 58 | Py_ssize_t size = 0; 59 | PyObject *item; 60 | int i = 0; 61 | 62 | fflush(stdout); 63 | printf("[*] Python list info\n"); 64 | if (PyList_CheckExact(p)) 65 | { 66 | size = PyList_GET_SIZE(p); 67 | printf("[*] Size of the Python List = %zd\n", size); 68 | printf("[*] Allocated = %lu\n", ((PyListObject *)p)->allocated); 69 | while (i < size) 70 | { 71 | item = PyList_GET_ITEM(p, i); 72 | printf("Element %d: %s\n", i, item->ob_type->tp_name); 73 | if (PyBytes_Check(item)) 74 | print_python_bytes(item); 75 | else if (PyFloat_Check(item)) 76 | print_python_float(item); 77 | i++; 78 | } 79 | } 80 | else 81 | printf(" [ERROR] Invalid List Object\n"); 82 | } 83 | -------------------------------------------------------------------------------- /0x05-python-exceptions/2-safe_print_list_integers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def safe_print_list_integers(my_list=[], x=0): 4 | """Print the first x elements of a list that are integers. 5 | 6 | Args: 7 | my_list (list): The list to print elements from. 8 | x (int): The number of elements of my_list to print. 9 | 10 | Returns: 11 | The number of elements printed. 12 | """ 13 | ret = 0 14 | for i in range(0, x): 15 | try: 16 | print("{:d}".format(my_list[i]), end="") 17 | ret += 1 18 | except (ValueError, TypeError): 19 | continue 20 | print("") 21 | return (ret) 22 | -------------------------------------------------------------------------------- /0x05-python-exceptions/3-safe_print_division.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def safe_print_division(a, b): 4 | """Returns the division of a by b.""" 5 | try: 6 | div = a / b 7 | except (TypeError, ZeroDivisionError): 8 | div = None 9 | finally: 10 | print("Inside result: {}".format(div)) 11 | return (div) 12 | -------------------------------------------------------------------------------- /0x05-python-exceptions/4-list_division.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def list_division(my_list_1, my_list_2, list_length): 4 | """Divides two lists element by element. 5 | 6 | Args: 7 | my_list_1 (list): The first list. 8 | my_list_2 (list): The second list. 9 | list_length (int): The number of elements to divide. 10 | 11 | Returns: 12 | A new list of length list_length containing all the divisions. 13 | """ 14 | new_list = [] 15 | for i in range(0, list_length): 16 | try: 17 | div = my_list_1[i] / my_list_2[i] 18 | except TypeError: 19 | print("wrong type") 20 | div = 0 21 | except ZeroDivisionError: 22 | print("division by 0") 23 | div = 0 24 | except IndexError: 25 | print("out of range") 26 | div = 0 27 | finally: 28 | new_list.append(div) 29 | return (new_list) 30 | -------------------------------------------------------------------------------- /0x05-python-exceptions/5-raise_exception.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def raise_exception(): 4 | """Raise a TypeError exception.""" 5 | raise TypeError 6 | -------------------------------------------------------------------------------- /0x05-python-exceptions/6-raise_exception_msg.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def raise_exception_msg(message=""): 4 | """Raise a NameError exception with a message.""" 5 | raise NameError(message) 6 | -------------------------------------------------------------------------------- /0x06-python-classes/0-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | """Define a class Square.""" 4 | 5 | 6 | class Square: 7 | """Represent a square.""" 8 | pass 9 | -------------------------------------------------------------------------------- /0x06-python-classes/1-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | """Define a class Square.""" 4 | 5 | 6 | class Square: 7 | """Represent a square.""" 8 | 9 | def __init__(self, size): 10 | """Initialize a new Square. 11 | 12 | Args: 13 | size (int): The size of the new square. 14 | """ 15 | self.__size = size 16 | -------------------------------------------------------------------------------- /0x06-python-classes/101-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | """Define a class Square.""" 4 | 5 | 6 | class Square: 7 | """Represent a square.""" 8 | 9 | def __init__(self, size=0, position=(0, 0)): 10 | """Initialize a new square. 11 | 12 | Args: 13 | size (int): The size of the new square. 14 | position (int, int): The position of the new square. 15 | """ 16 | self.size = size 17 | self.position = position 18 | 19 | @property 20 | def size(self): 21 | """Get/set the current size of the square.""" 22 | return (self.__size) 23 | 24 | @size.setter 25 | def size(self, value): 26 | if not isinstance(value, int): 27 | raise TypeError("size must be an integer") 28 | elif value < 0: 29 | raise ValueError("size must be >= 0") 30 | self.__size = value 31 | 32 | @property 33 | def position(self): 34 | """Get/set the current position of the square.""" 35 | return (self.__position) 36 | 37 | @position.setter 38 | def position(self, value): 39 | if (not isinstance(value, tuple) or 40 | len(value) != 2 or 41 | not all(isinstance(num, int) for num in value) or 42 | not all(num >= 0 for num in value)): 43 | raise TypeError("position must be a tuple of 2 positive integers") 44 | self.__position = value 45 | 46 | def area(self): 47 | """Return the current area of the square.""" 48 | return (self.__size * self.__size) 49 | 50 | def my_print(self): 51 | """Print the square with the # character.""" 52 | if self.__size == 0: 53 | print("") 54 | return 55 | 56 | [print("") for i in range(0, self.__position[1])] 57 | for i in range(0, self.__size): 58 | [print(" ", end="") for j in range(0, self.__position[0])] 59 | [print("#", end="") for k in range(0, self.__size)] 60 | print("") 61 | 62 | def __str__(self): 63 | """Define the print() representation of a Square.""" 64 | if self.__size != 0: 65 | [print("") for i in range(0, self.__position[1])] 66 | for i in range(0, self.__size): 67 | [print(" ", end="") for j in range(0, self.__position[0])] 68 | [print("#", end="") for k in range(0, self.__size)] 69 | if i != self.__size - 1: 70 | print("") 71 | return ("") 72 | -------------------------------------------------------------------------------- /0x06-python-classes/102-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | """Define a class Square.""" 4 | 5 | 6 | class Square: 7 | """Represent a square.""" 8 | 9 | def __init__(self, size=0): 10 | """Initialize a new square. 11 | 12 | Args: 13 | size (int): The size of the new square. 14 | """ 15 | self.size = size 16 | 17 | @property 18 | def size(self): 19 | """Get/set the current size of the square.""" 20 | return (self.__size) 21 | 22 | @size.setter 23 | def size(self, value): 24 | if not isinstance(value, int): 25 | raise TypeError("size must be an integer") 26 | elif value < 0: 27 | raise ValueError("size must be >= 0") 28 | self.__size = value 29 | 30 | def area(self): 31 | """Return the current area of the square.""" 32 | return (self.__size * self.__size) 33 | 34 | def __eq__(self, other): 35 | """Define the == comparision to a Square.""" 36 | return self.area() == other.area() 37 | 38 | def __ne__(self, other): 39 | """Define the != comparison to a Square.""" 40 | return self.area() != other.area() 41 | 42 | def __lt__(self, other): 43 | """Define the < comparison to a Square.""" 44 | return self.area() < other.area() 45 | 46 | def __le__(self, other): 47 | """Define the <= comparison to a Square.""" 48 | return self.area() <= other.area() 49 | 50 | def __gt__(self, other): 51 | """Define the > comparison to a Square.""" 52 | return self.area() > other.area() 53 | 54 | def __ge__(self, other): 55 | """Define the >= compmarison to a Square.""" 56 | return self.area() >= other.area() 57 | -------------------------------------------------------------------------------- /0x06-python-classes/103-magic_class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | """Define a MagicClass matching exactly a bytecode provided by Holberton.""" 4 | 5 | import math 6 | 7 | 8 | class MagicClass: 9 | """Represent a circle.""" 10 | 11 | def __init__(self, radius=0): 12 | """Initialize a MagicClass. 13 | 14 | Arg: 15 | radius (float or int): The radius of the new MagicClass. 16 | """ 17 | self.__radius = 0 18 | if type(radius) is not int and type(radius) is not float: 19 | raise TypeError("radius must be a number") 20 | self.__radius = radius 21 | 22 | def area(self): 23 | """Return the area of the MagicClass.""" 24 | return (self.__radius ** 2 * math.pi) 25 | 26 | def circumference(self): 27 | """Return The circumference of the MagicClass.""" 28 | return (2 * math.pi * self.__radius) 29 | -------------------------------------------------------------------------------- /0x06-python-classes/2-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | """Define a class Square.""" 4 | 5 | 6 | class Square: 7 | """Represent a square.""" 8 | 9 | def __init__(self, size=0): 10 | """Initialize a new Square. 11 | 12 | Args: 13 | size (int): The size of the new square. 14 | """ 15 | if not isinstance(size, int): 16 | raise TypeError("size must be an integer") 17 | elif size < 0: 18 | raise ValueError("size must be >= 0") 19 | self.__size = size 20 | -------------------------------------------------------------------------------- /0x06-python-classes/3-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | """Define a class Square.""" 4 | 5 | 6 | class Square: 7 | """Represent a square.""" 8 | 9 | def __init__(self, size=0): 10 | """Initialize a new square. 11 | 12 | Args: 13 | size (int): The size of the new square. 14 | """ 15 | if not isinstance(size, int): 16 | raise TypeError("size must be an integer") 17 | elif size < 0: 18 | raise ValueError("size must be >= 0") 19 | self.__size = size 20 | 21 | def area(self): 22 | """Return the current area of the square.""" 23 | return (self.__size * self.__size) 24 | -------------------------------------------------------------------------------- /0x06-python-classes/4-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | """Define a class Square.""" 4 | 5 | 6 | class Square: 7 | """Represent a square.""" 8 | 9 | def __init__(self, size=0): 10 | """Initialize a new square. 11 | 12 | Args: 13 | size (int): The size of the new square. 14 | """ 15 | self.size = size 16 | 17 | @property 18 | def size(self): 19 | """Get/set the current size of the square.""" 20 | return (self.__size) 21 | 22 | @size.setter 23 | def size(self, value): 24 | if not isinstance(value, int): 25 | raise TypeError("size must be an integer") 26 | elif value < 0: 27 | raise ValueError("size must be >= 0") 28 | self.__size = value 29 | 30 | def area(self): 31 | """Return the current area of the square.""" 32 | return (self.__size * self.__size) 33 | -------------------------------------------------------------------------------- /0x06-python-classes/5-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | """Define a class Square.""" 4 | 5 | 6 | class Square: 7 | """Represent a square.""" 8 | 9 | def __init__(self, size): 10 | """Initialize a new square. 11 | 12 | Args: 13 | size (int): The size of the new square. 14 | """ 15 | self.size = size 16 | 17 | @property 18 | def size(self): 19 | """Get/set the current size of the square.""" 20 | return (self.__size) 21 | 22 | @size.setter 23 | def size(self, value): 24 | if not isinstance(value, int): 25 | raise TypeError("size must be an integer") 26 | elif value < 0: 27 | raise ValueError("size must be >= 0") 28 | self.__size = value 29 | 30 | def area(self): 31 | """Return the current area of the square.""" 32 | return (self.__size * self.__size) 33 | 34 | def my_print(self): 35 | """Print the square with the # character.""" 36 | for i in range(0, self.__size): 37 | [print("#", end="") for j in range(self.__size)] 38 | print("") 39 | if self.__size == 0: 40 | print("") 41 | -------------------------------------------------------------------------------- /0x06-python-classes/6-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | """Define a class Square.""" 4 | 5 | 6 | class Square: 7 | """Represent a square.""" 8 | 9 | def __init__(self, size=0, position=(0, 0)): 10 | """Initialize a new square. 11 | 12 | Args: 13 | size (int): The size of the new square. 14 | position (int, int): The position of the new square. 15 | """ 16 | self.size = size 17 | self.position = position 18 | 19 | @property 20 | def size(self): 21 | """Get/set the current size of the square.""" 22 | return (self.__size) 23 | 24 | @size.setter 25 | def size(self, value): 26 | if not isinstance(value, int): 27 | raise TypeError("size must be an integer") 28 | elif value < 0: 29 | raise ValueError("size must be >= 0") 30 | self.__size = value 31 | 32 | @property 33 | def position(self): 34 | """Get/set the current position of the square.""" 35 | return (self.__position) 36 | 37 | @position.setter 38 | def position(self, value): 39 | if (not isinstance(value, tuple) or 40 | len(value) != 2 or 41 | not all(isinstance(num, int) for num in value) or 42 | not all(num >= 0 for num in value)): 43 | raise TypeError("position must be a tuple of 2 positive integers") 44 | self.__position = value 45 | 46 | def area(self): 47 | """Return the current area of the square.""" 48 | return (self.__size * self.__size) 49 | 50 | def my_print(self): 51 | """Print the square with the # character.""" 52 | if self.__size == 0: 53 | print("") 54 | return 55 | 56 | [print("") for i in range(0, self.__position[1])] 57 | for i in range(0, self.__size): 58 | [print(" ", end="") for j in range(0, self.__position[0])] 59 | [print("#", end="") for k in range(0, self.__size)] 60 | print("") 61 | -------------------------------------------------------------------------------- /0x06-python-classes/tests/0-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Square = __import__('0-square').Square 3 | 4 | my_square = Square() 5 | print(type(my_square)) 6 | print(my_square.__dict__) 7 | -------------------------------------------------------------------------------- /0x06-python-classes/tests/1-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Square = __import__('1-square').Square 3 | 4 | my_square = Square(3) 5 | print(type(my_square)) 6 | print(my_square.__dict__) 7 | 8 | try: 9 | print(my_square.size) 10 | except Exception as e: 11 | print(e) 12 | 13 | try: 14 | print(my_square.__size) 15 | except Exception as e: 16 | print(e) 17 | -------------------------------------------------------------------------------- /0x06-python-classes/tests/100-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | SinglyLinkedList = __import__('100-singly_linked_list').SinglyLinkedList 3 | 4 | sll = SinglyLinkedList() 5 | sll.sorted_insert(2) 6 | sll.sorted_insert(5) 7 | sll.sorted_insert(3) 8 | sll.sorted_insert(10) 9 | sll.sorted_insert(1) 10 | sll.sorted_insert(-4) 11 | sll.sorted_insert(-3) 12 | sll.sorted_insert(4) 13 | sll.sorted_insert(5) 14 | sll.sorted_insert(12) 15 | sll.sorted_insert(3) 16 | print(sll) 17 | -------------------------------------------------------------------------------- /0x06-python-classes/tests/101-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Square = __import__('101-square').Square 3 | 4 | my_square = Square(5, (0, 0)) 5 | print(my_square) 6 | 7 | print("--") 8 | 9 | my_square = Square(5, (4, 1)) 10 | print(my_square) 11 | -------------------------------------------------------------------------------- /0x06-python-classes/tests/102-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Square = __import__('102-square').Square 3 | 4 | s_5 = Square(5) 5 | s_6 = Square(6) 6 | 7 | if s_5 < s_6: 8 | print("Square 5 < Square 6") 9 | if s_5 <= s_6: 10 | print("Square 5 <= Square 6") 11 | if s_5 == s_6: 12 | print("Square 5 == Square 6") 13 | if s_5 != s_6: 14 | print("Square 5 != Square 6") 15 | if s_5 > s_6: 16 | print("Square 5 > Square 6") 17 | if s_5 >= s_6: 18 | print("Square 5 >= Square 6") 19 | -------------------------------------------------------------------------------- /0x06-python-classes/tests/2-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Square = __import__('2-square').Square 3 | 4 | my_square_1 = Square(3) 5 | print(type(my_square_1)) 6 | print(my_square_1.__dict__) 7 | 8 | my_square_2 = Square() 9 | print(type(my_square_2)) 10 | print(my_square_2.__dict__) 11 | 12 | try: 13 | print(my_square_1.size) 14 | except Exception as e: 15 | print(e) 16 | 17 | try: 18 | print(my_square_1.__size) 19 | except Exception as e: 20 | print(e) 21 | 22 | try: 23 | my_square_3 = Square("3") 24 | print(type(my_square_3)) 25 | print(my_square_3.__dict__) 26 | except Exception as e: 27 | print(e) 28 | 29 | try: 30 | my_square_4 = Square(-89) 31 | print(type(my_square_4)) 32 | print(my_square_4.__dict__) 33 | except Exception as e: 34 | print(e) 35 | -------------------------------------------------------------------------------- /0x06-python-classes/tests/3-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Square = __import__('3-square').Square 3 | 4 | my_square_1 = Square(3) 5 | print("Area: {}".format(my_square_1.area())) 6 | 7 | try: 8 | print(my_square_1.size) 9 | except Exception as e: 10 | print(e) 11 | 12 | try: 13 | print(my_square_1.__size) 14 | except Exception as e: 15 | print(e) 16 | 17 | my_square_2 = Square(5) 18 | print("Area: {}".format(my_square_2.area())) 19 | -------------------------------------------------------------------------------- /0x06-python-classes/tests/4-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Square = __import__('4-square').Square 3 | 4 | my_square = Square(89) 5 | print("Area: {} for size: {}".format(my_square.area(), my_square.size)) 6 | 7 | my_square.size = 3 8 | print("Area: {} for size: {}".format(my_square.area(), my_square.size)) 9 | 10 | try: 11 | my_square.size = "5 feet" 12 | print("Area: {} for size: {}".format(my_square.area(), my_square.size)) 13 | except Exception as e: 14 | print(e) 15 | -------------------------------------------------------------------------------- /0x06-python-classes/tests/5-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Square = __import__('5-square').Square 3 | 4 | my_square = Square(3) 5 | my_square.my_print() 6 | 7 | print("--") 8 | 9 | my_square.size = 10 10 | my_square.my_print() 11 | 12 | print("--") 13 | 14 | my_square.size = 0 15 | my_square.my_print() 16 | 17 | print("--") 18 | -------------------------------------------------------------------------------- /0x06-python-classes/tests/6-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Square = __import__('6-square').Square 3 | 4 | my_square_1 = Square(3) 5 | my_square_1.my_print() 6 | 7 | print("--") 8 | 9 | my_square_2 = Square(3, (1, 1)) 10 | my_square_2.my_print() 11 | 12 | print("--") 13 | 14 | my_square_3 = Square(3, (3, 0)) 15 | my_square_3.my_print() 16 | 17 | print("--") 18 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/0-add_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines an integer addition function.""" 3 | 4 | 5 | def add_integer(a, b=98): 6 | """Return the integer addition of a and b. 7 | 8 | Float arguments are typecasted to ints before addition is performed. 9 | 10 | Raises: 11 | TypeError: If either of a or b is a non-integer and non-float. 12 | """ 13 | if ((not isinstance(a, int) and not isinstance(a, float))): 14 | raise TypeError("a must be an integer") 15 | if ((not isinstance(b, int) and not isinstance(b, float))): 16 | raise TypeError("b must be an integer") 17 | return (int(a) + int(b)) 18 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/101-lazy_matrix_mul.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a matrix multiplication function using NumPy.""" 3 | import numpy as np 4 | 5 | 6 | def lazy_matrix_mul(m_a, m_b): 7 | """Return the multiplication of two matrices. 8 | 9 | Args: 10 | m_a (list of lists of ints/floats): The first matrix. 11 | m_b (list of lists of ints/floats): The second matrix. 12 | """ 13 | 14 | return (np.matmul(m_a, m_b)) 15 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/102-python.c: -------------------------------------------------------------------------------- 1 | #include "Python.h" 2 | 3 | /** 4 | * print_python_string - Prints information about Python strings. 5 | * @p: A PyObject string object. 6 | */ 7 | void print_python_string(PyObject *p) 8 | { 9 | long int length; 10 | 11 | fflush(stdout); 12 | 13 | printf("[.] string object info\n"); 14 | if (strcmp(p->ob_type->tp_name, "str") != 0) 15 | { 16 | printf(" [ERROR] Invalid String Object\n"); 17 | return; 18 | } 19 | 20 | length = ((PyASCIIObject *)(p))->length; 21 | 22 | if (PyUnicode_IS_COMPACT_ASCII(p)) 23 | printf(" type: compact ascii\n"); 24 | else 25 | printf(" type: compact unicode object\n"); 26 | printf(" length: %ld\n", length); 27 | printf(" value: %ls\n", PyUnicode_AsWideCharString(p, &length)); 28 | } 29 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/2-matrix_divided.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a matrix division function.""" 3 | 4 | 5 | def matrix_divided(matrix, div): 6 | """Divide all elements of a matrix. 7 | 8 | Args: 9 | matrix (list): A list of lists of ints or floats. 10 | div (int/float): The divisor. 11 | Raises: 12 | TypeError: If the matrix contains non-numbers. 13 | TypeError: If the matrix contains rows of different sizes. 14 | TypeError: If div is not an int or float. 15 | ZeroDivisionError: If div is 0. 16 | Returns: 17 | A new matrix representing the result of the division. 18 | """ 19 | if (not isinstance(matrix, list) or matrix == [] or 20 | not all(isinstance(row, list) for row in matrix) or 21 | not all((isinstance(ele, int) or isinstance(ele, float)) 22 | for ele in [num for row in matrix for num in row])): 23 | raise TypeError("matrix must be a matrix (list of lists) of " 24 | "integers/floats") 25 | 26 | if not all(len(row) == len(matrix[0]) for row in matrix): 27 | raise TypeError("Each row of the matrix must have the same size") 28 | 29 | if not isinstance(div, int) and not isinstance(div, float): 30 | raise TypeError("div must be a number") 31 | 32 | if div == 0: 33 | raise ZeroDivisionError("division by zero") 34 | 35 | return ([list(map(lambda x: round(x / div, 2), row)) for row in matrix]) 36 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/3-say_my_name.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a name-printing function.""" 3 | 4 | 5 | def say_my_name(first_name, last_name=""): 6 | """Print a name. 7 | 8 | Args: 9 | first_name (str): The first name to print. 10 | last_name (str): The last name to print. 11 | Raises: 12 | TypeError: If either of first_name or last_name are not strings. 13 | """ 14 | if not isinstance(first_name, str): 15 | raise TypeError("first_name must be a string") 16 | if not isinstance(last_name, str): 17 | raise TypeError("last_name must be a string") 18 | print("My name is {} {}".format(first_name, last_name)) 19 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/4-print_square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a square-printing function.""" 3 | 4 | 5 | def print_square(size): 6 | """Print a square with the # character. 7 | 8 | Args: 9 | size (int): The height/width of the square. 10 | Raises: 11 | TypeError: If size is not an integer. 12 | ValueError: If size is < 0 13 | """ 14 | if not isinstance(size, int): 15 | raise TypeError("size must be an integer") 16 | if size < 0: 17 | raise ValueError("size must be >= 0") 18 | 19 | for i in range(size): 20 | [print("#", end="") for j in range(size)] 21 | print("") 22 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/5-text_indentation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a text-indentation function.""" 3 | 4 | 5 | def text_indentation(text): 6 | """Print text with two new lines after each '.', '?', and ':'. 7 | 8 | Args: 9 | text (string): The text to print. 10 | Raises: 11 | TypeError: If text is not a string. 12 | """ 13 | if not isinstance(text, str): 14 | raise TypeError("text must be a string") 15 | 16 | c = 0 17 | while c < len(text) and text[c] == ' ': 18 | c += 1 19 | 20 | while c < len(text): 21 | print(text[c], end="") 22 | if text[c] == "\n" or text[c] in ".?:": 23 | if text[c] in ".?:": 24 | print("\n") 25 | c += 1 26 | while c < len(text) and text[c] == ' ': 27 | c += 1 28 | continue 29 | c += 1 30 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/6-max_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Module to find the max integer in a list 3 | """ 4 | 5 | 6 | def max_integer(list=[]): 7 | """Function to find and return the max integer in a list of integers 8 | If the list is empty, the function returns None 9 | """ 10 | if len(list) == 0: 11 | return None 12 | result = list[0] 13 | i = 1 14 | while i < len(list): 15 | if list[i] > result: 16 | result = list[i] 17 | i += 1 18 | return result 19 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/0-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | add_integer = __import__('0-add_integer').add_integer 3 | 4 | print(add_integer(1, 2)) 5 | print(add_integer(100, -2)) 6 | print(add_integer(2)) 7 | print(add_integer(100.3, -2)) 8 | try: 9 | print(add_integer(4, "School")) 10 | except Exception as e: 11 | print(e) 12 | try: 13 | print(add_integer(None)) 14 | except Exception as e: 15 | print(e) 16 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/100-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | matrix_mul = __import__('100-matrix_mul').matrix_mul 3 | 4 | print(matrix_mul([[1, 2], [3, 4]], [[1, 2], [3, 4]])) 5 | print(matrix_mul([[1, 2]], [[3, 4], [5, 6]])) 6 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/101-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | lazy_matrix_mul = __import__('101-lazy_matrix_mul').lazy_matrix_mul 3 | 4 | print(lazy_matrix_mul([[1, 2], [3, 4]], [[1, 2], [3, 4]])) 5 | print(lazy_matrix_mul([[1, 2]], [[3, 4], [5, 6]])) 6 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/2-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | matrix_divided = __import__('2-matrix_divided').matrix_divided 3 | 4 | matrix = [ 5 | [1, 2, 3], 6 | [4, 5, 6] 7 | ] 8 | print(matrix_divided(matrix, 3)) 9 | print(matrix) 10 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/3-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | say_my_name = __import__('3-say_my_name').say_my_name 3 | 4 | say_my_name("John", "Smith") 5 | say_my_name("Walter", "White") 6 | say_my_name("Bob") 7 | try: 8 | say_my_name(12, "White") 9 | except Exception as e: 10 | print(e) 11 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/3-say_my_name.txt: -------------------------------------------------------------------------------- 1 | 2 | =========================== 3 | How to Use 3-say_my_name.py 4 | =========================== 5 | 6 | This modules defines a function ``say_my_name(first_name, last_name="")``. 7 | 8 | Usage 9 | ===== 10 | 11 | ``say_my_name(...)`` prints "My name is ". 12 | 13 | :: 14 | 15 | >>> say_my_name = __import__('3-say_my_name').say_my_name 16 | >>> say_my_name("Brennan", "Baraban") 17 | My name is Brennan Baraban 18 | 19 | :: 20 | 21 | >>> say_my_name("Cornelius Maxwell", "Jones II") 22 | My name is Cornelius Maxwell Jones II 23 | 24 | The parameter ```last_name``` is optional. If no last name is provided, 25 | an empty string is printed instead. 26 | 27 | :: 28 | 29 | >>> say_my_name("Brennan") 30 | My name is Brennan 31 | 32 | Invalid Names 33 | ============= 34 | 35 | The parameters ``first_name`` and ``last_name``` must be strings. Otherwise, 36 | a TypeError is raised. 37 | 38 | :: 39 | 40 | >>> say_my_name(6, "James") 41 | Traceback (most recent call last): 42 | TypeError: first_name must be a string 43 | 44 | :: 45 | 46 | >>> say_my_name("LeBron", ["Cavs", "Lakers", "Heat"]) 47 | Traceback (most recent call last): 48 | TypeError: last_name must be a string 49 | 50 | :: 51 | 52 | >>> say_my_name({"LeBron": 6, "James": 23}, 7.7) 53 | Traceback (most recent call last): 54 | TypeError: first_name must be a string 55 | 56 | :: 57 | 58 | >>> say_my_name(None) 59 | Traceback (most recent call last): 60 | TypeError: first_name must be a string 61 | 62 | At least one name must be provided. 63 | 64 | :: 65 | 66 | >>> say_my_name() 67 | Traceback (most recent call last): 68 | TypeError: say_my_name() missing 1 required positional argument: 'first_name' 69 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/4-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | print_square = __import__('4-print_square').print_square 3 | 4 | print_square(4) 5 | print("") 6 | print_square(10) 7 | print("") 8 | print_square(0) 9 | print("") 10 | print_square(1) 11 | print("") 12 | try: 13 | print_square(-1) 14 | except Exception as e: 15 | print(e) 16 | print("") 17 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/4-print_square.txt: -------------------------------------------------------------------------------- 1 | 2 | ============================ 3 | How to Use 4-print_square.py 4 | ============================ 5 | 6 | This module defines a square-printing function ``print_square(size)``. 7 | 8 | Usage 9 | ===== 10 | 11 | Squares are printed using the ``#`` character. The parameter ``size`` 12 | represents the height and width of the square. 13 | 14 | :: 15 | 16 | >>> print_square = __import__('4-print_square').print_square 17 | >>> print_square(1) 18 | # 19 | 20 | :: 21 | 22 | >>> print_square(4) 23 | #### 24 | #### 25 | #### 26 | #### 27 | 28 | :: 29 | 30 | >>> print_square(10) 31 | ########## 32 | ########## 33 | ########## 34 | ########## 35 | ########## 36 | ########## 37 | ########## 38 | ########## 39 | ########## 40 | ########## 41 | 42 | If ``size`` is zero, the function prints nothing. 43 | 44 | :: 45 | 46 | >>> print_square(0) 47 | 48 | Invalid Sizes 49 | ============= 50 | 51 | The parameter ``size`` must be an integer. Otherwise, a TypeError is raised. 52 | 53 | :: 54 | 55 | >>> print_square("not an int") 56 | Traceback (most recent call last): 57 | TypeError: size must be an integer 58 | 59 | :: 60 | 61 | >>> print_square(5.5) 62 | Traceback (most recent call last): 63 | TypeError: size must be an integer 64 | 65 | :: 66 | 67 | >>> print_square(None) 68 | Traceback (most recent call last): 69 | TypeError: size must be an integer 70 | 71 | If ``size`` is less than zero, a ValueError is raised. 72 | 73 | :: 74 | 75 | >>> print_square(-7) 76 | Traceback (most recent call last): 77 | ValueError: size must be >= 0 78 | 79 | Note that type-checking occurs before value-checking. 80 | 81 | :: 82 | 83 | >>> print_square(-7.5) 84 | Traceback (most recent call last): 85 | TypeError: size must be an integer 86 | 87 | At least one argument must be provided. 88 | 89 | :: 90 | 91 | >>> print_square() 92 | Traceback (most recent call last): 93 | TypeError: print_square() missing 1 required positional argument: 'size' 94 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/5-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | text_indentation = __import__('5-text_indentation').text_indentation 3 | 4 | text_indentation("""Lorem ipsum dolor sit amet, consectetur adipiscing elit. \ 5 | Quonam modo? Utrum igitur tibi litteram videor an totas paginas commovere? \ 6 | Non autem hoc: igitur ne illud quidem. Fortasse id optimum, sed ubi illud: \ 7 | Plus semper voluptatis? Teneo, inquit, finem illi videri nihil dolere. \ 8 | Transfer idem ad modestiam vel temperantiam, quae est moderatio cupiditatum \ 9 | rationi oboediens. Si id dicis, vicimus. Inde sermone vario sex illa a Dipylo \ 10 | stadia confecimus. Sin aliud quid voles, postea. Quae animi affectio suum \ 11 | cuique tribuens atque hanc, quam dico. Utinam quidem dicerent alium alio \ 12 | beatiorem! Iam ruinas videres""") 13 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/6-max_integer_test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Unittests for max_integer([..]).""" 3 | 4 | import unittest 5 | max_integer = __import__('6-max_integer').max_integer 6 | 7 | 8 | class TestMaxInteger(unittest.TestCase): 9 | """Define unittests for max_integer([..]).""" 10 | 11 | def test_ordered_list(self): 12 | """Test an ordered list of integers.""" 13 | ordered = [1, 2, 3, 4] 14 | self.assertEqual(max_integer(ordered), 4) 15 | 16 | def test_unordered_list(self): 17 | """Test an unordered list of integers.""" 18 | unordered = [1, 2, 4, 3] 19 | self.assertEqual(max_integer(unordered), 4) 20 | 21 | def test_max_at_begginning(self): 22 | """Test a list with a beginning max value.""" 23 | max_at_beginning = [4, 3, 2, 1] 24 | self.assertEqual(max_integer(max_at_beginning), 4) 25 | 26 | def test_empty_list(self): 27 | """Test an empty list.""" 28 | empty = [] 29 | self.assertEqual(max_integer(empty), None) 30 | 31 | def test_one_element_list(self): 32 | """Test a list with a single element.""" 33 | one_element = [7] 34 | self.assertEqual(max_integer(one_element), 7) 35 | 36 | def test_floats(self): 37 | """Test a list of floats.""" 38 | floats = [1.53, 6.33, -9.123, 15.2, 6.0] 39 | self.assertEqual(max_integer(floats), 15.2) 40 | 41 | def test_ints_and_floats(self): 42 | """Test a list of ints and floats.""" 43 | ints_and_floats = [1.53, 15.5, -9, 15, 6] 44 | self.assertEqual(max_integer(ints_and_floats), 15.5) 45 | 46 | def test_string(self): 47 | """Test a string.""" 48 | string = "Brennan" 49 | self.assertEqual(max_integer(string), 'r') 50 | 51 | def test_list_of_strings(self): 52 | """Test a list of strings.""" 53 | strings = ["Brennan", "is", "my", "name"] 54 | self.assertEqual(max_integer(strings), "name") 55 | 56 | def test_empty_string(self): 57 | """Test an empty string.""" 58 | self.assertEqual(max_integer(""), None) 59 | 60 | if __name__ == '__main__': 61 | unittest.main() 62 | -------------------------------------------------------------------------------- /0x08-python-more_classes/0-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a Rectangle class.""" 3 | 4 | 5 | class Rectangle: 6 | """Represent a rectangle.""" 7 | pass 8 | -------------------------------------------------------------------------------- /0x08-python-more_classes/1-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a Rectangle class.""" 3 | 4 | 5 | class Rectangle: 6 | """Represent a rectangle.""" 7 | 8 | def __init__(self, width=0, height=0): 9 | """Initialize a new Rectangle. 10 | 11 | Args: 12 | width (int): The width of the new rectangle. 13 | height (int): The height of the new rectangle. 14 | """ 15 | self.width = width 16 | self.height = height 17 | 18 | @property 19 | def width(self): 20 | """Get/set the width of the rectangle.""" 21 | return self.__width 22 | 23 | @width.setter 24 | def width(self, value): 25 | if not isinstance(value, int): 26 | raise TypeError("width must be an integer") 27 | if value < 0: 28 | raise ValueError("width must be >= 0") 29 | self.__width = value 30 | 31 | @property 32 | def height(self): 33 | """Get/set the height of the rectangle.""" 34 | return self.__height 35 | 36 | @height.setter 37 | def height(self, value): 38 | if not isinstance(value, int): 39 | raise TypeError("height must be an integer") 40 | if value < 0: 41 | raise ValueError("height must be >= 0") 42 | self.__height = value 43 | -------------------------------------------------------------------------------- /0x08-python-more_classes/2-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a Rectangle class.""" 3 | 4 | 5 | class Rectangle: 6 | """Represent a rectangle.""" 7 | 8 | def __init__(self, width=0, height=0): 9 | """Initialize a new Rectangle. 10 | 11 | Args: 12 | width (int): The width of the new rectangle. 13 | height (int): The height of the new rectangle. 14 | """ 15 | self.width = width 16 | self.height = height 17 | 18 | @property 19 | def width(self): 20 | """Get/set the width of the Rectangle.""" 21 | return self.__width 22 | 23 | @width.setter 24 | def width(self, value): 25 | if not isinstance(value, int): 26 | raise TypeError("width must be an integer") 27 | if value < 0: 28 | raise ValueError("width must be >= 0") 29 | self.__width = value 30 | 31 | @property 32 | def height(self): 33 | """Get/set the height of the Rectangle.""" 34 | return self.__height 35 | 36 | @height.setter 37 | def height(self, value): 38 | if not isinstance(value, int): 39 | raise TypeError("height must be an integer") 40 | if value < 0: 41 | raise ValueError("height must be >= 0") 42 | self.__height = value 43 | 44 | def area(self): 45 | """Return the area of the Rectangle.""" 46 | return (self.__width * self.__height) 47 | 48 | def perimeter(self): 49 | """Return the perimeter of the Rectangle.""" 50 | if self.__width == 0 or self.__height == 0: 51 | return (0) 52 | return ((self.__width * 2) + (self.__height * 2)) 53 | -------------------------------------------------------------------------------- /0x08-python-more_classes/3-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a Rectangle class.""" 3 | 4 | 5 | class Rectangle: 6 | """Represent a rectangle.""" 7 | 8 | def __init__(self, width=0, height=0): 9 | """Initialize a new Rectangle. 10 | 11 | Args: 12 | width (int): The width of the new rectangle. 13 | height (int): The height of the new rectangle. 14 | """ 15 | self.width = width 16 | self.height = height 17 | 18 | @property 19 | def width(self): 20 | """Get/set the width of the Rectangle.""" 21 | return self.__width 22 | 23 | @width.setter 24 | def width(self, value): 25 | if not isinstance(value, int): 26 | raise TypeError("width must be an integer") 27 | if value < 0: 28 | raise ValueError("width must be >= 0") 29 | self.__width = value 30 | 31 | @property 32 | def height(self): 33 | """Get/set the height of the Rectangle.""" 34 | return self.__height 35 | 36 | @height.setter 37 | def height(self, value): 38 | if not isinstance(value, int): 39 | raise TypeError("height must be an integer") 40 | if value < 0: 41 | raise ValueError("height must be >= 0") 42 | self.__height = value 43 | 44 | def area(self): 45 | """Return the area of the Rectangle.""" 46 | return (self.__width * self.__height) 47 | 48 | def perimeter(self): 49 | """Return the perimeter of the Rectangle.""" 50 | if self.__width == 0 or self.__height == 0: 51 | return (0) 52 | return ((self.__width * 2) + (self.__height * 2)) 53 | 54 | def __str__(self): 55 | """Return the printable representation of the Rectangle. 56 | 57 | Represents the rectangle with the # character. 58 | """ 59 | if self.__width == 0 or self.__height == 0: 60 | return ("") 61 | 62 | rect = [] 63 | for i in range(self.__height): 64 | [rect.append('#') for j in range(self.__width)] 65 | if i != self.__height - 1: 66 | rect.append("\n") 67 | return ("".join(rect)) 68 | -------------------------------------------------------------------------------- /0x08-python-more_classes/4-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a Rectangle class.""" 3 | 4 | 5 | class Rectangle: 6 | """Represent a rectangle.""" 7 | 8 | def __init__(self, width=0, height=0): 9 | """Initialize a new Rectangle. 10 | 11 | Args: 12 | width (int): The width of the new rectangle. 13 | height (int): The height of the new rectangle. 14 | """ 15 | self.width = width 16 | self.height = height 17 | 18 | @property 19 | def width(self): 20 | """Get/set the width of the Rectangle.""" 21 | return self.__width 22 | 23 | @width.setter 24 | def width(self, value): 25 | if not isinstance(value, int): 26 | raise TypeError("width must be an integer") 27 | if value < 0: 28 | raise ValueError("width must be >= 0") 29 | self.__width = value 30 | 31 | @property 32 | def height(self): 33 | """Get/set the height of the Rectangle.""" 34 | return self.__height 35 | 36 | @height.setter 37 | def height(self, value): 38 | if not isinstance(value, int): 39 | raise TypeError("height must be an integer") 40 | if value < 0: 41 | raise ValueError("height must be >= 0") 42 | self.__height = value 43 | 44 | def area(self): 45 | """Return the area of the Rectangle.""" 46 | return (self.__width * self.__height) 47 | 48 | def perimeter(self): 49 | """Return the perimeter of the Rectangle.""" 50 | if self.__width == 0 or self.__height == 0: 51 | return (0) 52 | return ((self.__width * 2) + (self.__height * 2)) 53 | 54 | def __str__(self): 55 | """Return the printable representation of the Rectangle. 56 | 57 | Represents the rectangle with the # character. 58 | """ 59 | if self.__width == 0 or self.__height == 0: 60 | return ("") 61 | 62 | rect = [] 63 | for i in range(self.__height): 64 | [rect.append('#') for j in range(self.__width)] 65 | if i != self.__height - 1: 66 | rect.append("\n") 67 | return ("".join(rect)) 68 | 69 | def __repr__(self): 70 | """Return the string representation of the Rectangle.""" 71 | rect = "Rectangle(" + str(self.__width) 72 | rect += ", " + str(self.__height) + ")" 73 | return (rect) 74 | -------------------------------------------------------------------------------- /0x08-python-more_classes/5-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a Rectangle class.""" 3 | 4 | 5 | class Rectangle: 6 | """Represent a rectangle.""" 7 | 8 | def __init__(self, width=0, height=0): 9 | """Initialize a new Rectangle. 10 | 11 | Args: 12 | width (int): The width of the new rectangle. 13 | height (int): The height of the new rectangle. 14 | """ 15 | self.width = width 16 | self.height = height 17 | 18 | @property 19 | def width(self): 20 | """Get/set the width of the Rectangle.""" 21 | return self.__width 22 | 23 | @width.setter 24 | def width(self, value): 25 | if not isinstance(value, int): 26 | raise TypeError("width must be an integer") 27 | if value < 0: 28 | raise ValueError("width must be >= 0") 29 | self.__width = value 30 | 31 | @property 32 | def height(self): 33 | """Get/set the height of the Rectangle.""" 34 | return self.__height 35 | 36 | @height.setter 37 | def height(self, value): 38 | if not isinstance(value, int): 39 | raise TypeError("height must be an integer") 40 | if value < 0: 41 | raise ValueError("height must be >= 0") 42 | self.__height = value 43 | 44 | def area(self): 45 | """Return the area of the Rectangle.""" 46 | return (self.__width * self.__height) 47 | 48 | def perimeter(self): 49 | """Return the perimeter of the Rectangle.""" 50 | if self.__width == 0 or self.__height == 0: 51 | return (0) 52 | return ((self.__width * 2) + (self.__height * 2)) 53 | 54 | def __str__(self): 55 | """Return the printable representation of the Rectangle. 56 | 57 | Represents the rectangle with the # character. 58 | """ 59 | if self.__width == 0 or self.__height == 0: 60 | return ("") 61 | 62 | rect = [] 63 | for i in range(self.__height): 64 | [rect.append('#') for j in range(self.__width)] 65 | if i != self.__height - 1: 66 | rect.append("\n") 67 | return ("".join(rect)) 68 | 69 | def __repr__(self): 70 | """Return the string representation of the Rectangle.""" 71 | rect = "Rectangle(" + str(self.__width) 72 | rect += ", " + str(self.__height) + ")" 73 | return (rect) 74 | 75 | def __del__(self): 76 | """Print a message for every deletion of a Rectangle.""" 77 | print("Bye rectangle...") 78 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/0-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('0-rectangle').Rectangle 3 | 4 | my_rectangle = Rectangle() 5 | print(type(my_rectangle)) 6 | print(my_rectangle.__dict__) 7 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/1-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('1-rectangle').Rectangle 3 | 4 | my_rectangle = Rectangle(2, 4) 5 | print(my_rectangle.__dict__) 6 | 7 | my_rectangle.width = 10 8 | my_rectangle.height = 3 9 | print(my_rectangle.__dict__) 10 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/2-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('2-rectangle').Rectangle 3 | 4 | my_rectangle = Rectangle(2, 4) 5 | print("Area: {} - Perimeter: {}".format(my_rectangle.area(), my_rectangle.perimeter())) 6 | 7 | print("--") 8 | 9 | my_rectangle.width = 10 10 | my_rectangle.height = 3 11 | print("Area: {} - Perimeter: {}".format(my_rectangle.area(), my_rectangle.perimeter())) 12 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/3-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('3-rectangle').Rectangle 3 | 4 | my_rectangle = Rectangle(2, 4) 5 | print("Area: {} - Perimeter: {}".format(my_rectangle.area(), my_rectangle.perimeter())) 6 | 7 | print(str(my_rectangle)) 8 | print(repr(my_rectangle)) 9 | 10 | print("--") 11 | 12 | my_rectangle.width = 10 13 | my_rectangle.height = 3 14 | print(my_rectangle) 15 | print(repr(my_rectangle)) 16 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/4-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('4-rectangle').Rectangle 3 | 4 | my_rectangle = Rectangle(2, 4) 5 | print(str(my_rectangle)) 6 | print("--") 7 | print(my_rectangle) 8 | print("--") 9 | print(repr(my_rectangle)) 10 | print("--") 11 | print(hex(id(my_rectangle))) 12 | print("--") 13 | 14 | # create new instance based on representation 15 | new_rectangle = eval(repr(my_rectangle)) 16 | print(str(new_rectangle)) 17 | print("--") 18 | print(new_rectangle) 19 | print("--") 20 | print(repr(new_rectangle)) 21 | print("--") 22 | print(hex(id(new_rectangle))) 23 | print("--") 24 | 25 | print(new_rectangle is my_rectangle) 26 | print(type(new_rectangle) is type(my_rectangle)) 27 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/5-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('5-rectangle').Rectangle 3 | 4 | my_rectangle = Rectangle(2, 4) 5 | print("Area: {} - Perimeter: {}".format(my_rectangle.area(), my_rectangle.perimeter())) 6 | 7 | del my_rectangle 8 | 9 | try: 10 | print(my_rectangle) 11 | except Exception as e: 12 | print("[{}] {}".format(e.__class__.__name__, e)) 13 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/6-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('6-rectangle').Rectangle 3 | 4 | my_rectangle_1 = Rectangle(2, 4) 5 | my_rectangle_2 = Rectangle(2, 4) 6 | print("{:d} instances of Rectangle".format(Rectangle.number_of_instances)) 7 | del my_rectangle_1 8 | print("{:d} instances of Rectangle".format(Rectangle.number_of_instances)) 9 | del my_rectangle_2 10 | print("{:d} instances of Rectangle".format(Rectangle.number_of_instances)) 11 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/7-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('7-rectangle').Rectangle 3 | 4 | my_rectangle_1 = Rectangle(8, 4) 5 | print(my_rectangle_1) 6 | print("--") 7 | my_rectangle_1.print_symbol = "&" 8 | print(my_rectangle_1) 9 | print("--") 10 | 11 | my_rectangle_2 = Rectangle(2, 1) 12 | print(my_rectangle_2) 13 | print("--") 14 | Rectangle.print_symbol = "C" 15 | print(my_rectangle_2) 16 | print("--") 17 | 18 | my_rectangle_3 = Rectangle(7, 3) 19 | print(my_rectangle_3) 20 | 21 | print("--") 22 | 23 | my_rectangle_3.print_symbol = ["C", "is", "fun!"] 24 | print(my_rectangle_3) 25 | 26 | print("--") 27 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/8-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('8-rectangle').Rectangle 3 | 4 | my_rectangle_1 = Rectangle(8, 4) 5 | my_rectangle_2 = Rectangle(2, 3) 6 | 7 | if my_rectangle_1 is Rectangle.bigger_or_equal(my_rectangle_1, my_rectangle_2): 8 | print("my_rectangle_1 is bigger or equal to my_rectangle_2") 9 | else: 10 | print("my_rectangle_2 is bigger than my_rectangle_1") 11 | 12 | 13 | my_rectangle_2.width = 10 14 | my_rectangle_2.height = 5 15 | if my_rectangle_1 is Rectangle.bigger_or_equal(my_rectangle_1, my_rectangle_2): 16 | print("my_rectangle_1 is bigger or equal to my_rectangle_2") 17 | else: 18 | print("my_rectangle_2 is bigger than my_rectangle_1") 19 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/9-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('9-rectangle').Rectangle 3 | 4 | my_square = Rectangle.square(5) 5 | print("Area: {} - Perimeter: {}".format(my_square.area(), my_square.perimeter())) 6 | print(my_square) 7 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/0-answer.txt: -------------------------------------------------------------------------------- 1 | type 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/1-answer.txt: -------------------------------------------------------------------------------- 1 | id 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/10-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/100-magic_string.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def magic_string(): 3 | magic_string.n = getattr(magic_string, 'n', 0) + 1 4 | return ("BestSchool, " * (magic_string.n - 1) + "BestSchool") 5 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/101-locked_class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a locked class.""" 3 | 4 | 5 | class LockedClass: 6 | """ 7 | Prevent the user from instantiating new LockedClass attributes 8 | for anything but attributes called 'first_name'. 9 | """ 10 | 11 | __slots__ = ["first_name"] 12 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/103-line1.txt: -------------------------------------------------------------------------------- 1 | 0 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/103-line2.txt: -------------------------------------------------------------------------------- 1 | 0 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/104-line1.txt: -------------------------------------------------------------------------------- 1 | 1 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/104-line2.txt: -------------------------------------------------------------------------------- 1 | 1 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/104-line3.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/104-line4.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/104-line5.txt: -------------------------------------------------------------------------------- 1 | 1 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/105-line1.txt: -------------------------------------------------------------------------------- 1 | 262 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/106-line1.txt: -------------------------------------------------------------------------------- 1 | 1 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/106-line2.txt: -------------------------------------------------------------------------------- 1 | 0 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/106-line3.txt: -------------------------------------------------------------------------------- 1 | No 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/106-line4.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/106-line5.txt: -------------------------------------------------------------------------------- 1 | 1 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/11-answer.txt: -------------------------------------------------------------------------------- 1 | False 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/12-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/13-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/14-answer.txt: -------------------------------------------------------------------------------- 1 | [1, 2, 3, 4] 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/15-answer.txt: -------------------------------------------------------------------------------- 1 | [1, 2, 3] 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/16-answer.txt: -------------------------------------------------------------------------------- 1 | 1 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/17-answer.txt: -------------------------------------------------------------------------------- 1 | [1, 2, 3, 4] 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/18-answer.txt: -------------------------------------------------------------------------------- 1 | [1, 2, 3] 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/19-copy_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def copy_list(a): 3 | return a.copy() 4 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/2-answer.txt: -------------------------------------------------------------------------------- 1 | No 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/20-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/21-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/22-answer.txt: -------------------------------------------------------------------------------- 1 | No 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/23-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/24-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/25-answer.txt: -------------------------------------------------------------------------------- 1 | False 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/26-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/27-answer.txt: -------------------------------------------------------------------------------- 1 | No 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/28-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/3-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/4-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/5-answer.txt: -------------------------------------------------------------------------------- 1 | No 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/6-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/7-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/8-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/9-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/tests/100-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | magic_string = __import__('100-magic_string').magic_string 3 | 4 | for i in range(10): 5 | print(magic_string()) 6 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/tests/101-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | LockedClass = __import__('101-locked_class').LockedClass 3 | 4 | lc = LockedClass() 5 | lc.first_name = "John" 6 | try: 7 | lc.last_name = "Snow" 8 | except Exception as e: 9 | print("[{}] {}".format(e.__class__.__name__, e)) 10 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/tests/19-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | copy_list = __import__('19-copy_list').copy_list 3 | 4 | my_list = [1, 2, 3] 5 | print(my_list) 6 | 7 | new_list = copy_list(my_list) 8 | 9 | print(my_list) 10 | print(new_list) 11 | 12 | print(new_list == my_list) 13 | print(new_list is my_list) 14 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/0-lookup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines an object attribute lookup function.""" 3 | 4 | 5 | def lookup(obj): 6 | """Return a list of an object's available attributes.""" 7 | return (dir(obj)) 8 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/1-my_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines an inherited list class MyList.""" 3 | 4 | 5 | class MyList(list): 6 | """Implements sorted printing for the built-in list class.""" 7 | 8 | def print_sorted(self): 9 | """Print a list in sorted ascending order.""" 10 | print(sorted(self)) 11 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/10-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a Rectangle subclass Square.""" 3 | Rectangle = __import__('9-rectangle').Rectangle 4 | 5 | 6 | class Square(Rectangle): 7 | """Represent a square.""" 8 | 9 | def __init__(self, size): 10 | """Initialize a new square. 11 | 12 | Args: 13 | size (int): The size of the new square. 14 | """ 15 | self.integer_validator("size", size) 16 | super().__init__(size, size) 17 | self.__size = size 18 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/100-my_int.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a class MyInt that inherits from int.""" 3 | 4 | 5 | class MyInt(int): 6 | """Invert int operators == and !=.""" 7 | 8 | def __eq__(self, value): 9 | """Override == opeartor with != behavior.""" 10 | return self.real != value 11 | 12 | def __ne__(self, value): 13 | """Override != operator with == behavior.""" 14 | return self.real == value 15 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/101-add_attribute.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a function that adds attributes to objects.""" 3 | 4 | 5 | def add_attribute(obj, att, value): 6 | """Add a new attribute to an object if possible. 7 | 8 | Args: 9 | obj (any): The object to add an attribute to. 10 | att (str): The name of the attribute to add to obj. 11 | value (any): The value of att. 12 | Raises: 13 | TypeError: If the attribute cannot be added. 14 | """ 15 | if not hasattr(obj, "__dict__"): 16 | raise TypeError("can't add new attribute") 17 | setattr(obj, att, value) 18 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/11-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a Rectangle subclass Square.""" 3 | Rectangle = __import__('9-rectangle').Rectangle 4 | 5 | 6 | class Square(Rectangle): 7 | """Represent a square.""" 8 | 9 | def __init__(self, size): 10 | """Initialize a new square. 11 | 12 | Args: 13 | size (int): The size of the new square. 14 | """ 15 | self.integer_validator("size", size) 16 | super().__init__(size, size) 17 | self.__size = size 18 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/2-is_same_class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a class-checking function.""" 3 | 4 | 5 | def is_same_class(obj, a_class): 6 | """Check if an object is exactly an instance of a given class. 7 | 8 | Args: 9 | obj (any): The object to check. 10 | a_class (type): The class to match the type of obj to. 11 | Returns: 12 | If obj is exactly an instance of a_class - True. 13 | Otherwise - False. 14 | """ 15 | if type(obj) == a_class: 16 | return True 17 | return False 18 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/3-is_kind_of_class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a class and inherited class-checking function.""" 3 | 4 | 5 | def is_kind_of_class(obj, a_class): 6 | """Check if an object is an instance or inherited instance of a class. 7 | 8 | Args: 9 | obj (any): The object to check. 10 | a_class (type): The class to match the type of obj to. 11 | Returns: 12 | If obj is an instance or inherited instance of a_class - True. 13 | Otherwise - False. 14 | """ 15 | if isinstance(obj, a_class): 16 | return True 17 | return False 18 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/4-inherits_from.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines an inherited class-checking function.""" 3 | 4 | 5 | def inherits_from(obj, a_class): 6 | """Checks if an object is an inherited instance of a class. 7 | 8 | Args: 9 | obj (any): The object to check. 10 | a_class (type): The class to match the type of obj to. 11 | Returns: 12 | If obj is an inherited instance of a_class - True. 13 | Otherwise - False. 14 | """ 15 | if issubclass(type(obj), a_class) and type(obj) != a_class: 16 | return True 17 | return False 18 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/5-base_geometry.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines an empty class BaseGeometry.""" 3 | 4 | 5 | class BaseGeometry: 6 | """Represent base geometry.""" 7 | pass 8 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/6-base_geometry.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a base geometry class BaseGeometry.""" 3 | 4 | 5 | class BaseGeometry: 6 | """Represent base geometry.""" 7 | 8 | def area(self): 9 | """Not implemented.""" 10 | raise Exception("area() is not implemented") 11 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/7-base_geometry.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a base geometry class BaseGeometry.""" 3 | 4 | 5 | class BaseGeometry: 6 | """Reprsent base geometry.""" 7 | 8 | def area(self): 9 | """Not yet implemented.""" 10 | raise Exception("area() is not implemented") 11 | 12 | def integer_validator(self, name, value): 13 | """Validate a parameter as an integer. 14 | 15 | Args: 16 | name (str): The name of the parameter. 17 | value (int): The parameter to validate. 18 | Raises: 19 | TypeError: If value is not an integer. 20 | ValueError: If value is <= 0. 21 | """ 22 | if type(value) != int: 23 | raise TypeError("{} must be an integer".format(name)) 24 | if value <= 0: 25 | raise ValueError("{} must be greater than 0".format(name)) 26 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/8-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a class Rectangle that inherits from BaseGeometry.""" 3 | BaseGeometry = __import__('7-base_geometry').BaseGeometry 4 | 5 | 6 | class Rectangle(BaseGeometry): 7 | """Represent a rectangle using BaseGeometry.""" 8 | 9 | def __init__(self, width, height): 10 | """Intialize a new Rectangle. 11 | 12 | Args: 13 | width (int): The width of the new Rectangle. 14 | height (int): The height of the new Rectangle. 15 | """ 16 | self.integer_validator("width", width) 17 | self.__width = width 18 | self.integer_validator("height", height) 19 | self.__height = height 20 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/9-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a class Rectangle that inherits from BaseGeometry.""" 3 | BaseGeometry = __import__('7-base_geometry').BaseGeometry 4 | 5 | 6 | class Rectangle(BaseGeometry): 7 | """Represent a rectangle using BaseGeometry.""" 8 | 9 | def __init__(self, width, height): 10 | """Intialize a new Rectangle. 11 | 12 | Args: 13 | width (int): The width of the new Rectangle. 14 | height (int): The height of the new Rectangle. 15 | """ 16 | super().integer_validator("width", width) 17 | self.__width = width 18 | super().integer_validator("height", height) 19 | self.__height = height 20 | 21 | def area(self): 22 | """Return the area of the rectangle.""" 23 | return self.__width * self.__height 24 | 25 | def __str__(self): 26 | """Return the print() and str() representation of a Rectangle.""" 27 | string = "[" + str(self.__class__.__name__) + "] " 28 | string += str(self.__width) + "/" + str(self.__height) 29 | return string 30 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/0-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | lookup = __import__('0-lookup').lookup 3 | 4 | class MyClass1(object): 5 | pass 6 | 7 | class MyClass2(object): 8 | my_attr1 = 3 9 | def my_meth(self): 10 | pass 11 | 12 | print(lookup(MyClass1)) 13 | print(lookup(MyClass2)) 14 | print(lookup(int)) 15 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/1-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | MyList = __import__('1-my_list').MyList 3 | 4 | my_list = MyList() 5 | my_list.append(1) 6 | my_list.append(4) 7 | my_list.append(2) 8 | my_list.append(3) 9 | my_list.append(5) 10 | print(my_list) 11 | my_list.print_sorted() 12 | print(my_list) 13 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/1-my_list.txt: -------------------------------------------------------------------------------- 1 | Test for 1-my_list.py 2 | ------------------------------------------- 3 | 4 | case 0: import 5 | >>> MyList = __import__('1-my_list').MyList 6 | >>> 7 | ------------------------------------------- 8 | 9 | case 1: common case 10 | 11 | >>> my_list = MyList() 12 | >>> my_list.append(1) 13 | >>> my_list.append(4) 14 | >>> my_list.append(2) 15 | >>> my_list.append(3) 16 | >>> my_list.append(5) 17 | >>> print(my_list) 18 | [1, 4, 2, 3, 5] 19 | >>> my_list.print_sorted() 20 | [1, 2, 3, 4, 5] 21 | >>> print(my_list) 22 | [1, 4, 2, 3, 5] 23 | >>> 24 | 25 | ------------------------------------------- 26 | 27 | case 2: not defined object 28 | 29 | >>> MyList = __import__('1-my_list').MyList 30 | >>> my_list2.print_sorted() 31 | Traceback (most recent call last): 32 | File "", line 1, in 33 | NameError: name 'my_list2' is not defined 34 | >>> 35 | 36 | ------------------------------------------- 37 | 38 | case 3: passed a list 39 | 40 | >>> a = [1, 9, 4] 41 | >>> my_list = MyList(a) 42 | >>> my_list.print_sorted() 43 | [1, 4, 9] 44 | >>> 45 | 46 | ------------------------------------------- 47 | 48 | case 4: empty list 49 | 50 | >>> a = [] 51 | >>> my_list = MyList(a) 52 | >>> my_list.print_sorted() 53 | [] 54 | >>> 55 | 56 | ------------------------------------------- 57 | 58 | case 5: unique number 59 | 60 | >>> my_list = MyList() 61 | >>> my_list.append(1) 62 | >>> my_list.print_sorted() 63 | [1] 64 | >>> print(my_list) 65 | [1] 66 | >>> 67 | 68 | ------------------------------------------- 69 | 70 | case 6: same number 71 | 72 | >>> my_list2 = MyList() 73 | >>> my_list2.append(1) 74 | >>> my_list2.append(1) 75 | >>> my_list2.append(1) 76 | >>> my_list2.append(1) 77 | >>> my_list2.print_sorted() 78 | [1, 1, 1, 1] 79 | >>> 80 | 81 | ------------------------------------------- 82 | 83 | case 7: parent object 84 | >>> my_list = [1, 2, 3] 85 | >>> my_list.print_sorted() 86 | Traceback (most recent call last): 87 | File "", line 1, in 88 | AttributeError: 'list' object has no attribute 'print_sorted' 89 | >>> 90 | 91 | ------------------------------------------- 92 | 93 | case 8: negative numbers 94 | 95 | >>> MyList = __import__('1-my_list').MyList 96 | >>> my_list = MyList() 97 | >>> my_list.append(5) 98 | >>> my_list.append(1) 99 | >>> my_list.append(-1) 100 | >>> my_list.append(51) 101 | >>> my_list.append(-5) 102 | >>> my_list.print_sorted() 103 | [-5, -1, 1, 5, 51] 104 | >>> 105 | 106 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/10-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Square = __import__('10-square').Square 3 | 4 | s = Square(13) 5 | 6 | print(s) 7 | print(s.area()) 8 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/100-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | MyInt = __import__('100-my_int').MyInt 3 | 4 | my_i = MyInt(3) 5 | print(my_i) 6 | print(my_i == 3) 7 | print(my_i != 3) 8 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/101-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | add_attribute = __import__('101-add_attribute').add_attribute 3 | 4 | class MyClass(): 5 | pass 6 | 7 | mc = MyClass() 8 | add_attribute(mc, "name", "John") 9 | print(mc.name) 10 | 11 | try: 12 | a = "My String" 13 | add_attribute(a, "name", "Bob") 14 | print(a.name) 15 | except Exception as e: 16 | print("[{}] {}".format(e.__class__.__name__, e)) 17 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/11-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Square = __import__('11-square').Square 3 | 4 | s = Square(13) 5 | 6 | print(s) 7 | print(s.area()) 8 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/2-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | is_same_class = __import__('2-is_same_class').is_same_class 3 | 4 | a = 1 5 | if is_same_class(a, int): 6 | print("{} is an instance of the class {}".format(a, int.__name__)) 7 | if is_same_class(a, float): 8 | print("{} is an instance of the class {}".format(a, float.__name__)) 9 | if is_same_class(a, object): 10 | print("{} is an instance of the class {}".format(a, object.__name__)) 11 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/3-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | is_kind_of_class = __import__('3-is_kind_of_class').is_kind_of_class 3 | 4 | a = 1 5 | if is_kind_of_class(a, int): 6 | print("{} comes from {}".format(a, int.__name__)) 7 | if is_kind_of_class(a, float): 8 | print("{} comes from {}".format(a, float.__name__)) 9 | if is_kind_of_class(a, object): 10 | print("{} comes from {}".format(a, object.__name__)) 11 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/4-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | inherits_from = __import__('4-inherits_from').inherits_from 3 | 4 | a = True 5 | if inherits_from(a, int): 6 | print("{} inherited from class {}".format(a, int.__name__)) 7 | if inherits_from(a, bool): 8 | print("{} inherited from class {}".format(a, bool.__name__)) 9 | if inherits_from(a, object): 10 | print("{} inherited from class {}".format(a, object.__name__)) 11 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/5-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | BaseGeometry = __import__('5-base_geometry').BaseGeometry 3 | 4 | bg = BaseGeometry() 5 | 6 | print(bg) 7 | print(dir(bg)) 8 | print(dir(BaseGeometry)) 9 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/6-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | BaseGeometry = __import__('6-base_geometry').BaseGeometry 3 | 4 | bg = BaseGeometry() 5 | 6 | try: 7 | print(bg.area()) 8 | except Exception as e: 9 | print("[{}] {}".format(e.__class__.__name__, e)) 10 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/7-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | BaseGeometry = __import__('7-base_geometry').BaseGeometry 3 | 4 | bg = BaseGeometry() 5 | 6 | bg.integer_validator("my_int", 12) 7 | bg.integer_validator("width", 89) 8 | 9 | try: 10 | bg.integer_validator("name", "John") 11 | except Exception as e: 12 | print("[{}] {}".format(e.__class__.__name__, e)) 13 | 14 | try: 15 | bg.integer_validator("age", 0) 16 | except Exception as e: 17 | print("[{}] {}".format(e.__class__.__name__, e)) 18 | 19 | try: 20 | bg.integer_validator("distance", -4) 21 | except Exception as e: 22 | print("[{}] {}".format(e.__class__.__name__, e)) 23 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/8-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('8-rectangle').Rectangle 3 | 4 | r = Rectangle(3, 5) 5 | 6 | print(r) 7 | print(dir(r)) 8 | 9 | try: 10 | print("Rectangle: {} - {}".format(r.width, r.height)) 11 | except Exception as e: 12 | print("[{}] {}".format(e.__class__.__name__, e)) 13 | 14 | try: 15 | r2 = Rectangle(4, True) 16 | except Exception as e: 17 | print("[{}] {}".format(e.__class__.__name__, e)) 18 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/9-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('9-rectangle').Rectangle 3 | 4 | r = Rectangle(3, 5) 5 | 6 | print(r) 7 | print(r.area()) 8 | -------------------------------------------------------------------------------- /0x0B-python-input_output/0-read_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a text file-reading function.""" 3 | 4 | 5 | def read_file(filename=""): 6 | """Print the contents of a UTF8 text file to stdout.""" 7 | with open(filename, encoding="utf-8") as f: 8 | print(f.read(), end="") 9 | -------------------------------------------------------------------------------- /0x0B-python-input_output/1-write_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a file-writing function.""" 3 | 4 | 5 | def write_file(filename="", text=""): 6 | """Write a string to a UTF8 text file. 7 | 8 | Args: 9 | filename (str): The name of the file to write. 10 | text (str): The text to write to the file. 11 | Returns: 12 | The number of characters written. 13 | """ 14 | with open(filename, "w", encoding="utf-8") as f: 15 | return f.write(text) 16 | -------------------------------------------------------------------------------- /0x0B-python-input_output/10-student.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a class Student.""" 3 | 4 | 5 | class Student: 6 | """Represent a student.""" 7 | 8 | def __init__(self, first_name, last_name, age): 9 | """Initialize a new Student. 10 | 11 | Args: 12 | first_name (str): The first name of the student. 13 | last_name (str): The last name of the student. 14 | age (int): The age of the student. 15 | """ 16 | self.first_name = first_name 17 | self.last_name = last_name 18 | self.age = age 19 | 20 | def to_json(self, attrs=None): 21 | """Get a dictionary representation of the Student. 22 | 23 | If attrs is a list of strings, represents only those attributes 24 | included in the list. 25 | 26 | Args: 27 | attrs (list): (Optional) The attributes to represent. 28 | """ 29 | if (type(attrs) == list and 30 | all(type(ele) == str for ele in attrs)): 31 | return {k: getattr(self, k) for k in attrs if hasattr(self, k)} 32 | return self.__dict__ 33 | -------------------------------------------------------------------------------- /0x0B-python-input_output/100-append_after.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a text file insertion function.""" 3 | 4 | 5 | def append_after(filename="", search_string="", new_string=""): 6 | """Insert text after each line containing a given string in a file. 7 | 8 | Args: 9 | filename (str): The name of the file. 10 | search_string (str): The string to search for within the file. 11 | new_string (str): The string to insert. 12 | """ 13 | text = "" 14 | with open(filename) as r: 15 | for line in r: 16 | text += line 17 | if search_string in line: 18 | text += new_string 19 | with open(filename, "w") as w: 20 | w.write(text) 21 | -------------------------------------------------------------------------------- /0x0B-python-input_output/101-stats.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Reads from standard input and computes metrics. 3 | 4 | After every ten lines or the input of a keyboard interruption (CTRL + C), 5 | prints the following statistics: 6 | - Total file size up to that point. 7 | - Count of read status codes up to that point. 8 | """ 9 | 10 | 11 | def print_stats(size, status_codes): 12 | """Print accumulated metrics. 13 | 14 | Args: 15 | size (int): The accumulated read file size. 16 | status_codes (dict): The accumulated count of status codes. 17 | """ 18 | print("File size: {}".format(size)) 19 | for key in sorted(status_codes): 20 | print("{}: {}".format(key, status_codes[key])) 21 | 22 | 23 | if __name__ == "__main__": 24 | import sys 25 | 26 | size = 0 27 | status_codes = {} 28 | valid_codes = ['200', '301', '400', '401', '403', '404', '405', '500'] 29 | count = 0 30 | 31 | try: 32 | for line in sys.stdin: 33 | if count == 10: 34 | print_stats(size, status_codes) 35 | count = 1 36 | else: 37 | count += 1 38 | 39 | line = line.split() 40 | 41 | try: 42 | size += int(line[-1]) 43 | except (IndexError, ValueError): 44 | pass 45 | 46 | try: 47 | if line[-2] in valid_codes: 48 | if status_codes.get(line[-2], -1) == -1: 49 | status_codes[line[-2]] = 1 50 | else: 51 | status_codes[line[-2]] += 1 52 | except IndexError: 53 | pass 54 | 55 | print_stats(size, status_codes) 56 | 57 | except KeyboardInterrupt: 58 | print_stats(size, status_codes) 59 | raise 60 | -------------------------------------------------------------------------------- /0x0B-python-input_output/11-student.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a class Student.""" 3 | 4 | 5 | class Student: 6 | """Represent a student.""" 7 | 8 | def __init__(self, first_name, last_name, age): 9 | """Initialize a new Student. 10 | 11 | Args: 12 | first_name (str): The first name of the student. 13 | last_name (str): The last name of the student. 14 | age (int): The age of the student. 15 | """ 16 | self.first_name = first_name 17 | self.last_name = last_name 18 | self.age = age 19 | 20 | def to_json(self, attrs=None): 21 | """Get a dictionary representation of the Student. 22 | 23 | If attrs is a list of strings, represents only those attributes 24 | included in the list. 25 | 26 | Args: 27 | attrs (list): (Optional) The attributes to represent. 28 | """ 29 | if (type(attrs) == list and 30 | all(type(ele) == str for ele in attrs)): 31 | return {k: getattr(self, k) for k in attrs if hasattr(self, k)} 32 | return self.__dict__ 33 | 34 | def reload_from_json(self, json): 35 | """Replace all attributes of the Student. 36 | 37 | Args: 38 | json (dict): The key/value pairs to replace attributes with. 39 | """ 40 | for k, v in json.items(): 41 | setattr(self, k, v) 42 | -------------------------------------------------------------------------------- /0x0B-python-input_output/12-pascal_triangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a Pascal's Triangle function.""" 3 | 4 | 5 | def pascal_triangle(n): 6 | """Represent Pascal's Triangle of size n. 7 | 8 | Returns a list of lists of integers representing the triangle. 9 | """ 10 | if n <= 0: 11 | return [] 12 | 13 | triangles = [[1]] 14 | while len(triangles) != n: 15 | tri = triangles[-1] 16 | tmp = [1] 17 | for i in range(len(tri) - 1): 18 | tmp.append(tri[i] + tri[i + 1]) 19 | tmp.append(1) 20 | triangles.append(tmp) 21 | return triangles 22 | -------------------------------------------------------------------------------- /0x0B-python-input_output/2-append_write.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a file-appending function.""" 3 | 4 | 5 | def append_write(filename="", text=""): 6 | """Appends a string to the end of a UTF8 text file. 7 | 8 | Args: 9 | filename (str): The name of the file to append to. 10 | text (str): The string to append to the file. 11 | Returns: 12 | The number of characters appended. 13 | """ 14 | with open(filename, "a", encoding="utf-8") as f: 15 | return f.write(text) 16 | -------------------------------------------------------------------------------- /0x0B-python-input_output/3-to_json_string.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a string-to-JSON function.""" 3 | import json 4 | 5 | 6 | def to_json_string(my_obj): 7 | """Return the JSON representation of a string object.""" 8 | return json.dumps(my_obj) 9 | -------------------------------------------------------------------------------- /0x0B-python-input_output/4-from_json_string.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # 6-from_json_string.py 3 | """Defines a JSON-to-object function.""" 4 | import json 5 | 6 | 7 | def from_json_string(my_str): 8 | """Return the Python object representation of a JSON string.""" 9 | return json.loads(my_str) 10 | -------------------------------------------------------------------------------- /0x0B-python-input_output/5-save_to_json_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a JSON file-writing function.""" 3 | import json 4 | 5 | 6 | def save_to_json_file(my_obj, filename): 7 | """Write an object to a text file using JSON representation.""" 8 | with open(filename, "w") as f: 9 | json.dump(my_obj, f) 10 | -------------------------------------------------------------------------------- /0x0B-python-input_output/6-load_from_json_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a JSON file-reading function.""" 3 | import json 4 | 5 | 6 | def load_from_json_file(filename): 7 | """Create a Python object from a JSON file.""" 8 | with open(filename) as f: 9 | return json.load(f) 10 | -------------------------------------------------------------------------------- /0x0B-python-input_output/7-add_item.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Add all arguments to a Python list and save them to a file.""" 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | save_to_json_file = __import__('5-save_to_json_file').save_to_json_file 7 | load_from_json_file = \ 8 | __import__('6-load_from_json_file').load_from_json_file 9 | 10 | try: 11 | items = load_from_json_file("add_item.json") 12 | except FileNotFoundError: 13 | items = [] 14 | items.extend(sys.argv[1:]) 15 | save_to_json_file(items, "add_item.json") 16 | -------------------------------------------------------------------------------- /0x0B-python-input_output/8-class_to_json.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a Python class-to-JSON function.""" 3 | 4 | 5 | def class_to_json(obj): 6 | """Return the dictionary represntation of a simple data structure.""" 7 | return obj.__dict__ 8 | -------------------------------------------------------------------------------- /0x0B-python-input_output/9-student.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a class Student.""" 3 | 4 | 5 | class Student: 6 | """Represent a student.""" 7 | 8 | def __init__(self, first_name, last_name, age): 9 | """Initialize a new Student. 10 | 11 | Args: 12 | first_name (str): The first name of the student. 13 | last_name (str): The last name of the student. 14 | age (int): The age of the student. 15 | """ 16 | self.first_name = first_name 17 | self.last_name = last_name 18 | self.age = age 19 | 20 | def to_json(self): 21 | """Get a dictionary representation of the Student.""" 22 | return self.__dict__ 23 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/models/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ElHakikAmina/alx-higher_level_programming/bb9364d7175e3c6d2f57eee964e1fb7683370bd6/0x0C-python-almost_a_circle/models/__init__.py -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/tests/test_models/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ElHakikAmina/alx-higher_level_programming/bb9364d7175e3c6d2f57eee964e1fb7683370bd6/0x0C-python-almost_a_circle/tests/test_models/__init__.py -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/tests/test_models/__pycache__/__init__.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ElHakikAmina/alx-higher_level_programming/bb9364d7175e3c6d2f57eee964e1fb7683370bd6/0x0C-python-almost_a_circle/tests/test_models/__pycache__/__init__.cpython-310.pyc -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/tests/test_models/__pycache__/test_base.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ElHakikAmina/alx-higher_level_programming/bb9364d7175e3c6d2f57eee964e1fb7683370bd6/0x0C-python-almost_a_circle/tests/test_models/__pycache__/test_base.cpython-310.pyc -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/tests/test_models/__pycache__/test_rectangle.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ElHakikAmina/alx-higher_level_programming/bb9364d7175e3c6d2f57eee964e1fb7683370bd6/0x0C-python-almost_a_circle/tests/test_models/__pycache__/test_rectangle.cpython-310.pyc -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/tests/test_models/__pycache__/test_square.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ElHakikAmina/alx-higher_level_programming/bb9364d7175e3c6d2f57eee964e1fb7683370bd6/0x0C-python-almost_a_circle/tests/test_models/__pycache__/test_square.cpython-310.pyc -------------------------------------------------------------------------------- /0x0D-SQL_introduction/0-list_databases.sql: -------------------------------------------------------------------------------- 1 | -- Lists all databases of my MySQL server. 2 | SHOW DATABASES; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/1-create_database_if_missing.sql: -------------------------------------------------------------------------------- 1 | -- Creates the database hbtn_0c_0 in my MySQL server. 2 | CREATE DATABASE IF NOT EXISTS `hbtn_0c_0`; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/10-top_score.sql: -------------------------------------------------------------------------------- 1 | -- Lists all records of the table second_table. 2 | -- Records are ordered by descending score. 3 | SELECT `score`, `name` 4 | FROM `second_table` 5 | ORDER BY `score` DESC; 6 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/100-move_to_utf8.sql: -------------------------------------------------------------------------------- 1 | -- Converts the entire database hbtn_0c_0 to UTF8. 2 | USE `hbtn_0c_0` 3 | ALTER TABLE `first_table` 4 | CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; 5 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/101-avg_temperatures.sql: -------------------------------------------------------------------------------- 1 | -- Displays the average temperature (in Fahrenheit) by city ordered by descending temperature. 2 | SELECT `city`, AVG(`value`) AS `avg_temp` 3 | FROM `temperatures` 4 | GROUP BY `city` 5 | ORDER BY `avg_temp` DESC; 6 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/102-top_city.sql: -------------------------------------------------------------------------------- 1 | -- Displays the 3 cities with the highest average temperatures between July and August. 2 | SELECT `city`, AVG(`value`) AS `avg_temp` 3 | FROM `temperatures` 4 | WHERE `month` = 7 OR `month` = 8 5 | GROUP BY `city` 6 | ORDER BY `avg_temp` DESC 7 | LIMIT 3; 8 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/103-max_state.sql: -------------------------------------------------------------------------------- 1 | -- Displays the max temperature of each state, ordered by state name. 2 | SELECT `state`, MAX(`value`) AS `max_temp` 3 | FROM `temperatures` 4 | GROUP BY `state` 5 | ORDER BY `state`; 6 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/11-best_score.sql: -------------------------------------------------------------------------------- 1 | -- Lists all records in the table second_table with a score >= 10 in my MySQL server. 2 | -- Records are ordered by descending score. 3 | SELECT `score`, `name` 4 | FROM `second_table` 5 | WHERE `score` >= 10 6 | ORDER BY `score` DESC; 7 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/12-no_cheating.sql: -------------------------------------------------------------------------------- 1 | -- Updates the score of Bob to 10 in the table second_table in my MySQL server. 2 | UPDATE `second_table` 3 | SET `score` = 10 4 | WHERE `name` = "Bob"; 5 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/13-change_class.sql: -------------------------------------------------------------------------------- 1 | -- Removes all records with a score <= 5 in the table second_table in my MySQL server. 2 | DELETE FROM `second_table` 3 | WHERE `score` <= 5; 4 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/14-average.sql: -------------------------------------------------------------------------------- 1 | -- Computes the average score of all records in the table second_table in my MySQL server. 2 | SELECT AVG(`score`) AS `average` 3 | FROM `second_table`; 4 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/15-groups.sql: -------------------------------------------------------------------------------- 1 | -- Lists the number of records with the same score in the table second_table in my MySQL server. 2 | -- Records are ordered by descending count. 3 | SELECT `score`, COUNT(*) AS `number` 4 | FROM `second_table` 5 | GROUP BY `score` 6 | ORDER BY `number` DESC; 7 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/16-no_link.sql: -------------------------------------------------------------------------------- 1 | -- Lists all records of the table second_table having a name value in my MySQL server. 2 | -- Records are ordered by descending score. 3 | SELECT `score`, `name` 4 | FROM `second_table` 5 | WHERE `name` != "" 6 | ORDER BY `score` DESC 7 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/2-remove_database.sql: -------------------------------------------------------------------------------- 1 | -- Deletes the database hbtn_0c_0 from my MySQL server. 2 | DROP DATABASE IF EXISTS `hbtn_0c_0`; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/3-list_tables.sql: -------------------------------------------------------------------------------- 1 | -- Lists all tables of a database on my MySQL server. 2 | SHOW TABLES; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/4-first_table.sql: -------------------------------------------------------------------------------- 1 | -- Creates a table called first_table with values id and name in my MySQL server. 2 | CREATE TABLE IF NOT EXISTS `first_table` (`id` INT, `name` VARCHAR(256)); 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/5-full_table.sql: -------------------------------------------------------------------------------- 1 | -- Prints the full description of the table first_table in my MySQL server. 2 | SHOW CREATE TABLE `first_table`; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/6-list_values.sql: -------------------------------------------------------------------------------- 1 | -- Lists all rows of the table first_table in my MySQL server. 2 | SELECT * FROM `first_table`; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/7-insert_value.sql: -------------------------------------------------------------------------------- 1 | -- Inserts a new row into the table first_table in my MySQL server. 2 | INSERT INTO `first_table` (`id`, `name`) VALUES (89, "Best School"); 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/8-count_89.sql: -------------------------------------------------------------------------------- 1 | -- Displays the number of records with id = 89 in the table first_table in my MySQL server. 2 | SELECT COUNT(*) 3 | FROM `first_table` 4 | WHERE `id` = 89; 5 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/9-full_creation.sql: -------------------------------------------------------------------------------- 1 | -- Creates and fills a table second_table with attributes id, name and score in my MySQL server with multiple rows. 2 | CREATE TABLE IF NOT EXISTS `second_table` (`id` INT, `name` VARCHAR(256), `score` INT); 3 | INSERT INTO `second_table` (`id`, `name`, `score`) VALUES (1, "John", 10); 4 | INSERT INTO `second_table` (`id`, `name`, `score`) VALUES (2, "Alex", 3); 5 | INSERT INTO `second_table` (`id`, `name`, `score`) VALUES (3, "Bob", 14); 6 | INSERT INTO `second_table` (`id`, `name`, `score`) VALUES (4, "George", 8); 7 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/0-privileges.sql: -------------------------------------------------------------------------------- 1 | -- Lists all privileges of the MySQL users user_0d_1 and user_0d_2 2 | SHOW GRANTS FOR 'user_0d_1'@'localhost'; 3 | SHOW GRANTS FOR 'user_0d_2'@'localhost'; 4 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/1-create_user.sql: -------------------------------------------------------------------------------- 1 | -- creates the MySQL server user user_0d_1 and grant all priviledges 2 | CREATE USER IF NOT EXISTS user_0d_1@localhost IDENTIFIED BY 'user_0d_1_pwd'; 3 | GRANT ALL PRIVILEGES ON * . * TO user_0d_1@localhost; 4 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/10-genre_id_by_show.sql: -------------------------------------------------------------------------------- 1 | -- lists all shows contained in hbtn_0d_tvshows that have at least one genre linked 2 | -- lists all rows of a database that have one column in common 3 | SELECT tv_shows.title, tv_show_genres.genre_id FROM tv_shows INNER JOIN tv_show_genres ON tv_shows.id = tv_show_genres.show_id ORDER BY tv_shows.title ASC, tv_show_genres.genre_id ASC; 4 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/100-not_my_genres.sql: -------------------------------------------------------------------------------- 1 | -- uses the hbtn_0d_tvshows database to list all genres not linked to the show Dexter 2 | -- uses a database to list all rows not linked to one row 3 | SELECT name 4 | FROM tv_genres 5 | WHERE name NOT IN 6 | (SELECT name 7 | FROM tv_genres 8 | LEFT JOIN tv_show_genres ON tv_genres.id = tv_show_genres.genre_id 9 | LEFT JOIN tv_shows ON tv_show_genres.show_id = tv_shows.id 10 | WHERE tv_shows.title = 'Dexter') 11 | GROUP BY name 12 | ORDER BY name ASC; 13 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/101-not_a_comedy.sql: -------------------------------------------------------------------------------- 1 | -- lists all shows without the genre Comedy in the database hbtn_0d_tvshows 2 | -- uses a database to list all rows not linked to one row 3 | SELECT title 4 | FROM tv_shows 5 | WHERE title NOT IN 6 | (SELECT title 7 | FROM tv_shows 8 | LEFT JOIN tv_show_genres ON tv_shows.id = tv_show_genres.show_id 9 | LEFT JOIN tv_genres ON tv_show_genres.genre_id = tv_genres.id 10 | WHERE tv_genres.name = 'Comedy') 11 | GROUP BY title 12 | ORDER BY title ASC; 13 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/102-rating_shows.sql: -------------------------------------------------------------------------------- 1 | -- lists all shows from hbtn_0d_tvshows_rate by their rating 2 | -- lists all rows of a table by the sum of a linked row 3 | SELECT title, SUM(tv_show_ratings.rate) 'rating' 4 | FROM tv_shows 5 | LEFT JOIN tv_show_ratings ON tv_show_ratings.show_id = tv_shows.id 6 | GROUP BY title 7 | ORDER BY rating DESC; 8 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/103-rating_genres.sql: -------------------------------------------------------------------------------- 1 | -- lists all genres in the database hbtn_0d_tvshows_rate by their rating 2 | -- lists all rows in a database linked to a row in another table 3 | SELECT name, SUM(tv_show_ratings.rate) 'rating' 4 | FROM tv_genres 5 | INNER JOIN tv_show_genres ON tv_genres.id = tv_show_genres.genre_id 6 | INNER JOIN tv_show_ratings ON tv_show_genres.show_id = tv_show_ratings.show_id 7 | GROUP BY name 8 | ORDER BY rating DESC; 9 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/11-genre_id_all_shows.sql: -------------------------------------------------------------------------------- 1 | -- lists all shows contained in the database hbtn_0d_tvshows 2 | -- lists all rows of tables in a database 3 | SELECT tv_shows.title, tv_show_genres.genre_id 4 | FROM tv_shows LEFT JOIN tv_show_genres 5 | ON tv_shows.id = tv_show_genres.show_id 6 | ORDER BY tv_shows.title ASC, tv_show_genres.genre_id ASC; 7 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/12-no_genre.sql: -------------------------------------------------------------------------------- 1 | -- lists all shows contained in hbtn_0d_tvshows without a genre linked 2 | -- lists all rows of a database that don't have one column 3 | SELECT tv_shows.title, tv_show_genres.genre_id 4 | FROM tv_shows LEFT JOIN tv_show_genres 5 | ON tv_shows.id = tv_show_genres.show_id 6 | WHERE tv_show_genres.genre_id IS NULL 7 | ORDER BY tv_shows.title ASC, tv_show_genres.genre_id ASC; 8 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/13-count_shows_by_genre.sql: -------------------------------------------------------------------------------- 1 | -- lists all genres from hbtn_0d_tvshows and displays the number of shows linked to each 2 | -- lists all rows of a database meeting a condition 3 | SELECT tv_genres.name AS 'genre', COUNT(tv_show_genres.genre_id) AS 'number_of_shows' 4 | FROM tv_genres RIGHT JOIN tv_show_genres 5 | ON tv_genres.id = tv_show_genres.genre_id 6 | GROUP BY genre 7 | ORDER BY number_of_shows DESC; 8 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/14-my_genres.sql: -------------------------------------------------------------------------------- 1 | -- uses the hbtn_0d_tvshows database to lists all genres of the show Dexter 2 | -- uses a databse to lists all rows in a table corresponding to all rows in another 3 | SELECT name 4 | FROM tv_genres 5 | LEFT JOIN tv_show_genres ON tv_genres.id = tv_show_genres.genre_id 6 | LEFT JOIN tv_shows ON tv_show_genres.show_id = tv_shows.id 7 | WHERE tv_shows.title = 'Dexter' 8 | GROUP BY name 9 | ORDER BY name ASC; 10 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/15-comedy_only.sql: -------------------------------------------------------------------------------- 1 | -- lists all Comedy shows in the database hbtn_0d_tvshows 2 | -- lists all rows of a database corresponding to a column value 3 | SELECT title 4 | FROM tv_shows 5 | LEFT JOIN tv_show_genres ON tv_shows.id = tv_show_genres.show_id 6 | LEFT JOIN tv_genres ON tv_show_genres.genre_id = tv_genres.id 7 | WHERE tv_genres.name = 'Comedy' 8 | GROUP BY title 9 | ORDER BY title ASC; 10 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/16-shows_by_genre.sql: -------------------------------------------------------------------------------- 1 | -- lists all shows, and all genres linked to that show, from the database hbtn_0d_tvshows 2 | -- lists all rows of a table linked to another table 3 | SELECT title, name 4 | FROM tv_shows 5 | LEFT JOIN tv_show_genres ON tv_shows.id = tv_show_genres.show_id 6 | LEFT JOIN tv_genres ON tv_show_genres.genre_id = tv_genres.id 7 | ORDER BY title ASC, name ASC; 8 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/2-create_read_user.sql: -------------------------------------------------------------------------------- 1 | -- creates the database hbtn_0d_2 and the user user_0d_2 2 | -- creates a database 3 | CREATE DATABASE IF NOT EXISTS hbtn_0d_2; 4 | -- creates a user 5 | CREATE USER IF NOT EXISTS user_0d_2@localhost IDENTIFIED BY 'user_0d_2_pwd'; 6 | -- grants SELECT privileges to a user 7 | GRANT SELECT ON hbtn_0d_2.* TO user_0d_2@localhost; 8 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/3-force_name.sql: -------------------------------------------------------------------------------- 1 | -- creates the table force_name on your MySQL server 2 | -- creates a table in a database 3 | CREATE TABLE IF NOT EXISTS force_name (id INT, name VARCHAR(256) NOT NULL); 4 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/4-never_empty.sql: -------------------------------------------------------------------------------- 1 | -- creates the table id_not_null on your MySQL server 2 | -- creates a table 3 | CREATE TABLE IF NOT EXISTS id_not_null (id INT DEFAULT 1, name VARCHAR(256)); 4 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/5-unique_id.sql: -------------------------------------------------------------------------------- 1 | -- creates the table unique_id on your MySQL server 2 | -- creates a table 3 | CREATE TABLE IF NOT EXISTS unique_id (id INT DEFAULT 1 UNIQUE, name VARCHAR(256)); 4 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/6-states.sql: -------------------------------------------------------------------------------- 1 | -- creates the database hbtn_0d_usa and the table states (in the database hbtn_0d_usa) on your MySQL server 2 | -- creates a database 3 | CREATE DATABASE IF NOT EXISTS hbtn_0d_usa; 4 | -- use a database 5 | USE hbtn_0d_usa; 6 | -- creates a table 7 | CREATE TABLE IF NOT EXISTS states (id INT UNIQUE NOT NULL AUTO_INCREMENT, name VARCHAR(256) NOT NULL, PRIMARY KEY(id)); 8 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/7-cities.sql: -------------------------------------------------------------------------------- 1 | -- creates the database hbtn_0d_usa and the table cities (in the database hbtn_0d_usa) on your MySQL server 2 | -- creates a database 3 | CREATE DATABASE IF NOT EXISTS hbtn_0d_usa; 4 | -- use a database 5 | USE hbtn_0d_usa; 6 | -- creates a table 7 | CREATE TABLE IF NOT EXISTS cities (id INT UNIQUE AUTO_INCREMENT NOT NULL, 8 | state_id INT NOT NULL, 9 | name VARCHAR(256) NOT NULL, 10 | PRIMARY KEY(id), 11 | FOREIGN KEY(state_id) REFERENCES states(id)); 12 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/8-cities_of_california_subquery.sql: -------------------------------------------------------------------------------- 1 | -- lists all the cities of California that can be found in the database hbtn_0d_usa 2 | -- lists all rows of a column in a database 3 | SELECT id, name FROM cities WHERE state_id = (SELECT id FROM states WHERE name = 'California') ORDER BY id ASC; 4 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/9-cities_by_state_join.sql: -------------------------------------------------------------------------------- 1 | -- lists all cities contained in the database hbtn_0d_usa 2 | -- lists all rows of a particular column in a database 3 | SELECT cities.id, cities.name, states.name FROM cities LEFT JOIN states ON states.id = cities.state_id ORDER BY cities.id; 4 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/README.md: -------------------------------------------------------------------------------- 1 | # MORE QUERIES. 2 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/0-select_states.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Lists all states from the database hbtn_0e_0_usa 4 | """ 5 | import sys 6 | import MySQLdb 7 | 8 | if __name__ == '__main__': 9 | db = MySQLdb.connect(user=sys.argv[1], passwd=sys.argv[2], 10 | db=sys.argv[3], port=3306) 11 | 12 | cur = db.cursor() 13 | cur.execute("SELECT * FROM states;") 14 | states = cur.fetchall() 15 | 16 | for state in states: 17 | print(state) 18 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/1-filter_states.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Lists all states with a name starting with N 4 | """ 5 | import sys 6 | import MySQLdb 7 | 8 | if __name__ == '__main__': 9 | db = MySQLdb.connect(user=sys.argv[1], passwd=sys.argv[2], 10 | db=sys.argv[3], port=3306) 11 | 12 | cur = db.cursor() 13 | cur.execute("SELECT * \ 14 | FROM states \ 15 | WHERE CONVERT(`name` USING Latin1) \ 16 | COLLATE Latin1_General_CS \ 17 | LIKE 'N%';") 18 | states = cur.fetchall() 19 | 20 | for state in states: 21 | print(state) 22 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/10-model_state_my_get.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Prints the State object with the name passed as argument from the db 4 | """ 5 | import sys 6 | from model_state import Base, State 7 | from sqlalchemy import create_engine 8 | from sqlalchemy.orm import sessionmaker 9 | 10 | 11 | if __name__ == '__main__': 12 | engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}'. 13 | format(sys.argv[1], sys.argv[2], sys.argv[3]), 14 | pool_pre_ping=True) 15 | Session = sessionmaker(bind=engine) 16 | session = Session() 17 | 18 | state = session.query(State).filter(State.name == sys.argv[4]).first() 19 | print("Not found" if not state else state.id) 20 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/100-relationship_states_cities.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Creates the State "California" with the City "San Francisco" from a DB 4 | """ 5 | import sys 6 | from relationship_state import Base, State 7 | from relationship_city import City 8 | from sqlalchemy import create_engine 9 | from sqlalchemy.orm import sessionmaker 10 | 11 | 12 | if __name__ == '__main__': 13 | engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}'. 14 | format(sys.argv[1], sys.argv[2], sys.argv[3]), 15 | pool_pre_ping=True) 16 | Base.metadata.create_all(engine) 17 | 18 | Session = sessionmaker(bind=engine) 19 | session = Session() 20 | 21 | newState = State(name='California') 22 | newCity = City(name='San Francisco') 23 | newState.cities.append(newCity) 24 | 25 | session.add(newState) 26 | session.add(newCity) 27 | session.commit() 28 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/101-relationship_states_cities_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Lists all State objects and corresponding City objects contained in the DB 4 | """ 5 | import sys 6 | from relationship_state import Base, State 7 | from relationship_city import City 8 | from sqlalchemy import create_engine 9 | from sqlalchemy.orm import sessionmaker 10 | 11 | 12 | if __name__ == '__main__': 13 | engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}'. 14 | format(sys.argv[1], sys.argv[2], sys.argv[3]), 15 | pool_pre_ping=True) 16 | Base.metadata.create_all(engine) 17 | 18 | Session = sessionmaker(bind=engine) 19 | session = Session() 20 | 21 | st = session.query(State).outerjoin(City).order_by(State.id, City.id).all() 22 | 23 | for state in st: 24 | print("{}: {}".format(state.id, state.name)) 25 | for city in state.cities: 26 | print(" {}: {}".format(city.id, city.name)) 27 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/102-relationship_cities_states_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Lists all City objects from the database hbtn_0e_101_usa 4 | """ 5 | import sys 6 | from relationship_state import Base, State 7 | from relationship_city import City 8 | from sqlalchemy import create_engine 9 | from sqlalchemy.orm import sessionmaker 10 | 11 | 12 | if __name__ == '__main__': 13 | engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}'. 14 | format(sys.argv[1], sys.argv[2], sys.argv[3]), 15 | pool_pre_ping=True) 16 | 17 | Session = sessionmaker(bind=engine) 18 | session = Session() 19 | 20 | st = session.query(State).join(City).order_by(City.id).all() 21 | 22 | for state in st: 23 | for city in state.cities: 24 | print("{}: {} -> {}".format(city.id, city.name, state.name)) 25 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/11-model_state_insert.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Adds the State object "Lousiana" to the database hbtn_0e_6_usa 4 | """ 5 | import sys 6 | from model_state import Base, State 7 | from sqlalchemy import create_engine 8 | from sqlalchemy.orm import sessionmaker 9 | 10 | 11 | if __name__ == '__main__': 12 | engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}'. 13 | format(sys.argv[1], sys.argv[2], sys.argv[3]), 14 | pool_pre_ping=True) 15 | Session = sessionmaker(bind=engine) 16 | session = Session() 17 | 18 | newState = State(name='Louisiana') 19 | session.add(newState) 20 | session.commit() 21 | 22 | print(newState.id) 23 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/12-model_state_update_id_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Changes the name of a State object from the database hbtn_0e_6_usa 4 | """ 5 | import sys 6 | from model_state import Base, State 7 | from sqlalchemy import create_engine 8 | from sqlalchemy.orm import sessionmaker 9 | 10 | 11 | if __name__ == '__main__': 12 | engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}'. 13 | format(sys.argv[1], sys.argv[2], sys.argv[3]), 14 | pool_pre_ping=True) 15 | Session = sessionmaker(bind=engine) 16 | session = Session() 17 | 18 | stateUpdated = session.query(State).filter(State.id == 2).first() 19 | 20 | if stateUpdated: 21 | stateUpdated.name = 'New Mexico' 22 | session.commit() 23 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/13-model_state_delete_a.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Deletes all State objects with a name containing the letter a 4 | """ 5 | import sys 6 | from model_state import Base, State 7 | from sqlalchemy import create_engine 8 | from sqlalchemy.orm import sessionmaker 9 | 10 | 11 | if __name__ == '__main__': 12 | engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}'. 13 | format(sys.argv[1], sys.argv[2], sys.argv[3]), 14 | pool_pre_ping=True) 15 | Session = sessionmaker(bind=engine) 16 | session = Session() 17 | 18 | states = session.query(State).filter(State.name.like('%a%')).all() 19 | 20 | for state in states: 21 | session.delete(state) 22 | 23 | session.commit() 24 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/14-model_city_fetch_by_state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Prints all City objects from the database hbtn_0e_14_usa 4 | """ 5 | import sys 6 | from model_state import Base, State 7 | from model_city import City 8 | from sqlalchemy import create_engine 9 | from sqlalchemy.orm import sessionmaker 10 | 11 | 12 | if __name__ == '__main__': 13 | engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}'. 14 | format(sys.argv[1], sys.argv[2], sys.argv[3]), 15 | pool_pre_ping=True) 16 | Session = sessionmaker(bind=engine) 17 | session = Session() 18 | 19 | st_cty = session.query(State, City).filter(State.id == City.state_id).all() 20 | 21 | for state, city in st_cty: 22 | print("{}: ({}) {}".format(state.name, city.id, city.name)) 23 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/2-my_filter_states.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Lists all values in the states tables of a database where name 4 | matches the argument 5 | """ 6 | import sys 7 | import MySQLdb 8 | 9 | if __name__ == '__main__': 10 | db = MySQLdb.connect(user=sys.argv[1], passwd=sys.argv[2], 11 | db=sys.argv[3], port=3306) 12 | 13 | cur = db.cursor() 14 | cur.execute("SELECT * \ 15 | FROM states \ 16 | WHERE CONVERT(`name` USING Latin1) \ 17 | COLLATE Latin1_General_CS = '{}';".format(sys.argv[4])) 18 | states = cur.fetchall() 19 | 20 | for state in states: 21 | print(state) 22 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/3-my_safe_filter_states.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Lists all values in the states tables of a database where name 4 | matches the argument in a safe way 5 | """ 6 | import sys 7 | import MySQLdb 8 | 9 | if __name__ == '__main__': 10 | db = MySQLdb.connect(user=sys.argv[1], passwd=sys.argv[2], 11 | db=sys.argv[3], port=3306) 12 | 13 | cur = db.cursor() 14 | cur.execute("SELECT * FROM states WHERE name = %s;", (sys.argv[4],)) 15 | states = cur.fetchall() 16 | 17 | for state in states: 18 | print(state) 19 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/4-cities_by_state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | List all cities from a database 4 | """ 5 | import sys 6 | import MySQLdb 7 | 8 | if __name__ == '__main__': 9 | db = MySQLdb.connect(user=sys.argv[1], passwd=sys.argv[2], 10 | db=sys.argv[3], port=3306) 11 | 12 | cur = db.cursor() 13 | cur.execute("SELECT cities.id, cities.name, states.name \ 14 | FROM cities JOIN states ON cities.state_id = states.id;") 15 | states = cur.fetchall() 16 | 17 | for state in states: 18 | print(state) 19 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/5-filter_cities.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | List all cities of a state 4 | """ 5 | import sys 6 | import MySQLdb 7 | 8 | if __name__ == '__main__': 9 | db = MySQLdb.connect(user=sys.argv[1], passwd=sys.argv[2], 10 | db=sys.argv[3], port=3306) 11 | 12 | cur = db.cursor() 13 | cur.execute("SELECT cities.id, cities.name, states.name \ 14 | FROM cities JOIN states ON cities.state_id = states.id \ 15 | WHERE states.name = '{}';".format(sys.argv[4])) 16 | states = cur.fetchall() 17 | 18 | print(", ".join([state[1] for state in states])) 19 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/7-model_state_fetch_all.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Lists all State objects from the database hbtn_0e_6_usa 4 | """ 5 | import sys 6 | from model_state import Base, State 7 | from sqlalchemy import create_engine 8 | from sqlalchemy.orm import sessionmaker 9 | 10 | 11 | if __name__ == '__main__': 12 | engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}'. 13 | format(sys.argv[1], sys.argv[2], sys.argv[3]), 14 | pool_pre_ping=True) 15 | Session = sessionmaker(bind=engine) 16 | session = Session() 17 | 18 | states = session.query(State).order_by(State.id).all() 19 | 20 | for state in states: 21 | print("{}: {}".format(state.id, state.name)) 22 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/8-model_state_fetch_first.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Prints the first State object from the database hbtn_0e_6_usa 4 | """ 5 | import sys 6 | from model_state import Base, State 7 | from sqlalchemy import create_engine 8 | from sqlalchemy.orm import sessionmaker 9 | 10 | 11 | if __name__ == '__main__': 12 | engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}'. 13 | format(sys.argv[1], sys.argv[2], sys.argv[3]), 14 | pool_pre_ping=True) 15 | Session = sessionmaker(bind=engine) 16 | session = Session() 17 | 18 | state = session.query(State).order_by(State.id).first() 19 | 20 | print("Nothing" if not state else "{}: {}".format(state.id, state.name)) 21 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/9-model_state_filter_a.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Lists all State objects that contain the letter a from the database 4 | """ 5 | import sys 6 | from model_state import Base, State 7 | from sqlalchemy import create_engine 8 | from sqlalchemy.orm import sessionmaker 9 | 10 | 11 | if __name__ == '__main__': 12 | engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}'. 13 | format(sys.argv[1], sys.argv[2], sys.argv[3]), 14 | pool_pre_ping=True) 15 | Session = sessionmaker(bind=engine) 16 | session = Session() 17 | 18 | states = session.query(State).filter(State.name.like('%a%')).all() 19 | 20 | for state in states: 21 | print("{}: {}".format(state.id, state.name)) 22 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/model_city.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Contains the class definition of a City 4 | """ 5 | from model_state import Base 6 | from sqlalchemy import Column, Integer, String, ForeignKey 7 | from sqlalchemy.ext.declarative import declarative_base 8 | 9 | 10 | class City(Base): 11 | """ 12 | Class that defines each city 13 | """ 14 | __tablename__ = 'cities' 15 | id = Column(Integer, unique=True, nullable=False, primary_key=True) 16 | name = Column(String(128), nullable=False) 17 | state_id = Column(Integer, ForeignKey("states.id"), nullable=False) 18 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/model_state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Contains State class and Base, an instance of declarative_base() 4 | """ 5 | from sqlalchemy import Column, Integer, String, MetaData 6 | from sqlalchemy.ext.declarative import declarative_base 7 | 8 | mymetadata = MetaData() 9 | Base = declarative_base(metadata=mymetadata) 10 | 11 | 12 | class State(Base): 13 | """ 14 | Class with id and name attributes of each state 15 | """ 16 | __tablename__ = 'states' 17 | id = Column(Integer, unique=True, nullable=False, primary_key=True) 18 | name = Column(String(128), nullable=False) 19 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/relationship_city.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Contains the class definition of a City 4 | """ 5 | from relationship_state import Base 6 | from sqlalchemy import Column, Integer, String, ForeignKey 7 | from sqlalchemy.ext.declarative import declarative_base 8 | 9 | 10 | class City(Base): 11 | """ 12 | Class that defines each city 13 | """ 14 | __tablename__ = 'cities' 15 | id = Column(Integer, unique=True, nullable=False, primary_key=True) 16 | name = Column(String(128), nullable=False) 17 | state_id = Column(Integer, ForeignKey("states.id"), nullable=False) 18 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/relationship_state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Contains State class and Base, an instance of declarative_base() 4 | """ 5 | from sqlalchemy import Column, Integer, String, MetaData 6 | from sqlalchemy.ext.declarative import declarative_base 7 | from sqlalchemy.orm import relationship 8 | 9 | mymetadata = MetaData() 10 | Base = declarative_base(metadata=mymetadata) 11 | 12 | 13 | class State(Base): 14 | """ 15 | Class with id and name attributes of each state 16 | """ 17 | __tablename__ = 'states' 18 | id = Column(Integer, unique=True, nullable=False, primary_key=True) 19 | name = Column(String(128), nullable=False) 20 | cities = relationship("City", backref="states") 21 | -------------------------------------------------------------------------------- /0x10-python-network_0/0-body_size.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Get the byte size of the HTTP response header for a given URL. 3 | curl -s "$1" | wc -c 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/1-body.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Get the response body for a given URL for 200 status code responses. 3 | curl -sL "$1" 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/100-status_code.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Sends a GET request to a given URL and display the response status code. 3 | curl -s -o /dev/null -w "%{http_code}" "$1" 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/101-post_json.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Sends a JSON POST request to a given URL with a given JSON file. 3 | curl -s -H "Content-Type: application/json" -d "$(cat "$2")" "$1" 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/102-catch_me.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Makes a request to 0.0.0.0:5000/catch_me that gets the message "You got me!". 3 | curl -sL -X PUT -H "Origin: HolbertonSchool" -d "user_id=98" 0.0.0.0:5000/catch_me 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/2-delete.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Send a DELETE request to a given URL and display the response body. 3 | curl -sX DELETE "$1" 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/3-methods.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Display all HTTP methods the server of a given URL will accept. 3 | curl -sI "$1" | grep "Allow" | cut -d " " -f 2- 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/4-header.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Send a GET request to a given URL with a header variable. 3 | curl -sH "X-HolbertonSchool-User-Id: 98" "${1}" 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/5-post_params.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Bash scripts that sends a POST request to a given URL. 3 | curl -s -X POST -d "email=test@gmail.com&subject=I will always be here for PLD" "$1" 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/6-peak.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Finds a peak in a list of unsorted integers""" 3 | 4 | 5 | def find_peak(list_of_integers): 6 | """Finds a peak in list_of_integers""" 7 | 8 | if list_of_integers is None or list_of_integers == []: 9 | return None 10 | lo = 0 11 | hi = len(list_of_integers) 12 | mid = ((hi - lo) // 2) + lo 13 | mid = int(mid) 14 | if hi == 1: 15 | return list_of_integers[0] 16 | if hi == 2: 17 | return max(list_of_integers) 18 | if list_of_integers[mid] >= list_of_integers[mid - 1] and\ 19 | list_of_integers[mid] >= list_of_integers[mid + 1]: 20 | return list_of_integers[mid] 21 | if mid > 0 and list_of_integers[mid] < list_of_integers[mid + 1]: 22 | return find_peak(list_of_integers[mid:]) 23 | if mid > 0 and list_of_integers[mid] < list_of_integers[mid - 1]: 24 | return find_peak(list_of_integers[:mid]) 25 | -------------------------------------------------------------------------------- /0x10-python-network_0/6-peak.txt: -------------------------------------------------------------------------------- 1 | O(log(n)) 2 | -------------------------------------------------------------------------------- /0x11-python-network_1/0-hbtn_status.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """A script that 3 | - fetches https://alx-intranet.hbtn.io/status. 4 | - uses urlib package 5 | """ 6 | 7 | 8 | if __name__ == '__main__': 9 | import urllib.request 10 | 11 | with urllib.request.urlopen('https://alx-intranet.hbtn.io/status') as res: 12 | content = res.read() 13 | print("Body response:") 14 | print("\t- type: {}".format(type(content))) 15 | print("\t- content: {}".format(content)) 16 | print("\t- utf8 content: {}".format(content.decode('utf-8'))) 17 | -------------------------------------------------------------------------------- /0x11-python-network_1/1-hbtn_header.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """A script that: 3 | - takes in a URL, 4 | - sends a request to the URL and displays the value 5 | - of the X-Request-Id variable found in the header ofthe response. 6 | """ 7 | import sys 8 | import urllib.request 9 | 10 | if __name__ == "__main__": 11 | url = sys.argv[1] 12 | 13 | request = urllib.request.Request(url) 14 | with urllib.request.urlopen(request) as response: 15 | print(dict(response.headers).get("X-Request-Id")) 16 | -------------------------------------------------------------------------------- /0x11-python-network_1/10-my_github.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """A script that: 3 | - takes your GitHub credentials (username and password) 4 | - uses the GitHub API to display your id 5 | """ 6 | import sys 7 | import requests 8 | from requests.auth import HTTPBasicAuth 9 | 10 | 11 | if __name__ == "__main__": 12 | auth = HTTPBasicAuth(sys.argv[1], sys.argv[2]) 13 | r = requests.get("https://api.github.com/user", auth=auth) 14 | print(r.json().get("id")) 15 | -------------------------------------------------------------------------------- /0x11-python-network_1/100-github_commits.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """lists the 10 most recent commits on a given GitHub repository. 3 | """ 4 | import sys 5 | import requests 6 | 7 | 8 | if __name__ == "__main__": 9 | url = "https://api.github.com/repos/{}/{}/commits".format( 10 | sys.argv[2], sys.argv[1]) 11 | 12 | r = requests.get(url) 13 | commits = r.json() 14 | try: 15 | for i in range(10): 16 | print("{}: {}".format( 17 | commits[i].get("sha"), 18 | commits[i].get("commit").get("author").get("name"))) 19 | except IndexError: 20 | pass 21 | -------------------------------------------------------------------------------- /0x11-python-network_1/2-post_email.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """A script that: 3 | - takes in a URL 4 | - sends a POST request to the passed URL 5 | - takes email as a parameter 6 | - displays the body of the response 7 | """ 8 | import sys 9 | import urllib.parse 10 | import urllib.request 11 | 12 | 13 | if __name__ == "__main__": 14 | url = sys.argv[1] 15 | value = {"email": sys.argv[2]} 16 | data = urllib.parse.urlencode(value).encode("ascii") 17 | 18 | request = urllib.request.Request(url, data) 19 | with urllib.request.urlopen(request) as response: 20 | print(response.read().decode("utf-8")) 21 | -------------------------------------------------------------------------------- /0x11-python-network_1/3-error_code.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """A script that: 3 | - takes in a URL, 4 | - sends a request to the URL 5 | - displays the body of the response (decoded in utf-8). 6 | """ 7 | 8 | 9 | if __name__ == "__main__": 10 | import sys 11 | from urllib import request, error 12 | 13 | try: 14 | with request.urlopen(sys.argv[1]) as res: 15 | print(res.read().decode('UTF-8')) 16 | except error.HTTPError as er: 17 | print('Error code:', er.code) 18 | -------------------------------------------------------------------------------- /0x11-python-network_1/4-hbtn_status.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Python script that fetches an URL with requests package 4 | """ 5 | import requests 6 | 7 | 8 | if __name__ == "__main__": 9 | r = requests.get('https://alx-intranet.hbtn.io/status') 10 | t = r.text 11 | print('Body response:\n\t- type: {}\n\t- content: {}'.format(type(t), t)) 12 | -------------------------------------------------------------------------------- /0x11-python-network_1/5-hbtn_header.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Displays the X-Request-Id header variable of a request to a given URL 3 | """ 4 | import sys 5 | import requests 6 | 7 | 8 | if __name__ == "__main__": 9 | url = sys.argv[1] 10 | 11 | r = requests.get(url) 12 | print(r.headers.get("X-Request-Id")) 13 | -------------------------------------------------------------------------------- /0x11-python-network_1/6-post_email.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ post email """ 3 | import requests 4 | import sys 5 | 6 | 7 | if __name__ == "__main__": 8 | email = {'email': sys.argv[2]} 9 | r = requests.post(sys.argv[1], data=email) 10 | print(r.text) 11 | -------------------------------------------------------------------------------- /0x11-python-network_1/7-error_code.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """A script that 3 | - takes in a URL 4 | - sends a request to the URL 5 | - displays the body of the response. 6 | """ 7 | import sys 8 | import requests 9 | 10 | 11 | if __name__ == "__main__": 12 | url = sys.argv[1] 13 | 14 | r = requests.get(url) 15 | if r.status_code >= 400: 16 | print("Error code: {}".format(r.status_code)) 17 | else: 18 | print(r.text) 19 | -------------------------------------------------------------------------------- /0x11-python-network_1/8-json_api.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """A script tha: 3 | - takes in a letter 4 | - sends POST request to http://0.0.0.0:5000/search_user 5 | with the letter as a parameter. 6 | """ 7 | import sys 8 | import requests 9 | 10 | 11 | if __name__ == "__main__": 12 | letter = "" if len(sys.argv) == 1 else sys.argv[1] 13 | payload = {"q": letter} 14 | 15 | r = requests.post("http://0.0.0.0:5000/search_user", data=payload) 16 | try: 17 | response = r.json() 18 | if response == {}: 19 | print("No result") 20 | else: 21 | print("[{}] {}".format(response.get("id"), response.get("name"))) 22 | except ValueError: 23 | print("Not a valid JSON") 24 | -------------------------------------------------------------------------------- /0x11-python-network_1/README.md: -------------------------------------------------------------------------------- 1 | # 0x11-python-network_1 2 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/0-javascript_is_amazing.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const myVar = 'JavaScript is amazing'; 3 | console.log(myVar); 4 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/1-multi_languages.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | console.log('C is fun'); 3 | console.log('Python is cool'); 4 | console.log('JavaScript is amazing'); 5 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/10-factorial.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | function factorial (n) { 3 | return n === 0 || isNaN(n) ? 1 : n * factorial(n - 1); 4 | } 5 | 6 | console.log(factorial(Number(process.argv[2]))); 7 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/100-let_me_const.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | myVar = 333; 3 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/101-call_me_moby.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | exports.callMeMoby = function (x, theFunction) { 3 | for (let i = 0; i < x; i++) theFunction(); 4 | }; 5 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/102-add_me_maybe.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | exports.addMeMaybe = function (number, theFunction) { 3 | theFunction(++number); 4 | }; 5 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/103-object_fct.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const myObject = { 3 | type: 'object', 4 | value: 12 5 | }; 6 | console.log(myObject); 7 | myObject.incr = function () { 8 | this.value++; 9 | }; 10 | myObject.incr(); 11 | console.log(myObject); 12 | myObject.incr(); 13 | console.log(myObject); 14 | myObject.incr(); 15 | console.log(myObject); 16 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/11-second_biggest.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | if (process.argv.length <= 3) { 3 | console.log(0); 4 | } else { 5 | const args = process.argv.map(Number) 6 | .slice(2, process.argv.length) 7 | .sort((a, b) => a - b); 8 | console.log(args[args.length - 2]); 9 | } 10 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/12-object.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const myObject = { 3 | type: 'object', 4 | value: 12 5 | }; 6 | console.log(myObject); 7 | myObject.value = 89; 8 | console.log(myObject); 9 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/13-add.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | exports.add = (a, b) => a + b; 3 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/2-arguments.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const count = process.argv.length; 3 | console.log(count === 2 ? 'No argument' : count === 3 ? 'Argument found' : 'Arguments found'); 4 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/3-value_argument.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | console.log(typeof process.argv[2] === 'undefined' ? 'No argument' : process.argv[2]); 3 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/4-concat.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | console.log(`${process.argv[2]} is ${process.argv[3]}`); 3 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/5-to_integer.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const num = Math.floor(Number(process.argv[2])); 3 | console.log(isNaN(num) ? 'Not a number' : `My number: ${num}`); 4 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/6-multi_languages_loop.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | for (const line of ['C is fun', 'Python is cool', 'JavaScript is amazing']) { 3 | console.log(line); 4 | } 5 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/7-multi_c.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const x = Math.floor(Number(process.argv[2])); 3 | if (isNaN(x)) { 4 | console.log('Missing number of occurrences'); 5 | } else { 6 | for (let i = 0; i < x; i++) { 7 | console.log('C is fun'); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/8-square.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const size = Math.floor(Number(process.argv[2])); 3 | if (isNaN(size)) { 4 | console.log('Missing size'); 5 | } else { 6 | for (let r = 0; r < size; r++) { 7 | let row = ''; 8 | for (let c = 0; c < size; c++) row += 'X'; 9 | console.log(row); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/9-add.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | function add (a, b) { 3 | return a + b; 4 | } 5 | 6 | console.log(add(Number(process.argv[2]), Number(process.argv[3]))); 7 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/README.md: -------------------------------------------------------------------------------- 1 | #JavaScript 2 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/0-rectangle.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | class Rectangle { 3 | } 4 | 5 | module.exports = Rectangle; 6 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/1-rectangle.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | class Rectangle { 3 | constructor (w, h) { 4 | this.width = w; 5 | this.height = h; 6 | } 7 | } 8 | 9 | module.exports = Rectangle; 10 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/10-converter.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | exports.converter = function (base) { 4 | return function (num) { 5 | return num.toString(base); 6 | }; 7 | }; 8 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/100-map.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const list = require('./100-data').list; 3 | const newList = list.map(function (num, index) { 4 | return num * index; 5 | }); 6 | 7 | console.log(list); 8 | console.log(newList); 9 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/101-sorted.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const dict = require('./101-data').dict; 3 | 4 | const totalist = Object.entries(dict); 5 | const vals = Object.values(dict); 6 | const valsUniq = [...new Set(vals)]; 7 | const newDict = {}; 8 | for (const j in valsUniq) { 9 | const list = []; 10 | for (const k in totalist) { 11 | if (totalist[k][1] === valsUniq[j]) { 12 | list.unshift(totalist[k][0]); 13 | } 14 | } 15 | newDict[valsUniq[j]] = list; 16 | } 17 | console.log(newDict); 18 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/102-concat.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const fs = require('fs'); 3 | 4 | const fArg = fs.readFileSync(process.argv[2]).toString(); 5 | const sArg = fs.readFileSync(process.argv[3]).toString(); 6 | fs.writeFileSync(process.argv[4], fArg + sArg); 7 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/2-rectangle.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | class Rectangle { 3 | constructor (w, h) { 4 | if ((w > 0) && (h > 0)) { 5 | this.width = w; 6 | this.height = h; 7 | } 8 | } 9 | } 10 | 11 | module.exports = Rectangle; 12 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/3-rectangle.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | class Rectangle { 3 | constructor (w, h) { 4 | if ((w > 0) && (h > 0)) { 5 | this.width = w; 6 | this.height = h; 7 | } 8 | } 9 | 10 | print () { 11 | for (let i = 0; i < this.height; i++) { 12 | let s = ''; 13 | for (let j = 0; j < this.width; j++) { 14 | s += 'X'; 15 | } 16 | console.log(s); 17 | } 18 | } 19 | } 20 | 21 | module.exports = Rectangle; 22 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/4-rectangle.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | class Rectangle { 3 | constructor (w, h) { 4 | if ((w > 0) && (h > 0)) { 5 | this.width = w; 6 | this.height = h; 7 | } 8 | } 9 | 10 | print () { 11 | for (let i = 0; i < this.height; i++) { 12 | let s = ''; 13 | for (let j = 0; j < this.width; j++) { 14 | s += 'X'; 15 | } 16 | console.log(s); 17 | } 18 | } 19 | 20 | rotate () { 21 | const aux = this.width; 22 | this.width = this.height; 23 | this.height = aux; 24 | } 25 | 26 | double () { 27 | this.width *= 2; 28 | this.height *= 2; 29 | } 30 | } 31 | 32 | module.exports = Rectangle; 33 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/5-square.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const Rectangle = require('./4-rectangle'); 3 | 4 | class Square extends Rectangle { 5 | constructor (size) { 6 | super(size, size); 7 | } 8 | } 9 | 10 | module.exports = Square; 11 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/6-square.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const SquareP = require('./5-square'); 3 | 4 | class Square extends SquareP { 5 | charPrint (c) { 6 | if (c === undefined) { 7 | c = 'X'; 8 | } 9 | for (let i = 0; i < this.height; i++) { 10 | let s = ''; 11 | for (let j = 0; j < this.width; j++) { 12 | s += c; 13 | } 14 | console.log(s); 15 | } 16 | } 17 | } 18 | 19 | module.exports = Square; 20 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/7-occurrences.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | exports.nbOccurences = function (list, searchElement) { 3 | let nOccurrences = 0; 4 | for (let i = 0; i < list.length; i++) { 5 | if (searchElement === list[i]) { 6 | nOccurrences++; 7 | } 8 | } 9 | return nOccurrences; 10 | }; 11 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/8-esrever.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | exports.esrever = function (list) { 3 | let len = list.length - 1; 4 | let i = 0; 5 | while ((len - i) > 0) { 6 | const aux = list[len]; 7 | list[len] = list[i]; 8 | list[i] = aux; 9 | i++; 10 | len--; 11 | } 12 | return list; 13 | }; 14 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/9-logme.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | let narg = 0; 3 | 4 | exports.logMe = function (item) { 5 | console.log(narg + ': ' + item); 6 | narg++; 7 | }; 8 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/0-readme.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const fs = require('fs'); 3 | fs.readFile(process.argv[2], 'utf8', function (error, content) { 4 | console.log(error || content); 5 | }); 6 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/1-writeme.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const fs = require('fs'); 3 | fs.writeFile(process.argv[2], process.argv[3], error => { 4 | if (error) console.log(error); 5 | }); 6 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/100-starwars_characters.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | const req = require('request'); 4 | const id = process.argv[2]; 5 | const url = 'https://swapi-api.hbtn.io/api/films/'; 6 | req.get(url + id, function (error, res, body) { 7 | if (error) { 8 | console.log(error); 9 | } 10 | const data = JSON.parse(body); 11 | const dd = data.characters; 12 | for (const i of dd) { 13 | req.get(i, function (error, res, body1) { 14 | if (error) { 15 | console.log(error); 16 | } 17 | const data1 = JSON.parse(body1); 18 | console.log(data1.name); 19 | }); 20 | } 21 | }); 22 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/101-starwars_characters.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const request = require('request'); 3 | const url = 'https://swapi-api.hbtn.io/api/films/' + process.argv[2]; 4 | request(url, function (error, response, body) { 5 | if (!error) { 6 | const characters = JSON.parse(body).characters; 7 | printCharacters(characters, 0); 8 | } 9 | }); 10 | 11 | function printCharacters (characters, index) { 12 | request(characters[index], function (error, response, body) { 13 | if (!error) { 14 | console.log(JSON.parse(body).name); 15 | if (index + 1 < characters.length) { 16 | printCharacters(characters, index + 1); 17 | } 18 | } 19 | }); 20 | } 21 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/2-statuscode.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const request = require('request'); 3 | request.get(process.argv[2]).on('response', function (response) { 4 | console.log(`code: ${response.statusCode}`); 5 | }); 6 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/3-starwars_title.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const request = require('request'); 3 | let url = 'http://swapi.co/api/films/' + process.argv[2]; 4 | request(url, function (error, response, body) { 5 | console.log(error || JSON.parse(body).title); 6 | }); 7 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/4-starwars_count.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const request = require('request'); 3 | request(process.argv[2], function (error, response, body) { 4 | if (!error) { 5 | const results = JSON.parse(body).results; 6 | console.log(results.reduce((count, movie) => { 7 | return movie.characters.find((character) => character.endsWith('/18/')) 8 | ? count + 1 9 | : count; 10 | }, 0)); 11 | } 12 | }); 13 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/5-request_store.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const fs = require('fs'); 3 | const request = require('request'); 4 | request(process.argv[2]).pipe(fs.createWriteStream(process.argv[3])); 5 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/6-completed_tasks.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const request = require('request'); 3 | request(process.argv[2], function (error, response, body) { 4 | if (!error) { 5 | const todos = JSON.parse(body); 6 | let completed = {}; 7 | todos.forEach((todo) => { 8 | if (todo.completed && completed[todo.userId] === undefined) { 9 | completed[todo.userId] = 1; 10 | } else if (todo.completed) { 11 | completed[todo.userId] += 1; 12 | } 13 | }); 14 | console.log(completed); 15 | } 16 | }); 17 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/README.md: -------------------------------------------------------------------------------- 1 | # 0x14. Javascript - Web scraping 2 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/0-script.js: -------------------------------------------------------------------------------- 1 | document.querySelector('HEADER').style.color = '#FF0000'; 2 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/1-script.js: -------------------------------------------------------------------------------- 1 | $('HEADER').css('color', '#FF0000'); 2 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/100-script.js: -------------------------------------------------------------------------------- 1 | document.addEventListener('DOMContentLoaded', function () { 2 | document.querySelector('HEADER').style.color = '#FF0000'; 3 | }); 4 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/101-script.js: -------------------------------------------------------------------------------- 1 | $('document').ready(function () { 2 | $('DIV#add_item').click(function () { 3 | $('UL.my_list').append('
  • Item
  • '); 4 | }); 5 | $('DIV#remove_item').click(function () { 6 | $('UL.my_list li:last').remove(); 7 | }); 8 | $('DIV#clear_list').click(function () { 9 | $('UL.my_list').empty(); 10 | }); 11 | }); 12 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/102-script.js: -------------------------------------------------------------------------------- 1 | $('document').ready(function () { 2 | const url = 'https://www.fourtonfish.com/hellosalut/?'; 3 | $('INPUT#btn_translate').click(function () { 4 | $.get(url + $.param({ lang: $('INPUT#language_code').val() }), function (data) { 5 | $('DIV#hello').html(data.hello); 6 | }); 7 | }); 8 | }); 9 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/103-script.js: -------------------------------------------------------------------------------- 1 | $('document').ready(function () { 2 | $('INPUT#btn_translate').click(translate); 3 | $('INPUT#language_code').focus(function () { 4 | $(this).keydown(function (e) { 5 | if (e.keyCode === 13) { 6 | translate(); 7 | } 8 | }); 9 | }); 10 | }); 11 | 12 | function translate () { 13 | const url = 'https://www.fourtonfish.com/hellosalut/?'; 14 | $.get(url + $.param({ lang: $('INPUT#language_code').val() }), function (data) { 15 | $('DIV#hello').html(data.hello); 16 | }); 17 | } 18 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/2-script.js: -------------------------------------------------------------------------------- 1 | $('DIV#red_header').click(function () { 2 | $('HEADER').css('color', '#FF0000'); 3 | }); 4 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/3-script.js: -------------------------------------------------------------------------------- 1 | $('DIV#red_header').click(function () { 2 | $('HEADER').addClass('red'); 3 | }); 4 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/4-script.js: -------------------------------------------------------------------------------- 1 | $('DIV#toggle_header').click(function () { 2 | $('HEADER').toggleClass('green red'); 3 | }); 4 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/5-script.js: -------------------------------------------------------------------------------- 1 | $('DIV#add_item').click(function () { 2 | $('UL.my_list').append('
  • Item
  • '); 3 | }); 4 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/6-script.js: -------------------------------------------------------------------------------- 1 | $('DIV#update_header').click(function () { 2 | $('HEADER').text('New Header!!!'); 3 | }); 4 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/7-script.js: -------------------------------------------------------------------------------- 1 | $.get('https://swapi.co/api/people/5/?format=json', function (data) { 2 | $('DIV#character').text(data.name); 3 | }); 4 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/8-script.js: -------------------------------------------------------------------------------- 1 | $.get('https://swapi.co/api/films/?format=json', function (data) { 2 | $('UL#list_movies').append(...data.results.map(movie => `
  • ${movie.title}
  • `)); 3 | }); 4 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/9-script.js: -------------------------------------------------------------------------------- 1 | $('document').ready(function () { 2 | $.get('https://fourtonfish.com/hellosalut/?lang=fr', function (data) { 3 | $('DIV#hello').text(data.hello); 4 | }); 5 | }); 6 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/README.md: -------------------------------------------------------------------------------- 1 | # 0x15-javascript-web_jquery 2 | --------------------------------------------------------------------------------