├── 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 ├── 100-print_tebahpla.py ├── 101-remove_char_at.py ├── 102-magic_calculation.py ├── 11-pow.py ├── 12-fizzbuzz.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 ├── 8-uppercase.py ├── 9-print_last_digit.py ├── README.md └── lists.h ├── 0x02-python-import_modules ├── 0-add.py ├── 0-import_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 ├── hidden_4.pyc └── variable_load_5.py ├── 0x03-python-data_structures ├── 0-main.py ├── 0-print_list_integer.py ├── 1-element_at.py ├── 1-main.py ├── 10-divisible_by_2.py ├── 10-main.py ├── 100-print_python_list_info.c ├── 11-delete_at.py ├── 11-main.py ├── 12-switch.py ├── 13-is_palindrome.c ├── 13-main.c ├── 2-main.py ├── 2-replace_in_list.py ├── 3-main.py ├── 3-print_reversed_list_integer.py ├── 4-main.py ├── 4-new_in_list.py ├── 5-main.py ├── 5-no_c.py ├── 6-main.py ├── 6-print_matrix_integer.py ├── 7-add_tuple.py ├── 7-main.py ├── 8-main.py ├── 8-multiple_returns.py ├── 9-main.py ├── 9-max_integer.py ├── README.md ├── linked_lists.c └── 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 ├── 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 ├── 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 ├── 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 ├── 2-matrix_divided.txt ├── 3-say_my_name.py ├── 4-print_square.py ├── 5-text_indentation.py ├── README.md ├── __pycache__ │ ├── 0-add_integer.cpython-38.pyc │ ├── 100-matrix_mul.cpython-38.pyc │ ├── 101-lazy_matrix_mul.cpython-38.pyc │ └── 2-matrix_divided.cpython-38.pyc └── tests │ ├── 0-add_integer.txt │ ├── 100-matrix_mul.txt │ ├── 101-lazy_matrix_mul.txt │ ├── 2-matrix_divided.txt │ ├── 3-say_my_name.txt │ ├── 4-print_square.txt │ ├── 5-text_indentation.txt │ ├── 6-max_integer_test.py │ └── __pycache__ │ └── 6-max_integer_test.cpython-38.pyc ├── 0x08-python-more_classes ├── 0-main.py ├── 0-rectangle.py ├── 1-main.py ├── 1-rectangle.py ├── 101-nqueens.py ├── 2-main.py ├── 2-rectangle.py ├── 3-main.py ├── 3-rectangle.py ├── 4-main.py ├── 4-rectangle.py ├── 5-main.py ├── 5-rectangle.py ├── 6-main.py ├── 6-rectangle.py ├── 7-main.py ├── 7-rectangle.py ├── 8-main.py ├── 8-rectangle.py ├── 9-main.py ├── 9-rectangle.py ├── README.md └── __pycache__ │ ├── 0-rectangle.cpython-310.pyc │ ├── 1-rectangle.cpython-310.pyc │ ├── 2-rectangle.cpython-310.pyc │ ├── 3-rectangle.cpython-310.pyc │ ├── 4-rectangle.cpython-310.pyc │ ├── 5-rectangle.cpython-310.pyc │ ├── 6-rectangle.cpython-310.pyc │ ├── 7-rectangle.cpython-310.pyc │ ├── 8-rectangle.cpython-310.pyc │ └── 9-rectangle.cpython-310.pyc ├── 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 ├── 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 │ ├── 1-my_list.txt │ └── 7-base_geometry.txt ├── 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 └── my_file_0.txt ├── 0x0C-python-almost_a_circle ├── Project_manual │ ├── 21.txt │ └── README.md ├── README.md ├── main_files │ ├── 0-main.py │ ├── 1-main.py │ ├── 10-main.py │ ├── 11-main.py │ ├── 12-main.py │ ├── 13-main.py │ ├── 14-main.py │ ├── 15-main.py │ ├── 16-main.py │ ├── 17-main.py │ ├── 18-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 │ ├── Rectangle.json │ └── Square.json ├── models │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-34.pyc │ │ ├── __init__.cpython-38.pyc │ │ ├── base.cpython-34.pyc │ │ ├── base.cpython-38.pyc │ │ ├── rectangle.cpython-34.pyc │ │ ├── rectangle.cpython-38.pyc │ │ ├── square.cpython-34.pyc │ │ └── square.cpython-38.pyc │ ├── base.py │ ├── rectangle.py │ └── square.py └── tests │ ├── __init__.py │ └── test_models │ ├── __init__.py │ ├── __pycache__ │ ├── __init__.cpython-34.pyc │ ├── __init__.cpython-38.pyc │ ├── test_base.cpython-34.pyc │ ├── test_base.cpython-38.pyc │ ├── test_rectangle.cpython-34.pyc │ ├── test_rectangle.cpython-38.pyc │ └── test_square.cpython-38.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 ├── 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 ├── 0-select_states.sql ├── 1-filter_states.py ├── 10-model_state_my_get.py ├── 100-relationship_states_cities.py ├── 100-relationship_states_cities.sql ├── 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 ├── 14-model_city_fetch_by_state.sql ├── 2-my_filter_states.py ├── 3-my_safe_filter_states.py ├── 4-cities_by_state.py ├── 4-cities_by_state.sql ├── 5-filter_cities.py ├── 6-model_state.py ├── 6-model_state.sql ├── 7-model_state_fetch_all.py ├── 7-model_state_fetch_all.sql ├── 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 ├── 101-starwars.py ├── 102-starwars.py ├── 103-search_twitter.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 ├── 9-starwars.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-data.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 ├── README.md └── python-tests_1 ├── 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 ├── __pycache__ └── 6-max_integer.cpython-38.pyc ├── besthor.txt ├── main.c ├── python.h └── tests ├── 0-add_integer.txt ├── 100-matrix_mul.txt ├── 101-lazy_matrix_mul.txt ├── 2-matrix_divided.txt ├── 3-say_my_name.txt ├── 4-print_square.txt ├── 5-text_indentation.txt ├── 6-max_integer_test.py └── __pycache__ └── 6-max_integer_test.cpython-38.pyc /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/README.md: -------------------------------------------------------------------------------- 1 | # `INTRODUCTION TO PYTHON` 2 | 3 | ## My First Python Program 4 | 5 | 6 | ![](https://wollen.org/blog/wp-content/uploads/2021/04/hello_world_title3.gif) 7 | -------------------------------------------------------------------------------- /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} is positive") 6 | elif number == 0: 7 | print(f"{number} is zero") 8 | else: 9 | print(f"{number} 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 | if number < 0: 5 | lastdigit = number % -10 6 | else: 7 | lastdigit = number % 10 8 | if lastdigit > 5: 9 | print("Last digit of {:d} is {:d} and is greater than 5" 10 | .format(number, lastdigit)) 11 | elif lastdigit < 6 and lastdigit != 0: 12 | print("Last digit of {:d} is {:d} and is less than 6 and not 0" 13 | .format(number, lastdigit)) 14 | else: 15 | print("Last digit of {:d} is 0 and is 0".format(number)) 16 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/10-add.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def add(a, b): 3 | return (a + b) 4 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/100-print_tebahpla.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for i in range(ord('z'), ord('a') - 1, -1): 3 | if i % 2 == 0: 4 | diff = 0 5 | else: 6 | diff = 32 7 | print('{}'.format(chr(i - diff)), end='') 8 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/101-remove_char_at.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def remove_char_at(str, n): 3 | if n < 0: 4 | return (str) 5 | return (str[:n] + str[n+1:]) 6 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/102-magic_calculation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def magic_calculation(a, b, c): 3 | if a < b: 4 | return (c) 5 | if c > b: 6 | return (a + b) 7 | return (a*b - c) 8 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/11-pow.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def pow(a, b): 3 | return (a ** b) 4 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/12-fizzbuzz.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def fizzbuzz(): 3 | for number in range(1, 101): 4 | if number % 3 == 0 and number % 5 == 0: 5 | print("FizzBuzz ", end="") 6 | elif number % 3 == 0: 7 | print("Fizz ", end="") 8 | elif number % 5 == 0: 9 | print("Buzz ", end="") 10 | else: 11 | print("{} ".format(number), end="") 12 | -------------------------------------------------------------------------------- /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 | * Return: 0 If the function fails or pointer to the new node. 8 | */ 9 | listint_t *insert_node(listint_t **head, int number) 10 | { 11 | listint_t *node = *head, *new; 12 | 13 | new = malloc(sizeof(listint_t)); 14 | if (new == NULL) 15 | return (NULL); 16 | new->n = number; 17 | 18 | if (node == NULL || node->n >= number) 19 | { 20 | new->next = node; 21 | *head = new; 22 | return (new); 23 | } 24 | 25 | while (node && node->next && node->next->n < number) 26 | node = node->next; 27 | 28 | new->next = node->next; 29 | node->next = new; 30 | 31 | return (new); 32 | } -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/2-print_alphabet.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for i in range(ord('a'), ord('z') + 1): 3 | print('{:c}'.format(i), end='') 4 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/3-print_alphabt.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for i in range(ord('a'), ord('z') + 1): 3 | if chr(i) != 'e' and chr(i) != 'q': 4 | print('{:c}'.format(i), end='') 5 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/4-print_hexa.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for num in range(0, 99): 3 | print('{} = 0x{:x}'.format(num, num)) 4 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/5-print_comb2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for num in range(0, 99): 3 | print('{:02d}, '.format(num), end='') 4 | print('99') 5 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/6-print_comb3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for x in range(0, 10): 3 | for y in range(x + 1, 10): 4 | if x == 8 and y == 9: 5 | print('89') 6 | else: 7 | print('{}{}, '.format(x, y), end='') 8 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/7-islower.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def islower(c): 3 | if ord(c) >= 97 and ord(c) <= 122: 4 | return True 5 | else: 6 | return False 7 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/8-uppercase.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def uppercase(str): 3 | for i in str: 4 | if ord(i) >= 97 and ord(i) <= 122: 5 | i = chr(ord(i) - 32) 6 | print("{}".format(i), end="") 7 | print() 8 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/9-print_last_digit.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def print_last_digit(number): 3 | if number < 0: 4 | last_digit = number % -(10) 5 | print(-(last_digit), end='') 6 | else: 7 | last_digit = number % 10 8 | print(last_digit, end='') 9 | return abs(last_digit) 10 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/README.md: -------------------------------------------------------------------------------- 1 | # Solution to tasks on conditionals & loops 2 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/lists.h: -------------------------------------------------------------------------------- 1 | #ifndef LISTS_H 2 | #define LISTS_H 3 | 4 | #include 5 | /** 6 | * struct listint_s - singly linked list 7 | * @n: integer 8 | * @next: points to the next node 9 | * 10 | * Description: singly linked list node structure 11 | * 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 | 23 | listint_t *insert_node(listint_t **head, int number); 24 | 25 | #endif /* LISTS_H */ -------------------------------------------------------------------------------- /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/0-import_add.py: -------------------------------------------------------------------------------- 1 | __import__("0-add") 2 | -------------------------------------------------------------------------------- /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/README.md: -------------------------------------------------------------------------------- 1 | General 2 | 3 | Why Python programming is awesome 4 | 5 | How to import functions from another file 6 | 7 | How to use imported functions 8 | 9 | How to create a module 10 | 11 | How to use the built-in function dir() 12 | 13 | How to prevent code in your script from being executed when imported 14 | 15 | How to use command line arguments with your Python programs 16 | -------------------------------------------------------------------------------- /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 | 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 | 14 | 15 | def sub(a, b): 16 | """My subtraction function 17 | 18 | Args: 19 | a: first integer 20 | b: second integer 21 | 22 | Returns: 23 | The return value. a - b 24 | """ 25 | return (a - b) 26 | 27 | 28 | def mul(a, b): 29 | """My multiplication function 30 | 31 | Args: 32 | a: first integer 33 | b: second integer 34 | 35 | Returns: 36 | The return value. a * b 37 | """ 38 | return (a * b) 39 | 40 | 41 | def div(a, b): 42 | """My division function 43 | 44 | Args: 45 | a: first integer 46 | b: second integer 47 | 48 | Returns: 49 | The return value. a / b 50 | """ 51 | return int(a / b) 52 | -------------------------------------------------------------------------------- /0x02-python-import_modules/hidden_4.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/0x02-python-import_modules/hidden_4.pyc -------------------------------------------------------------------------------- /0x02-python-import_modules/variable_load_5.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | a = 98 3 | """Simple variable 4 | """ -------------------------------------------------------------------------------- /0x03-python-data_structures/0-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | print_list_integer = __import__('0-print_list_integer').print_list_integer 3 | 4 | my_list = [1, 2, 3, 4, 5] 5 | print_list_integer(my_list) 6 | -------------------------------------------------------------------------------- /0x03-python-data_structures/0-print_list_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def print_list_integer(my_list=[]): 4 | for i in my_list: 5 | print('{:d}'.format(i)) 6 | -------------------------------------------------------------------------------- /0x03-python-data_structures/1-element_at.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def element_at(my_list, idx): 4 | if idx < 0 or idx >= len(my_list): 5 | return ("None") 6 | else: 7 | return my_list[idx] 8 | -------------------------------------------------------------------------------- /0x03-python-data_structures/1-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | element_at = __import__('1-element_at').element_at 3 | 4 | my_list = [1, 2, 3, 4, 5] 5 | idx = 3 6 | print("Element at index {:d} is {}".format(idx, element_at(my_list, idx))) 7 | -------------------------------------------------------------------------------- /0x03-python-data_structures/10-divisible_by_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def divisible_by_2(my_list=[]): 4 | new_list = [] 5 | 6 | for i in my_list: 7 | if i % 2 == 0: 8 | new_list.append(True) 9 | else: 10 | new_list.append(False) 11 | return (new_list) 12 | -------------------------------------------------------------------------------- /0x03-python-data_structures/10-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | divisible_by_2 = __import__('10-divisible_by_2').divisible_by_2 3 | 4 | my_list = [0, 1, 2, 3, 4, 5, 6] 5 | list_result = divisible_by_2(my_list) 6 | 7 | i = 0 8 | while i < len(list_result): 9 | print("{:d} {:s} divisible by 2".format(my_list[i], "is" if list_result[i] else "is not")) 10 | i += 1 11 | -------------------------------------------------------------------------------- /0x03-python-data_structures/100-print_python_list_info.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | /** 6 | * print_python_list_info - prints some basic info about pytohn list 7 | * @p: python object 8 | **/ 9 | 10 | void print_python_list_info(PyObject *p) 11 | { 12 | long int size = PyList_Size(p); 13 | int i; 14 | PyListObject *obj = (PyListObject *)p; 15 | 16 | printf("[*] Size of the Python List = %li\n", size); 17 | printf("[*] Allocated = %li\n", obj->allocated); 18 | for (i = 0; i < size; i++) 19 | printf("Element %i: %s\n", i, Py_TYPE(obj->ob_item[i])->tp_name); 20 | } 21 | -------------------------------------------------------------------------------- /0x03-python-data_structures/11-delete_at.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def delete_at(my_list=[], idx=0): 4 | if 0 <= idx < len(my_list): 5 | del(my_list[idx]) 6 | return (my_list) 7 | -------------------------------------------------------------------------------- /0x03-python-data_structures/11-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | delete_at = __import__('11-delete_at').delete_at 3 | 4 | my_list = [1, 2, 3, 4, 5] 5 | idx = 3 6 | new_list = delete_at(my_list, idx) 7 | print(new_list) 8 | print(my_list) 9 | -------------------------------------------------------------------------------- /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 | * Return: pointer to the first node in the new list 7 | */ 8 | void reverse_listint(listint_t **head) 9 | { 10 | listint_t *prev = NULL; 11 | listint_t *current = *head; 12 | listint_t *next = NULL; 13 | 14 | while (current) 15 | { 16 | next = current->next; 17 | current->next = prev; 18 | prev = current; 19 | current = next; 20 | } 21 | 22 | *head = prev; 23 | } 24 | 25 | /** 26 | * is_palindrome - checks if a linked list is a palindrome 27 | * @head: double pointer to the linked list 28 | * 29 | * Return: 1 if it is, 0 if not 30 | */ 31 | int is_palindrome(listint_t **head) 32 | { 33 | listint_t *slow = *head, *fast = *head, *temp = *head, *dup = NULL; 34 | 35 | if (*head == NULL || (*head)->next == NULL) 36 | return (1); 37 | 38 | while (1) 39 | { 40 | fast = fast->next->next; 41 | if (!fast) 42 | { 43 | dup = slow->next; 44 | break; 45 | } 46 | if (!fast->next) 47 | { 48 | dup = slow->next->next; 49 | break; 50 | } 51 | slow = slow->next; 52 | } 53 | 54 | reverse_listint(&dup); 55 | 56 | while (dup && temp) 57 | { 58 | if (temp->n == dup->n) 59 | { 60 | dup = dup->next; 61 | temp = temp->next; 62 | } 63 | else 64 | return (0); 65 | } 66 | 67 | if (!dup) 68 | return (1); 69 | 70 | return (0); 71 | } 72 | -------------------------------------------------------------------------------- /0x03-python-data_structures/13-main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "lists.h" 4 | 5 | /** 6 | * main - check the code for 7 | * 8 | * Return: Always 0. 9 | */ 10 | int main(void) 11 | { 12 | listint_t *head; 13 | 14 | head = NULL; 15 | add_nodeint_end(&head, 1); 16 | add_nodeint_end(&head, 17); 17 | add_nodeint_end(&head, 972); 18 | add_nodeint_end(&head, 50); 19 | add_nodeint_end(&head, 98); 20 | add_nodeint_end(&head, 98); 21 | add_nodeint_end(&head, 50); 22 | add_nodeint_end(&head, 972); 23 | add_nodeint_end(&head, 17); 24 | add_nodeint_end(&head, 1); 25 | print_listint(head); 26 | 27 | if (is_palindrome(&head) == 1) 28 | printf("Linked list is a palindrome\n"); 29 | else 30 | printf("Linked list is not a palindrome\n"); 31 | 32 | free_listint(head); 33 | 34 | return (0); 35 | } -------------------------------------------------------------------------------- /0x03-python-data_structures/2-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | replace_in_list = __import__('2-replace_in_list').replace_in_list 3 | 4 | my_list = [1, 2, 3, 4, 5] 5 | idx = 3 6 | new_element = 9 7 | new_list = replace_in_list(my_list, idx, new_element) 8 | 9 | print(new_list) 10 | print(my_list) -------------------------------------------------------------------------------- /0x03-python-data_structures/2-replace_in_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def replace_in_list(my_list, idx, element): 4 | if idx < 0 or idx >= len(my_list): 5 | return (my_list) 6 | else: 7 | my_list[idx] = element 8 | return (my_list) 9 | -------------------------------------------------------------------------------- /0x03-python-data_structures/3-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | print_reversed_list_integer = __import__('3-print_reversed_list_integer').print_reversed_list_integer 3 | 4 | my_list = [1, 2, 3, 4, 5] 5 | print_reversed_list_integer(my_list) -------------------------------------------------------------------------------- /0x03-python-data_structures/3-print_reversed_list_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def print_reversed_list_integer(my_list=[]): 4 | 5 | if my_list: 6 | for i in reversed(my_list): 7 | print('{:d}'.format(i)) 8 | -------------------------------------------------------------------------------- /0x03-python-data_structures/4-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | new_in_list = __import__('4-new_in_list').new_in_list 3 | 4 | my_list = [1, 2, 3, 4, 5] 5 | idx = 3 6 | new_element = 9 7 | new_list = new_in_list(my_list, idx, new_element) 8 | 9 | print(new_list) 10 | print(my_list) 11 | -------------------------------------------------------------------------------- /0x03-python-data_structures/4-new_in_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def new_in_list(my_list, idx, element): 4 | if my_list: 5 | if idx < 0 or idx >= len(my_list): 6 | return my_list 7 | else: 8 | new_list = my_list.copy() 9 | new_list[idx] = element 10 | return new_list 11 | -------------------------------------------------------------------------------- /0x03-python-data_structures/5-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | no_c = __import__('5-no_c').no_c 3 | 4 | print(no_c("Best School")) 5 | print(no_c("Chicago")) 6 | print(no_c("C is fun!")) -------------------------------------------------------------------------------- /0x03-python-data_structures/5-no_c.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def no_c(my_string): 4 | updated_str = '' 5 | for i in my_string: 6 | if i != 'c' and i != 'C': 7 | updated_str += i 8 | return (updated_str) 9 | -------------------------------------------------------------------------------- /0x03-python-data_structures/6-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | print_matrix_integer = __import__('6-print_matrix_integer').print_matrix_integer 3 | 4 | matrix = [ 5 | [1, 2, 3], 6 | [4, 5, 6], 7 | [7, 8, 9] 8 | ] 9 | 10 | print_matrix_integer(matrix) 11 | print("--") 12 | print_matrix_integer() 13 | -------------------------------------------------------------------------------- /0x03-python-data_structures/6-print_matrix_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def print_matrix_integer(matrix=[[]]): 4 | for row in matrix: 5 | for column in row: 6 | if column == row[-1]: 7 | print('{:d}'.format(column), end='') 8 | else: 9 | print('{:d}'.format(column), end=' ') 10 | print() 11 | -------------------------------------------------------------------------------- /0x03-python-data_structures/7-add_tuple.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def add_tuple(tuple_a=(), tuple_b=()): 4 | if len(tuple_a) < 2: 5 | if len(tuple_a) == 0: 6 | tuple_a = 0, 0 7 | else: 8 | tuple_a = tuple_a[0], 0 9 | 10 | if len(tuple_b) < 2: 11 | if len(tuple_b) == 0: 12 | tuple_b = 0, 0 13 | else: 14 | tuple_b = tuple_b[0], 0 15 | 16 | added_tuple = tuple_a[0] + tuple_b[0], tuple_a[1] + tuple_b[1] 17 | return added_tuple 18 | -------------------------------------------------------------------------------- /0x03-python-data_structures/7-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | add_tuple = __import__('7-add_tuple').add_tuple 3 | 4 | tuple_a = (1, 89) 5 | tuple_b = (88, 11) 6 | new_tuple = add_tuple(tuple_a, tuple_b) 7 | print(new_tuple) 8 | 9 | print(add_tuple(tuple_a, (1, ))) 10 | print(add_tuple(tuple_a, ())) -------------------------------------------------------------------------------- /0x03-python-data_structures/8-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | multiple_returns = __import__('8-multiple_returns').multiple_returns 3 | 4 | sentence = "At school, I learnt C!" 5 | length, first = multiple_returns(sentence) 6 | print("Length: {:d} - First character: {}".format(length, first)) -------------------------------------------------------------------------------- /0x03-python-data_structures/8-multiple_returns.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def multiple_returns(sentence): 4 | if sentence != '': 5 | first_char = sentence[0] 6 | else: 7 | first_char = None 8 | return (len(sentence), first_char) 9 | -------------------------------------------------------------------------------- /0x03-python-data_structures/9-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | max_integer = __import__('9-max_integer').max_integer 3 | 4 | my_list = [1, 90, 2, 13, 34, 5, -13, 3] 5 | max_value = max_integer(my_list) 6 | print("Max: {}".format(max_value)) 7 | -------------------------------------------------------------------------------- /0x03-python-data_structures/9-max_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def max_integer(my_list=[]): 4 | if len(my_list) == 0: 5 | return (None) 6 | else: 7 | max_int = my_list[0] 8 | for i in range(len(my_list)): 9 | if my_list[i] > max_int: 10 | max_int = my_list[i] 11 | return (max_int) 12 | -------------------------------------------------------------------------------- /0x03-python-data_structures/README.md: -------------------------------------------------------------------------------- 1 | General 2 | 3 | Why Python programming is awesome 4 | 5 | What are lists and how to use them 6 | 7 | What are the differences and similarities between strings and lists 8 | 9 | What are the most common methods of lists and how to use them 10 | 11 | How to use lists as stacks and queues 12 | 13 | What are list comprehensions and how to use them 14 | 15 | What are tuples and how to use them 16 | 17 | When to use tuples versus lists 18 | 19 | What is a sequence 20 | 21 | What is tuple packing 22 | 23 | What is sequence unpacking 24 | 25 | What is the del statement and how to use it 26 | -------------------------------------------------------------------------------- /0x03-python-data_structures/lists.h: -------------------------------------------------------------------------------- 1 | #ifndef LISTS_H 2 | #define LISTS_H 3 | 4 | #include 5 | /** 6 | * struct listint_s - singly linked list 7 | * @n: integer 8 | * @next: points to the next node 9 | * 10 | * Description: singly linked list node structure 11 | * for project 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 | 23 | int is_palindrome(listint_t **head); 24 | 25 | #endif /* LISTS_H */ -------------------------------------------------------------------------------- /0x04-python-more_data_structures/0-square_matrix_simple.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def square_matrix_simple(matrix=[]): 3 | """computes the square value of all integers of a matrix.""" 4 | if not matrix: 5 | return None 6 | 7 | return list(list(map(lambda a: a*a, num_list)) for num_list in matrix) 8 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/1-search_replace.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def search_replace(my_list, search, replace): 3 | if not my_list: 4 | return my_list 5 | return [val if val != search else replace for val in my_list] 6 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/10-best_score.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def best_score(a_dictionary): 3 | """returns a key with the biggest integer value.""" 4 | if not a_dictionary: 5 | return None 6 | return max(a_dictionary, key=a_dictionary.get) 7 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/100-weight_average.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def weight_average(my_list=[]): 3 | """ returns the weighted average""" 4 | """ of all integers tuple (, )""" 5 | if not my_list: 6 | return 0 7 | 8 | num = 0 9 | den = 0 10 | 11 | for tup in my_list: 12 | num += tup[0] * tup[1] 13 | den += tup[1] 14 | 15 | return (num / den) 16 | -------------------------------------------------------------------------------- /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 y: y**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 | list_keys = list(a_dictionary.keys()) 4 | 5 | for value_dic in list_keys: 6 | if value == a_dictionary.get(value_dic): 7 | del a_dictionary[value_dic] 8 | 9 | return (a_dictionary) 10 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/103-python.c: -------------------------------------------------------------------------------- 1 | #include "/usr/include/python3.4/Python.h" 2 | #include 3 | 4 | void print_hexn(const char *str, int n) 5 | { 6 | int i = 0; 7 | 8 | for (; i < n - 1; ++i) 9 | printf("%02x ", (unsigned char) str[i]); 10 | 11 | printf("%02x", str[i]); 12 | } 13 | 14 | void print_python_bytes(PyObject *p) 15 | { 16 | PyBytesObject *clone = (PyBytesObject *) p; 17 | int calc_bytes, clone_size = 0; 18 | 19 | printf("[.] bytes object info\n"); 20 | if (PyBytes_Check(clone)) 21 | { 22 | clone_size = PyBytes_Size(p); 23 | calc_bytes = clone_size + 1; 24 | 25 | if (calc_bytes >= 10) 26 | calc_bytes = 10; 27 | 28 | printf(" size: %d\n", clone_size); 29 | printf(" trying string: %s\n", clone->ob_sval); 30 | printf(" first %d bytes: ", calc_bytes); 31 | print_hexn(clone->ob_sval, calc_bytes); 32 | printf("\n"); 33 | } 34 | else 35 | { 36 | printf(" [ERROR] Invalid Bytes Object\n"); 37 | } 38 | } 39 | 40 | void print_python_list(PyObject *p) 41 | { 42 | int i = 0, list_len = 0; 43 | PyObject *item; 44 | PyListObject *clone = (PyListObject *) p; 45 | 46 | printf("[*] Python list info\n"); 47 | list_len = PyList_GET_SIZE(p); 48 | printf("[*] Size of the Python List = %d\n", list_len); 49 | printf("[*] Allocated = %d\n", (int) clone->allocated); 50 | 51 | for (; i < list_len; ++i) 52 | { 53 | item = PyList_GET_ITEM(p, i); 54 | printf("Element %d: %s\n", i, item->ob_type->tp_name); 55 | 56 | if (PyBytes_Check(item)) 57 | print_python_bytes(item); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /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 x: x * 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 | """ converts a Roman numeral to an integer.""" 4 | romans = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} 5 | if (roman_string is None) or (type(roman_string) is not str): 6 | return 0 7 | 8 | number = len(roman_string) 9 | value_int = romans[roman_string[number-1]] 10 | for i in range(number - 1, 0, -1): 11 | current_value = romans[roman_string[i]] 12 | previous_value = romans[roman_string[i-1]] 13 | 14 | if previous_value >= current_value: 15 | value_int += previous_value 16 | else: 17 | value_int -= previous_value 18 | 19 | return value_int 20 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/2-uniq_add.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def uniq_add(my_list=[]): 3 | """adds all unique integers in a list (only once for each integer).""" 4 | sum = 0 5 | for i in set(my_list): 6 | sum += i 7 | return sum 8 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/3-common_elements.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def common_elements(set_1, set_2): 3 | """returns a set of common elements in two sets.""" 4 | return (set_1 & set_2) 5 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/4-only_diff_elements.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def only_diff_elements(set_1, set_2): 3 | """returns a set of all elements present in only one set.""" 4 | return (set_1 ^ set_2) 5 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/5-number_keys.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def number_keys(a_dictionary): 3 | """returns the number of keys in a dictionary.""" 4 | return len(a_dictionary.keys()) 5 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/6-print_sorted_dictionary.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def print_sorted_dictionary(a_dictionary): 3 | """prints a dictionary by ordered keys.""" 4 | for key in sorted(a_dictionary.keys()): 5 | print("{}: {}".format(key, a_dictionary[key])) 6 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/7-update_dictionary.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def update_dictionary(a_dictionary, key, value): 3 | """ replaces or adds key/value in a dictionary.""" 4 | a_dictionary[key] = value 5 | return a_dictionary 6 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/8-simple_delete.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def simple_delete(a_dictionary, key=""): 3 | """deletes a key in a dictionary.""" 4 | if key in a_dictionary: 5 | del a_dictionary[key] 6 | return a_dictionary 7 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/9-multiply_by_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def multiply_by_2(a_dictionary): 3 | """returns a new dictionary with""" 4 | """all values multiplied by 2""" 5 | new_dict = {x: (a_dictionary[x] * 2) for x in a_dictionary} 6 | return new_dict 7 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/README.md: -------------------------------------------------------------------------------- 1 | General 2 | 3 | Why Python programming is awesome 4 | 5 | What are sets and how to use them 6 | 7 | What are the most common methods of set and how to use them 8 | 9 | When to use sets versus lists 10 | 11 | How to iterate into a set 12 | 13 | What are dictionaries and how to use them 14 | 15 | When to use dictionaries versus lists or sets 16 | 17 | What is a key in a dictionary 18 | 19 | How to iterate over a dictionary 20 | 21 | What is a lambda function 22 | 23 | What are the map, reduce and filter functions 24 | -------------------------------------------------------------------------------- /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 | Args: 6 | my_list (list): The list to print elements from. 7 | x (int): The number of elements of my_list to print. 8 | Returns: 9 | The number of elements printed. 10 | """ 11 | ret = 0 12 | for i in range(x): 13 | try: 14 | print("{}".format(my_list[i]), end="") 15 | ret += 1 16 | except IndexError: 17 | break 18 | print("") 19 | return (ret) 20 | -------------------------------------------------------------------------------- /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 | Args: 6 | value (int): The integer to print. 7 | Returns: 8 | If a TypeError or ValueError occurs - False. 9 | Otherwise - True. 10 | """ 11 | try: 12 | print("{:d}".format(value)) 13 | return (True) 14 | except (TypeError, ValueError): 15 | return (False) 16 | -------------------------------------------------------------------------------- /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 | If a ValueError message is caught, a corresponding 9 | message is printed to standard error. 10 | Args: 11 | value (int): The integer to print. 12 | Returns: 13 | If a TypeError or ValueError occurs - False. 14 | Otherwise - True. 15 | """ 16 | try: 17 | print("{:d}".format(value)) 18 | return (True) 19 | except (TypeError, ValueError): 20 | print("Exception: {}".format(sys.exc_info()[1]), file=sys.stderr) 21 | return (False) 22 | -------------------------------------------------------------------------------- /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/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 | Args: 6 | my_list (list): The list to print elements from. 7 | x (int): The number of elements of my_list to print. 8 | Returns: 9 | The number of elements printed. 10 | """ 11 | ret = 0 12 | for i in range(0, x): 13 | try: 14 | print("{:d}".format(my_list[i]), end="") 15 | ret += 1 16 | except (ValueError, TypeError): 17 | continue 18 | print("") 19 | return (ret) 20 | -------------------------------------------------------------------------------- /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 | Args: 6 | my_list_1 (list): The first list. 7 | my_list_2 (list): The second list. 8 | list_length (int): The number of elements to divide. 9 | Returns: 10 | A new list of length list_length containing all the divisions. 11 | """ 12 | new_list = [] 13 | for i in range(0, list_length): 14 | try: 15 | div = my_list_1[i] / my_list_2[i] 16 | except TypeError: 17 | print("wrong type") 18 | div = 0 19 | except ZeroDivisionError: 20 | print("division by 0") 21 | div = 0 22 | except IndexError: 23 | print("out of range") 24 | div = 0 25 | finally: 26 | new_list.append(div) 27 | return (new_list) 28 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /0x05-python-exceptions/README.md: -------------------------------------------------------------------------------- 1 | # Python - Exceptions 2 | 3 | # Learning Objectives 4 | At the end of this project, you are expected to be able to explain to anyone, without the help of Google: 5 | 6 | ## General 7 | - Why Python programming is awesome 8 | - What’s the difference between errors and exceptions 9 | - What are exceptions and how to use them 10 | - When do we need to use exceptions 11 | - How to correctly handle an exception 12 | - What’s the purpose of catching exceptions 13 | - How to raise a builtin exception 14 | - When do we need to implement a clean-up action after an exception 15 | 16 | ![](https://files.realpython.com/media/try_except_else_finally.a7fac6c36c55.png) 17 | -------------------------------------------------------------------------------- /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 | Args: 12 | size (int): The size of the new square. 13 | """ 14 | self.__size = size 15 | -------------------------------------------------------------------------------- /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 | Args: 12 | size (int): The size of the new square. 13 | """ 14 | self.size = size 15 | 16 | @property 17 | def size(self): 18 | """Get/set the current size of the square.""" 19 | return (self.__size) 20 | 21 | @size.setter 22 | def size(self, value): 23 | if not isinstance(value, int): 24 | raise TypeError("size must be an integer") 25 | elif value < 0: 26 | raise ValueError("size must be >= 0") 27 | self.__size = value 28 | 29 | def area(self): 30 | """Return the current area of the square.""" 31 | return (self.__size * self.__size) 32 | 33 | def __eq__(self, other): 34 | """Define the == comparision to a Square.""" 35 | return self.area() == other.area() 36 | 37 | def __ne__(self, other): 38 | """Define the != comparison to a Square.""" 39 | return self.area() != other.area() 40 | 41 | def __lt__(self, other): 42 | """Define the < comparison to a Square.""" 43 | return self.area() < other.area() 44 | 45 | def __le__(self, other): 46 | """Define the <= comparison to a Square.""" 47 | return self.area() <= other.area() 48 | 49 | def __gt__(self, other): 50 | """Define the > comparison to a Square.""" 51 | return self.area() > other.area() 52 | 53 | def __ge__(self, other): 54 | """Define the >= compmarison to a Square.""" 55 | return self.area() >= other.area() 56 | -------------------------------------------------------------------------------- /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 | Arg: 14 | radius (float or int): The radius of the new MagicClass. 15 | """ 16 | self.__radius = 0 17 | if type(radius) is not int and type(radius) is not float: 18 | raise TypeError("radius must be a number") 19 | self.__radius = radius 20 | 21 | def area(self): 22 | """Return the area of the MagicClass.""" 23 | return (self.__radius ** 2 * math.pi) 24 | 25 | def circumference(self): 26 | """Return The circumference of the MagicClass.""" 27 | return (2 * math.pi * self.__radius) 28 | -------------------------------------------------------------------------------- /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 | Args: 12 | size (int): The size of the new square. 13 | """ 14 | if not isinstance(size, int): 15 | raise TypeError("size must be an integer") 16 | elif size < 0: 17 | raise ValueError("size must be >= 0") 18 | self.__size = size 19 | -------------------------------------------------------------------------------- /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 | Args: 12 | size (int): The size of the new square. 13 | """ 14 | if not isinstance(size, int): 15 | raise TypeError("size must be an integer") 16 | elif size < 0: 17 | raise ValueError("size must be >= 0") 18 | self.__size = size 19 | 20 | def area(self): 21 | """Return the current area of the square.""" 22 | return (self.__size * self.__size) 23 | -------------------------------------------------------------------------------- /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 | Args: 12 | size (int): The size of the new square. 13 | """ 14 | self.size = size 15 | 16 | @property 17 | def size(self): 18 | """Get/set the current size of the square.""" 19 | return (self.__size) 20 | 21 | @size.setter 22 | def size(self, value): 23 | if not isinstance(value, int): 24 | raise TypeError("size must be an integer") 25 | elif value < 0: 26 | raise ValueError("size must be >= 0") 27 | self.__size = value 28 | 29 | def area(self): 30 | """Return the current area of the square.""" 31 | return (self.__size * self.__size) 32 | -------------------------------------------------------------------------------- /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 | Args: 12 | size (int): The size of the new square. 13 | """ 14 | self.size = size 15 | 16 | @property 17 | def size(self): 18 | """Get/set the current size of the square.""" 19 | return (self.__size) 20 | 21 | @size.setter 22 | def size(self, value): 23 | if not isinstance(value, int): 24 | raise TypeError("size must be an integer") 25 | elif value < 0: 26 | raise ValueError("size must be >= 0") 27 | self.__size = value 28 | 29 | def area(self): 30 | """Return the current area of the square.""" 31 | return (self.__size * self.__size) 32 | 33 | def my_print(self): 34 | """Print the square with the # character.""" 35 | for i in range(0, self.__size): 36 | [print("#", end="") for j in range(self.__size)] 37 | print("") 38 | if self.__size == 0: 39 | print("") 40 | -------------------------------------------------------------------------------- /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/__pycache__/0-add_integer.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/0x07-python-test_driven_development/__pycache__/0-add_integer.cpython-38.pyc -------------------------------------------------------------------------------- /0x07-python-test_driven_development/__pycache__/100-matrix_mul.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/0x07-python-test_driven_development/__pycache__/100-matrix_mul.cpython-38.pyc -------------------------------------------------------------------------------- /0x07-python-test_driven_development/__pycache__/101-lazy_matrix_mul.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/0x07-python-test_driven_development/__pycache__/101-lazy_matrix_mul.cpython-38.pyc -------------------------------------------------------------------------------- /0x07-python-test_driven_development/__pycache__/2-matrix_divided.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/0x07-python-test_driven_development/__pycache__/2-matrix_divided.cpython-38.pyc -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/__pycache__/6-max_integer_test.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/0x07-python-test_driven_development/tests/__pycache__/6-max_integer_test.cpython-38.pyc -------------------------------------------------------------------------------- /0x08-python-more_classes/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/0-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """A class that defines a rectangle""" 3 | 4 | 5 | class Rectangle: 6 | """An empty class that represents a rectangle""" 7 | pass 8 | -------------------------------------------------------------------------------- /0x08-python-more_classes/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/1-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """A class that defines a rectangle""" 3 | 4 | 5 | class Rectangle: 6 | """this represents a rectangle""" 7 | 8 | def __init__(self, width=0, height=0): 9 | """Initializing this rectangle class 10 | Args: 11 | width: represents the width of the rectangle 12 | height: represents the height of the rectangle 13 | Raises: 14 | TypeError: if size is not integer 15 | ValueError: if size is less than zero 16 | """ 17 | self.width = width 18 | self.height = height 19 | 20 | @property 21 | def width(self): 22 | """retrieves width attribute""" 23 | return self.__width 24 | 25 | @width.setter 26 | def width(self, value): 27 | """sets width attribute""" 28 | if not isinstance(value, int): 29 | raise TypeError("width must be an integer") 30 | if value < 0: 31 | raise ValueError("width must be >= 0") 32 | self.__width = value 33 | 34 | @property 35 | def height(self): 36 | """retrieves height attribute""" 37 | return self.__height 38 | 39 | @height.setter 40 | def height(self, value): 41 | """sets height attribute""" 42 | if not isinstance(value, int): 43 | raise TypeError("height must be an integer") 44 | if value < 0: 45 | raise ValueError("height must be >= 0") 46 | self.__height = value 47 | -------------------------------------------------------------------------------- /0x08-python-more_classes/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/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/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/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/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/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/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/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 | -------------------------------------------------------------------------------- /0x08-python-more_classes/README.md: -------------------------------------------------------------------------------- 1 | # `Python_More_Classes` 2 | 3 | ## Enjoy! 4 | ![](https://www.codingninjas.com/blog/wp-content/uploads/2020/08/blog-19.png) 5 | - 6 | ## The Zen of Python, by Tim Peters 7 | 8 | - Beautiful is better than ugly. 9 | - Explicit is better than implicit. 10 | - Simple is better than complex. 11 | - Complex is better than complicated. 12 | - Flat is better than nested. 13 | - Sparse is better than dense. 14 | - Readability counts. 15 | - Special cases aren't special enough to break the rules. 16 | - Although practicality beats purity. 17 | - Errors should never pass silently. 18 | - Unless explicitly silenced. 19 | - In the face of ambiguity, refuse the temptation to guess. 20 | - There should be one-- and preferably only one --obvious way to do it. 21 | - Although that way may not be obvious at first unless you're Dutch. 22 | - Now is better than never. 23 | - Although never is often better than *right* now. 24 | - If the implementation is hard to explain, it's a bad idea. 25 | - If the implementation is easy to explain, it may be a good idea. 26 | - Namespaces are one honking great idea -- let's do more of those! 27 | -------------------------------------------------------------------------------- /0x08-python-more_classes/__pycache__/0-rectangle.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/0x08-python-more_classes/__pycache__/0-rectangle.cpython-310.pyc -------------------------------------------------------------------------------- /0x08-python-more_classes/__pycache__/1-rectangle.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/0x08-python-more_classes/__pycache__/1-rectangle.cpython-310.pyc -------------------------------------------------------------------------------- /0x08-python-more_classes/__pycache__/2-rectangle.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/0x08-python-more_classes/__pycache__/2-rectangle.cpython-310.pyc -------------------------------------------------------------------------------- /0x08-python-more_classes/__pycache__/3-rectangle.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/0x08-python-more_classes/__pycache__/3-rectangle.cpython-310.pyc -------------------------------------------------------------------------------- /0x08-python-more_classes/__pycache__/4-rectangle.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/0x08-python-more_classes/__pycache__/4-rectangle.cpython-310.pyc -------------------------------------------------------------------------------- /0x08-python-more_classes/__pycache__/5-rectangle.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/0x08-python-more_classes/__pycache__/5-rectangle.cpython-310.pyc -------------------------------------------------------------------------------- /0x08-python-more_classes/__pycache__/6-rectangle.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/0x08-python-more_classes/__pycache__/6-rectangle.cpython-310.pyc -------------------------------------------------------------------------------- /0x08-python-more_classes/__pycache__/7-rectangle.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/0x08-python-more_classes/__pycache__/7-rectangle.cpython-310.pyc -------------------------------------------------------------------------------- /0x08-python-more_classes/__pycache__/8-rectangle.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/0x08-python-more_classes/__pycache__/8-rectangle.cpython-310.pyc -------------------------------------------------------------------------------- /0x08-python-more_classes/__pycache__/9-rectangle.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/0x08-python-more_classes/__pycache__/9-rectangle.cpython-310.pyc -------------------------------------------------------------------------------- /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/README.md: -------------------------------------------------------------------------------- 1 | # `General` 2 | 3 | ![](https://techvidvan.com/tutorials/wp-content/uploads/sites/2/2020/01/python-classes.jpg) 4 | 5 | -------------------------------------------------------------------------------- /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 | Args: 12 | size (int): The size of the new square. 13 | """ 14 | self.integer_validator("size", size) 15 | super().__init__(size, size) 16 | self.__size = size 17 | -------------------------------------------------------------------------------- /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 | Args: 8 | obj (any): The object to add an attribute to. 9 | att (str): The name of the attribute to add to obj. 10 | value (any): The value of att. 11 | Raises: 12 | TypeError: If the attribute cannot be added. 13 | """ 14 | if not hasattr(obj, "__dict__"): 15 | raise TypeError("can't add new attribute") 16 | setattr(obj, att, value) 17 | -------------------------------------------------------------------------------- /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 | Args: 12 | size (int): The size of the new square. 13 | """ 14 | self.integer_validator("size", size) 15 | super().__init__(size, size) 16 | self.__size = size 17 | -------------------------------------------------------------------------------- /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 | Args: 8 | obj (any): The object to check. 9 | a_class (type): The class to match the type of obj to. 10 | Returns: 11 | If obj is exactly an instance of a_class - True. 12 | Otherwise - False. 13 | """ 14 | if type(obj) == a_class: 15 | return True 16 | return False 17 | -------------------------------------------------------------------------------- /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 | Args: 8 | obj (any): The object to check. 9 | a_class (type): The class to match the type of obj to. 10 | Returns: 11 | If obj is an instance or inherited instance of a_class - True. 12 | Otherwise - False. 13 | """ 14 | if isinstance(obj, a_class): 15 | return True 16 | return False 17 | -------------------------------------------------------------------------------- /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 | Args: 8 | obj (any): The object to check. 9 | a_class (type): The class to match the type of obj to. 10 | Returns: 11 | If obj is an inherited instance of a_class - True. 12 | Otherwise - False. 13 | """ 14 | if issubclass(type(obj), a_class) and type(obj) != a_class: 15 | return True 16 | return False 17 | -------------------------------------------------------------------------------- /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 | Args: 15 | name (str): The name of the parameter. 16 | value (int): The parameter to validate. 17 | Raises: 18 | TypeError: If value is not an integer. 19 | ValueError: If value is <= 0. 20 | """ 21 | if type(value) != int: 22 | raise TypeError("{} must be an integer".format(name)) 23 | if value <= 0: 24 | raise ValueError("{} must be greater than 0".format(name)) 25 | -------------------------------------------------------------------------------- /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 | Args: 12 | width (int): The width of the new Rectangle. 13 | height (int): The height of the new Rectangle. 14 | """ 15 | self.integer_validator("width", width) 16 | self.__width = width 17 | self.integer_validator("height", height) 18 | self.__height = height 19 | -------------------------------------------------------------------------------- /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 | Args: 12 | width (int): The width of the new Rectangle. 13 | height (int): The height of the new Rectangle. 14 | """ 15 | super().integer_validator("width", width) 16 | self.__width = width 17 | super().integer_validator("height", height) 18 | self.__height = height 19 | 20 | def area(self): 21 | """Return the area of the rectangle.""" 22 | return self.__width * self.__height 23 | 24 | def __str__(self): 25 | """Return the print() and str() representation of a Rectangle.""" 26 | string = "[" + str(self.__class__.__name__) + "] " 27 | string += str(self.__width) + "/" + str(self.__height) 28 | return string 29 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/README.md: -------------------------------------------------------------------------------- 1 | # 2 | # Python - Inheritance 3 | ![](https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSmNSR7DAT1mRXYhMTsOAQShwv-GabwZv1ygA&usqp=CAU) 4 | # Learning Objectives 5 | At the end of this project, you are expected to be able to explain to anyone, without the help of Google: 6 | 7 | # General 8 | - Why Python programming is awesome 9 | - What is a superclass, baseclass or parentclass 10 | - What is a subclass 11 | - How to list all attributes and methods of a class or instance 12 | - When can an instance have new attributes 13 | - How to inherit class from another 14 | - How to define a class with multiple base classes 15 | - What is the default class every class inherit from 16 | - How to override a method or attribute inherited from the base class 17 | - Which attributes or methods are available by heritage to subclasses 18 | - What is the purpose of inheritance 19 | - What are, when and how to use isinstance, issubclass, type and super built-in functions 20 | -------------------------------------------------------------------------------- /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 | Args: 8 | filename (str): The name of the file to write. 9 | text (str): The text to write to the file. 10 | Returns: 11 | The number of characters written. 12 | """ 13 | with open(filename, "w", encoding="utf-8") as f: 14 | return f.write(text) 15 | -------------------------------------------------------------------------------- /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 | Args: 11 | first_name (str): The first name of the student. 12 | last_name (str): The last name of the student. 13 | age (int): The age of the student. 14 | """ 15 | self.first_name = first_name 16 | self.last_name = last_name 17 | self.age = age 18 | 19 | def to_json(self, attrs=None): 20 | """Get a dictionary representation of the Student. 21 | If attrs is a list of strings, represents only those attributes 22 | included in the list. 23 | Args: 24 | attrs (list): (Optional) The attributes to represent. 25 | """ 26 | if (type(attrs) == list and 27 | all(type(ele) == str for ele in attrs)): 28 | return {k: getattr(self, k) for k in attrs if hasattr(self, k)} 29 | return self.__dict__ 30 | -------------------------------------------------------------------------------- /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 | Args: 8 | filename (str): The name of the file. 9 | search_string (str): The string to search for within the file. 10 | new_string (str): The string to insert. 11 | """ 12 | text = "" 13 | with open(filename) as r: 14 | for line in r: 15 | text += line 16 | if search_string in line: 17 | text += new_string 18 | with open(filename, "w") as w: 19 | w.write(text) 20 | -------------------------------------------------------------------------------- /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 | Args: 11 | first_name (str): The first name of the student. 12 | last_name (str): The last name of the student. 13 | age (int): The age of the student. 14 | """ 15 | self.first_name = first_name 16 | self.last_name = last_name 17 | self.age = age 18 | 19 | def to_json(self, attrs=None): 20 | """Get a dictionary representation of the Student. 21 | If attrs is a list of strings, represents only those attributes 22 | included in the list. 23 | Args: 24 | attrs (list): (Optional) The attributes to represent. 25 | """ 26 | if (type(attrs) == list and 27 | all(type(ele) == str for ele in attrs)): 28 | return {k: getattr(self, k) for k in attrs if hasattr(self, k)} 29 | return self.__dict__ 30 | 31 | def reload_from_json(self, json): 32 | """Replace all attributes of the Student. 33 | Args: 34 | json (dict): The key/value pairs to replace attributes with. 35 | """ 36 | for k, v in json.items(): 37 | setattr(self, k, v) 38 | -------------------------------------------------------------------------------- /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 | Returns a list of lists of integers representing the triangle. 8 | """ 9 | if n <= 0: 10 | return [] 11 | 12 | triangles = [[1]] 13 | while len(triangles) != n: 14 | tri = triangles[-1] 15 | tmp = [1] 16 | for i in range(len(tri) - 1): 17 | tmp.append(tri[i] + tri[i + 1]) 18 | tmp.append(1) 19 | triangles.append(tmp) 20 | return triangles 21 | -------------------------------------------------------------------------------- /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 | Args: 8 | filename (str): The name of the file to append to. 9 | text (str): The string to append to the file. 10 | Returns: 11 | The number of characters appended. 12 | """ 13 | with open(filename, "a", encoding="utf-8") as f: 14 | return f.write(text) 15 | -------------------------------------------------------------------------------- /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 | Args: 11 | first_name (str): The first name of the student. 12 | last_name (str): The last name of the student. 13 | age (int): The age of the student. 14 | """ 15 | self.first_name = first_name 16 | self.last_name = last_name 17 | self.age = age 18 | 19 | def to_json(self): 20 | """Get a dictionary representation of the Student.""" 21 | return self.__dict__ 22 | -------------------------------------------------------------------------------- /0x0B-python-input_output/README.md: -------------------------------------------------------------------------------- 1 | General 2 | 3 | Why Python programming is awesome 4 | 5 | How to open a file 6 | 7 | How to write text in a file 8 | 9 | How to read the full content of a file 10 | 11 | How to read a file line by line 12 | 13 | How to move the cursor in a file 14 | 15 | How to make sure a file is closed after using it 16 | 17 | What is and how to use the with statement 18 | 19 | What is JSON 20 | 21 | What is serialization 22 | 23 | What is deserialization 24 | 25 | How to convert a Python data structure to a JSON string 26 | 27 | How to convert a JSON string to a Python data structure 28 | -------------------------------------------------------------------------------- /0x0B-python-input_output/my_file_0.txt: -------------------------------------------------------------------------------- 1 | We offer a truly innovative approach to education: 2 | focus on building reliable applications and scalable systems, take on real-world challenges, collaborate with your peers. 3 | 4 | A school every software engineer would have dreamt of! 5 | 6 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/Project_manual/README.md: -------------------------------------------------------------------------------- 1 | # `Turtle Graphics in Python` 2 | ![](https://replit.com/public/images/mindjoy-python-turtle/og-new.jpg) 3 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/README.md: -------------------------------------------------------------------------------- 1 | # `Python Turtle` 2 | ![](https://preview.redd.it/10z0h79eecl81.gif?width=1273&auto=webp&s=b1ee287ede01d1cc2bea2763e7bccbf7a257fc6b) 3 | 4 | 5 | 6 | ![](https://media.tenor.com/ElmsBeoLQmEAAAAC/logisz-infinity.gif) 7 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/main_files/0-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 0-main """ 3 | from models.base import Base 4 | 5 | if __name__ == "__main__": 6 | 7 | b1 = Base() 8 | print(b1.id) 9 | 10 | b2 = Base() 11 | print(b2.id) 12 | 13 | b3 = Base() 14 | print(b3.id) 15 | 16 | b4 = Base(12) 17 | print(b4.id) 18 | 19 | b5 = Base() 20 | print(b5.id) 21 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/main_files/1-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 1-main """ 3 | from models.rectangle import Rectangle 4 | 5 | if __name__ == "__main__": 6 | 7 | r1 = Rectangle(10, 2) 8 | print(r1.id) 9 | 10 | r2 = Rectangle(2, 10) 11 | print(r2.id) 12 | 13 | r3 = Rectangle(10, 2, 0, 0, 12) 14 | print(r3.id) 15 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/main_files/10-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 10-main """ 3 | from models.square import Square 4 | 5 | if __name__ == "__main__": 6 | 7 | s1 = Square(5) 8 | print(s1) 9 | print(s1.size) 10 | s1.size = 10 11 | print(s1) 12 | 13 | try: 14 | s1.size = "9" 15 | except Exception as e: 16 | print("[{}] {}".format(e.__class__.__name__, e)) 17 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/main_files/11-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 11-main """ 3 | from models.square import Square 4 | 5 | if __name__ == "__main__": 6 | 7 | s1 = Square(5) 8 | print(s1) 9 | 10 | s1.update(10) 11 | print(s1) 12 | 13 | s1.update(1, 2) 14 | print(s1) 15 | 16 | s1.update(1, 2, 3) 17 | print(s1) 18 | 19 | s1.update(1, 2, 3, 4) 20 | print(s1) 21 | 22 | s1.update(x=12) 23 | print(s1) 24 | 25 | s1.update(size=7, y=1) 26 | print(s1) 27 | 28 | s1.update(size=7, id=89, y=1) 29 | print(s1) 30 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/main_files/12-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 12-main """ 3 | from models.rectangle import Rectangle 4 | 5 | if __name__ == "__main__": 6 | 7 | r1 = Rectangle(10, 2, 1, 9) 8 | print(r1) 9 | r1_dictionary = r1.to_dictionary() 10 | print(r1_dictionary) 11 | print(type(r1_dictionary)) 12 | 13 | r2 = Rectangle(1, 1) 14 | print(r2) 15 | r2.update(**r1_dictionary) 16 | print(r2) 17 | print(r1 == r2) 18 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/main_files/13-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 13-main """ 3 | from models.square import Square 4 | 5 | if __name__ == "__main__": 6 | 7 | s1 = Square(10, 2, 1) 8 | print(s1) 9 | s1_dictionary = s1.to_dictionary() 10 | print(s1_dictionary) 11 | print(type(s1_dictionary)) 12 | 13 | s2 = Square(1, 1) 14 | print(s2) 15 | s2.update(**s1_dictionary) 16 | print(s2) 17 | print(s1 == s2) 18 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/main_files/14-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 14-main """ 3 | from models.base import Base 4 | from models.rectangle import Rectangle 5 | 6 | if __name__ == "__main__": 7 | 8 | r1 = Rectangle(10, 7, 2, 8) 9 | dictionary = r1.to_dictionary() 10 | json_dictionary = Base.to_json_string([dictionary]) 11 | print(dictionary) 12 | print(type(dictionary)) 13 | print(json_dictionary) 14 | print(type(json_dictionary)) 15 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/main_files/15-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 15-main """ 3 | from models.rectangle import Rectangle 4 | 5 | if __name__ == "__main__": 6 | 7 | r1 = Rectangle(10, 7, 2, 8) 8 | r2 = Rectangle(2, 4) 9 | Rectangle.save_to_file([r1, r2]) 10 | 11 | with open("Rectangle.json", "r") as file: 12 | print(file.read()) 13 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/main_files/16-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 16-main """ 3 | from models.rectangle import Rectangle 4 | 5 | if __name__ == "__main__": 6 | 7 | list_input = [ 8 | {'id': 89, 'width': 10, 'height': 4}, 9 | {'id': 7, 'width': 1, 'height': 7} 10 | ] 11 | json_list_input = Rectangle.to_json_string(list_input) 12 | list_output = Rectangle.from_json_string(json_list_input) 13 | print("[{}] {}".format(type(list_input), list_input)) 14 | print("[{}] {}".format(type(json_list_input), json_list_input)) 15 | print("[{}] {}".format(type(list_output), list_output)) 16 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/main_files/17-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 17-main """ 3 | from models.rectangle import Rectangle 4 | 5 | if __name__ == "__main__": 6 | 7 | r1 = Rectangle(3, 5, 1) 8 | r1_dictionary = r1.to_dictionary() 9 | r2 = Rectangle.create(**r1_dictionary) 10 | print(r1) 11 | print(r2) 12 | print(r1 is r2) 13 | print(r1 == r2) 14 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/main_files/18-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 18-main """ 3 | from models.rectangle import Rectangle 4 | from models.square import Square 5 | 6 | if __name__ == "__main__": 7 | 8 | r1 = Rectangle(10, 7, 2, 8) 9 | r2 = Rectangle(2, 4) 10 | list_rectangles_input = [r1, r2] 11 | 12 | Rectangle.save_to_file(list_rectangles_input) 13 | 14 | list_rectangles_output = Rectangle.load_from_file() 15 | 16 | for rect in list_rectangles_input: 17 | print("[{}] {}".format(id(rect), rect)) 18 | 19 | print("---") 20 | 21 | for rect in list_rectangles_output: 22 | print("[{}] {}".format(id(rect), rect)) 23 | 24 | print("---") 25 | print("---") 26 | 27 | s1 = Square(5) 28 | s2 = Square(7, 9, 1) 29 | list_squares_input = [s1, s2] 30 | 31 | Square.save_to_file(list_squares_input) 32 | 33 | list_squares_output = Square.load_from_file() 34 | 35 | for square in list_squares_input: 36 | print("[{}] {}".format(id(square), square)) 37 | 38 | print("---") 39 | 40 | for square in list_squares_output: 41 | print("[{}] {}".format(id(square), square)) 42 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/main_files/2-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 2-main """ 3 | from models.rectangle import Rectangle 4 | 5 | if __name__ == "__main__": 6 | 7 | try: 8 | Rectangle(10, "2") 9 | except Exception as e: 10 | print("[{}] {}".format(e.__class__.__name__, e)) 11 | 12 | try: 13 | r = Rectangle(10, 2) 14 | r.width = -10 15 | except Exception as e: 16 | print("[{}] {}".format(e.__class__.__name__, e)) 17 | 18 | try: 19 | r = Rectangle(10, 2) 20 | r.x = {} 21 | except Exception as e: 22 | print("[{}] {}".format(e.__class__.__name__, e)) 23 | 24 | try: 25 | Rectangle(10, 2, 3, -1) 26 | except Exception as e: 27 | print("[{}] {}".format(e.__class__.__name__, e)) 28 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/main_files/3-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3-main """ 3 | from models.rectangle import Rectangle 4 | 5 | if __name__ == "__main__": 6 | 7 | r1 = Rectangle(3, 2) 8 | print(r1.area()) 9 | 10 | r2 = Rectangle(2, 10) 11 | print(r2.area()) 12 | 13 | r3 = Rectangle(8, 7, 0, 0, 12) 14 | print(r3.area()) 15 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/main_files/4-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 4-main """ 3 | from models.rectangle import Rectangle 4 | 5 | if __name__ == "__main__": 6 | 7 | r1 = Rectangle(4, 6) 8 | r1.display() 9 | 10 | print("---") 11 | 12 | r1 = Rectangle(2, 2) 13 | r1.display() 14 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/main_files/5-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 5-main """ 3 | from models.rectangle import Rectangle 4 | 5 | if __name__ == "__main__": 6 | 7 | r1 = Rectangle(4, 6, 2, 1, 12) 8 | print(r1) 9 | 10 | r2 = Rectangle(5, 5, 1) 11 | print(r2) 12 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/main_files/6-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 6-main """ 3 | from models.rectangle import Rectangle 4 | 5 | if __name__ == "__main__": 6 | 7 | r1 = Rectangle(2, 3, 2, 2) 8 | r1.display() 9 | 10 | print("---") 11 | 12 | r2 = Rectangle(3, 2, 1, 0) 13 | r2.display() 14 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/main_files/7-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ Doc """ 3 | from models.rectangle import Rectangle 4 | 5 | if __name__ == "__main__": 6 | 7 | r1 = Rectangle(10, 10, 10, 10) 8 | print(r1) 9 | 10 | r1.update(89) 11 | print(r1) 12 | 13 | r1.update(89, 2) 14 | print(r1) 15 | 16 | r1.update(89, 2, 3) 17 | print(r1) 18 | 19 | r1.update(89, 2, 3, 4) 20 | print(r1) 21 | 22 | r1.update(89, 2, 3, 4, 5) 23 | print(r1) 24 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/main_files/8-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 8-main """ 3 | from models.rectangle import Rectangle 4 | 5 | if __name__ == "__main__": 6 | 7 | r1 = Rectangle(10, 10, 10, 10) 8 | print(r1) 9 | 10 | r1.update(height=1) 11 | print(r1) 12 | 13 | r1.update(width=1, x=2) 14 | print(r1) 15 | 16 | r1.update(y=1, width=2, x=3, id=89) 17 | print(r1) 18 | 19 | r1.update(x=1, height=2, y=3, width=4) 20 | print(r1) 21 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/main_files/9-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 9-main """ 3 | from models.square import Square 4 | 5 | if __name__ == "__main__": 6 | 7 | s1 = Square(5) 8 | print(s1) 9 | print(s1.area()) 10 | s1.display() 11 | 12 | print("---") 13 | 14 | s2 = Square(2, 2) 15 | print(s2) 16 | print(s2.area()) 17 | s2.display() 18 | 19 | print("---") 20 | 21 | s3 = Square(3, 1, 3) 22 | print(s3) 23 | print(s3.area()) 24 | s3.display() 25 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/main_files/Rectangle.json: -------------------------------------------------------------------------------- 1 | [{"id": 1, "width": 10, "height": 7, "x": 2, "y": 8}, {"id": 2, "width": 2, "height": 4, "x": 0, "y": 0}] -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/main_files/Square.json: -------------------------------------------------------------------------------- 1 | [{"id": 5, "size": 5, "x": 0, "y": 0}, {"id": 6, "size": 7, "x": 9, "y": 1}] -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/models/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/0x0C-python-almost_a_circle/models/__init__.py -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/models/__pycache__/__init__.cpython-34.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/0x0C-python-almost_a_circle/models/__pycache__/__init__.cpython-34.pyc -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/models/__pycache__/__init__.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/0x0C-python-almost_a_circle/models/__pycache__/__init__.cpython-38.pyc -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/models/__pycache__/base.cpython-34.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/0x0C-python-almost_a_circle/models/__pycache__/base.cpython-34.pyc -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/models/__pycache__/base.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/0x0C-python-almost_a_circle/models/__pycache__/base.cpython-38.pyc -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/models/__pycache__/rectangle.cpython-34.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/0x0C-python-almost_a_circle/models/__pycache__/rectangle.cpython-34.pyc -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/models/__pycache__/rectangle.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/0x0C-python-almost_a_circle/models/__pycache__/rectangle.cpython-38.pyc -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/models/__pycache__/square.cpython-34.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/0x0C-python-almost_a_circle/models/__pycache__/square.cpython-34.pyc -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/models/__pycache__/square.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/0x0C-python-almost_a_circle/models/__pycache__/square.cpython-38.pyc -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/models/square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | '''Module for Square class.''' 3 | from models.rectangle import Rectangle 4 | 5 | 6 | class Square(Rectangle): 7 | '''A Square class.''' 8 | 9 | def __init__(self, size, x=0, y=0, id=None): 10 | '''Constructor.''' 11 | super().__init__(size, size, x, y, id) 12 | 13 | def __str__(self): 14 | '''Returns string info about this square.''' 15 | return '[{}] ({}) {}/{} - {}'.\ 16 | format(type(self).__name__, self.id, self.x, self.y, self.width) 17 | 18 | @property 19 | def size(self): 20 | '''Size of this square.''' 21 | return self.width 22 | 23 | @size.setter 24 | def size(self, value): 25 | self.width = value 26 | self.height = value 27 | 28 | def __update(self, id=None, size=None, x=None, y=None): 29 | '''Internal method that updates instance attributes via */**args.''' 30 | if id is not None: 31 | self.id = id 32 | if size is not None: 33 | self.size = size 34 | if x is not None: 35 | self.x = x 36 | if y is not None: 37 | self.y = y 38 | 39 | def update(self, *args, **kwargs): 40 | '''Updates instance attributes via no-keyword & keyword args.''' 41 | if args: 42 | self.__update(*args) 43 | elif kwargs: 44 | self.__update(**kwargs) 45 | 46 | def to_dictionary(self): 47 | '''Returns dictionary representation of this class.''' 48 | return {"id": self.id, "size": self.width, 49 | "x": self.x, "y": self.y} 50 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/0x0C-python-almost_a_circle/tests/__init__.py -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/tests/test_models/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/0x0C-python-almost_a_circle/tests/test_models/__init__.py -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/tests/test_models/__pycache__/__init__.cpython-34.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/0x0C-python-almost_a_circle/tests/test_models/__pycache__/__init__.cpython-34.pyc -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/tests/test_models/__pycache__/__init__.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/0x0C-python-almost_a_circle/tests/test_models/__pycache__/__init__.cpython-38.pyc -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/tests/test_models/__pycache__/test_base.cpython-34.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/0x0C-python-almost_a_circle/tests/test_models/__pycache__/test_base.cpython-34.pyc -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/tests/test_models/__pycache__/test_base.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/0x0C-python-almost_a_circle/tests/test_models/__pycache__/test_base.cpython-38.pyc -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/tests/test_models/__pycache__/test_rectangle.cpython-34.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/0x0C-python-almost_a_circle/tests/test_models/__pycache__/test_rectangle.cpython-34.pyc -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/tests/test_models/__pycache__/test_rectangle.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/0x0C-python-almost_a_circle/tests/test_models/__pycache__/test_rectangle.cpython-38.pyc -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/tests/test_models/__pycache__/test_square.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/0x0C-python-almost_a_circle/tests/test_models/__pycache__/test_square.cpython-38.pyc -------------------------------------------------------------------------------- /0x0D-SQL_introduction/0-list_databases.sql: -------------------------------------------------------------------------------- 1 | -- This script lists all databases in MySQL server 2 | SHOW DATABASES; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/1-create_database_if_missing.sql: -------------------------------------------------------------------------------- 1 | -- Create database; does not fail, if already exists 2 | CREATE DATABASE IF NOT EXISTS hbtn_0c_0; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/10-top_score.sql: -------------------------------------------------------------------------------- 1 | -- List all records descending by score 2 | SELECT score, name FROM second_table ORDER BY score DESC; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/100-move_to_utf8.sql: -------------------------------------------------------------------------------- 1 | -- Converts UTF8 to utf8mb4 2 | ALTER DATABASE hbtn_0c_0 CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; 3 | USE hbtn_0c_0; 4 | ALTER TABLE first_table CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; 5 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/101-avg_temperatures.sql: -------------------------------------------------------------------------------- 1 | -- Display average city temps in descending order 2 | SELECT city, AVG(value) AS avg_temp FROM temperatures GROUP BY city ORDER BY avg_temp DESC; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/102-top_city.sql: -------------------------------------------------------------------------------- 1 | -- Display cities with top average temps in descending order 2 | SELECT city, AVG(value) AS avg_temp FROM temperatures WHERE month = 7 OR month = 8 GROUP BY city ORDER BY avg_temp DESC LIMIT 3; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/103-max_state.sql: -------------------------------------------------------------------------------- 1 | -- List max temperature in weach state; order by name 2 | SELECT state, MAX(value) AS max_temp FROM temperatures GROUP BY state ORDER BY state ASC; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/11-best_score.sql: -------------------------------------------------------------------------------- 1 | -- List records with scores greater than or equal to 10 2 | SELECT score, name FROM second_table WHERE score >= 10 ORDER BY score DESC; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/12-no_cheating.sql: -------------------------------------------------------------------------------- 1 | -- Update score of table item 2 | UPDATE second_table SET score = 10 WHERE name = "Bob"; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/13-change_class.sql: -------------------------------------------------------------------------------- 1 | -- Remove records with score less than or equal to 5 2 | DELETE FROM second_table WHERE score <= 5; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/14-average.sql: -------------------------------------------------------------------------------- 1 | -- Return average of all records 2 | SELECT AVG(score) AS average FROM second_table 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/15-groups.sql: -------------------------------------------------------------------------------- 1 | -- List by occurences of scores 2 | SELECT score, COUNT(*) AS number FROM second_table GROUP BY score ORDER BY number DESC; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/16-no_link.sql: -------------------------------------------------------------------------------- 1 | -- List records with name value by descending score 2 | SELECT score, name FROM second_table WHERE name IS NOT NULL ORDER BY score DESC; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/2-remove_database.sql: -------------------------------------------------------------------------------- 1 | -- Delete database, if existing 2 | DROP DATABASE IF EXISTS hbtn_0c_0; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/3-list_tables.sql: -------------------------------------------------------------------------------- 1 | -- List tables of given database 2 | SHOW TABLES; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/4-first_table.sql: -------------------------------------------------------------------------------- 1 | -- Create new table safely 2 | CREATE TABLE IF NOT EXISTS first_table (id INT, name VARCHAR(256)); 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/5-full_table.sql: -------------------------------------------------------------------------------- 1 | -- Print full description of table 2 | SHOW CREATE TABLE first_table; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/6-list_values.sql: -------------------------------------------------------------------------------- 1 | -- List all rows of table 2 | SELECT * FROM first_table; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/7-insert_value.sql: -------------------------------------------------------------------------------- 1 | -- Insert new row into table 2 | INSERT INTO first_table (`id`, `name`) VALUES(89, 'Holberton School'); 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/8-count_89.sql: -------------------------------------------------------------------------------- 1 | -- Print number of records with an id of 89 2 | SELECT COUNT(*) FROM first_table WHERE id = 89; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/9-full_creation.sql: -------------------------------------------------------------------------------- 1 | -- Create and populate new table 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), (2, "Alex", 3), (3, "Bob", 14), (4, "George", 8); 4 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/README.md: -------------------------------------------------------------------------------- 1 | # `SQL - Introduction` 2 | ## SQL (Structured Query Language) is a programming language used for managing and manipulating data in relational databases. 3 | ![](https://www.selecthub.com/wp-content/uploads/2022/07/SQL-Commands.jpg) 4 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/0-privileges.sql: -------------------------------------------------------------------------------- 1 | -- List privileges for user_0d_1 2 | SHOW GRANTS FOR user_0d_1@localhost; 3 | -- List privileges for user_0d_2 4 | SHOW GRANTS FOR user_0d_2@localhost; 5 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/1-create_user.sql: -------------------------------------------------------------------------------- 1 | -- Create new user 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 | -- List shows with genre 2 | SELECT tv_shows.title, tv_show_genres.genre_id 3 | FROM tv_genres 4 | JOIN tv_show_genres 5 | JOIN tv_shows 6 | ON tv_shows.id = show_id AND tv_genres.id = genre_id 7 | ORDER BY tv_shows.title ASC, tv_show_genres.genre_id ASC; 8 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/100-not_my_genres.sql: -------------------------------------------------------------------------------- 1 | -- a script that uses the hbtn_0d_tvshows database to list all genres not linked to the show Dexter 2 | SELECT tv_genres.name 3 | FROM tv_genres 4 | WHERE tv_genres.name NOT IN 5 | (SELECT tv_genres.name 6 | FROM tv_genres 7 | LEFT JOIN tv_show_genres 8 | ON tv_genres.id = tv_show_genres.genre_id 9 | LEFT JOIN tv_shows 10 | ON tv_shows.id = tv_show_genres.show_id 11 | WHERE tv_shows.title = "Dexter") 12 | ORDER BY tv_genres.name; 13 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/101-not_a_comedy.sql: -------------------------------------------------------------------------------- 1 | -- a script that lists all shows without the genre Comedy in the database hbtn_0d_tvshows. 2 | SELECT tv_shows.title 3 | FROM tv_shows 4 | WHERE tv_shows.title NOT IN 5 | (SELECT tv_shows.title 6 | FROM tv_shows 7 | JOIN tv_show_genres 8 | ON tv_shows.id = tv_show_genres.show_id 9 | JOIN tv_genres 10 | ON tv_genres.id = tv_show_genres.genre_id 11 | WHERE tv_genres.name = "Comedy") 12 | ORDER BY tv_shows.title ASC; 13 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/102-rating_shows.sql: -------------------------------------------------------------------------------- 1 | -- a script that lists all shows from hbtn_0d_tvshows_rate by their rating 2 | SELECT tv_shows.title, SUM(tv_show_ratings.rate) AS rating 3 | FROM tv_shows 4 | JOIN tv_show_ratings 5 | ON tv_shows.id = tv_show_ratings.show_id 6 | GROUP BY tv_shows.title 7 | ORDER BY rating DESC; 8 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/103-rating_genres.sql: -------------------------------------------------------------------------------- 1 | -- a script that lists all genres in the database hbtn_0d_tvshows_rate by their rating. 2 | SELECT tv_genres.name, SUM(tv_show_ratings.rate) AS rating 3 | FROM tv_genres 4 | JOIN tv_show_genres 5 | ON tv_genres.id = tv_show_genres.genre_id 6 | JOIN tv_shows 7 | ON tv_shows.id = tv_show_genres.show_id 8 | JOIN tv_show_ratings 9 | ON tv_shows.id = tv_show_ratings.show_id 10 | GROUP BY tv_genres.name 11 | ORDER BY rating DESC; 12 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/11-genre_id_all_shows.sql: -------------------------------------------------------------------------------- 1 | -- List all shows 2 | SELECT tv_shows.title, tv_show_genres.genre_id 3 | FROM tv_shows 4 | LEFT JOIN tv_show_genres 5 | ON tv_shows.id = tv_show_genres.show_id 6 | LEFT JOIN tv_genres 7 | ON tv_genres.id = tv_show_genres.genre_id 8 | ORDER BY tv_shows.title ASC, tv_show_genres.genre_id ASC; 9 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/12-no_genre.sql: -------------------------------------------------------------------------------- 1 | -- a script that lists all shows contained in hbtn_0d_tvshows without a genre linked. 2 | SELECT tv_shows.title, tsg.genre_id 3 | FROM tv_shows 4 | LEFT JOIN tv_show_genres AS tsg 5 | ON tv_shows.id = tsg.show_id 6 | WHERE tsg.genre_id IS NULL 7 | ORDER BY tv_shows.title ASC, tsg.genre_id ASC; 8 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/13-count_shows_by_genre.sql: -------------------------------------------------------------------------------- 1 | -- a script that lists all genres from hbtn_0d_tvshows and displays the number of shows linked to each. 2 | SELECT tv_genres.name AS genre, COUNT(*) AS number_of_shows 3 | FROM tv_genres 4 | 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 | -- List all genres of show Dexter 2 | SELECT tv_genres.name 3 | FROM tv_shows 4 | JOIN tv_show_genres 5 | ON tv_shows.id = tv_show_genres.show_id 6 | JOIN tv_genres 7 | ON tv_genres.id = tv_show_genres.genre_id 8 | WHERE tv_shows.title = "Dexter" 9 | ORDER BY tv_genres.name ASC; 10 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/15-comedy_only.sql: -------------------------------------------------------------------------------- 1 | -- a script that lists all Comedy shows in the database hbtn_0d_tvshows 2 | SELECT tv_shows.title 3 | FROM tv_shows 4 | JOIN tv_show_genres 5 | ON tv_shows.id = tv_show_genres.show_id 6 | JOIN tv_genres 7 | ON tv_genres.id = tv_show_genres.genre_id 8 | WHERE tv_genres.name = "Comedy" 9 | ORDER BY tv_shows.title ASC; 10 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/16-shows_by_genre.sql: -------------------------------------------------------------------------------- 1 | -- a script that lists all shows, and all genres linked to that show, from the database hbtn_0d_tvshows. 2 | SELECT tv_shows.title, tv_genres.name 3 | FROM tv_shows 4 | LEFT JOIN tv_show_genres 5 | ON tv_shows.id = tv_show_genres.show_id 6 | LEFT JOIN tv_genres 7 | ON tv_genres.id = tv_show_genres.genre_id 8 | ORDER BY tv_shows.title ASC, tv_genres.name ASC; 9 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/2-create_read_user.sql: -------------------------------------------------------------------------------- 1 | -- Create database and user 2 | CREATE DATABASE IF NOT EXISTS hbtn_0d_2; 3 | CREATE USER IF NOT EXISTS 'user_0d_2'@'localhost' IDENTIFIED BY 'user_0d_2_pwd'; 4 | GRANT SELECT ON hbtn_0d_2.* TO 'user_0d_2'@'localhost'; 5 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/3-force_name.sql: -------------------------------------------------------------------------------- 1 | -- Create table 2 | CREATE TABLE IF NOT EXISTS force_name (id INT, name VARCHAR(256) NOT NULL); 3 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/4-never_empty.sql: -------------------------------------------------------------------------------- 1 | -- Create table with non-null id's 2 | CREATE TABLE IF NOT EXISTS id_not_null (id INT DEFAULT 1, name VARCHAR(256)); 3 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/5-unique_id.sql: -------------------------------------------------------------------------------- 1 | -- Create table with defaul/unique id field 2 | CREATE TABLE IF NOT EXISTS unique_id (id INT DEFAULT 1 UNIQUE, name VARCHAR(256)); 3 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/6-states.sql: -------------------------------------------------------------------------------- 1 | -- Create database and table 2 | CREATE DATABASE IF NOT EXISTS hbtn_0d_usa; 3 | USE hbtn_0d_usa; 4 | CREATE TABLE IF NOT EXISTS states (id INT UNIQUE AUTO_INCREMENT NOT NULL PRIMARY KEY, name VARCHAR(256)); 5 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/7-cities.sql: -------------------------------------------------------------------------------- 1 | -- Create database and table 2 | CREATE DATABASE IF NOT EXISTS hbtn_0d_usa; 3 | USE hbtn_0d_usa; 4 | CREATE TABLE IF NOT EXISTS cities (id INT UNIQUE AUTO_INCREMENT NOT NULL PRIMARY KEY, state_id INT NOT NULL, CONSTRAINT FOREIGN KEY (state_id) REFERENCES states(id) ON UPDATE RESTRICT, name VARCHAR(256) NOT NULL); 5 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/8-cities_of_california_subquery.sql: -------------------------------------------------------------------------------- 1 | -- List all cities of CA in database 2 | SELECT id, name FROM cities WHERE state_id = 1 ORDER BY cities.id ASC; 3 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/9-cities_by_state_join.sql: -------------------------------------------------------------------------------- 1 | -- List all cities in database 2 | SELECT DISTINCT cities.id, cities.name, states.name 3 | FROM cities JOIN (states) ON cities.state_id = states.id 4 | ORDER BY id ASC; 5 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/README.md: -------------------------------------------------------------------------------- 1 | 2 | # `SQL - More queries` 3 | ## These SQL scripts provide a more in-depth introduction to MySQL databases, covering topics such as 4 | - ### `permissions` 5 | - ### `advanced queries` 6 | - ### `and joins` 7 | # 8 | ![](https://media.geeksforgeeks.org/wp-content/cdn-uploads/20230305181855/SQL2.png) 9 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/0-select_states.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ lists all states from the database hbtn_0e_0_usa """ 3 | import MySQLdb 4 | import sys 5 | 6 | 7 | if __name__ == "__main__": 8 | db = MySQLdb.connect(host="localhost", user=sys.argv[1], 9 | passwd=sys.argv[2], db=sys.argv[3], port=3306) 10 | cur = db.cursor() 11 | cur.execute("SELECT * FROM states") 12 | rows = cur.fetchall() 13 | for row in rows: 14 | print(row) 15 | cur.close() 16 | db.close() 17 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/0-select_states.sql: -------------------------------------------------------------------------------- 1 | -- Create states table in hbtn_0e_0_usa with some data 2 | CREATE DATABASE IF NOT EXISTS hbtn_0e_0_usa; 3 | USE hbtn_0e_0_usa; 4 | CREATE TABLE IF NOT EXISTS states ( 5 | id INT NOT NULL AUTO_INCREMENT, 6 | name VARCHAR(256) NOT NULL, 7 | PRIMARY KEY (id) 8 | ); 9 | INSERT INTO states (name) VALUES ("California"), ("Arizona"), ("Texas"), ("New York"), ("Nevada"); 10 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/1-filter_states.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ lists all states from the database hbtn_0e_0_usa """ 3 | import MySQLdb 4 | import sys 5 | 6 | 7 | if __name__ == "__main__": 8 | db = MySQLdb.connect(host="localhost", user=sys.argv[1], 9 | passwd=sys.argv[2], db=sys.argv[3], port=3306) 10 | cur = db.cursor() 11 | cur.execute("""SELECT * FROM states WHERE name 12 | LIKE BINARY 'N%' ORDER BY states.id""") 13 | rows = cur.fetchall() 14 | for row in rows: 15 | print(row) 16 | cur.close() 17 | db.close() 18 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/10-model_state_my_get.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ prints the State object with the name passed as argument from the database 3 | """ 4 | import sys 5 | from model_state import Base, State 6 | from sqlalchemy import (create_engine) 7 | from sqlalchemy.orm import sessionmaker 8 | 9 | 10 | if __name__ == "__main__": 11 | engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}' 12 | .format(sys.argv[1], sys.argv[2], sys.argv[3])) 13 | Base.metadata.create_all(engine) 14 | Session = sessionmaker(bind=engine) 15 | session = Session() 16 | instance = session.query(State).filter(State.name == (sys.argv[4],)) 17 | try: 18 | print(instance[0].id) 19 | except IndexError: 20 | print("Not found") 21 | -------------------------------------------------------------------------------- /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/100-relationship_states_cities.sql: -------------------------------------------------------------------------------- 1 | -- Create the database hbtn_0e_100_usa 2 | CREATE DATABASE IF NOT EXISTS hbtn_0e_100_usa; 3 | USE hbtn_0e_100_usa; 4 | 5 | SELECT * FROM states; 6 | SELECT * FROM cities; 7 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/101-relationship_states_cities_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ prints the State object with the name passed as argument from the database 3 | """ 4 | import sys 5 | from relationship_state import Base, State 6 | from relationship_city import City 7 | from sqlalchemy import (create_engine) 8 | from sqlalchemy.orm import sessionmaker 9 | from sqlalchemy.orm import relationship 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 | Base.metadata.create_all(engine) 16 | Session = sessionmaker(bind=engine) 17 | session = Session() 18 | for instance in session.query(State).order_by(State.id): 19 | print(instance.id, instance.name, sep=": ") 20 | for city_ins in instance.cities: 21 | print(" ", end="") 22 | print(city_ins.id, city_ins.name, sep=": ") 23 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/102-relationship_cities_states_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ prints the State object with the name passed as argument from the database 3 | """ 4 | import sys 5 | from relationship_state import Base, State 6 | from relationship_city import City 7 | from sqlalchemy import (create_engine) 8 | from sqlalchemy.orm import sessionmaker 9 | from sqlalchemy.orm import relationship 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 | Base.metadata.create_all(engine) 16 | Session = sessionmaker(bind=engine) 17 | session = Session() 18 | for instance in session.query(State).order_by(State.id): 19 | for city_ins in instance.cities: 20 | print(city_ins.id, city_ins.name, sep=": ", end="") 21 | print(" -> " + instance.name) 22 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/11-model_state_insert.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ prints the State object with the name passed as argument from the database 3 | """ 4 | import sys 5 | from model_state import Base, State 6 | from sqlalchemy import (create_engine) 7 | from sqlalchemy.orm import sessionmaker 8 | 9 | 10 | if __name__ == "__main__": 11 | engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}' 12 | .format(sys.argv[1], sys.argv[2], sys.argv[3])) 13 | Base.metadata.create_all(engine) 14 | Session = sessionmaker(bind=engine) 15 | session = Session() 16 | new_state = State(name='Louisiana') 17 | session.add(new_state) 18 | new_instance = session.query(State).filter_by(name='Louisiana').first() 19 | print(new_instance.id) 20 | session.commit() 21 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/12-model_state_update_id_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ prints the State object with the name passed as argument from the database 3 | """ 4 | import sys 5 | from model_state import Base, State 6 | from sqlalchemy import (create_engine) 7 | from sqlalchemy.orm import sessionmaker 8 | 9 | 10 | if __name__ == "__main__": 11 | engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}' 12 | .format(sys.argv[1], sys.argv[2], sys.argv[3])) 13 | Base.metadata.create_all(engine) 14 | Session = sessionmaker(bind=engine) 15 | session = Session() 16 | new_instance = session.query(State).filter_by(id=2).first() 17 | new_instance.name = 'New Mexico' 18 | session.commit() 19 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/13-model_state_delete_a.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ prints the State object with the name passed as argument from the database 3 | """ 4 | import sys 5 | from model_state import Base, State 6 | from sqlalchemy import (create_engine) 7 | from sqlalchemy.orm import sessionmaker 8 | 9 | 10 | if __name__ == "__main__": 11 | engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}' 12 | .format(sys.argv[1], sys.argv[2], sys.argv[3])) 13 | Base.metadata.create_all(engine) 14 | Session = sessionmaker(bind=engine) 15 | session = Session() 16 | for instance in session.query(State).filter(State.name.like('%a%')): 17 | session.delete(instance) 18 | session.commit() 19 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/14-model_city_fetch_by_state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ prints the State object with the name passed as argument from the database 3 | """ 4 | import sys 5 | from model_state import Base, State 6 | from model_city import City 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 | Base.metadata.create_all(engine) 15 | Session = sessionmaker(bind=engine) 16 | session = Session() 17 | for instance in (session.query(State.name, City.id, City.name) 18 | .filter(State.id == City.state_id)): 19 | print(instance[0] + ": (" + str(instance[1]) + ") " + instance[2]) 20 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/14-model_city_fetch_by_state.sql: -------------------------------------------------------------------------------- 1 | -- Create database hbtn_0e_14_usa, tables states and cities + some data 2 | CREATE DATABASE IF NOT EXISTS hbtn_0e_14_usa; 3 | USE hbtn_0e_14_usa; 4 | 5 | CREATE TABLE IF NOT EXISTS states ( 6 | id INT NOT NULL AUTO_INCREMENT, 7 | name VARCHAR(256) NOT NULL, 8 | PRIMARY KEY (id) 9 | ); 10 | INSERT INTO states (name) VALUES ("California"), ("Arizona"), ("Texas"), ("New York"), ("Nevada"); 11 | 12 | CREATE TABLE IF NOT EXISTS cities ( 13 | id INT NOT NULL AUTO_INCREMENT, 14 | state_id INT NOT NULL, 15 | name VARCHAR(256) NOT NULL, 16 | PRIMARY KEY (id), 17 | FOREIGN KEY(state_id) REFERENCES states(id) 18 | ); 19 | INSERT INTO cities (state_id, name) VALUES (1, "San Francisco"), (1, "San Jose"), (1, "Los Angeles"), (1, "Fremont"), (1, "Livermore"); 20 | INSERT INTO cities (state_id, name) VALUES (2, "Page"), (2, "Phoenix"); 21 | INSERT INTO cities (state_id, name) VALUES (3, "Dallas"), (3, "Houston"), (3, "Austin"); 22 | INSERT INTO cities (state_id, name) VALUES (4, "New York"); 23 | INSERT INTO cities (state_id, name) VALUES (5, "Las Vegas"), (5, "Reno"), (5, "Henderson"), (5, "Carson City"); 24 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/2-my_filter_states.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ lists all states from the database hbtn_0e_0_usa """ 3 | import MySQLdb 4 | import sys 5 | 6 | 7 | if __name__ == "__main__": 8 | db = MySQLdb.connect(host="localhost", user=sys.argv[1], 9 | passwd=sys.argv[2], db=sys.argv[3], port=3306) 10 | cur = db.cursor() 11 | cur.execute("SELECT * FROM states WHERE name LIKE BINARY '{}'" 12 | .format(sys.argv[4])) 13 | rows = cur.fetchall() 14 | for row in rows: 15 | print(row) 16 | cur.close() 17 | db.close() 18 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/3-my_safe_filter_states.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ lists all states from the database hbtn_0e_0_usa """ 3 | import MySQLdb 4 | import sys 5 | 6 | 7 | if __name__ == "__main__": 8 | db = MySQLdb.connect(host="localhost", user=sys.argv[1], 9 | passwd=sys.argv[2], db=sys.argv[3], port=3306) 10 | cur = db.cursor() 11 | match = sys.argv[4] 12 | cur.execute("SELECT * FROM states WHERE name LIKE %s", (match, )) 13 | rows = cur.fetchall() 14 | for row in rows: 15 | print(row) 16 | cur.close() 17 | db.close() 18 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/4-cities_by_state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ lists all states from the database hbtn_0e_0_usa """ 3 | import MySQLdb 4 | import sys 5 | 6 | 7 | if __name__ == "__main__": 8 | db = MySQLdb.connect(host="localhost", user=sys.argv[1], 9 | passwd=sys.argv[2], db=sys.argv[3], port=3306) 10 | cur = db.cursor() 11 | cur.execute("""SELECT cities.id, cities.name, states.name FROM 12 | cities INNER JOIN states ON states.id=cities.state_id""") 13 | rows = cur.fetchall() 14 | for row in rows: 15 | print(row) 16 | cur.close() 17 | db.close() 18 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/4-cities_by_state.sql: -------------------------------------------------------------------------------- 1 | -- Create states table in hbtn_0e_4_usa with some data 2 | CREATE DATABASE IF NOT EXISTS hbtn_0e_4_usa; 3 | USE hbtn_0e_4_usa; 4 | CREATE TABLE IF NOT EXISTS states ( 5 | id INT NOT NULL AUTO_INCREMENT, 6 | name VARCHAR(256) NOT NULL, 7 | PRIMARY KEY (id) 8 | ); 9 | INSERT INTO states (name) VALUES ("California"), ("Arizona"), ("Texas"), ("New York"), ("Nevada"); 10 | 11 | CREATE TABLE IF NOT EXISTS cities ( 12 | id INT NOT NULL AUTO_INCREMENT, 13 | state_id INT NOT NULL, 14 | name VARCHAR(256) NOT NULL, 15 | PRIMARY KEY (id), 16 | FOREIGN KEY(state_id) REFERENCES states(id) 17 | ); 18 | INSERT INTO cities (state_id, name) VALUES (1, "San Francisco"), (1, "San Jose"), (1, "Los Angeles"), (1, "Fremont"), (1, "Livermore"); 19 | INSERT INTO cities (state_id, name) VALUES (2, "Page"), (2, "Phoenix"); 20 | INSERT INTO cities (state_id, name) VALUES (3, "Dallas"), (3, "Houston"), (3, "Austin"); 21 | INSERT INTO cities (state_id, name) VALUES (4, "New York"); 22 | INSERT INTO cities (state_id, name) VALUES (5, "Las Vegas"), (5, "Reno"), (5, "Henderson"), (5, "Carson City"); 23 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/5-filter_cities.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ lists all states from the database hbtn_0e_0_usa """ 3 | import MySQLdb 4 | import sys 5 | 6 | 7 | if __name__ == "__main__": 8 | db = MySQLdb.connect(host="localhost", user=sys.argv[1], 9 | passwd=sys.argv[2], db=sys.argv[3], port=3306) 10 | cur = db.cursor() 11 | cur.execute("""SELECT cities.name FROM 12 | cities INNER JOIN states ON states.id=cities.state_id 13 | WHERE states.name=%s""", (sys.argv[4],)) 14 | rows = cur.fetchall() 15 | tmp = list(row[0] for row in rows) 16 | print(*tmp, sep=", ") 17 | cur.close() 18 | db.close() 19 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/6-model_state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Start link class to table in database 3 | """ 4 | import sys 5 | from model_state import Base, State 6 | 7 | from sqlalchemy import (create_engine) 8 | 9 | if __name__ == "__main__": 10 | engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}'.format(sys.argv[1], sys.argv[2], sys.argv[3]), pool_pre_ping=True) 11 | Base.metadata.create_all(engine) 12 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/6-model_state.sql: -------------------------------------------------------------------------------- 1 | -- Create database hbtn_0e_6_usa 2 | CREATE DATABASE IF NOT EXISTS hbtn_0e_6_usa; 3 | USE hbtn_0e_6_usa; 4 | SHOW CREATE TABLE states; 5 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/7-model_state_fetch_all.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Start link class to table in database 3 | """ 4 | import sys 5 | from model_state import Base, State 6 | from sqlalchemy import (create_engine) 7 | from sqlalchemy.orm import sessionmaker 8 | 9 | 10 | if __name__ == "__main__": 11 | engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}' 12 | .format(sys.argv[1], sys.argv[2], sys.argv[3])) 13 | Base.metadata.create_all(engine) 14 | Session = sessionmaker(bind=engine) 15 | session = Session() 16 | for instance in session.query(State).order_by(State.id): 17 | print(instance.id, instance.name, sep=": ") 18 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/7-model_state_fetch_all.sql: -------------------------------------------------------------------------------- 1 | -- Insert states 2 | INSERT INTO states (name) VALUES ("California"), ("Arizona"), ("Texas"), ("New York"), ("Nevada"); 3 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/8-model_state_fetch_first.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ prints the first State object from the database hbtn_0e_6_usa 3 | """ 4 | import sys 5 | from model_state import Base, State 6 | from sqlalchemy import (create_engine) 7 | from sqlalchemy.orm import sessionmaker 8 | 9 | 10 | if __name__ == "__main__": 11 | engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}' 12 | .format(sys.argv[1], sys.argv[2], sys.argv[3])) 13 | Base.metadata.create_all(engine) 14 | Session = sessionmaker(bind=engine) 15 | session = Session() 16 | instance = session.query(State).first() 17 | if instance is None: 18 | print("Nothing") 19 | else: 20 | print(instance.id, instance.name, sep=": ") 21 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/9-model_state_filter_a.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ prints the first State object from the database hbtn_0e_6_usa 3 | """ 4 | import sys 5 | from model_state import Base, State 6 | from sqlalchemy import (create_engine) 7 | from sqlalchemy.orm import sessionmaker 8 | 9 | 10 | if __name__ == "__main__": 11 | engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}' 12 | .format(sys.argv[1], sys.argv[2], sys.argv[3])) 13 | Base.metadata.create_all(engine) 14 | Session = sessionmaker(bind=engine) 15 | session = Session() 16 | for instance in session.query(State).filter(State.name.like('%a%')): 17 | print(instance.id, instance.name, sep=": ") 18 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/README.md: -------------------------------------------------------------------------------- 1 | # Python - Object-relational mapping 2 | ![](https://www.fullstackpython.com/img/visuals/orms-bridge.png) 3 | 4 | # Resources 5 | ## Read or watch: 6 | - Object-relational mappers 7 | - mysqlclient/MySQLdb documentation (please don’t pay attention to _mysql) 8 | - MySQLdb tutorial 9 | - SQLAlchemy tutorial 10 | - SQLAlchemy 11 | - mysqlclient/MySQLdb 12 | - Introduction to SQLAlchemy 13 | - Flask SQLAlchemy 14 | - 10 common stumbling blocks for SQLAlchemy newbies 15 | - Python SQLAlchemy Cheatsheet 16 | - SQLAlchemy ORM Tutorial for Python Developers (Warning: This tutorial is with PostgreSQL, but the concept of SQLAlchemy is the same with MySQL) 17 | - SQLAlchemy Tutorial 18 | 19 | # General 20 | - Why Python programming is awesome 21 | - How to connect to a MySQL database from a Python script 22 | - How to SELECT rows in a MySQL table from a Python script 23 | - How to INSERT rows in a MySQL table from a Python script 24 | - What ORM means 25 | - How to map a Python Class to a MySQL table 26 | -------------------------------------------------------------------------------- /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 | This script defines a City class 4 | to work with MySQLAlchemy ORM. 5 | """ 6 | 7 | from relationship_state import Base, State 8 | from sqlalchemy import Column, Integer, String, ForeignKey 9 | 10 | 11 | class City(Base): 12 | """City class 13 | Attributes: 14 | __tablename__ (str): The table name of the class 15 | id (int): The id of the class 16 | name (str): The name of the class 17 | state_id (int): The state the city belongs to 18 | """ 19 | __tablename__ = 'cities' 20 | 21 | id = Column(Integer, primary_key=True) 22 | name = Column(String(128), nullable=False) 23 | state_id = Column(Integer, ForeignKey('states.id'), nullable=False) 24 | -------------------------------------------------------------------------------- /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 | # A Bash script that takes in a URL, sends a request and displays the size of the body of the response 3 | curl -sI "$1" | grep "Content-Length:" | cut -d " " -f 2 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/1-body.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # A Bash script that takes in a URL, sends a GET request and displays only the body of a 200 status code response 3 | curl -Ls "$1" 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/100-status_code.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Script that sends a request to a URL passed as an argument, and displays only the status code of the response 3 | curl -so /dev/null -w "%{http_code}" "$1" 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/101-post_json.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Script that sends a JSON POST request to a URL passed as the first argument, and displays the body of the response 3 | curl -s "$1" -d "@$2" -X POST -H "Content-Type: application/json" 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/102-catch_me.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Script that makes a request to causes an specific response 3 | curl -sL 0.0.0.0:5000/catch_me_3 -X PUT -H "Origin:HolbertonSchool" 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/2-delete.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # A script that sends a DELETE request to the URL passed as the first argument and displays the body of the response 3 | curl -s "$1" -X DELETE 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/3-methods.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Script that takes an URL and shows the Allowed OPTIONS 3 | curl -sI -X OPTIONS "$1" | grep "Allow:" | cut -d " " -f 2- 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/4-header.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Script that takes an URL and displays the body of the response 3 | curl -sH "X-School-User-Id: 98" "${1}" 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/5-post_params.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Script that sends a POST request and displays the body response 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 | -------------------------------------------------------------------------------- /0x10-python-network_0/README.md: -------------------------------------------------------------------------------- 1 | # `Python_Network_#0` 2 | 3 | ![](https://data-flair.training/blogs/wp-content/uploads/sites/2/2018/05/Socket-Vocabulary-01.jpg) 4 | -------------------------------------------------------------------------------- /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 | """ 3 | Python script that takes in a URL, sends a request and displays 4 | the value of the X-Request-Id variable found in the header 5 | """ 6 | import urllib.request 7 | import sys 8 | 9 | 10 | if __name__ == "__main__": 11 | with urllib.request.urlopen(sys.argv[1]) as response: 12 | html = response.info() 13 | print(html.get('X-Request-Id')) 14 | -------------------------------------------------------------------------------- /0x11-python-network_1/10-my_github.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Python script that takes GitHub credentials 4 | and uses the GitHub API to display the user id 5 | """ 6 | from requests import get, auth 7 | import sys 8 | 9 | 10 | if __name__ == "__main__": 11 | url = 'https://api.github.com/user' 12 | user = sys.argv[1] 13 | password = sys.argv[2] 14 | r = get(url, auth=auth.HTTPBasicAuth(user, password)) 15 | print(r.json().get('id')) 16 | -------------------------------------------------------------------------------- /0x11-python-network_1/100-github_commits.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Python script that sends a request to the URL and 3 | displays the value of a variable in the response header 4 | """ 5 | import sys 6 | import requests 7 | 8 | 9 | if __name__ == "__main__": 10 | url = "https://api.github.com/repos/{}/{}/commits".format( 11 | sys.argv[2], sys.argv[1]) 12 | 13 | r = requests.get(url) 14 | commits = r.json() 15 | try: 16 | for i in range(10): 17 | print("{}: {}".format( 18 | commits[i].get("sha"), 19 | commits[i].get("commit").get("author").get("name"))) 20 | except IndexError: 21 | pass 22 | -------------------------------------------------------------------------------- /0x11-python-network_1/101-starwars.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Python script that sends a search request to the 4 | Star Wars API, searching people 5 | """ 6 | import requests 7 | import sys 8 | 9 | 10 | if __name__ == "__main__": 11 | page = 1 12 | while page: 13 | s = sys.argv[1] 14 | url = 'https://swapi.co/api/people/?search={}&page={}'.format(s, page) 15 | r = requests.get(url) 16 | json_o = r.json() 17 | if page == 1: 18 | print("Number of results: {}".format(json_o.get('count'))) 19 | for character in json_o.get('results'): 20 | print(character.get('name')) 21 | if not json_o.get('next'): 22 | break 23 | page += 1 24 | -------------------------------------------------------------------------------- /0x11-python-network_1/102-starwars.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Python script that sends a search request to the 4 | Star Wars API, searching people 5 | """ 6 | import requests 7 | import sys 8 | 9 | 10 | if __name__ == "__main__": 11 | page = 1 12 | 13 | films = {} 14 | 15 | for num in range(1, 8): 16 | url = 'https://swapi.co/api/films/{}/'.format(num) 17 | r = requests.get(url) 18 | films[url] = r.json().get('title') 19 | 20 | while page: 21 | s = sys.argv[1] 22 | url = 'https://swapi.co/api/people/?search={}&page={}'.format(s, page) 23 | r = requests.get(url) 24 | json_o = r.json() 25 | if page == 1: 26 | print("Number of results: {}".format(json_o.get('count'))) 27 | for character in json_o.get('results'): 28 | print(character.get('name')) 29 | for film in character.get('films'): 30 | print("\t{}".format(films[film])) 31 | if not json_o.get('next'): 32 | break 33 | page += 1 34 | -------------------------------------------------------------------------------- /0x11-python-network_1/103-search_twitter.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Python script that sends a search request to the Twitter API 4 | """ 5 | import requests 6 | import base64 7 | import sys 8 | 9 | 10 | if __name__ == "__main__": 11 | client_key = sys.argv[1] 12 | client_secret = sys.argv[2] 13 | 14 | key_s = '{}:{}'.format(client_key, client_secret).encode('ascii') 15 | b64_key = base64.b64encode(key_s) 16 | b64_key = b64_key.decode('ascii') 17 | 18 | b_url = 'https://api.twitter.com/' 19 | a_url = '{}oauth2/token'.format(b_url) 20 | 21 | a_headers = { 22 | 'Authorization': 'Basic {}'.format(b64_key), 23 | 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' 24 | } 25 | 26 | a_data = { 27 | 'grant_type': 'client_credentials' 28 | } 29 | 30 | a_resp = requests.post(a_url, headers=a_headers, data=a_data) 31 | 32 | access_token = a_resp.json().get('access_token') 33 | 34 | s_headers = { 35 | 'Authorization': 'Bearer {}'.format(access_token) 36 | } 37 | 38 | s_params = { 39 | 'q': sys.argv[3], 40 | 'result_type': 'recent', 41 | 'count': 5 42 | } 43 | 44 | s_url = '{}1.1/search/tweets.json'.format(b_url) 45 | s_resp = requests.get(s_url, headers=s_headers, params=s_params) 46 | 47 | tweet_data = s_resp.json() 48 | 49 | for x in tweet_data['statuses']: 50 | print("[{}] {} by {}".format(x.get('id'), x.get('text'), 51 | x.get('user').get('name'))) 52 | -------------------------------------------------------------------------------- /0x11-python-network_1/2-post_email.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Python script that takes in a URL and an email, sends a POST 4 | request to the passed URL with the email as a parameter, and 5 | displays the body of the response 6 | """ 7 | from urllib import request, parse 8 | import sys 9 | 10 | 11 | if __name__ == "__main__": 12 | values = {'email': sys.argv[2]} 13 | data = parse.urlencode(values) 14 | data = data.encode('ascii') 15 | req = request.Request(sys.argv[1], data) 16 | with request.urlopen(req) as response: 17 | body = response.read() 18 | print(body.decode('utf-8')) 19 | -------------------------------------------------------------------------------- /0x11-python-network_1/3-error_code.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Python script that takes in a URL, sends a request and displays 4 | the value of the X-Request-Id variable found in the header 5 | (handling HTTP errors) 6 | """ 7 | from urllib import request, error 8 | import sys 9 | 10 | 11 | if __name__ == "__main__": 12 | try: 13 | with request.urlopen(sys.argv[1]) as response: 14 | body = response.read() 15 | print(body.decode('utf-8')) 16 | except error.HTTPError as err: 17 | print('Error code: {}'.format(err.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 | """ 3 | Python script that takes in a URL and an email address, 4 | sends a POST request to the passed URL with the email, 5 | and displays the body of the response 6 | """ 7 | import requests 8 | import sys 9 | 10 | 11 | if __name__ == "__main__": 12 | r = requests.post(sys.argv[1], data={'email': sys.argv[2]}) 13 | print(r.text) 14 | -------------------------------------------------------------------------------- /0x11-python-network_1/7-error_code.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Python script that sends a request to the URL and 4 | displays: 5 | - The body of the response if there are no errors 6 | - The error code when there is an HTTP error. 7 | """ 8 | import requests 9 | import sys 10 | 11 | 12 | if __name__ == "__main__": 13 | r = requests.get(sys.argv[1]) 14 | if r.status_code >= 400: 15 | print("Error code: {}".format(r.status_code)) 16 | else: 17 | print(r.text) 18 | -------------------------------------------------------------------------------- /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/9-starwars.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Python script that sends a search request to the 4 | Star Wars API, searching people 5 | """ 6 | import requests 7 | import sys 8 | 9 | 10 | if __name__ == "__main__": 11 | search = 'https://swapi.co/api/people/?search={}'.format(sys.argv[1]) 12 | r = requests.get(search) 13 | json_o = r.json() 14 | print("Number of results: {}".format(json_o.get('count'))) 15 | for character in json_o.get('results'): 16 | print(character.get('name')) 17 | -------------------------------------------------------------------------------- /0x11-python-network_1/README.md: -------------------------------------------------------------------------------- 1 | # Network 1 2 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/0-javascript_is_amazing.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | // a script that prints “JavaScript is amazing” using the 'node' intepreter 3 | 4 | // This creates a const variable called myVar and assigns the string value to it. 5 | const myVar = 'JavaScript is amazing'; 6 | 7 | // console.log() function is used to print the value of myVar to the console. 8 | console.log(myVar); 9 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/1-multi_languages.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | // a script that prints 3 lines 3 | 4 | // created constant variables, each with the desired message. 5 | const line1 = 'C is fun'; 6 | const line2 = 'Python is cool'; 7 | const line3 = 'JavaScript is amazing'; 8 | 9 | // the console.log() function is used three times to print each line to the console, one at a time. 10 | console.log(line1); 11 | console.log(line2); 12 | console.log(line3); 13 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/10-factorial.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | function factorial (n) { 3 | if (n < 0) { 4 | return (-1); 5 | } 6 | if (n === 0 || isNaN(n)) { 7 | return (1); 8 | } 9 | return (n * factorial(n - 1)); 10 | } 11 | 12 | console.log(factorial(Number(process.argv[2]))); 13 | -------------------------------------------------------------------------------- /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++) { 4 | theFunction(); 5 | } 6 | }; 7 | -------------------------------------------------------------------------------- /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 arr = process.argv.slice(2).map(Number); 6 | const second = arr.sort(function (a, b) { return b - a; })[1]; 7 | console.log(second); 8 | } 9 | -------------------------------------------------------------------------------- /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 = function (a, b) { 3 | return (a + b); 4 | }; 5 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/2-arguments.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | // calculate the number of arguments passed to the script using 'process.argv.length - 2' 4 | // sbtracting 2 to exclude the 'node' command and the name of the script itself 5 | 6 | const argsCount = process.argv.length - 2; 7 | 8 | // using 'if...else' statement to check the value of 'argsCount' 9 | // using 'console.log' to print the appropriate message 10 | 11 | if (argsCount === 0) { 12 | console.log('No argument'); 13 | } else if (argsCount === 1) { 14 | console.log('Argument found'); 15 | } else { 16 | console.log('Arguments found'); 17 | } 18 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/3-value_argument.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | // using destruct 3 | // using slice(2) to start the slice from the third element of the process.argv array, 4 | // skipping over the node command and the name of the script itself 5 | 6 | const [arg] = process.argv.slice(2); 7 | 8 | // using an if...else statement to check if arg exists 9 | if (!arg) { 10 | console.log('No argument'); 11 | 12 | // Otherwise, we print arg using console.log(...) 13 | } else { 14 | console.log(arg); 15 | } 16 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/4-concat.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | // process.argv is an array that contains the command-line arguments passed to the script 3 | // so we access the third and fourth elements (process.argv[2] and process.argv[3]) to get the two arguments that we want to print. 4 | 5 | const arg1 = process.argv[2]; 6 | const arg2 = process.argv[3]; 7 | 8 | // use template literals (the backtick characters surrounding the string) to interpolate the values of arg1 and arg2 into the output string in the specified format 9 | 10 | console.log(`${arg1} is ${arg2}`); 11 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/5-to_integer.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | // using the isNaN() function to check if the first argument (arg) can be converted to an integer. 3 | 4 | const arg = process.argv[2]; 5 | 6 | // using the ! (logical NOT) operator to invert the boolean value returned by isNaN() 7 | // printing the result using template literals to interpolate the value into the output string in the specified format. 8 | if (!isNaN(parseInt(arg))) { 9 | console.log(`My number: ${parseInt(arg)}`); 10 | // If it can't be converted to an integer, we print "Not a number" instead. 11 | } else { 12 | console.log('Not a number'); 13 | } 14 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/6-multi_languages_loop.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | // Basic print with Javascript 3 | for (const line of ['C is fun', 'Python is cool', 'JavaScript is amazing']) { 4 | console.log(line); 5 | } 6 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/7-multi_c.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | if (process.argv[2] === undefined || isNaN(process.argv[2])) { 3 | console.log('Missing number of occurrences'); 4 | } else { 5 | const x = Number(process.argv[2]); 6 | let i = 0; 7 | while (i < x) { 8 | console.log('C is fun'); 9 | i++; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/8-square.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | if (process.argv[2] === undefined || isNaN(process.argv[2])) { 3 | console.log('Missing size'); 4 | } else { 5 | const x = Number(process.argv[2]); 6 | let i = 0; 7 | while (i < x) { 8 | console.log('X'.repeat(x)); 9 | i++; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/9-add.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | function add (a, b) { 3 | const c = a + b; 4 | console.log(c); 5 | } 6 | 7 | add(Number(process.argv[2]), Number(process.argv[3])); 8 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/README.md: -------------------------------------------------------------------------------- 1 | # `Background Context` 2 | # Why JavaScript is Amazing! 3 | ![](https://iwearshorts.com/wp-content/uploads/2015/05/javascript-site-1070x580.jpg) 4 | - ### `Versatile:` Can be used for a variety of purposes, from creating simple animations to developing complex web applications. 5 | - ### `Compatibility:` Can run on any browser or platform, making it accessible to a broad audience. 6 | - ### `Front-end integration:` Can interact with HTML and CSS, making it an essential part of front-end web development. 7 | - ### `Constantly evolving:` New updates and features are released regularly, ensuring that it remains relevant and adaptable to changing technology trends. 8 | - ### `Dynamic:` Allows for real-time interactions and immediate feedback, making for a seamless user experience. 9 | - ### `Large community:` A vast community of developers provides support, resources, and a wealth of knowledge and expertise. 10 | 11 | 12 | -------------------------------------------------------------------------------- /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-data.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | exports.list = [1, 2, 3, 4, 5]; 3 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/100-map.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const list = require('./100-data').list; 3 | console.log(list); 4 | console.log(list.map((x, i) => x * i)); 5 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/101-sorted.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const dict = require('./101-data').dict; 3 | const dKeys = Object.keys(dict); 4 | const values = Object.values(dict); 5 | let matched; 6 | const result = {}; 7 | // loop over the values 8 | for (let i = 0; i < values.length; i++) { 9 | result[JSON.stringify(values[i])] = []; 10 | matched = dKeys.filter(key => dict[key] === values[i]); 11 | matched.forEach(item => result[JSON.stringify(values[i])].push(item)); 12 | } 13 | console.log(result); 14 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/102-concat.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const { readFileSync, writeFile } = require('fs'); 3 | const { argv } = require('process'); 4 | 5 | const getContent = (file) => { 6 | return readFileSync(file, 'utf8'); 7 | }; 8 | 9 | const concated = getContent(argv[2]) + '' + getContent(argv[3]); 10 | 11 | writeFile(argv[4], concated, 'utf8', err => { 12 | if (err) throw err; 13 | }); 14 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/README.md: -------------------------------------------------------------------------------- 1 | # `JavaScript_Objects_Scopes_Closures` 2 | 3 | ![](https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRtiNswythrhdDbb7EeERcaHCPe-6txyPbwfEt3gT5Clv_0RTHFolZVKLGa-EQH7V-hfzI&usqp=CAU) 4 | # 5 | ![](https://www.scientecheasy.com/wp-content/uploads/2022/03/types-of-objects-in-javascript.png) 6 | -------------------------------------------------------------------------------- /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 | 3 | const request = require('request'); 4 | const episodeNum = process.argv[2]; 5 | const API_URL = 'https://swapi-api.hbtn.io/api/films/'; 6 | 7 | request(API_URL + episodeNum, function (err, response, body) { 8 | if (err) { 9 | console.log(err); 10 | } else if (response.statusCode === 200) { 11 | const responseJSON = JSON.parse(body); 12 | console.log(responseJSON.title); 13 | } else { 14 | console.log('Error code: ' + response.statusCode); 15 | } 16 | }); 17 | -------------------------------------------------------------------------------- /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 | 3 | const request = require('request'); 4 | const url = process.argv[2]; 5 | 6 | request(url, function (err, response, body) { 7 | if (err) { 8 | console.log(err); 9 | } else if (response.statusCode === 200) { 10 | const completed = {}; 11 | const tasks = JSON.parse(body); 12 | for (const i in tasks) { 13 | const task = tasks[i]; 14 | if (task.completed === true) { 15 | if (completed[task.userId] === undefined) { 16 | completed[task.userId] = 1; 17 | } else { 18 | completed[task.userId]++; 19 | } 20 | } 21 | } 22 | console.log(completed); 23 | } else { 24 | console.log('An error occured. Status code: ' + response.statusCode); 25 | } 26 | }); 27 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/README.md: -------------------------------------------------------------------------------- 1 | # `Javascript-web_scraping` 2 | 3 | ![](https://res.cloudinary.com/practicaldev/image/fetch/s--Hee-36uP--/c_imagga_scale,f_auto,fl_progressive,h_500,q_auto,w_1000/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/njjyqjkdad411h6ysa2u.jpg) 4 | 5 | 6 | # `General` 7 | - ## Why JavaScript programming is amazing 8 | - ## How to manipulate JSON data 9 | - ## How to use request and fetch API 10 | - ## How to read and write a file using fs module 11 | 12 | ## Install Node 10 13 | ``` 14 | curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash - 15 | sudo apt-get install -y nodejs 16 | ``` 17 | 18 | ## Install semi-standard 19 | ``` 20 | sudo npm install semistandard --global 21 | ``` 22 | 23 | ## Install request module and use it 24 | ``` 25 | sudo npm install request --global 26 | export NODE_PATH=/usr/lib/node_modules 27 | ``` 28 | ![](https://cms.iproyal.com/uploads/Web_Scraping_With_Java_Script_and_Node_js_Without_Getting_Blocked_847x300_5e48f3d270.jpg) 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![img](https://assets.imaginablefutures.com/media/images/ALX_Logo.max-200x150.png) 2 | # `Alx-higher_level_programming` 3 | - ### This repository houses a comprehensive collection of projects completed using the Python and Javascript programming languages 4 | - ### Overall, this repository offers a valuable resource for anyone looking to learn or enhance their skills in Python and JavaScript programming. 5 | 6 | # Welcome to the exciting world of Python programming! 7 | ![](https://media3.giphy.com/media/coxQHKASG60HrHtvkt/giphy.gif?cid=6c09b952exccjrbpzizbaofik0ppffuhik96ew0z3wehubpq&ep=v1_gifs_search&rid=giphy.gif&ct=g) 8 | ## Why Python programming is awesome 9 | - ### Whether you're a beginner or an experienced programmer, the Python world has something to offer 10 | - ### Python syntax is designed to be easy to read and write, making it an excellent language for beginners to learn. 11 | - ### Python's large standard library and numerous third-party packages make it a highly customizable language, capable of addressing a diverse range of programming needs. 12 | -------------------------------------------------------------------------------- /python-tests_1/0-add_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def add_integer(a, b=98): 3 | """function that add 2 numbers""" 4 | 5 | if not a or (type(a) != int and type(a) != float): 6 | raise TypeError("a must be an integer") 7 | if type(b) != int and type(b) != float: 8 | raise TypeError("b must be an integer") 9 | 10 | return(int(a) + int(b)) 11 | -------------------------------------------------------------------------------- /python-tests_1/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 | Args: 9 | m_a (list of lists of ints/floats): The first matrix. 10 | m_b (list of lists of ints/floats): The second matrix. 11 | """ 12 | 13 | return (np.matmul(m_a, m_b)) 14 | -------------------------------------------------------------------------------- /python-tests_1/102-python.c: -------------------------------------------------------------------------------- 1 | #include "python.h" 2 | #include 3 | 4 | /** 5 | * print_python_string - Prints information about Python strings. 6 | * @p: A PyObject string object. 7 | */ 8 | void print_python_string(PyObject *p) 9 | { 10 | long int length; 11 | 12 | fflush(stdout); 13 | 14 | printf("[.] string object info\n"); 15 | if (strcmp(p->ob_type->tp_name, "str") != 0) 16 | { 17 | printf(" [ERROR] Invalid String Object\n"); 18 | return; 19 | } 20 | 21 | length = ((PyASCIIObject *)(p))->length; 22 | 23 | if (PyUnicode_IS_COMPACT_ASCII(p)) 24 | printf(" type: compact ascii\n"); 25 | else 26 | printf(" type: compact unicode object\n"); 27 | printf(" length: %ld\n", length); 28 | printf(" value: %ls\n", PyUnicode_AsWideCharString(p, &length)); 29 | } 30 | -------------------------------------------------------------------------------- /python-tests_1/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 | Args: 8 | matrix (list): A list of lists of ints or floats. 9 | div (int/float): The divisor. 10 | Raises: 11 | TypeError: If the matrix contains non-numbers. 12 | TypeError: If the matrix contains rows of different sizes. 13 | TypeError: If div is not an int or float. 14 | ZeroDivisionError: If div is 0. 15 | Returns: 16 | A new matrix representing the result of the division. 17 | """ 18 | if (not isinstance(matrix, list) or matrix == [] or 19 | not all(isinstance(row, list) for row in matrix) or 20 | not all((isinstance(ele, int) or isinstance(ele, float)) 21 | for ele in [num for row in matrix for num in row])): 22 | raise TypeError("matrix must be a matrix (list of lists) of " 23 | "integers/floats") 24 | 25 | if not all(len(row) == len(matrix[0]) for row in matrix): 26 | raise TypeError("Each row of the matrix must have the same size") 27 | 28 | if not isinstance(div, int) and not isinstance(div, float): 29 | raise TypeError("div must be a number") 30 | 31 | if div == 0: 32 | raise ZeroDivisionError("division by zero") 33 | 34 | return ([list(map(lambda x: round(x / div, 2), row)) for row in matrix]) 35 | -------------------------------------------------------------------------------- /python-tests_1/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 | Args: 8 | first_name (str): The first name to print. 9 | last_name (str): The last name to print. 10 | Raises: 11 | TypeError: If either of first_name or last_name are not strings. 12 | """ 13 | if not isinstance(first_name, str): 14 | raise TypeError("first_name must be a string") 15 | if not isinstance(last_name, str): 16 | raise TypeError("last_name must be a string") 17 | print("My name is {} {}".format(first_name, last_name)) 18 | -------------------------------------------------------------------------------- /python-tests_1/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 | Args: 8 | size (int): The height/width of the square. 9 | Raises: 10 | TypeError: If size is not an integer. 11 | ValueError: If size is < 0 12 | """ 13 | if not isinstance(size, int): 14 | raise TypeError("size must be an integer") 15 | if size < 0: 16 | raise ValueError("size must be >= 0") 17 | 18 | for i in range(size): 19 | [print("#", end="") for j in range(size)] 20 | print("") 21 | -------------------------------------------------------------------------------- /python-tests_1/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 | Args: 8 | text (string): The text to print. 9 | Raises: 10 | TypeError: If text is not a string. 11 | """ 12 | if not isinstance(text, str): 13 | raise TypeError("text must be a string") 14 | 15 | c = 0 16 | while c < len(text) and text[c] == ' ': 17 | c += 1 18 | 19 | while c < len(text): 20 | print(text[c], end="") 21 | if text[c] == "\n" or text[c] in ".?:": 22 | if text[c] in ".?:": 23 | print("\n") 24 | c += 1 25 | while c < len(text) and text[c] == ' ': 26 | c += 1 27 | continue 28 | c += 1 29 | -------------------------------------------------------------------------------- /python-tests_1/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 | -------------------------------------------------------------------------------- /python-tests_1/__pycache__/6-max_integer.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/python-tests_1/__pycache__/6-max_integer.cpython-38.pyc -------------------------------------------------------------------------------- /python-tests_1/besthor.txt: -------------------------------------------------------------------------------- 1 | Hey geeks 2 | so i was working on my sandbox while carrying out my projects 3 | i was in that "speed typing" zone 4 | feeling like a super human 5 | i was done with my project files 6 | wrote a meanifull commit message 7 | and was about to push the files 8 | after typing "git push" 9 | while the process was still loading, 10 | i hurriedly typed the command "clear" to erase my interface 11 | i wasnt patient enough to see the "git push process" run to the end 12 | the "clear " command i typed interferred with the proccess 13 | and it made my "git push" process to start lagging 14 | It was so slow unlike the usual super speed it takes to load the process 15 | 16 | for a long moment, i was so unsure of what next to do 17 | my files couldnt jurney through into my GitHub 18 | i became really worrid 19 | i resulted into using another IDE (WSL, vagrant, VSCODE, GitBash e.t.c) 20 | Suprisingly, they all behaved in similar ways to my sandbox 21 | 22 | In my quest for a fast solution, i was impatient and i destroyed my sandbox 23 | It was so funny to me, because i have never thought i would be part of those little livered persons 24 | that results into sandbox destruct at the any sightrst provocation. 25 | 26 | But i had to do that, to be satisfied that maybe my sandbox would be restored to its original state 27 | no doubt i lost my local repositories and other valuable directories 28 | Luckily, they can all be recovered and brought back into my local machine again 29 | all thanks to open source version control tool (GitHub) 30 | -------------------------------------------------------------------------------- /python-tests_1/main.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 | -------------------------------------------------------------------------------- /python-tests_1/python.h: -------------------------------------------------------------------------------- 1 | #ifndef PTYHON_H 2 | #define PYTHON_H 3 | #include 4 | 5 | void print_python_string(PyObject *p) 6 | 7 | #endif 8 | -------------------------------------------------------------------------------- /python-tests_1/tests/0-add_integer.txt: -------------------------------------------------------------------------------- 1 | 2 | ''' 3 | # Importing the required function 4 | >>> from importlib import import_module 5 | >>> add_integer = import_module('0-add_integer').add_integer 6 | 7 | # Valid test arguments 8 | >>> add_integer(3, 4) 9 | 7 10 | >>> add_integer(2) 11 | 100 12 | >>> add_integer(1.2, 5.8) 13 | 6 14 | 15 | # Test for invalid arguments 16 | >>> try: 17 | ... add_integer('3', 3) 18 | ... except TypeError as ex: 19 | ... print(ex.args[0]) 20 | a must be an integer 21 | >>> try: 22 | ... add_integer(('3'), 3) 23 | ... except TypeError as ex: 24 | ... print(ex.args[0]) 25 | a must be an integer 26 | >>> try: 27 | ... add_integer(3, None) 28 | ... except TypeError as ex: 29 | ... print(ex.args[0]) 30 | b must be an integer 31 | >>> try: 32 | ... add_integer(3, '4') 33 | ... except TypeError as ex: 34 | ... print(ex.args[0]) 35 | b must be an integer 36 | >>> try: 37 | ... add_integer(float('inf'), float('inf')) 38 | ... except Exception as ex: 39 | ... print(ex.args[0]) 40 | cannot convert float infinity to integer 41 | >>> try: 42 | ... add_integer(float('inf'), 4) 43 | ... except Exception as ex: 44 | ... print(ex.args[0]) 45 | cannot convert float infinity to integer 46 | >>> try: 47 | ... add_integer(float('NaN'), 5) 48 | ... except Exception as ex: 49 | ... print(ex.args[0]) 50 | cannot convert float NaN to integer 51 | 52 | ''' 53 | -------------------------------------------------------------------------------- /python-tests_1/tests/__pycache__/6-max_integer_test.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/besthor/alx-higher_level_programming/f470e2bab6c5b66c04321ac1fc94e377387f4898/python-tests_1/tests/__pycache__/6-max_integer_test.cpython-38.pyc --------------------------------------------------------------------------------