├── 0x00-python-hello_world ├── 0-run ├── 1-run_inline ├── 10-check_cycle.c ├── 10-linked_lists.c ├── 10-main.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 └── main.py ├── 0x01-python-if_else_loops_functions ├── 0-positive_or_negative.py ├── 1-last_digit.py ├── 10-add.py ├── 10-main.py ├── 100-print_tebahpla.py ├── 101-main.py ├── 101-remove_char_at.py ├── 102-magic_calculation.py ├── 11-main.py ├── 11-pow.py ├── 12-fizzbuzz.py ├── 12-main.py ├── 13-insert_number.c ├── 2-print_alphabet.py ├── 3-print_alphabt.py ├── 4-print_hexa.py ├── 5-print_comb2.py ├── 6-print_comb3.py ├── 7-islower.py ├── 7-main.py ├── 8-main.py ├── 8-uppercase.py ├── 9-main.py ├── 9-print_last_digit.py ├── README.md └── lists.h ├── 0x02-python-import_modules ├── 0-add.py ├── 1-calculation.py ├── 100-my_calculator.py ├── 101-easy_print.py ├── 102-magic_calculation.py ├── 103-fast_alphabet.py ├── 2-args.py ├── 3-infinite_add.py ├── 4-hidden_discovery.py ├── 5-variable_load.py ├── README.md ├── add_0.py ├── calculator_1.py └── variable_load_5.py ├── 0x03-python-data_structures ├── .0-print_list_integer.py.swp ├── 0-print_list_integer.py ├── 1-element_at.py ├── 10-divisible_by_2.py ├── 100-print_python_list_info.c ├── 100-test_lists.py ├── 11-delete_at.py ├── 12-switch.py ├── 13-is_palindrome.c ├── 2-replace_in_list.py ├── 3-print_reversed_list_integer.py ├── 4-new_in_list.py ├── 5-no_c.py ├── 6-print_matrix_integer.py ├── 7-add_tuple.py ├── 8-multiple_returns.py ├── 9-max_integer.py ├── README.md └── lists.h ├── 0x04-python-more_data_structures ├── 0-square_matrix_simple.py ├── 1-search_replace.py ├── 10-best_score.py ├── 100-weight_average.py ├── 101-square_matrix_map.py ├── 102-complex_delete.py ├── 103-python.c ├── 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 └── tests │ ├── 0-main.py │ ├── 1-main.py │ ├── 100-main.py │ ├── 101-main.py │ ├── 102-main.py │ ├── 2-main.py │ ├── 3-main.py │ ├── 4-main.py │ ├── 5-main.py │ └── 6-main.py ├── 0x07-python-test_driven_development ├── 0-add_integer.py ├── 100-matrix_mul.py ├── 101-lazy_matrix_mul.py ├── 102-python.c ├── 2-matrix_divided.py ├── 3-say_my_name.py ├── 4-print_square.py ├── 5-text_indentation.py ├── 6-max_integer.py ├── README.md └── tests │ ├── 0-add_integer.txt │ ├── 0-main.py │ ├── 100-main.py │ ├── 100-matrix_mul.txt │ ├── 101-lazy_matrix_mul.txt │ ├── 101-main.py │ ├── 2-main.py │ ├── 2-matrix_divided.txt │ ├── 3-main.py │ ├── 4-main.py │ ├── 4-print_square.txt │ ├── 5-main.py │ ├── 5-text_indentation.txt │ └── 6-max_integer_test.py ├── 0x08-python-more_classes ├── 0-rectangle.py ├── 1-rectangle.py ├── 101-nqueens.py ├── 2-rectangle.py ├── 3-rectangle.py ├── 4-rectangle.py ├── 5-rectangle.py ├── 6-rectangle.py ├── 7-rectangle.py ├── 8-rectangle.py ├── 9-rectangle.py ├── README.md └── tests │ ├── 0-main.py │ ├── 1-main.py │ ├── 2-main.py │ ├── 3-main.py │ ├── 4-main.py │ ├── 5-main.py │ ├── 6-main.py │ ├── 7-main.py │ ├── 8-main.py │ └── 9-main.py ├── 0x09-python-everything_is_object ├── 0-answer.txt ├── 1-answer.txt ├── 10-answer.txt ├── 100-magic_string.py ├── 101-locked_class.py ├── 103-line1.txt ├── 103-line2.txt ├── 104-line1.txt ├── 104-line2.txt ├── 104-line3.txt ├── 104-line4.txt ├── 104-line5.txt ├── 105-line1.txt ├── 106-line1.txt ├── 106-line2.txt ├── 106-line3.txt ├── 106-line4.txt ├── 106-line5.txt ├── 11-answer.txt ├── 12-answer.txt ├── 13-answer.txt ├── 14-answer.txt ├── 15-answer.txt ├── 16-answer.txt ├── 17-answer.txt ├── 18-answer.txt ├── 19-copy_list.py ├── 2-answer.txt ├── 20-answer.txt ├── 21-answer.txt ├── 22-answer.txt ├── 23-answer.txt ├── 24-answer.txt ├── 25-answer.txt ├── 26-answer.txt ├── 27-answer.txt ├── 28-answer.txt ├── 3-answer.txt ├── 4-answer.txt ├── 5-answer.txt ├── 6-answer.txt ├── 7-answer.txt ├── 8-answer.txt ├── 9-answer.txt ├── README.md └── tests │ ├── 100-main.py │ ├── 101-main.py │ └── 19-main.py ├── 0x0A-python-inheritance ├── 0-lookup.py ├── 1-my_list.py ├── 10-square.py ├── 100-my_int.py ├── 101-add_attribute.py ├── 11-square.py ├── 2-is_same_class.py ├── 3-is_kind_of_class.py ├── 4-inherits_from.py ├── 5-base_geometry.py ├── 6-base_geometry.py ├── 7-base_geometry.py ├── 8-rectangle.py ├── 9-rectangle.py ├── README.md └── tests │ ├── 0-main.py │ ├── 1-main.py │ ├── 1-my_list.txt │ ├── 10-main.py │ ├── 100-main.py │ ├── 101-main.py │ ├── 11-main.py │ ├── 2-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 ├── 0x0B-python-input_output ├── 0-read_file.py ├── 1-write_file.py ├── 10-student.py ├── 100-append_after.py ├── 101-stats.py ├── 11-student.py ├── 12-pascal_triangle.py ├── 2-append_write.py ├── 3-to_json_string.py ├── 4-from_json_string.py ├── 5-save_to_json_file.py ├── 6-load_from_json_file.py ├── 7-add_item.py ├── 8-class_to_json.py ├── 9-student.py └── README.md ├── 0x0C-python-almost_a_circle ├── README.md ├── models │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-34.pyc │ │ └── base.cpython-34.pyc │ ├── base.py │ ├── rectangle.py │ └── square.py └── tests │ └── test_models │ ├── __init__.py │ ├── __pycache__ │ ├── __init__.cpython-34.pyc │ └── test_base.cpython-34.pyc │ ├── test_base.py │ ├── test_rectangle.py │ └── test_square.py ├── 0x0D-SQL_introduction ├── 0-list_databases.sql ├── 1-create_database_if_missing.sql ├── 10-top_score.sql ├── 100-move_to_utf8.sql ├── 101-avg_temperatures.sql ├── 102-top_city.sql ├── 103-max_state.sql ├── 11-best_score.sql ├── 12-no_cheating.sql ├── 13-change_class.sql ├── 14-average.sql ├── 15-groups.sql ├── 16-no_link.sql ├── 2-remove_database.sql ├── 3-list_tables.sql ├── 4-first_table.sql ├── 5-full_table.sql ├── 6-list_values.sql ├── 7-insert_value.sql ├── 8-count_89.sql ├── 9-full_creation.sql ├── README.md └── temperatures.sql ├── 0x0E-SQL_more_queries ├── 0-privileges.sql ├── 1-create_user.sql ├── 10-genre_id_by_show.sql ├── 100-not_my_genres.sql ├── 101-not_a_comedy.sql ├── 102-rating_shows.sql ├── 103-rating_genres.sql ├── 11-genre_id_all_shows.sql ├── 12-no_genre.sql ├── 13-count_shows_by_genre.sql ├── 14-my_genres.sql ├── 15-comedy_only.sql ├── 16-shows_by_genre.sql ├── 2-create_read_user.sql ├── 3-force_name.sql ├── 4-never_empty.sql ├── 5-unique_id.sql ├── 6-states.sql ├── 7-cities.sql ├── 8-cities_of_california_subquery.sql ├── 9-cities_by_state_join.sql └── README.md ├── 0x0F-python-object_relational_mapping ├── 0-select_states.py ├── 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 └── tests │ ├── 0-select_states.sql │ ├── 100-relationship_states_cities.sql │ ├── 101-relationship_states_cities_list.sql │ ├── 14-model_city_fetch_by_state.sql │ ├── 4-cities_by_state.sql │ ├── 6-model_state.py │ ├── 6-model_state.sql │ └── 7-model_state_fetch_all.sql ├── 0x10-python-network_0 ├── 0-body_size.sh ├── 1-body.sh ├── 100-status_code.sh ├── 101-post_json.sh ├── 102-catch_me.sh ├── 2-delete.sh ├── 3-methods.sh ├── 4-header.sh ├── 5-post_params.sh ├── 6-peak.py ├── 6-peak.txt └── README.md ├── 0x11-python-network_1 ├── 0-hbtn_status.py ├── 1-hbtn_header.py ├── 10-my_github.py ├── 100-github_commits.py ├── 2-post_email.py ├── 3-error_code.py ├── 4-hbtn_status.py ├── 5-hbtn_header.py ├── 6-post_email.py ├── 7-error_code.py ├── 8-json_api.py └── README.md ├── 0x12-javascript-warm_up ├── 0-javascript_is_amazing.js ├── 1-multi_languages.js ├── 10-factorial.js ├── 100-let_me_const.js ├── 101-call_me_moby.js ├── 102-add_me_maybe.js ├── 103-object_fct.js ├── 11-second_biggest.js ├── 12-object.js ├── 13-add.js ├── 2-arguments.js ├── 3-value_argument.js ├── 4-concat.js ├── 5-to_integer.js ├── 6-multi_languages_loop.js ├── 7-multi_c.js ├── 8-square.js ├── 9-add.js └── README.md ├── 0x13-javascript_objects_scopes_closures ├── 0-rectangle.js ├── 1-rectangle.js ├── 10-converter.js ├── 100-map.js ├── 101-sorted.js ├── 102-concat.js ├── 2-rectangle.js ├── 3-rectangle.js ├── 4-rectangle.js ├── 5-square.js ├── 6-square.js ├── 7-occurrences.js ├── 8-esrever.js ├── 9-logme.js └── README.md ├── 0x14-javascript-web_scraping ├── 0-readme.js ├── 1-writeme.js ├── 100-starwars_characters.js ├── 101-starwars_characters.js ├── 102-search_twitter.js ├── 2-statuscode.js ├── 3-starwars_title.js ├── 4-starwars_count.js ├── 5-request_store.js ├── 6-completed_tasks.js └── README.md ├── 0x15-javascript-web_jquery ├── 0-script.js ├── 1-script.js ├── 100-script.js ├── 101-script.js ├── 102-script.js ├── 103-script.js ├── 2-script.js ├── 3-script.js ├── 4-script.js ├── 5-script.js ├── 6-script.js ├── 7-script.js ├── 8-script.js ├── 9-script.js └── README.md └── README.md /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 -c "$PYCODE" 3 | -------------------------------------------------------------------------------- /0x00-python-hello_world/10-check_cycle.c: -------------------------------------------------------------------------------- 1 | #include "lists.h" 2 | 3 | /** 4 | * check_cycle - check for loop in LL 5 | * @list: head of linked list 6 | * 7 | * Description - check for loops in LL 8 | * Return: 1 if cycled, 0 if not 9 | */ 10 | 11 | int check_cycle(listint_t *list) 12 | { 13 | listint_t *slow, *fast; 14 | 15 | if (!list) 16 | { 17 | return (0); 18 | } 19 | slow = list; 20 | fast = list->next; 21 | while (fast && slow && fast->next) 22 | { 23 | if (slow == fast) 24 | { 25 | return (1); 26 | } 27 | slow = slow->next; 28 | fast = fast->next->next; 29 | } 30 | return (0); 31 | } 32 | -------------------------------------------------------------------------------- /0x00-python-hello_world/10-linked_lists.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "lists.h" 4 | 5 | /** 6 | * print_listint - prints all elements of a listint_t list 7 | * @h: pointer to head of list 8 | * Return: number of nodes 9 | */ 10 | size_t print_listint(const listint_t *h) 11 | { 12 | const listint_t *current; 13 | unsigned int n; 14 | 15 | current = h; 16 | n = 0; 17 | while (current != NULL) 18 | { 19 | printf("%i\n", current->n); 20 | current = current->next; 21 | n++; 22 | } 23 | return (n); 24 | } 25 | 26 | /** 27 | * add_nodeint - adds a new node at the beginning of a listint_t list 28 | * @head: pointer to a pointer of the start of the list 29 | * @n: integer to be included in node 30 | * Return: address of the new element or NULL if it fails 31 | */ 32 | listint_t *add_nodeint(listint_t **head, const int n) 33 | { 34 | listint_t *new; 35 | 36 | new = malloc(sizeof(listint_t)); 37 | if (new == NULL) 38 | { 39 | return (NULL); 40 | } 41 | new->n = n; 42 | new->next = *head; 43 | *head = new; 44 | return (new); 45 | } 46 | 47 | /** 48 | * free_listint - frees a listint_t list 49 | * @head: pointer to list to be freed 50 | * Return: void 51 | */ 52 | void free_listint(listint_t *head) 53 | { 54 | listint_t *current; 55 | 56 | while (head != NULL) 57 | { 58 | current = head; 59 | head = head->next; 60 | free(current); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /0x00-python-hello_world/10-main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "lists.h" 5 | 6 | /** 7 | * main - check the code for Holberton School students. 8 | * 9 | * Return: Always 0. 10 | */ 11 | int main(void) 12 | { 13 | listint_t *head; 14 | listint_t *current; 15 | listint_t *temp; 16 | int i; 17 | 18 | head = NULL; 19 | add_nodeint(&head, 0); 20 | add_nodeint(&head, 1); 21 | add_nodeint(&head, 2); 22 | add_nodeint(&head, 3); 23 | add_nodeint(&head, 4); 24 | add_nodeint(&head, 98); 25 | add_nodeint(&head, 402); 26 | add_nodeint(&head, 1024); 27 | print_listint(head); 28 | 29 | if (check_cycle(head) == 0) 30 | printf("Linked list has no cycle\n"); 31 | else if (check_cycle(head) == 1) 32 | printf("Linked list has a cycle\n"); 33 | 34 | current = head; 35 | for (i = 0; i < 4; i++) 36 | current = current->next; 37 | temp = current->next; 38 | current->next = head; 39 | 40 | if (check_cycle(head) == 0) 41 | printf("Linked list has no cycle\n"); 42 | else if (check_cycle(head) == 1) 43 | printf("Linked list has a cycle\n"); 44 | 45 | current = head; 46 | for (i = 0; i < 4; i++) 47 | current = current->next; 48 | current->next = temp; 49 | 50 | free_listint(head); 51 | 52 | return (0); 53 | } 54 | -------------------------------------------------------------------------------- /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 -c "import py_compile; py_compile.compile('$PYFILE', '$PYFILE' + 'c')" 3 | -------------------------------------------------------------------------------- /0x00-python-hello_world/102-magic_calculation.py: -------------------------------------------------------------------------------- 1 | def magic_calculation(a, b): 2 | return (98 + a ** b) 3 | -------------------------------------------------------------------------------- /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(str * 3) 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:67] + str[107:112] + str[:6] 5 | print(str) 6 | -------------------------------------------------------------------------------- /0x00-python-hello_world/9-easter_egg.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import this 3 | -------------------------------------------------------------------------------- /0x00-python-hello_world/lists.h: -------------------------------------------------------------------------------- 1 | #ifndef LISTS_H 2 | #define LISTS_H 3 | 4 | #include 5 | 6 | /** 7 | * struct listint_s - singly linked list 8 | * @n: integer 9 | * @next: points to the next node 10 | * 11 | * Description: singly linked list node structure 12 | * for Holberton project 13 | */ 14 | typedef struct listint_s 15 | { 16 | int n; 17 | struct listint_s *next; 18 | } listint_t; 19 | 20 | size_t print_listint(const listint_t *h); 21 | listint_t *add_nodeint(listint_t **head, const int n); 22 | void free_listint(listint_t *head); 23 | int check_cycle(listint_t *list); 24 | 25 | #endif /* LISTS_H */ 26 | -------------------------------------------------------------------------------- /0x00-python-hello_world/main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | print("Holberton School") 3 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/0-positive_or_negative.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import random 3 | number = random.randint(-10, 10) 4 | if number > 0: 5 | print(f"{number:d} is positive") 6 | elif number == 0: 7 | print(f"{number:d} is zero") 8 | else: 9 | print(f"{number:d} is negative") 10 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/1-last_digit.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import random 3 | number = random.randint(-10000, 10000) 4 | digit = abs(number) % 10 5 | if number < 0: 6 | digit = -digit 7 | print(f"Last digit of {number:d} is {digit:d} and is ", end="") 8 | if digit > 5: 9 | print("greater than 5") 10 | elif digit == 0: 11 | print("0") 12 | else: 13 | print("less than 6 and not 0") 14 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/10-add.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Author - Godswill Kalu 3 | def add(a, b): 4 | """Return the addition of a and b.""" 5 | return (a + b) 6 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/10-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | add = __import__('10-add').add 3 | 4 | print(add(1, 2)) 5 | print(add(98, 0)) 6 | print(add(100, -2)) 7 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/100-print_tebahpla.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Author - Godswill Kalu 3 | 4 | i = 0 5 | for c in range(ord('z'), ord('a') - 1, -1): 6 | print("{}".format(chr(c - i)), end="") 7 | i = 32 if i == 0 else 0 8 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/101-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | remove_char_at = __import__('101-remove_char_at').remove_char_at 3 | 4 | print(remove_char_at("Best School", 3)) 5 | print(remove_char_at("Chicago", 2)) 6 | print(remove_char_at("C is fun!", 0)) 7 | print(remove_char_at("School", 10)) 8 | print(remove_char_at("Python", -2)) 9 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/101-remove_char_at.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Author - Godswill Kalu 3 | 4 | def remove_char_at(str, n): 5 | if n < 0: 6 | return (str) 7 | return (str[:n] + str[n+1:]) 8 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/102-magic_calculation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Author - Godswill Kalu 3 | 4 | def magic_calculation(a, b, c): 5 | """Match bytecode provided by Holberton School.""" 6 | if a < b: 7 | return (c) 8 | if c > b: 9 | return (a + b) 10 | return (a*b - c) 11 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/11-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | pow = __import__('11-pow').pow 3 | 4 | print(pow(2, 2)) 5 | print(pow(98, 2)) 6 | print(pow(98, 0)) 7 | print(pow(100, -2)) 8 | print(pow(-4, 5)) 9 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/11-pow.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Author -Godswill Kalu 3 | 4 | def pow(a, b): 5 | return (a ** b) 6 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/12-fizzbuzz.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Author - Godswill Kalu 3 | """Print the numbers from 1 to 100 separated by a space. 4 | For multiples of three, print Fizz instead of the number 5 | For multiples of five, print Buzz instead of the number. 6 | For multiples of three and five, print FizzBuzz instead of the number. 7 | """ 8 | 9 | 10 | def fizzbuzz(): 11 | for number in range(1, 101): 12 | if number % 3 == 0 and number % 5 == 0: 13 | print("FizzBuzz ", end="") 14 | elif number % 3 == 0: 15 | print("Fizz ", end="") 16 | elif number % 5 == 0: 17 | print("Buzz ", end="") 18 | else: 19 | print("{} ".format(number), end="") 20 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/12-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | fizzbuzz = __import__('12-fizzbuzz').fizzbuzz 3 | 4 | fizzbuzz() 5 | print("") 6 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/13-insert_number.c: -------------------------------------------------------------------------------- 1 | #include "lists.h" 2 | 3 | /** 4 | * insert_node - Inserts a number into a sorted singly-linked list. 5 | * @head: A pointer the head of the linked list. 6 | * @number: The number to insert. 7 | * Author - Tolulope Fakunle 8 | * Return: If the function fails - NULL. 9 | * Otherwise - a pointer to the new node. 10 | */ 11 | listint_t *insert_node(listint_t **head, int number) 12 | { 13 | listint_t *node = *head, *new; 14 | 15 | new = malloc(sizeof(listint_t)); 16 | if (new == NULL) 17 | return (NULL); 18 | new->n = number; 19 | 20 | if (node == NULL || node->n >= number) 21 | { 22 | new->next = node; 23 | *head = new; 24 | return (new); 25 | } 26 | 27 | while (node && node->next && node->next->n < number) 28 | node = node->next; 29 | 30 | new->next = node->next; 31 | node->next = new; 32 | 33 | return (new); 34 | } 35 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/2-print_alphabet.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Print the alphabet in lowercase, not followed by a new line.""" 3 | 4 | for letter in range(97, 123): 5 | print("{}".format(chr(letter)), end="") 6 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/3-print_alphabt.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Author - Godswill Kalu 3 | for letter in range(97, 123): 4 | if chr(letter) != 'q' and chr(letter) != 'e': 5 | print("{}".format(chr(letter)), end="") 6 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/4-print_hexa.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Author - Godswill Kalu 3 | 4 | """Print numbers 0 to 98 in decimal and hexadecimal.""" 5 | for number in range(0, 99): 6 | print("{} = {}".format(number, hex(number))) 7 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/5-print_comb2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for number in range(0, 100): 3 | if number == 99: 4 | print("{}".format(number)) 5 | else: 6 | print("{:02}".format(number), end=", ") 7 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/6-print_comb3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Author - Godswill Kalu 3 | 4 | for digit1 in range(0, 10): 5 | for digit2 in range(digit1 + 1, 10): 6 | if digit1 == 8 and digit2 == 9: 7 | print("{}{}".format(digit1, digit2)) 8 | else: 9 | print("{}{}".format(digit1, digit2), end=", ") 10 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/7-islower.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Author - Godswill Kalu 3 | 4 | def islower(c): 5 | """Function checks for lowercase characters.""" 6 | if ord(c) >= 97 and ord(c) <= 122: 7 | return True 8 | else: 9 | return False 10 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/7-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | islower = __import__('7-islower').islower 3 | 4 | print("a is {}".format("lower" if islower("a") else "upper")) 5 | print("H is {}".format("lower" if islower("H") else "upper")) 6 | print("A is {}".format("lower" if islower("A") else "upper")) 7 | print("3 is {}".format("lower" if islower("3") else "upper")) 8 | print("g is {}".format("lower" if islower("g") else "upper")) 9 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/8-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | uppercase = __import__('8-uppercase').uppercase 3 | 4 | uppercase("best") 5 | uppercase("Best School 98 Battery street") 6 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/8-uppercase.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Author - Godswill Kalu 3 | 4 | def uppercase(str): 5 | """Print a string in uppercase.""" 6 | for c in str: 7 | if ord(c) >= 97 and ord(c) <= 122: 8 | c = chr(ord(c) - 32) 9 | print("{}".format(c), end="") 10 | print("") 11 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/9-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | print_last_digit = __import__('9-print_last_digit').print_last_digit 3 | 4 | print_last_digit(98) 5 | print_last_digit(0) 6 | r = print_last_digit(-1024) 7 | print(r) 8 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/9-print_last_digit.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Author - Godswill Kalu 3 | 4 | def print_last_digit(number): 5 | print(abs(number) % 10, end="") 6 | return (abs(number) % 10) 7 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/lists.h: -------------------------------------------------------------------------------- 1 | #ifndef LISTS_H 2 | #define LISTS_H 3 | 4 | #include 5 | 6 | /** 7 | * struct listint_s - singly linked list 8 | * @n: integer 9 | * @next: points to the next node 10 | * 11 | * Description: singly linked list node structure 12 | */ 13 | typedef struct listint_s 14 | { 15 | int n; 16 | struct listint_s *next; 17 | } listint_t; 18 | 19 | size_t print_listint(const listint_t *h); 20 | listint_t *add_nodeint_end(listint_t **head, const int n); 21 | void free_listint(listint_t *head); 22 | listint_t *insert_node(listint_t **head, int number); 23 | 24 | #endif /* LISTS_H */ 25 | -------------------------------------------------------------------------------- /0x02-python-import_modules/0-add.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | if __name__ == "__main__": 4 | """Print the sum of 1 and 2.""" 5 | from add_0 import add 6 | 7 | a = 1 8 | b = 2 9 | print("{} + {} = {}".format(a, b, add(a, b))) 10 | -------------------------------------------------------------------------------- /0x02-python-import_modules/1-calculation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | if __name__ == "__main__": 4 | """Print the sum, difference, multiple and quotient of 10 and 5.""" 5 | from calculator_1 import add, sub, mul, div 6 | 7 | a = 10 8 | b = 5 9 | 10 | print("{} + {} = {}".format(a, b, add(a, b))) 11 | print("{} - {} = {}".format(a, b, sub(a, b))) 12 | print("{} * {} = {}".format(a, b, mul(a, b))) 13 | print("{} / {} = {}".format(a, b, div(a, b))) 14 | -------------------------------------------------------------------------------- /0x02-python-import_modules/100-my_calculator.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | if __name__ == "__main__": 4 | """Handle basic arithmetic operations.""" 5 | from calculator_1 import add, sub, mul, div 6 | import sys 7 | 8 | if len(sys.argv) - 1 != 3: 9 | print("Usage: ./100-my_calculator.py ") 10 | sys.exit(1) 11 | 12 | ops = {"+": add, "-": sub, "*": mul, "/": div} 13 | if sys.argv[2] not in list(ops.keys()): 14 | print("Unknown operator. Available operators: +, -, * and /") 15 | sys.exit(1) 16 | 17 | a = int(sys.argv[1]) 18 | b = int(sys.argv[3]) 19 | print("{} {} {} = {}".format(a, sys.argv[2], b, ops[sys.argv[2]](a, b))) 20 | -------------------------------------------------------------------------------- /0x02-python-import_modules/101-easy_print.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | __import__("os").write(1, "#pythoniscool\n".encode("UTF-8")) 3 | -------------------------------------------------------------------------------- /0x02-python-import_modules/102-magic_calculation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def magic_calculation(a, b): 4 | """Match bytecode provided by Holberton School.""" 5 | from magic_calculation_102 import add, sub 6 | 7 | if a < b: 8 | c = add(a, b) 9 | for i in range(4, 6): 10 | c = add(c, i) 11 | return (c) 12 | 13 | else: 14 | return(sub(a, b)) 15 | -------------------------------------------------------------------------------- /0x02-python-import_modules/103-fast_alphabet.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import string 3 | print(string.ascii_uppercase) 4 | -------------------------------------------------------------------------------- /0x02-python-import_modules/2-args.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | if __name__ == "__main__": 4 | """Print the number of and list of arguments.""" 5 | import sys 6 | 7 | count = len(sys.argv) - 1 8 | if count == 0: 9 | print("0 arguments.") 10 | elif count == 1: 11 | print("1 argument:") 12 | else: 13 | print("{} arguments:".format(count)) 14 | for i in range(count): 15 | print("{}: {}".format(i + 1, sys.argv[i + 1])) 16 | -------------------------------------------------------------------------------- /0x02-python-import_modules/3-infinite_add.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | if __name__ == "__main__": 4 | """Print the addition of all arguments.""" 5 | import sys 6 | 7 | total = 0 8 | for i in range(len(sys.argv) - 1): 9 | total += int(sys.argv[i + 1]) 10 | print("{}".format(total)) 11 | -------------------------------------------------------------------------------- /0x02-python-import_modules/4-hidden_discovery.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | if __name__ == "__main__": 4 | """Print all names defined by hidden_4 module.""" 5 | import hidden_4 6 | 7 | names = dir(hidden_4) 8 | for name in names: 9 | if name[:2] != "__": 10 | print(name) 11 | -------------------------------------------------------------------------------- /0x02-python-import_modules/5-variable_load.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | if __name__ == "__main__": 4 | """Print the value of variable a from variable_load_5.""" 5 | from variable_load_5 import a 6 | 7 | print(a) 8 | -------------------------------------------------------------------------------- /0x02-python-import_modules/add_0.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def add(a, b): 3 | """My addition function 4 | 5 | Args: 6 | a: first integer 7 | b: second integer 8 | 9 | Returns: 10 | The return value. a + b 11 | """ 12 | return (a + b) 13 | -------------------------------------------------------------------------------- /0x02-python-import_modules/calculator_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def add(a, b): 4 | """My addition function 5 | 6 | Args: 7 | a: first integer 8 | b: second integer 9 | 10 | Returns: 11 | The return value. a + b 12 | """ 13 | return (a + b) 14 | 15 | 16 | def sub(a, b): 17 | """My subtraction function 18 | 19 | Args: 20 | a: first integer 21 | b: second integer 22 | 23 | Returns: 24 | The return value. a - b 25 | """ 26 | return (a - b) 27 | 28 | 29 | def mul(a, b): 30 | """My multiplication function 31 | 32 | Args: 33 | a: first integer 34 | b: second integer 35 | 36 | Returns: 37 | The return value. a * b 38 | """ 39 | return (a * b) 40 | 41 | 42 | def div(a, b): 43 | """My division function 44 | 45 | Args: 46 | a: first integer 47 | b: second integer 48 | 49 | Returns: 50 | The return value. a / b 51 | """ 52 | return int(a / b) 53 | -------------------------------------------------------------------------------- /0x02-python-import_modules/variable_load_5.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | a = 98 3 | """Simple variable 4 | """ 5 | -------------------------------------------------------------------------------- /0x03-python-data_structures/.0-print_list_integer.py.swp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lordwill1/alx-higher_level_programming/34ec76359456d05dff1b2ef82444f231b3a6b848/0x03-python-data_structures/.0-print_list_integer.py.swp -------------------------------------------------------------------------------- /0x03-python-data_structures/0-print_list_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def print_list_integer(my_list=[]): 3 | for i in range(len(my_list)): 4 | print("{:d}".format(my_list[i])) 5 | -------------------------------------------------------------------------------- /0x03-python-data_structures/1-element_at.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def element_at(my_list, idx): 3 | if idx < 0 or idx > len(my_list) - 1: 4 | return 'None' 5 | else: 6 | return my_list[idx] 7 | -------------------------------------------------------------------------------- /0x03-python-data_structures/10-divisible_by_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def divisible_by_2(my_list=[]): 3 | new_list = [] 4 | for i in range(len(my_list)): 5 | if my_list[i] % 2 == 0: 6 | new_list.append(True) 7 | else: 8 | new_list.append(False) 9 | return new_list 10 | -------------------------------------------------------------------------------- /0x03-python-data_structures/100-print_python_list_info.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | void print_python_list_info(PyObject *p) 6 | { 7 | long int size = PyList_Size(p); 8 | int i; 9 | PyListObject *obj = (PyListObject *)p; 10 | 11 | printf("[*] Size of the Python List = %li\n", size); 12 | printf("[*] Allocated = %li\n", obj->allocated); 13 | for (i = 0; i < size; i++) 14 | printf("Element %i: %s\n", i, Py_TYPE(obj->ob_item[i])->tp_name); 15 | } 16 | -------------------------------------------------------------------------------- /0x03-python-data_structures/100-test_lists.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | 3 | lib = ctypes.CDLL('./libPyList.so') 4 | lib.print_python_list_info.argtypes = [ctypes.py_object] 5 | l = ['hello', 'World'] 6 | lib.print_python_list_info(l) 7 | del l[1] 8 | lib.print_python_list_info(l) 9 | l = l + [4, 5, 6.0, (9, 8), [9, 8, 1024], "Holberton"] 10 | lib.print_python_list_info(l) 11 | l = [] 12 | lib.print_python_list_info(l) 13 | l.append(0) 14 | lib.print_python_list_info(l) 15 | l.append(1) 16 | l.append(2) 17 | l.append(3) 18 | l.append(4) 19 | lib.print_python_list_info(l) 20 | l.pop() 21 | lib.print_python_list_info(l) 22 | -------------------------------------------------------------------------------- /0x03-python-data_structures/11-delete_at.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def delete_at(my_list=[], idx=0): 3 | if idx < 0 or idx > len(my_list) - 1: 4 | return my_list 5 | else: 6 | del my_list[idx] 7 | return my_list 8 | -------------------------------------------------------------------------------- /0x03-python-data_structures/12-switch.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | a = 89 3 | b = 10 4 | a, b = b, a 5 | print("a={:d} - b={:d}".format(a, b)) 6 | -------------------------------------------------------------------------------- /0x03-python-data_structures/13-is_palindrome.c: -------------------------------------------------------------------------------- 1 | #include "lists.h" 2 | 3 | /** 4 | * reverse_listint - reverses a linked list 5 | * @head: pointer to the first node in the list 6 | * 7 | * Return: pointer to the first node in the new list 8 | */ 9 | void reverse_listint(listint_t **head) 10 | { 11 | listint_t *prev = NULL; 12 | listint_t *current = *head; 13 | listint_t *next = NULL; 14 | 15 | while (current) 16 | { 17 | next = current->next; 18 | current->next = prev; 19 | prev = current; 20 | current = next; 21 | } 22 | 23 | *head = prev; 24 | } 25 | 26 | /** 27 | * is_palindrome - checks if a linked list is a palindrome 28 | * @head: double pointer to the linked list 29 | * 30 | * Return: 1 if it is, 0 if not 31 | */ 32 | int is_palindrome(listint_t **head) 33 | { 34 | listint_t *slow = *head, *fast = *head, *temp = *head, *dup = NULL; 35 | 36 | if (*head == NULL || (*head)->next == NULL) 37 | return (1); 38 | 39 | while (1) 40 | { 41 | fast = fast->next->next; 42 | if (!fast) 43 | { 44 | dup = slow->next; 45 | break; 46 | } 47 | if (!fast->next) 48 | { 49 | dup = slow->next->next; 50 | break; 51 | } 52 | slow = slow->next; 53 | } 54 | 55 | reverse_listint(&dup); 56 | 57 | while (dup && temp) 58 | { 59 | if (temp->n == dup->n) 60 | { 61 | dup = dup->next; 62 | temp = temp->next; 63 | } 64 | else 65 | return (0); 66 | } 67 | 68 | if (!dup) 69 | return (1); 70 | 71 | return (0); 72 | } 73 | -------------------------------------------------------------------------------- /0x03-python-data_structures/2-replace_in_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def replace_in_list(my_list, idx, element): 3 | if idx < 0 or idx > len(my_list) - 1: 4 | return my_list 5 | else: 6 | my_list[idx] = element 7 | return my_list 8 | -------------------------------------------------------------------------------- /0x03-python-data_structures/3-print_reversed_list_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def print_reversed_list_integer(my_list=[]): 3 | if my_list: 4 | my_list.reverse() 5 | for i in range(len(my_list)): 6 | print("{:d}".format(my_list[i])) 7 | -------------------------------------------------------------------------------- /0x03-python-data_structures/4-new_in_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def new_in_list(my_list, idx, element): 3 | copy = my_list.copy() 4 | if idx < 0 or idx > len(my_list) - 1: 5 | return my_list.copy() 6 | else: 7 | copy[idx] = element 8 | return copy 9 | -------------------------------------------------------------------------------- /0x03-python-data_structures/5-no_c.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def no_c(my_string): 3 | new_string = my_string.translate({ord(i): None for i in 'cC'}) 4 | return new_string 5 | -------------------------------------------------------------------------------- /0x03-python-data_structures/6-print_matrix_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def print_matrix_integer(matrix=[[]]): 3 | for row in matrix: 4 | for col in row: 5 | print("{:d}".format(col), end=" " if col != row[-1] else "") 6 | print() 7 | -------------------------------------------------------------------------------- /0x03-python-data_structures/7-add_tuple.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def add_tuple(tuple_a=(), tuple_b=()): 3 | new_tuple = () 4 | tuple_1 = tuple_a + (0, 0) 5 | tuple_2 = tuple_b + (0, 0) 6 | new_tuple = tuple_1[0] + tuple_2[0], tuple_1[1] + tuple_2[1] 7 | return new_tuple 8 | -------------------------------------------------------------------------------- /0x03-python-data_structures/8-multiple_returns.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def multiple_returns(sentence): 3 | my_tuple = () 4 | if len(sentence) == 0: 5 | my_tuple = 0, "None" 6 | else: 7 | my_tuple = len(sentence), sentence[0] 8 | return my_tuple 9 | -------------------------------------------------------------------------------- /0x03-python-data_structures/9-max_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def max_integer(my_list=[]): 3 | if len(my_list) == 0: 4 | return "None" 5 | else: 6 | max = my_list[0] 7 | for i in range(len(my_list)): 8 | if my_list[i] > max: 9 | max = my_list[i] 10 | return max 11 | -------------------------------------------------------------------------------- /0x03-python-data_structures/README.md: -------------------------------------------------------------------------------- 1 | # 0x03. Python - Data Structures: Lists, Tuples 2 | ### I executed 12-switch.py using `chmod u+x 12-switch.py` for the checker to successfully check. 3 | 4 | ## Table of contents 5 | Files | Description 6 | ----- | ----------- 7 | [0-print_list_integer.py](./0-print_list_integer.py) | Python function that prints all integers of a list 8 | [1-element_at.py](./1-element_at.py) | Python function that retrieves an element from a list like in C 9 | [2-replace_in_list.py](./2-replace_in_list.py) | Python function that replaces an element of a list at a specific position (like in C) 10 | [3-print_reversed_list_integer.py](./3-print_reversed_list_integer.py) | Python function that prints all integers of a list, in reverse order 11 | [4-new_in_list.py](./4-new_in_list.py) | Python function that replaces an element in a list at a specific position without modifying the original list (like in C) 12 | [5-no_c.py](./5-no_c.py) | Python function that removes all characters c and C from a string 13 | [6-print_matrix_integer.py](./6-print_matrix_integer.py) | Python function that prints a matrix of integers 14 | [7-add_tuple.py](./7-add_tuple.py) | Python function that adds 2 tuples 15 | [8-multiple_returns.py](./8-multiple_returns.py) | Python function that returns a tuple with the length of a string and its first character 16 | [9-max_integer.py](./9-max_integer.py) | Python function that finds the biggest integer of a list 17 | [10-divisible_by_2.py](./10-divisible_by_2.py) | Python function that finds all multiples of 2 in a list 18 | [11-delete_at.py](./11-delete_at.py) | Python function that deletes the item at a specific position in a list 19 | [12-switch.py](./12-switch.py) | Python program that completes source code in order to switch value of a and b 20 | [13-is_palindrome.c](./13-is_palindrome.c) | C program that checks if a singly linked list is a palindrome 21 | [lists.h](./lists.h) | Header file for the C program 22 | [100-print_python_list_info.c](./100-print_python_list_info.c) | C function to compile in a shared library that prints info on a Python list 23 | [100-test_lists.py](./100-test_lists.py) | Python script to test the C function above. 24 | -------------------------------------------------------------------------------- /0x03-python-data_structures/lists.h: -------------------------------------------------------------------------------- 1 | #ifndef LISTS_H 2 | #define LISTS_H 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | /** 9 | * struct listint_s - singly linked list 10 | * @n: integer 11 | * @next: points to the next node 12 | * 13 | * Description: singly linked list node structure 14 | * for Holberton project 15 | */ 16 | typedef struct listint_s 17 | { 18 | int n; 19 | struct listint_s *next; 20 | } listint_t; 21 | 22 | size_t print_listint(const listint_t *h); 23 | listint_t *add_nodeint_end(listint_t **head, const int n); 24 | void free_listint(listint_t *head); 25 | 26 | void reverse_listint(listint_t **head); 27 | int is_palindrome(listint_t **head); 28 | 29 | #endif /* LISTS_H */ 30 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/0-square_matrix_simple.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | 4 | def square_matrix_simple(matrix=[]): 5 | """ 6 | wordA function that computes the square 7 | value of all integers of a matrix. 8 | """ 9 | new_matrix = [] 10 | for col in matrix: 11 | result = list(map(lambda x: x**2, col)) 12 | new_matrix.append(result) 13 | return new_matrix 14 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/1-search_replace.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | 4 | def search_replace(my_list, search, replace): 5 | """ 6 | A function that replaces all occurrences 7 | of an element by another in a new list 8 | """ 9 | new_list = [] 10 | for element in my_list: 11 | if element == search: 12 | new_list.append(replace) 13 | else: 14 | new_list.append(element) 15 | return new_list 16 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/10-best_score.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | 4 | def best_score(a_dictionary): 5 | """ 6 | A function that returns a key with the biggest integer value. 7 | """ 8 | if a_dictionary: 9 | my_list = list(a_dictionary.keys()) 10 | score = 0 11 | leader = "" 12 | for i in my_list: 13 | if a_dictionary[i] > score: 14 | score = a_dictionary[i] 15 | leader = i 16 | return leader 17 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/100-weight_average.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def weight_average(my_list=[]): 3 | if not my_list: 4 | return 0 5 | 6 | num = 0 7 | den = 0 8 | 9 | for tup in my_list: 10 | num += tup[0] * tup[1] 11 | den += tup[1] 12 | 13 | return (num / den) 14 | -------------------------------------------------------------------------------- /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 2 | #include 3 | 4 | /** 5 | * print_python_bytes - Prints bytes information 6 | * 7 | * @p: Python Object 8 | * Return: no return 9 | */ 10 | void print_python_bytes(PyObject *p) 11 | { 12 | char *string; 13 | long int size, i, limit; 14 | 15 | printf("[.] bytes object info\n"); 16 | if (!PyBytes_Check(p)) 17 | { 18 | printf(" [ERROR] Invalid Bytes Object\n"); 19 | return; 20 | } 21 | 22 | size = ((PyVarObject *)(p))->ob_size; 23 | string = ((PyBytesObject *)p)->ob_sval; 24 | 25 | printf(" size: %ld\n", size); 26 | printf(" trying string: %s\n", string); 27 | 28 | if (size >= 10) 29 | limit = 10; 30 | else 31 | limit = size + 1; 32 | 33 | printf(" first %ld bytes:", limit); 34 | 35 | for (i = 0; i < limit; i++) 36 | if (string[i] >= 0) 37 | printf(" %02x", string[i]); 38 | else 39 | printf(" %02x", 256 + string[i]); 40 | 41 | printf("\n"); 42 | } 43 | 44 | /** 45 | * print_python_list - Prints list information 46 | * 47 | * @p: Python Object 48 | * Return: no return 49 | */ 50 | void print_python_list(PyObject *p) 51 | { 52 | long int size, i; 53 | PyListObject *list; 54 | PyObject *obj; 55 | 56 | size = ((PyVarObject *)(p))->ob_size; 57 | list = (PyListObject *)p; 58 | 59 | printf("[*] Python list info\n"); 60 | printf("[*] Size of the Python List = %ld\n", size); 61 | printf("[*] Allocated = %ld\n", list->allocated); 62 | 63 | for (i = 0; i < size; i++) 64 | { 65 | obj = ((PyListObject *)p)->ob_item[i]; 66 | printf("Element %ld: %s\n", i, ((obj)->ob_type)->tp_name); 67 | if (PyBytes_Check(obj)) 68 | print_python_bytes(obj); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/11-multiply_list_map.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def multiply_list_map(my_list=[], number=0): 3 | return (list(map((lambda i: i * number), my_list))) 4 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/12-roman_to_int.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def to_subtract(list_num): 3 | to_sub = 0 4 | max_list = max(list_num) 5 | 6 | for n in list_num: 7 | if max_list > n: 8 | to_sub += n 9 | 10 | return (max_list - to_sub) 11 | 12 | 13 | def roman_to_int(roman_string): 14 | if not roman_string: 15 | return 0 16 | 17 | if not isinstance(roman_string, str): 18 | return 0 19 | 20 | rom_n = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} 21 | list_keys = list(rom_n.keys()) 22 | 23 | num = 0 24 | last_rom = 0 25 | list_num = [0] 26 | 27 | for ch in roman_string: 28 | for r_num in list_keys: 29 | if r_num == ch: 30 | if rom_n.get(ch) <= last_rom: 31 | num += to_subtract(list_num) 32 | list_num = [rom_n.get(ch)] 33 | else: 34 | list_num.append(rom_n.get(ch)) 35 | 36 | last_rom = rom_n.get(ch) 37 | 38 | num += to_subtract(list_num) 39 | 40 | return (num) 41 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/2-uniq_add.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | 4 | def uniq_add(my_list=[]): 5 | """ 6 | A function that adds all unique 7 | integers in a list (only once for each integer) 8 | """ 9 | new_list = [] 10 | sum = 0 11 | for num in my_list: 12 | if num not in new_list: 13 | sum += num 14 | new_list.append(num) 15 | return sum 16 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/3-common_elements.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | 4 | def common_elements(set_1, set_2): 5 | """ 6 | A function that returns a set of 7 | common elements in two sets 8 | """ 9 | return(set_1 & set_2) 10 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/4-only_diff_elements.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | 4 | def only_diff_elements(set_1, set_2): 5 | """ 6 | A function that returns a set of all elements 7 | present in only one set. 8 | """ 9 | return (set_1 ^ set_2) 10 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/5-number_keys.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | 4 | def number_keys(a_dictionary): 5 | """ 6 | A function that returns the number of keys in a dictionary. 7 | """ 8 | return len(a_dictionary) 9 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/6-print_sorted_dictionary.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | 4 | def print_sorted_dictionary(a_dictionary): 5 | """ 6 | A function that prints a dictionary by ordered keys 7 | """ 8 | keys = list(a_dictionary.keys()) 9 | keys.sort() 10 | for key in keys: 11 | print("{}: {}".format(key, a_dictionary[key])) 12 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/7-update_dictionary.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | 4 | def update_dictionary(a_dictionary, key, value): 5 | """ 6 | A function that replaces or adds 7 | key/value in a dictionary. 8 | """ 9 | a_dictionary[key] = value 10 | return a_dictionary 11 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/8-simple_delete.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | 4 | def simple_delete(a_dictionary, key=""): 5 | """ 6 | A function that deletes a key in a dictionary. 7 | """ 8 | if key in a_dictionary: 9 | del a_dictionary[key] 10 | return a_dictionary 11 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/9-multiply_by_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | 4 | def multiply_by_2(a_dictionary): 5 | """ 6 | A function that returns a new dictionary 7 | with all values multiplied by 2 8 | """ 9 | new_dict = {} 10 | for key, value in a_dictionary.items(): 11 | new_dict.update({key: (value * 2)}) 12 | return new_dict 13 | -------------------------------------------------------------------------------- /0x05-python-exceptions/0-safe_print_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def safe_print_list(my_list=[], x=0): 4 | """Print x elememts of a list. 5 | 6 | Args: 7 | my_list (list): The list to print elements from. 8 | x (int): The number of elements of my_list to print. 9 | 10 | Returns: 11 | The number of elements printed. 12 | """ 13 | ret = 0 14 | for i in range(x): 15 | try: 16 | print("{}".format(my_list[i]), end="") 17 | ret += 1 18 | except IndexError: 19 | break 20 | print("") 21 | return (ret) 22 | -------------------------------------------------------------------------------- /0x05-python-exceptions/1-safe_print_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def safe_print_integer(value): 4 | """Print an integer with "{:d}".format(). 5 | 6 | Args: 7 | value (int): The integer to print. 8 | 9 | Returns: 10 | If a TypeError or ValueError occurs - False. 11 | Otherwise - True. 12 | """ 13 | try: 14 | print("{:d}".format(value)) 15 | return (True) 16 | except (TypeError, ValueError): 17 | return (False) 18 | -------------------------------------------------------------------------------- /0x05-python-exceptions/100-safe_print_integer_err.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import sys 4 | 5 | 6 | def safe_print_integer_err(value): 7 | """Prints an integer with "{:d}".format(). 8 | 9 | If a ValueError message is caught, a corresponding 10 | message is printed to standard error. 11 | 12 | Args: 13 | value (int): The integer to print. 14 | 15 | Returns: 16 | If a TypeError or ValueError occurs - False. 17 | Otherwise - True. 18 | """ 19 | try: 20 | print("{:d}".format(value)) 21 | return (True) 22 | except (TypeError, ValueError): 23 | print("Exception: {}".format(sys.exc_info()[1]), file=sys.stderr) 24 | return (False) 25 | -------------------------------------------------------------------------------- /0x05-python-exceptions/101-safe_function.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | from __future__ import print_function 3 | import sys 4 | 5 | 6 | def safe_function(fct, *args): 7 | try: 8 | res = fct(*args) 9 | except Exception as e: 10 | print("Exception: {}".format(e), file=sys.stderr) 11 | return None 12 | else: 13 | return res 14 | -------------------------------------------------------------------------------- /0x05-python-exceptions/102-magic_calculation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def magic_calculation(a, b): 3 | result = 0 4 | for i in range(1, 3): 5 | try: 6 | if i > a: 7 | raise Exception('Too far') 8 | result += a ** b / i 9 | except Exception: 10 | result = b + a 11 | break 12 | return result 13 | -------------------------------------------------------------------------------- /0x05-python-exceptions/2-safe_print_list_integers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def safe_print_list_integers(my_list=[], x=0): 4 | """Print the first x elements of a list that are integers. 5 | 6 | Args: 7 | my_list (list): The list to print elements from. 8 | x (int): The number of elements of my_list to print. 9 | 10 | Returns: 11 | The number of elements printed. 12 | """ 13 | ret = 0 14 | for i in range(0, x): 15 | try: 16 | print("{:d}".format(my_list[i]), end="") 17 | ret += 1 18 | except (ValueError, TypeError): 19 | continue 20 | print("") 21 | return (ret) 22 | -------------------------------------------------------------------------------- /0x05-python-exceptions/3-safe_print_division.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def safe_print_division(a, b): 4 | """Returns the division of a by b.""" 5 | try: 6 | div = a / b 7 | except (TypeError, ZeroDivisionError): 8 | div = None 9 | finally: 10 | print("Inside result: {}".format(div)) 11 | return (div) 12 | -------------------------------------------------------------------------------- /0x05-python-exceptions/4-list_division.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def list_division(my_list_1, my_list_2, list_length): 4 | """Divides two lists element by element. 5 | 6 | Args: 7 | my_list_1 (list): The first list. 8 | my_list_2 (list): The second list. 9 | list_length (int): The number of elements to divide. 10 | 11 | Returns: 12 | A new list of length list_length containing all the divisions. 13 | """ 14 | new_list = [] 15 | for i in range(0, list_length): 16 | try: 17 | div = my_list_1[i] / my_list_2[i] 18 | except TypeError: 19 | print("wrong type") 20 | div = 0 21 | except ZeroDivisionError: 22 | print("division by 0") 23 | div = 0 24 | except IndexError: 25 | print("out of range") 26 | div = 0 27 | finally: 28 | new_list.append(div) 29 | return (new_list) 30 | -------------------------------------------------------------------------------- /0x05-python-exceptions/5-raise_exception.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def raise_exception(): 4 | """Raise a TypeError exception.""" 5 | raise TypeError 6 | -------------------------------------------------------------------------------- /0x05-python-exceptions/6-raise_exception_msg.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def raise_exception_msg(message=""): 4 | """Raise a NameError exception with a message.""" 5 | raise NameError(message) 6 | -------------------------------------------------------------------------------- /0x06-python-classes/0-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | """Define a class Square.""" 4 | 5 | 6 | class Square: 7 | """Represent a square.""" 8 | pass 9 | -------------------------------------------------------------------------------- /0x06-python-classes/1-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | """Define a class Square.""" 4 | 5 | 6 | class Square: 7 | """Represent a square.""" 8 | 9 | def __init__(self, size): 10 | """Initialize a new Square. 11 | 12 | Args: 13 | size (int): The size of the new square. 14 | """ 15 | self.__size = size 16 | -------------------------------------------------------------------------------- /0x06-python-classes/102-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | """Define a class Square.""" 4 | 5 | 6 | class Square: 7 | """Represent a square.""" 8 | 9 | def __init__(self, size=0): 10 | """Initialize a new square. 11 | 12 | Args: 13 | size (int): The size of the new square. 14 | """ 15 | self.size = size 16 | 17 | @property 18 | def size(self): 19 | """Get/set the current size of the square.""" 20 | return (self.__size) 21 | 22 | @size.setter 23 | def size(self, value): 24 | if not isinstance(value, int): 25 | raise TypeError("size must be an integer") 26 | elif value < 0: 27 | raise ValueError("size must be >= 0") 28 | self.__size = value 29 | 30 | def area(self): 31 | """Return the current area of the square.""" 32 | return (self.__size * self.__size) 33 | 34 | def __eq__(self, other): 35 | """Define the == comparision to a Square.""" 36 | return self.area() == other.area() 37 | 38 | def __ne__(self, other): 39 | """Define the != comparison to a Square.""" 40 | return self.area() != other.area() 41 | 42 | def __lt__(self, other): 43 | """Define the < comparison to a Square.""" 44 | return self.area() < other.area() 45 | 46 | def __le__(self, other): 47 | """Define the <= comparison to a Square.""" 48 | return self.area() <= other.area() 49 | 50 | def __gt__(self, other): 51 | """Define the > comparison to a Square.""" 52 | return self.area() > other.area() 53 | 54 | def __ge__(self, other): 55 | """Define the >= compmarison to a Square.""" 56 | return self.area() >= other.area() 57 | -------------------------------------------------------------------------------- /0x06-python-classes/103-magic_class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | """Define a MagicClass matching exactly a bytecode provided by Holberton.""" 4 | 5 | import math 6 | 7 | 8 | class MagicClass: 9 | """Represent a circle.""" 10 | 11 | def __init__(self, radius=0): 12 | """Initialize a MagicClass. 13 | 14 | Arg: 15 | radius (float or int): The radius of the new MagicClass. 16 | """ 17 | self.__radius = 0 18 | if type(radius) is not int and type(radius) is not float: 19 | raise TypeError("radius must be a number") 20 | self.__radius = radius 21 | 22 | def area(self): 23 | """Return the area of the MagicClass.""" 24 | return (self.__radius ** 2 * math.pi) 25 | 26 | def circumference(self): 27 | """Return The circumference of the MagicClass.""" 28 | return (2 * math.pi * self.__radius) 29 | -------------------------------------------------------------------------------- /0x06-python-classes/2-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | """Define a class Square.""" 4 | 5 | 6 | class Square: 7 | """Represent a square.""" 8 | 9 | def __init__(self, size=0): 10 | """Initialize a new Square. 11 | 12 | Args: 13 | size (int): The size of the new square. 14 | """ 15 | if not isinstance(size, int): 16 | raise TypeError("size must be an integer") 17 | elif size < 0: 18 | raise ValueError("size must be >= 0") 19 | self.__size = size 20 | -------------------------------------------------------------------------------- /0x06-python-classes/3-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | """Define a class Square.""" 4 | 5 | 6 | class Square: 7 | """Represent a square.""" 8 | 9 | def __init__(self, size=0): 10 | """Initialize a new square. 11 | 12 | Args: 13 | size (int): The size of the new square. 14 | """ 15 | if not isinstance(size, int): 16 | raise TypeError("size must be an integer") 17 | elif size < 0: 18 | raise ValueError("size must be >= 0") 19 | self.__size = size 20 | 21 | def area(self): 22 | """Return the current area of the square.""" 23 | return (self.__size * self.__size) 24 | -------------------------------------------------------------------------------- /0x06-python-classes/4-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | """Define a class Square.""" 4 | 5 | 6 | class Square: 7 | """Represent a square.""" 8 | 9 | def __init__(self, size=0): 10 | """Initialize a new square. 11 | 12 | Args: 13 | size (int): The size of the new square. 14 | """ 15 | self.size = size 16 | 17 | @property 18 | def size(self): 19 | """Get/set the current size of the square.""" 20 | return (self.__size) 21 | 22 | @size.setter 23 | def size(self, value): 24 | if not isinstance(value, int): 25 | raise TypeError("size must be an integer") 26 | elif value < 0: 27 | raise ValueError("size must be >= 0") 28 | self.__size = value 29 | 30 | def area(self): 31 | """Return the current area of the square.""" 32 | return (self.__size * self.__size) 33 | -------------------------------------------------------------------------------- /0x06-python-classes/5-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | """Define a class Square.""" 4 | 5 | 6 | class Square: 7 | """Represent a square.""" 8 | 9 | def __init__(self, size): 10 | """Initialize a new square. 11 | 12 | Args: 13 | size (int): The size of the new square. 14 | """ 15 | self.size = size 16 | 17 | @property 18 | def size(self): 19 | """Get/set the current size of the square.""" 20 | return (self.__size) 21 | 22 | @size.setter 23 | def size(self, value): 24 | if not isinstance(value, int): 25 | raise TypeError("size must be an integer") 26 | elif value < 0: 27 | raise ValueError("size must be >= 0") 28 | self.__size = value 29 | 30 | def area(self): 31 | """Return the current area of the square.""" 32 | return (self.__size * self.__size) 33 | 34 | def my_print(self): 35 | """Print the square with the # character.""" 36 | for i in range(0, self.__size): 37 | [print("#", end="") for j in range(self.__size)] 38 | print("") 39 | if self.__size == 0: 40 | print("") 41 | -------------------------------------------------------------------------------- /0x06-python-classes/6-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | """Define a class Square.""" 4 | 5 | 6 | class Square: 7 | """Represent a square.""" 8 | 9 | def __init__(self, size=0, position=(0, 0)): 10 | """Initialize a new square. 11 | 12 | Args: 13 | size (int): The size of the new square. 14 | position (int, int): The position of the new square. 15 | """ 16 | self.size = size 17 | self.position = position 18 | 19 | @property 20 | def size(self): 21 | """Get/set the current size of the square.""" 22 | return (self.__size) 23 | 24 | @size.setter 25 | def size(self, value): 26 | if not isinstance(value, int): 27 | raise TypeError("size must be an integer") 28 | elif value < 0: 29 | raise ValueError("size must be >= 0") 30 | self.__size = value 31 | 32 | @property 33 | def position(self): 34 | """Get/set the current position of the square.""" 35 | return (self.__position) 36 | 37 | @position.setter 38 | def position(self, value): 39 | if (not isinstance(value, tuple) or 40 | len(value) != 2 or 41 | not all(isinstance(num, int) for num in value) or 42 | not all(num >= 0 for num in value)): 43 | raise TypeError("position must be a tuple of 2 positive integers") 44 | self.__position = value 45 | 46 | def area(self): 47 | """Return the current area of the square.""" 48 | return (self.__size * self.__size) 49 | 50 | def my_print(self): 51 | """Print the square with the # character.""" 52 | if self.__size == 0: 53 | print("") 54 | return 55 | 56 | [print("") for i in range(0, self.__position[1])] 57 | for i in range(0, self.__size): 58 | [print(" ", end="") for j in range(0, self.__position[0])] 59 | [print("#", end="") for k in range(0, self.__size)] 60 | print("") 61 | -------------------------------------------------------------------------------- /0x06-python-classes/tests/0-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Square = __import__('0-square').Square 3 | 4 | my_square = Square() 5 | print(type(my_square)) 6 | print(my_square.__dict__) 7 | -------------------------------------------------------------------------------- /0x06-python-classes/tests/1-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Square = __import__('1-square').Square 3 | 4 | my_square = Square(3) 5 | print(type(my_square)) 6 | print(my_square.__dict__) 7 | 8 | try: 9 | print(my_square.size) 10 | except Exception as e: 11 | print(e) 12 | 13 | try: 14 | print(my_square.__size) 15 | except Exception as e: 16 | print(e) 17 | -------------------------------------------------------------------------------- /0x06-python-classes/tests/100-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | SinglyLinkedList = __import__('100-singly_linked_list').SinglyLinkedList 3 | 4 | sll = SinglyLinkedList() 5 | sll.sorted_insert(2) 6 | sll.sorted_insert(5) 7 | sll.sorted_insert(3) 8 | sll.sorted_insert(10) 9 | sll.sorted_insert(1) 10 | sll.sorted_insert(-4) 11 | sll.sorted_insert(-3) 12 | sll.sorted_insert(4) 13 | sll.sorted_insert(5) 14 | sll.sorted_insert(12) 15 | sll.sorted_insert(3) 16 | print(sll) 17 | -------------------------------------------------------------------------------- /0x06-python-classes/tests/101-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Square = __import__('101-square').Square 3 | 4 | my_square = Square(5, (0, 0)) 5 | print(my_square) 6 | 7 | print("--") 8 | 9 | my_square = Square(5, (4, 1)) 10 | print(my_square) 11 | -------------------------------------------------------------------------------- /0x06-python-classes/tests/102-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Square = __import__('102-square').Square 3 | 4 | s_5 = Square(5) 5 | s_6 = Square(6) 6 | 7 | if s_5 < s_6: 8 | print("Square 5 < Square 6") 9 | if s_5 <= s_6: 10 | print("Square 5 <= Square 6") 11 | if s_5 == s_6: 12 | print("Square 5 == Square 6") 13 | if s_5 != s_6: 14 | print("Square 5 != Square 6") 15 | if s_5 > s_6: 16 | print("Square 5 > Square 6") 17 | if s_5 >= s_6: 18 | print("Square 5 >= Square 6") 19 | -------------------------------------------------------------------------------- /0x06-python-classes/tests/2-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Square = __import__('2-square').Square 3 | 4 | my_square_1 = Square(3) 5 | print(type(my_square_1)) 6 | print(my_square_1.__dict__) 7 | 8 | my_square_2 = Square() 9 | print(type(my_square_2)) 10 | print(my_square_2.__dict__) 11 | 12 | try: 13 | print(my_square_1.size) 14 | except Exception as e: 15 | print(e) 16 | 17 | try: 18 | print(my_square_1.__size) 19 | except Exception as e: 20 | print(e) 21 | 22 | try: 23 | my_square_3 = Square("3") 24 | print(type(my_square_3)) 25 | print(my_square_3.__dict__) 26 | except Exception as e: 27 | print(e) 28 | 29 | try: 30 | my_square_4 = Square(-89) 31 | print(type(my_square_4)) 32 | print(my_square_4.__dict__) 33 | except Exception as e: 34 | print(e) 35 | -------------------------------------------------------------------------------- /0x06-python-classes/tests/3-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Square = __import__('3-square').Square 3 | 4 | my_square_1 = Square(3) 5 | print("Area: {}".format(my_square_1.area())) 6 | 7 | try: 8 | print(my_square_1.size) 9 | except Exception as e: 10 | print(e) 11 | 12 | try: 13 | print(my_square_1.__size) 14 | except Exception as e: 15 | print(e) 16 | 17 | my_square_2 = Square(5) 18 | print("Area: {}".format(my_square_2.area())) 19 | -------------------------------------------------------------------------------- /0x06-python-classes/tests/4-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Square = __import__('4-square').Square 3 | 4 | my_square = Square(89) 5 | print("Area: {} for size: {}".format(my_square.area(), my_square.size)) 6 | 7 | my_square.size = 3 8 | print("Area: {} for size: {}".format(my_square.area(), my_square.size)) 9 | 10 | try: 11 | my_square.size = "5 feet" 12 | print("Area: {} for size: {}".format(my_square.area(), my_square.size)) 13 | except Exception as e: 14 | print(e) 15 | -------------------------------------------------------------------------------- /0x06-python-classes/tests/5-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Square = __import__('5-square').Square 3 | 4 | my_square = Square(3) 5 | my_square.my_print() 6 | 7 | print("--") 8 | 9 | my_square.size = 10 10 | my_square.my_print() 11 | 12 | print("--") 13 | 14 | my_square.size = 0 15 | my_square.my_print() 16 | 17 | print("--") 18 | -------------------------------------------------------------------------------- /0x06-python-classes/tests/6-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Square = __import__('6-square').Square 3 | 4 | my_square_1 = Square(3) 5 | my_square_1.my_print() 6 | 7 | print("--") 8 | 9 | my_square_2 = Square(3, (1, 1)) 10 | my_square_2.my_print() 11 | 12 | print("--") 13 | 14 | my_square_3 = Square(3, (3, 0)) 15 | my_square_3.my_print() 16 | 17 | print("--") 18 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/0-add_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines an integer addition function.""" 3 | 4 | 5 | def add_integer(a, b=98): 6 | """Return the integer addition of a and b. 7 | 8 | Float arguments are typecasted to ints before addition is performed. 9 | 10 | Raises: 11 | TypeError: If either of a or b is a non-integer and non-float. 12 | """ 13 | if ((not isinstance(a, int) and not isinstance(a, float))): 14 | raise TypeError("a must be an integer") 15 | if ((not isinstance(b, int) and not isinstance(b, float))): 16 | raise TypeError("b must be an integer") 17 | return (int(a) + int(b)) 18 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/101-lazy_matrix_mul.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a matrix multiplication function using NumPy.""" 3 | import numpy as np 4 | 5 | 6 | def lazy_matrix_mul(m_a, m_b): 7 | """Return the multiplication of two matrices. 8 | 9 | Args: 10 | m_a (list of lists of ints/floats): The first matrix. 11 | m_b (list of lists of ints/floats): The second matrix. 12 | """ 13 | 14 | return (np.matmul(m_a, m_b)) 15 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/102-python.c: -------------------------------------------------------------------------------- 1 | #include "Python.h" 2 | 3 | /** 4 | * print_python_string - Prints information about Python strings. 5 | * @p: A PyObject string object. 6 | */ 7 | void print_python_string(PyObject *p) 8 | { 9 | long int length; 10 | 11 | fflush(stdout); 12 | 13 | printf("[.] string object info\n"); 14 | if (strcmp(p->ob_type->tp_name, "str") != 0) 15 | { 16 | printf(" [ERROR] Invalid String Object\n"); 17 | return; 18 | } 19 | 20 | length = ((PyASCIIObject *)(p))->length; 21 | 22 | if (PyUnicode_IS_COMPACT_ASCII(p)) 23 | printf(" type: compact ascii\n"); 24 | else 25 | printf(" type: compact unicode object\n"); 26 | printf(" length: %ld\n", length); 27 | printf(" value: %ls\n", PyUnicode_AsWideCharString(p, &length)); 28 | } 29 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/2-matrix_divided.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a matrix division function.""" 3 | 4 | 5 | def matrix_divided(matrix, div): 6 | """Divide all elements of a matrix. 7 | 8 | Args: 9 | matrix (list): A list of lists of ints or floats. 10 | div (int/float): The divisor. 11 | Raises: 12 | TypeError: If the matrix contains non-numbers. 13 | TypeError: If the matrix contains rows of different sizes. 14 | TypeError: If div is not an int or float. 15 | ZeroDivisionError: If div is 0. 16 | Returns: 17 | A new matrix representing the result of the division. 18 | """ 19 | if (not isinstance(matrix, list) or matrix == [] or 20 | not all(isinstance(row, list) for row in matrix) or 21 | not all((isinstance(ele, int) or isinstance(ele, float)) 22 | for ele in [num for row in matrix for num in row])): 23 | raise TypeError("matrix must be a matrix (list of lists) of " 24 | "integers/floats") 25 | 26 | if not all(len(row) == len(matrix[0]) for row in matrix): 27 | raise TypeError("Each row of the matrix must have the same size") 28 | 29 | if not isinstance(div, int) and not isinstance(div, float): 30 | raise TypeError("div must be a number") 31 | 32 | if div == 0: 33 | raise ZeroDivisionError("division by zero") 34 | 35 | return ([list(map(lambda x: round(x / div, 2), row)) for row in matrix]) 36 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/3-say_my_name.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a name-printing function.""" 3 | 4 | 5 | def say_my_name(first_name, last_name=""): 6 | """Print a name. 7 | 8 | Args: 9 | first_name (str): The first name to print. 10 | last_name (str): The last name to print. 11 | Raises: 12 | TypeError: If either of first_name or last_name are not strings. 13 | """ 14 | if not isinstance(first_name, str): 15 | raise TypeError("first_name must be a string") 16 | if not isinstance(last_name, str): 17 | raise TypeError("last_name must be a string") 18 | print("My name is {} {}".format(first_name, last_name)) 19 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/4-print_square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a square-printing function.""" 3 | 4 | 5 | def print_square(size): 6 | """Print a square with the # character. 7 | 8 | Args: 9 | size (int): The height/width of the square. 10 | Raises: 11 | TypeError: If size is not an integer. 12 | ValueError: If size is < 0 13 | """ 14 | if not isinstance(size, int): 15 | raise TypeError("size must be an integer") 16 | if size < 0: 17 | raise ValueError("size must be >= 0") 18 | 19 | for i in range(size): 20 | [print("#", end="") for j in range(size)] 21 | print("") 22 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/5-text_indentation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a text-indentation function.""" 3 | 4 | 5 | def text_indentation(text): 6 | """Print text with two new lines after each '.', '?', and ':'. 7 | 8 | Args: 9 | text (string): The text to print. 10 | Raises: 11 | TypeError: If text is not a string. 12 | """ 13 | if not isinstance(text, str): 14 | raise TypeError("text must be a string") 15 | 16 | c = 0 17 | while c < len(text) and text[c] == ' ': 18 | c += 1 19 | 20 | while c < len(text): 21 | print(text[c], end="") 22 | if text[c] == "\n" or text[c] in ".?:": 23 | if text[c] in ".?:": 24 | print("\n") 25 | c += 1 26 | while c < len(text) and text[c] == ' ': 27 | c += 1 28 | continue 29 | c += 1 30 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/6-max_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Module to find the max integer in a list 3 | """ 4 | 5 | 6 | def max_integer(list=[]): 7 | """Function to find and return the max integer in a list of integers 8 | If the list is empty, the function returns None 9 | """ 10 | if len(list) == 0: 11 | return None 12 | result = list[0] 13 | i = 1 14 | while i < len(list): 15 | if list[i] > result: 16 | result = list[i] 17 | i += 1 18 | return result 19 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/0-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | add_integer = __import__('0-add_integer').add_integer 3 | 4 | print(add_integer(1, 2)) 5 | print(add_integer(100, -2)) 6 | print(add_integer(2)) 7 | print(add_integer(100.3, -2)) 8 | try: 9 | print(add_integer(4, "School")) 10 | except Exception as e: 11 | print(e) 12 | try: 13 | print(add_integer(None)) 14 | except Exception as e: 15 | print(e) 16 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/100-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | matrix_mul = __import__('100-matrix_mul').matrix_mul 3 | 4 | print(matrix_mul([[1, 2], [3, 4]], [[1, 2], [3, 4]])) 5 | print(matrix_mul([[1, 2]], [[3, 4], [5, 6]])) 6 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/101-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | lazy_matrix_mul = __import__('101-lazy_matrix_mul').lazy_matrix_mul 3 | 4 | print(lazy_matrix_mul([[1, 2], [3, 4]], [[1, 2], [3, 4]])) 5 | print(lazy_matrix_mul([[1, 2]], [[3, 4], [5, 6]])) 6 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/2-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | matrix_divided = __import__('2-matrix_divided').matrix_divided 3 | 4 | matrix = [ 5 | [1, 2, 3], 6 | [4, 5, 6] 7 | ] 8 | print(matrix_divided(matrix, 3)) 9 | print(matrix) 10 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/3-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | say_my_name = __import__('3-say_my_name').say_my_name 3 | 4 | say_my_name("John", "Smith") 5 | say_my_name("Walter", "White") 6 | say_my_name("Bob") 7 | try: 8 | say_my_name(12, "White") 9 | except Exception as e: 10 | print(e) 11 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/4-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | print_square = __import__('4-print_square').print_square 3 | 4 | print_square(4) 5 | print("") 6 | print_square(10) 7 | print("") 8 | print_square(0) 9 | print("") 10 | print_square(1) 11 | print("") 12 | try: 13 | print_square(-1) 14 | except Exception as e: 15 | print(e) 16 | print("") 17 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/4-print_square.txt: -------------------------------------------------------------------------------- 1 | 2 | ============================ 3 | How to Use 4-print_square.py 4 | ============================ 5 | 6 | This module defines a square-printing function ``print_square(size)``. 7 | 8 | Usage 9 | ===== 10 | 11 | Squares are printed using the ``#`` character. The parameter ``size`` 12 | represents the height and width of the square. 13 | 14 | :: 15 | 16 | >>> print_square = __import__('4-print_square').print_square 17 | >>> print_square(1) 18 | # 19 | 20 | :: 21 | 22 | >>> print_square(4) 23 | #### 24 | #### 25 | #### 26 | #### 27 | 28 | :: 29 | 30 | >>> print_square(10) 31 | ########## 32 | ########## 33 | ########## 34 | ########## 35 | ########## 36 | ########## 37 | ########## 38 | ########## 39 | ########## 40 | ########## 41 | 42 | If ``size`` is zero, the function prints nothing. 43 | 44 | :: 45 | 46 | >>> print_square(0) 47 | 48 | Invalid Sizes 49 | ============= 50 | 51 | The parameter ``size`` must be an integer. Otherwise, a TypeError is raised. 52 | 53 | :: 54 | 55 | >>> print_square("not an int") 56 | Traceback (most recent call last): 57 | TypeError: size must be an integer 58 | 59 | :: 60 | 61 | >>> print_square(5.5) 62 | Traceback (most recent call last): 63 | TypeError: size must be an integer 64 | 65 | :: 66 | 67 | >>> print_square(None) 68 | Traceback (most recent call last): 69 | TypeError: size must be an integer 70 | 71 | If ``size`` is less than zero, a ValueError is raised. 72 | 73 | :: 74 | 75 | >>> print_square(-7) 76 | Traceback (most recent call last): 77 | ValueError: size must be >= 0 78 | 79 | Note that type-checking occurs before value-checking. 80 | 81 | :: 82 | 83 | >>> print_square(-7.5) 84 | Traceback (most recent call last): 85 | TypeError: size must be an integer 86 | 87 | At least one argument must be provided. 88 | 89 | :: 90 | 91 | >>> print_square() 92 | Traceback (most recent call last): 93 | TypeError: print_square() missing 1 required positional argument: 'size' 94 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/5-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | text_indentation = __import__('5-text_indentation').text_indentation 3 | 4 | text_indentation("""Lorem ipsum dolor sit amet, consectetur adipiscing elit. \ 5 | Quonam modo? Utrum igitur tibi litteram videor an totas paginas commovere? \ 6 | Non autem hoc: igitur ne illud quidem. Fortasse id optimum, sed ubi illud: \ 7 | Plus semper voluptatis? Teneo, inquit, finem illi videri nihil dolere. \ 8 | Transfer idem ad modestiam vel temperantiam, quae est moderatio cupiditatum \ 9 | rationi oboediens. Si id dicis, vicimus. Inde sermone vario sex illa a Dipylo \ 10 | stadia confecimus. Sin aliud quid voles, postea. Quae animi affectio suum \ 11 | cuique tribuens atque hanc, quam dico. Utinam quidem dicerent alium alio \ 12 | beatiorem! Iam ruinas videres""") 13 | -------------------------------------------------------------------------------- /0x08-python-more_classes/0-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a Rectangle class.""" 3 | 4 | 5 | class Rectangle: 6 | """Represent a rectangle.""" 7 | pass 8 | -------------------------------------------------------------------------------- /0x08-python-more_classes/1-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a Rectangle class.""" 3 | 4 | 5 | class Rectangle: 6 | """Represent a rectangle.""" 7 | 8 | def __init__(self, width=0, height=0): 9 | """Initialize a new Rectangle. 10 | 11 | Args: 12 | width (int): The width of the new rectangle. 13 | height (int): The height of the new rectangle. 14 | """ 15 | self.width = width 16 | self.height = height 17 | 18 | @property 19 | def width(self): 20 | """Get/set the width of the rectangle.""" 21 | return self.__width 22 | 23 | @width.setter 24 | def width(self, value): 25 | if not isinstance(value, int): 26 | raise TypeError("width must be an integer") 27 | if value < 0: 28 | raise ValueError("width must be >= 0") 29 | self.__width = value 30 | 31 | @property 32 | def height(self): 33 | """Get/set the height of the rectangle.""" 34 | return self.__height 35 | 36 | @height.setter 37 | def height(self, value): 38 | if not isinstance(value, int): 39 | raise TypeError("height must be an integer") 40 | if value < 0: 41 | raise ValueError("height must be >= 0") 42 | self.__height = value 43 | -------------------------------------------------------------------------------- /0x08-python-more_classes/2-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a Rectangle class.""" 3 | 4 | 5 | class Rectangle: 6 | """Represent a rectangle.""" 7 | 8 | def __init__(self, width=0, height=0): 9 | """Initialize a new Rectangle. 10 | 11 | Args: 12 | width (int): The width of the new rectangle. 13 | height (int): The height of the new rectangle. 14 | """ 15 | self.width = width 16 | self.height = height 17 | 18 | @property 19 | def width(self): 20 | """Get/set the width of the Rectangle.""" 21 | return self.__width 22 | 23 | @width.setter 24 | def width(self, value): 25 | if not isinstance(value, int): 26 | raise TypeError("width must be an integer") 27 | if value < 0: 28 | raise ValueError("width must be >= 0") 29 | self.__width = value 30 | 31 | @property 32 | def height(self): 33 | """Get/set the height of the Rectangle.""" 34 | return self.__height 35 | 36 | @height.setter 37 | def height(self, value): 38 | if not isinstance(value, int): 39 | raise TypeError("height must be an integer") 40 | if value < 0: 41 | raise ValueError("height must be >= 0") 42 | self.__height = value 43 | 44 | def area(self): 45 | """Return the area of the Rectangle.""" 46 | return (self.__width * self.__height) 47 | 48 | def perimeter(self): 49 | """Return the perimeter of the Rectangle.""" 50 | if self.__width == 0 or self.__height == 0: 51 | return (0) 52 | return ((self.__width * 2) + (self.__height * 2)) 53 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/0-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('0-rectangle').Rectangle 3 | 4 | my_rectangle = Rectangle() 5 | print(type(my_rectangle)) 6 | print(my_rectangle.__dict__) 7 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/1-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('1-rectangle').Rectangle 3 | 4 | my_rectangle = Rectangle(2, 4) 5 | print(my_rectangle.__dict__) 6 | 7 | my_rectangle.width = 10 8 | my_rectangle.height = 3 9 | print(my_rectangle.__dict__) 10 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/2-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('2-rectangle').Rectangle 3 | 4 | my_rectangle = Rectangle(2, 4) 5 | print("Area: {} - Perimeter: {}".format(my_rectangle.area(), my_rectangle.perimeter())) 6 | 7 | print("--") 8 | 9 | my_rectangle.width = 10 10 | my_rectangle.height = 3 11 | print("Area: {} - Perimeter: {}".format(my_rectangle.area(), my_rectangle.perimeter())) 12 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/3-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('3-rectangle').Rectangle 3 | 4 | my_rectangle = Rectangle(2, 4) 5 | print("Area: {} - Perimeter: {}".format(my_rectangle.area(), my_rectangle.perimeter())) 6 | 7 | print(str(my_rectangle)) 8 | print(repr(my_rectangle)) 9 | 10 | print("--") 11 | 12 | my_rectangle.width = 10 13 | my_rectangle.height = 3 14 | print(my_rectangle) 15 | print(repr(my_rectangle)) 16 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/4-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('4-rectangle').Rectangle 3 | 4 | my_rectangle = Rectangle(2, 4) 5 | print(str(my_rectangle)) 6 | print("--") 7 | print(my_rectangle) 8 | print("--") 9 | print(repr(my_rectangle)) 10 | print("--") 11 | print(hex(id(my_rectangle))) 12 | print("--") 13 | 14 | # create new instance based on representation 15 | new_rectangle = eval(repr(my_rectangle)) 16 | print(str(new_rectangle)) 17 | print("--") 18 | print(new_rectangle) 19 | print("--") 20 | print(repr(new_rectangle)) 21 | print("--") 22 | print(hex(id(new_rectangle))) 23 | print("--") 24 | 25 | print(new_rectangle is my_rectangle) 26 | print(type(new_rectangle) is type(my_rectangle)) 27 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/5-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('5-rectangle').Rectangle 3 | 4 | my_rectangle = Rectangle(2, 4) 5 | print("Area: {} - Perimeter: {}".format(my_rectangle.area(), my_rectangle.perimeter())) 6 | 7 | del my_rectangle 8 | 9 | try: 10 | print(my_rectangle) 11 | except Exception as e: 12 | print("[{}] {}".format(e.__class__.__name__, e)) 13 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/6-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('6-rectangle').Rectangle 3 | 4 | my_rectangle_1 = Rectangle(2, 4) 5 | my_rectangle_2 = Rectangle(2, 4) 6 | print("{:d} instances of Rectangle".format(Rectangle.number_of_instances)) 7 | del my_rectangle_1 8 | print("{:d} instances of Rectangle".format(Rectangle.number_of_instances)) 9 | del my_rectangle_2 10 | print("{:d} instances of Rectangle".format(Rectangle.number_of_instances)) 11 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/7-main.py: -------------------------------------------------------------------------------- 1 | ectangle = __import__('7-rectangle').Rectangle 2 | 3 | my_rectangle_1 = Rectangle(8, 4) 4 | print(my_rectangle_1) 5 | print("--") 6 | my_rectangle_1.print_symbol = "&" 7 | print(my_rectangle_1) 8 | print("--") 9 | 10 | my_rectangle_2 = Rectangle(2, 1) 11 | print(my_rectangle_2) 12 | print("--") 13 | Rectangle.print_symbol = "C" 14 | print(my_rectangle_2) 15 | print("--") 16 | 17 | my_rectangle_3 = Rectangle(7, 3) 18 | print(my_rectangle_3) 19 | 20 | print("--") 21 | 22 | my_rectangle_3.print_symbol = ["C", "is", "fun!"] 23 | print(my_rectangle_3) 24 | 25 | print("--") 26 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/8-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('8-rectangle').Rectangle 3 | 4 | my_rectangle_1 = Rectangle(8, 4) 5 | my_rectangle_2 = Rectangle(2, 3) 6 | 7 | if my_rectangle_1 is Rectangle.bigger_or_equal(my_rectangle_1, my_rectangle_2): 8 | print("my_rectangle_1 is bigger or equal to my_rectangle_2") 9 | else: 10 | print("my_rectangle_2 is bigger than my_rectangle_1") 11 | 12 | 13 | my_rectangle_2.width = 10 14 | my_rectangle_2.height = 5 15 | if my_rectangle_1 is Rectangle.bigger_or_equal(my_rectangle_1, my_rectangle_2): 16 | print("my_rectangle_1 is bigger or equal to my_rectangle_2") 17 | else: 18 | print("my_rectangle_2 is bigger than my_rectangle_1") 19 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/9-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('9-rectangle').Rectangle 3 | 4 | my_square = Rectangle.square(5) 5 | print("Area: {} - Perimeter: {}".format(my_square.area(), my_square.perimeter())) 6 | print(my_square) 7 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/0-answer.txt: -------------------------------------------------------------------------------- 1 | type 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/1-answer.txt: -------------------------------------------------------------------------------- 1 | id 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/10-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/100-magic_string.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def magic_string(): 3 | magic_string.n = getattr(magic_string, 'n', 0) + 1 4 | return ("BestSchool, " * (magic_string.n - 1) + "BestSchool") 5 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/101-locked_class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a locked class.""" 3 | 4 | 5 | class LockedClass: 6 | """ 7 | Prevent the user from instantiating new LockedClass attributes 8 | for anything but attributes called 'first_name'. 9 | """ 10 | 11 | __slots__ = ["first_name"] 12 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/103-line1.txt: -------------------------------------------------------------------------------- 1 | 0 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/103-line2.txt: -------------------------------------------------------------------------------- 1 | 0 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/104-line1.txt: -------------------------------------------------------------------------------- 1 | 1 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/104-line2.txt: -------------------------------------------------------------------------------- 1 | 1 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/104-line3.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/104-line4.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/104-line5.txt: -------------------------------------------------------------------------------- 1 | 1 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/105-line1.txt: -------------------------------------------------------------------------------- 1 | 262 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/106-line1.txt: -------------------------------------------------------------------------------- 1 | 1 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/106-line2.txt: -------------------------------------------------------------------------------- 1 | 0 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/106-line3.txt: -------------------------------------------------------------------------------- 1 | No 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/106-line4.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/106-line5.txt: -------------------------------------------------------------------------------- 1 | 1 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/11-answer.txt: -------------------------------------------------------------------------------- 1 | False 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/12-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/13-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/14-answer.txt: -------------------------------------------------------------------------------- 1 | [1, 2, 3, 4] 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/15-answer.txt: -------------------------------------------------------------------------------- 1 | [1, 2, 3] 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/16-answer.txt: -------------------------------------------------------------------------------- 1 | 1 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/17-answer.txt: -------------------------------------------------------------------------------- 1 | [1, 2, 3, 4] 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/18-answer.txt: -------------------------------------------------------------------------------- 1 | [1, 2, 3] 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/19-copy_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def copy_list(a): 3 | return a.copy() 4 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/2-answer.txt: -------------------------------------------------------------------------------- 1 | No 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/20-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/21-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/22-answer.txt: -------------------------------------------------------------------------------- 1 | No 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/23-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/24-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/25-answer.txt: -------------------------------------------------------------------------------- 1 | False 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/26-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/27-answer.txt: -------------------------------------------------------------------------------- 1 | No 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/28-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/3-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/4-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/5-answer.txt: -------------------------------------------------------------------------------- 1 | No 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/6-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/7-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/8-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/9-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/tests/100-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | magic_string = __import__('100-magic_string').magic_string 3 | 4 | for i in range(10): 5 | print(magic_string()) 6 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/tests/101-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | LockedClass = __import__('101-locked_class').LockedClass 3 | 4 | lc = LockedClass() 5 | lc.first_name = "John" 6 | try: 7 | lc.last_name = "Snow" 8 | except Exception as e: 9 | print("[{}] {}".format(e.__class__.__name__, e)) 10 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/tests/19-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | copy_list = __import__('19-copy_list').copy_list 3 | 4 | my_list = [1, 2, 3] 5 | print(my_list) 6 | 7 | new_list = copy_list(my_list) 8 | 9 | print(my_list) 10 | print(new_list) 11 | 12 | print(new_list == my_list) 13 | print(new_list is my_list) 14 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/0-lookup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines an object attribute lookup function.""" 3 | 4 | 5 | def lookup(obj): 6 | """Return a list of an object's available attributes.""" 7 | return (dir(obj)) 8 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/1-my_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | contains the MyList class 4 | """ 5 | 6 | 7 | class MyList(list): 8 | """a subclass of list""" 9 | def __init__(self): 10 | """initializes the object""" 11 | super().__init__() 12 | 13 | def print_sorted(self): 14 | """prints the sorted list""" 15 | print(sorted(self)) 16 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/10-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a Rectangle subclass Square.""" 3 | Rectangle = __import__('9-rectangle').Rectangle 4 | 5 | 6 | class Square(Rectangle): 7 | """Represent a square.""" 8 | 9 | def __init__(self, size): 10 | """Initialize a new square. 11 | 12 | Args: 13 | size (int): The size of the new square. 14 | """ 15 | self.integer_validator("size", size) 16 | super().__init__(size, size) 17 | self.__size = size 18 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/100-my_int.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a class MyInt that inherits from int.""" 3 | 4 | 5 | class MyInt(int): 6 | """Invert int operators == and !=.""" 7 | 8 | def __eq__(self, value): 9 | """Override == opeartor with != behavior.""" 10 | return self.real != value 11 | 12 | def __ne__(self, value): 13 | """Override != operator with == behavior.""" 14 | return self.real == value 15 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/101-add_attribute.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a function that adds attributes to objects.""" 3 | 4 | 5 | def add_attribute(obj, att, value): 6 | """Add a new attribute to an object if possible. 7 | 8 | Args: 9 | obj (any): The object to add an attribute to. 10 | att (str): The name of the attribute to add to obj. 11 | value (any): The value of att. 12 | Raises: 13 | TypeError: If the attribute cannot be added. 14 | """ 15 | if not hasattr(obj, "__dict__"): 16 | raise TypeError("can't add new attribute") 17 | setattr(obj, att, value) 18 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/11-square.py: -------------------------------------------------------------------------------- 1 | a Rectangle subclass Square.""" 2 | Rectangle = __import__('9-rectangle').Rectangle 3 | 4 | 5 | class Square(Rectangle): 6 | """Represent a square.""" 7 | 8 | def __init__(self, size): 9 | """Initialize a new square. 10 | 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 | 8 | Args: 9 | obj (any): The object to check. 10 | a_class (type): The class to match the type of obj to. 11 | Returns: 12 | If obj is exactly an instance of a_class - True. 13 | Otherwise - False. 14 | """ 15 | if type(obj) == a_class: 16 | return True 17 | return False 18 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/3-is_kind_of_class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a class and inherited class-checking function.""" 3 | 4 | 5 | def is_kind_of_class(obj, a_class): 6 | """Check if an object is an instance or inherited instance of a class. 7 | 8 | Args: 9 | obj (any): The object to check. 10 | a_class (type): The class to match the type of obj to. 11 | Returns: 12 | If obj is an instance or inherited instance of a_class - True. 13 | Otherwise - False. 14 | """ 15 | if isinstance(obj, a_class): 16 | return True 17 | return False 18 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/4-inherits_from.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines an inherited class-checking function.""" 3 | 4 | 5 | def inherits_from(obj, a_class): 6 | """Checks if an object is an inherited instance of a class. 7 | 8 | Args: 9 | obj (any): The object to check. 10 | a_class (type): The class to match the type of obj to. 11 | Returns: 12 | If obj is an inherited instance of a_class - True. 13 | Otherwise - False. 14 | """ 15 | if issubclass(type(obj), a_class) and type(obj) != a_class: 16 | return True 17 | return False 18 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/5-base_geometry.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines an empty class BaseGeometry.""" 3 | 4 | 5 | class BaseGeometry: 6 | """Represent base geometry.""" 7 | pass 8 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/6-base_geometry.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a base geometry class BaseGeometry.""" 3 | 4 | 5 | class BaseGeometry: 6 | """Represent base geometry.""" 7 | 8 | def area(self): 9 | """Not implemented.""" 10 | raise Exception("area() is not implemented") 11 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/7-base_geometry.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a base geometry class BaseGeometry.""" 3 | 4 | 5 | class BaseGeometry: 6 | """Reprsent base geometry.""" 7 | 8 | def area(self): 9 | """Not yet implemented.""" 10 | raise Exception("area() is not implemented") 11 | 12 | def integer_validator(self, name, value): 13 | """Validate a parameter as an integer. 14 | 15 | Args: 16 | name (str): The name of the parameter. 17 | value (int): The parameter to validate. 18 | Raises: 19 | TypeError: If value is not an integer. 20 | ValueError: If value is <= 0. 21 | """ 22 | if type(value) != int: 23 | raise TypeError("{} must be an integer".format(name)) 24 | if value <= 0: 25 | raise ValueError("{} must be greater than 0".format(name)) 26 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/8-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a class Rectangle that inherits from BaseGeometry.""" 3 | BaseGeometry = __import__('7-base_geometry').BaseGeometry 4 | 5 | 6 | class Rectangle(BaseGeometry): 7 | """Represent a rectangle using BaseGeometry.""" 8 | 9 | def __init__(self, width, height): 10 | """Intialize a new Rectangle. 11 | 12 | Args: 13 | width (int): The width of the new Rectangle. 14 | height (int): The height of the new Rectangle. 15 | """ 16 | self.integer_validator("width", width) 17 | self.__width = width 18 | self.integer_validator("height", height) 19 | self.__height = height 20 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/9-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a class Rectangle that inherits from BaseGeometry.""" 3 | BaseGeometry = __import__('7-base_geometry').BaseGeometry 4 | 5 | 6 | class Rectangle(BaseGeometry): 7 | """Represent a rectangle using BaseGeometry.""" 8 | 9 | def __init__(self, width, height): 10 | """Intialize a new Rectangle. 11 | 12 | Args: 13 | width (int): The width of the new Rectangle. 14 | height (int): The height of the new Rectangle. 15 | """ 16 | super().integer_validator("width", width) 17 | self.__width = width 18 | super().integer_validator("height", height) 19 | self.__height = height 20 | 21 | def area(self): 22 | """Return the area of the rectangle.""" 23 | return self.__width * self.__height 24 | 25 | def __str__(self): 26 | """Return the print() and str() representation of a Rectangle.""" 27 | string = "[" + str(self.__class__.__name__) + "] " 28 | string += str(self.__width) + "/" + str(self.__height) 29 | return string 30 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/README.md: -------------------------------------------------------------------------------- 1 | # 0x0A. Python - Inheritance 2 | 3 | As I am diving deeper in Object Oriented Programming (OOP) with python, this project introduce me to the concept of `inheritance` 4 | 5 | 6 | Inheritance is a mechanism in which one class acquires the property of another class. For example, a child inherits the traits of his/her parents. With inheritance, we can reuse the fields and methods of the existing class. Hence, inheritance facilitates Reusability and is an important concept of OOPs. 7 | 8 | 9 | Python has two built-in functions that work with inheritance: 10 | 11 | - Use `isinstance()` to check an instance’s type: `isinstance(obj, int)` will be `True` only if `obj.__class__` is `int` or some class derived from `int`. 12 | 13 | - Use `issubclass()` to check class inheritance: `issubclass(bool, int)` is `True` since bool is a subclass of int. However, issubclass(float, int) is `False` since `float` is not a subclass of `int`. 14 | 15 | 16 | In this project, I learnt: 17 | - Why Python programming is awesome 18 | - What is a superclass, baseclass or parentclass 19 | - What is a subclass 20 | - How to list all attributes and methods of a class or instance 21 | - When can an instance have new attributes 22 | - How to inherit class from another 23 | - How to define a class with multiple base classes 24 | - What is the default class every class inherit from 25 | - How to override a method or attribute inherited from the base class 26 | - Which attributes or methods are available by heritage to subclasses 27 | - What is the purpose of inheritance 28 | - What are, when and how to use isinstance, issubclass, type and super built-in functions 29 | 30 | 31 | # Resources 32 | - [python documentation](https://docs.python.org/3/tutorial/classes.html#inheritance) 33 | - [analyticsvidhya.com](https://www.analyticsvidhya.com/blog/2020/10/inheritance-object-oriented-programming/#:~:text=super()%20function-,What%20is%20Inheritance%20in%20Object%20Oriented%20Programming%3F,known%20as%20the%20Parent%20class.) 34 | - [youtube](https://www.youtube.com/watch?v=d8kCdLCi6Lk) 35 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/0-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | lookup = __import__('0-lookup').lookup 3 | 4 | class MyClass1(object): 5 | pass 6 | 7 | class MyClass2(object): 8 | my_attr1 = 3 9 | def my_meth(self): 10 | pass 11 | 12 | print(lookup(MyClass1)) 13 | print(lookup(MyClass2)) 14 | print(lookup(int)) 15 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/1-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | MyList = __import__('1-my_list').MyList 3 | 4 | my_list = MyList() 5 | my_list.append(1) 6 | my_list.append(4) 7 | my_list.append(2) 8 | my_list.append(3) 9 | my_list.append(5) 10 | print(my_list) 11 | my_list.print_sorted() 12 | print(my_list) 13 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/1-my_list.txt: -------------------------------------------------------------------------------- 1 | Checking for module docstring: 2 | >>> m = __import__("1-my_list").__doc__ 3 | >>> len(m) > 1 4 | True 5 | 6 | Checking for class docstring: 7 | >>> c = __import__("1-my_list").MyList.__doc__ 8 | >>> len(c) > 1 9 | True 10 | 11 | Checking for method docstring: 12 | >>> mod = __import__("1-my_list").MyList.print_sorted.__doc__ 13 | >>> len(mod) > 1 14 | True 15 | 16 | Checking that MyList inherits from list: 17 | >>> issubclass(MyList, list) 18 | True 19 | 20 | Checking for empty list: 21 | >>> l = MyList() 22 | >>> l.print_sorted() 23 | [] 24 | 25 | Checking that appendng works: 26 | >>> l.append(1) 27 | >>> l.append(2) 28 | >>> l.append(3) 29 | >>> l.append(4) 30 | >>> print(l) 31 | [1, 2, 3, 4] 32 | 33 | Checking for list already in correct order: 34 | >>> l.print_sorted() 35 | [1, 2, 3, 4] 36 | 37 | Checking for reversed order list: 38 | >>> l = MyList() 39 | >>> l.append(4) 40 | >>> l.append(3) 41 | >>> l.append(2) 42 | >>> l.append(1) 43 | >>> print(l) 44 | [4, 3, 2, 1] 45 | >>> l.print_sorted() 46 | [1, 2, 3, 4] 47 | >>> print(l) 48 | [4, 3, 2, 1] 49 | 50 | Checking for one negative number: 51 | >>> l.append(-1) 52 | >>> l.append(5) 53 | >>> print(l) 54 | [4, 3, 2, 1, -1, 5] 55 | >>> l.print_sorted() 56 | [-1, 1, 2, 3, 4, 5] 57 | >>> print(l) 58 | [4, 3, 2, 1, -1, 5] 59 | 60 | Checking for all negative numbers: 61 | >>> l = MyList() 62 | >>> l.append(-10) 63 | >>> l.append(-1) 64 | >>> l.append(-7) 65 | >>> l.append(-2) 66 | >>> l.append(-8) 67 | >>> print(l) 68 | [-10, -1, -7, -2, -8] 69 | >>> l.print_sorted() 70 | [-10, -8, -7, -2, -1] 71 | >>> print(l) 72 | [-10, -1, -7, -2, -8] 73 | 74 | Checking for too many arguments: 75 | >>> l.print_sorted(1) 76 | Traceback (most recent call last): 77 | ... 78 | TypeError: print_sorted() takes 1 positional argument but 2 were given 79 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/10-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Square = __import__('10-square').Square 3 | 4 | s = Square(13) 5 | 6 | print(s) 7 | print(s.area()) 8 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/100-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | MyInt = __import__('100-my_int').MyInt 3 | 4 | my_i = MyInt(3) 5 | print(my_i) 6 | print(my_i == 3) 7 | print(my_i != 3) 8 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/101-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | add_attribute = __import__('101-add_attribute').add_attribute 3 | 4 | class MyClass(): 5 | pass 6 | 7 | mc = MyClass() 8 | add_attribute(mc, "name", "John") 9 | print(mc.name) 10 | 11 | try: 12 | a = "My String" 13 | add_attribute(a, "name", "Bob") 14 | print(a.name) 15 | except Exception as e: 16 | print("[{}] {}".format(e.__class__.__name__, e)) 17 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/11-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Square = __import__('11-square').Square 3 | 4 | s = Square(13) 5 | 6 | print(s) 7 | print(s.area()) 8 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/2-is_same_class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a class-checking function.""" 3 | 4 | 5 | def is_same_class(obj, a_class): 6 | """Check if an object is exactly an instance of a given class. 7 | 8 | Args: 9 | obj (any): The object to check. 10 | a_class (type): The class to match the type of obj to. 11 | Returns: 12 | If obj is exactly an instance of a_class - True. 13 | Otherwise - False. 14 | """ 15 | if type(obj) == a_class: 16 | return True 17 | return False 18 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/3-is_kind_of_class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a class and inherited class-checking function.""" 3 | 4 | 5 | def is_kind_of_class(obj, a_class): 6 | """Check if an object is an instance or inherited instance of a class. 7 | 8 | Args: 9 | obj (any): The object to check. 10 | a_class (type): The class to match the type of obj to. 11 | Returns: 12 | If obj is an instance or inherited instance of a_class - True. 13 | Otherwise - False. 14 | """ 15 | if isinstance(obj, a_class): 16 | return True 17 | return False 18 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/4-inherits_from.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines an inherited class-checking function.""" 3 | 4 | 5 | def inherits_from(obj, a_class): 6 | """Checks if an object is an inherited instance of a class. 7 | 8 | Args: 9 | obj (any): The object to check. 10 | a_class (type): The class to match the type of obj to. 11 | Returns: 12 | If obj is an inherited instance of a_class - True. 13 | Otherwise - False. 14 | """ 15 | if issubclass(type(obj), a_class) and type(obj) != a_class: 16 | return True 17 | return False 18 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/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/tests/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/tests/7-base_geometry.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a base geometry class BaseGeometry.""" 3 | 4 | 5 | class BaseGeometry: 6 | """Reprsent base geometry.""" 7 | 8 | def area(self): 9 | """Not yet implemented.""" 10 | raise Exception("area() is not implemented") 11 | 12 | def integer_validator(self, name, value): 13 | """Validate a parameter as an integer. 14 | 15 | Args: 16 | name (str): The name of the parameter. 17 | value (int): The parameter to validate. 18 | Raises: 19 | TypeError: If value is not an integer. 20 | ValueError: If value is <= 0. 21 | """ 22 | if type(value) != int: 23 | raise TypeError("{} must be an integer".format(name)) 24 | if value <= 0: 25 | raise ValueError("{} must be greater than 0".format(name)) 26 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/8-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a class Rectangle that inherits from BaseGeometry.""" 3 | BaseGeometry = __import__('7-base_geometry').BaseGeometry 4 | 5 | 6 | class Rectangle(BaseGeometry): 7 | """Represent a rectangle using BaseGeometry.""" 8 | 9 | def __init__(self, width, height): 10 | """Intialize a new Rectangle. 11 | 12 | Args: 13 | width (int): The width of the new Rectangle. 14 | height (int): The height of the new Rectangle. 15 | """ 16 | self.integer_validator("width", width) 17 | self.__width = width 18 | self.integer_validator("height", height) 19 | self.__height = height 20 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/9-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a class Rectangle that inherits from BaseGeometry.""" 3 | BaseGeometry = __import__('7-base_geometry').BaseGeometry 4 | 5 | 6 | class Rectangle(BaseGeometry): 7 | """Represent a rectangle using BaseGeometry.""" 8 | 9 | def __init__(self, width, height): 10 | """Intialize a new Rectangle. 11 | 12 | Args: 13 | width (int): The width of the new Rectangle. 14 | height (int): The height of the new Rectangle. 15 | """ 16 | super().integer_validator("width", width) 17 | self.__width = width 18 | super().integer_validator("height", height) 19 | self.__height = height 20 | 21 | def area(self): 22 | """Return the area of the rectangle.""" 23 | return self.__width * self.__height 24 | 25 | def __str__(self): 26 | """Return the print() and str() representation of a Rectangle.""" 27 | string = "[" + str(self.__class__.__name__) + "] " 28 | string += str(self.__width) + "/" + str(self.__height) 29 | return string 30 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/README.md: -------------------------------------------------------------------------------- 1 | . Python - Inheritance 2 | 3 | As I am diving deeper in Object Oriented Programming (OOP) with python, this project introduce me to the concept of `inheritance` 4 | 5 | 6 | Inheritance is a mechanism in which one class acquires the property of another class. For example, a child inherits the traits of his/her parents. With inheritance, we can reuse the fields and methods of the existing class. Hence, inheritance facilitates Reusability and is an important concept of OOPs. 7 | 8 | 9 | Python has two built-in functions that work with inheritance: 10 | 11 | - Use `isinstance()` to check an instance’s type: `isinstance(obj, int)` will be `True` only if `obj.__class__` is `int` or some class derived from `int`. 12 | 13 | - Use `issubclass()` to check class inheritance: `issubclass(bool, int)` is `True` since bool is a subclass of int. However, issubclass(float, int) is `False` since `float` is not a subclass of `int`. 14 | 15 | 16 | In this project, I learnt: 17 | - Why Python programming is awesome 18 | - What is a superclass, baseclass or parentclass 19 | - What is a subclass 20 | - How to list all attributes and methods of a class or instance 21 | - When can an instance have new attributes 22 | - How to inherit class from another 23 | - How to define a class with multiple base classes 24 | - What is the default class every class inherit from 25 | - How to override a method or attribute inherited from the base class 26 | - Which attributes or methods are available by heritage to subclasses 27 | - What is the purpose of inheritance 28 | - What are, when and how to use isinstance, issubclass, type and super built-in functions 29 | 30 | 31 | # Resources 32 | - [python documentation](https://docs.python.org/3/tutorial/classes.html#inheritance) 33 | - [analyticsvidhya.com](https://www.analyticsvidhya.com/blog/2020/10/inheritance-object-oriented-programming/#:~:text=super()%20function-,What%20is%20Inheritance%20in%20Object%20Oriented%20Programming%3F,known%20as%20the%20Parent%20class.) 34 | - [youtube](https://www.youtube.com/watch?v=d8kCdLCi6Lk) 35 | -------------------------------------------------------------------------------- /0x0B-python-input_output/0-read_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a text file-reading function.""" 3 | 4 | 5 | def read_file(filename=""): 6 | """Print the contents of a UTF8 text file to stdout.""" 7 | with open(filename, encoding="utf-8") as f: 8 | print(f.read(), end="") 9 | -------------------------------------------------------------------------------- /0x0B-python-input_output/1-write_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a file-writing function.""" 3 | 4 | 5 | def write_file(filename="", text=""): 6 | """Write a string to a UTF8 text file. 7 | 8 | Args: 9 | filename (str): The name of the file to write. 10 | text (str): The text to write to the file. 11 | Returns: 12 | The number of characters written. 13 | """ 14 | with open(filename, "w", encoding="utf-8") as f: 15 | return f.write(text) 16 | -------------------------------------------------------------------------------- /0x0B-python-input_output/10-student.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a class Student.""" 3 | 4 | 5 | class Student: 6 | """Represent a student.""" 7 | 8 | def __init__(self, first_name, last_name, age): 9 | """Initialize a new Student. 10 | 11 | Args: 12 | first_name (str): The first name of the student. 13 | last_name (str): The last name of the student. 14 | age (int): The age of the student. 15 | """ 16 | self.first_name = first_name 17 | self.last_name = last_name 18 | self.age = age 19 | 20 | def to_json(self, attrs=None): 21 | """Get a dictionary representation of the Student. 22 | 23 | If attrs is a list of strings, represents only those attributes 24 | included in the list. 25 | 26 | Args: 27 | attrs (list): (Optional) The attributes to represent. 28 | """ 29 | if (type(attrs) == list and 30 | all(type(ele) == str for ele in attrs)): 31 | return {k: getattr(self, k) for k in attrs if hasattr(self, k)} 32 | return self.__dict__ 33 | -------------------------------------------------------------------------------- /0x0B-python-input_output/100-append_after.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a text file insertion function.""" 3 | 4 | 5 | def append_after(filename="", search_string="", new_string=""): 6 | """Insert text after each line containing a given string in a file. 7 | 8 | Args: 9 | filename (str): The name of the file. 10 | search_string (str): The string to search for within the file. 11 | new_string (str): The string to insert. 12 | """ 13 | text = "" 14 | with open(filename) as r: 15 | for line in r: 16 | text += line 17 | if search_string in line: 18 | text += new_string 19 | with open(filename, "w") as w: 20 | w.write(text) 21 | -------------------------------------------------------------------------------- /0x0B-python-input_output/101-stats.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Reads from standard input and computes metrics. 3 | 4 | After every ten lines or the input of a keyboard interruption (CTRL + C), 5 | prints the following statistics: 6 | - Total file size up to that point. 7 | - Count of read status codes up to that point. 8 | """ 9 | 10 | 11 | def print_stats(size, status_codes): 12 | """Print accumulated metrics. 13 | 14 | Args: 15 | size (int): The accumulated read file size. 16 | status_codes (dict): The accumulated count of status codes. 17 | """ 18 | print("File size: {}".format(size)) 19 | for key in sorted(status_codes): 20 | print("{}: {}".format(key, status_codes[key])) 21 | 22 | 23 | if __name__ == "__main__": 24 | import sys 25 | 26 | size = 0 27 | status_codes = {} 28 | valid_codes = ['200', '301', '400', '401', '403', '404', '405', '500'] 29 | count = 0 30 | 31 | try: 32 | for line in sys.stdin: 33 | if count == 10: 34 | print_stats(size, status_codes) 35 | count = 1 36 | else: 37 | count += 1 38 | 39 | line = line.split() 40 | 41 | try: 42 | size += int(line[-1]) 43 | except (IndexError, ValueError): 44 | pass 45 | 46 | try: 47 | if line[-2] in valid_codes: 48 | if status_codes.get(line[-2], -1) == -1: 49 | status_codes[line[-2]] = 1 50 | else: 51 | status_codes[line[-2]] += 1 52 | except IndexError: 53 | pass 54 | 55 | print_stats(size, status_codes) 56 | 57 | except KeyboardInterrupt: 58 | print_stats(size, status_codes) 59 | raise 60 | -------------------------------------------------------------------------------- /0x0B-python-input_output/11-student.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a class Student.""" 3 | 4 | 5 | class Student: 6 | """Represent a student.""" 7 | 8 | def __init__(self, first_name, last_name, age): 9 | """Initialize a new Student. 10 | 11 | Args: 12 | first_name (str): The first name of the student. 13 | last_name (str): The last name of the student. 14 | age (int): The age of the student. 15 | """ 16 | self.first_name = first_name 17 | self.last_name = last_name 18 | self.age = age 19 | 20 | def to_json(self, attrs=None): 21 | """Get a dictionary representation of the Student. 22 | 23 | If attrs is a list of strings, represents only those attributes 24 | included in the list. 25 | 26 | Args: 27 | attrs (list): (Optional) The attributes to represent. 28 | """ 29 | if (type(attrs) == list and 30 | all(type(ele) == str for ele in attrs)): 31 | return {k: getattr(self, k) for k in attrs if hasattr(self, k)} 32 | return self.__dict__ 33 | 34 | def reload_from_json(self, json): 35 | """Replace all attributes of the Student. 36 | 37 | Args: 38 | json (dict): The key/value pairs to replace attributes with. 39 | """ 40 | for k, v in json.items(): 41 | setattr(self, k, v) 42 | -------------------------------------------------------------------------------- /0x0B-python-input_output/12-pascal_triangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a Pascal's Triangle function.""" 3 | 4 | 5 | def pascal_triangle(n): 6 | """Represent Pascal's Triangle of size n. 7 | 8 | Returns a list of lists of integers representing the triangle. 9 | """ 10 | if n <= 0: 11 | return [] 12 | 13 | triangles = [[1]] 14 | while len(triangles) != n: 15 | tri = triangles[-1] 16 | tmp = [1] 17 | for i in range(len(tri) - 1): 18 | tmp.append(tri[i] + tri[i + 1]) 19 | tmp.append(1) 20 | triangles.append(tmp) 21 | return triangles 22 | -------------------------------------------------------------------------------- /0x0B-python-input_output/2-append_write.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a file-appending function.""" 3 | 4 | 5 | def append_write(filename="", text=""): 6 | """Appends a string to the end of a UTF8 text file. 7 | 8 | Args: 9 | filename (str): The name of the file to append to. 10 | text (str): The string to append to the file. 11 | Returns: 12 | The number of characters appended. 13 | """ 14 | with open(filename, "a", encoding="utf-8") as f: 15 | return f.write(text) 16 | -------------------------------------------------------------------------------- /0x0B-python-input_output/3-to_json_string.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a string-to-JSON function.""" 3 | import json 4 | 5 | 6 | def to_json_string(my_obj): 7 | """Return the JSON representation of a string object.""" 8 | return json.dumps(my_obj) 9 | -------------------------------------------------------------------------------- /0x0B-python-input_output/4-from_json_string.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # 6-from_json_string.py 3 | """Defines a JSON-to-object function.""" 4 | import json 5 | 6 | 7 | def from_json_string(my_str): 8 | """Return the Python object representation of a JSON string.""" 9 | return json.loads(my_str) 10 | -------------------------------------------------------------------------------- /0x0B-python-input_output/5-save_to_json_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a JSON file-writing function.""" 3 | import json 4 | 5 | 6 | def save_to_json_file(my_obj, filename): 7 | """Write an object to a text file using JSON representation.""" 8 | with open(filename, "w") as f: 9 | json.dump(my_obj, f) 10 | -------------------------------------------------------------------------------- /0x0B-python-input_output/6-load_from_json_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a JSON file-reading function.""" 3 | import json 4 | 5 | 6 | def load_from_json_file(filename): 7 | """Create a Python object from a JSON file.""" 8 | with open(filename) as f: 9 | return json.load(f) 10 | -------------------------------------------------------------------------------- /0x0B-python-input_output/7-add_item.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Add all arguments to a Python list and save them to a file.""" 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | save_to_json_file = __import__('5-save_to_json_file').save_to_json_file 7 | load_from_json_file = \ 8 | __import__('6-load_from_json_file').load_from_json_file 9 | 10 | try: 11 | items = load_from_json_file("add_item.json") 12 | except FileNotFoundError: 13 | items = [] 14 | items.extend(sys.argv[1:]) 15 | save_to_json_file(items, "add_item.json") 16 | -------------------------------------------------------------------------------- /0x0B-python-input_output/8-class_to_json.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a Python class-to-JSON function.""" 3 | 4 | 5 | def class_to_json(obj): 6 | """Return the dictionary represntation of a simple data structure.""" 7 | return obj.__dict__ 8 | -------------------------------------------------------------------------------- /0x0B-python-input_output/9-student.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a class Student.""" 3 | 4 | 5 | class Student: 6 | """Represent a student.""" 7 | 8 | def __init__(self, first_name, last_name, age): 9 | """Initialize a new Student. 10 | 11 | Args: 12 | first_name (str): The first name of the student. 13 | last_name (str): The last name of the student. 14 | age (int): The age of the student. 15 | """ 16 | self.first_name = first_name 17 | self.last_name = last_name 18 | self.age = age 19 | 20 | def to_json(self): 21 | """Get a dictionary representation of the Student.""" 22 | return self.__dict__ 23 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/models/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lordwill1/alx-higher_level_programming/34ec76359456d05dff1b2ef82444f231b3a6b848/0x0C-python-almost_a_circle/models/__init__.py -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/models/__pycache__/__init__.cpython-34.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lordwill1/alx-higher_level_programming/34ec76359456d05dff1b2ef82444f231b3a6b848/0x0C-python-almost_a_circle/models/__pycache__/__init__.cpython-34.pyc -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/models/__pycache__/base.cpython-34.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lordwill1/alx-higher_level_programming/34ec76359456d05dff1b2ef82444f231b3a6b848/0x0C-python-almost_a_circle/models/__pycache__/base.cpython-34.pyc -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/tests/test_models/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lordwill1/alx-higher_level_programming/34ec76359456d05dff1b2ef82444f231b3a6b848/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/Lordwill1/alx-higher_level_programming/34ec76359456d05dff1b2ef82444f231b3a6b848/0x0C-python-almost_a_circle/tests/test_models/__pycache__/__init__.cpython-34.pyc -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/tests/test_models/__pycache__/test_base.cpython-34.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lordwill1/alx-higher_level_programming/34ec76359456d05dff1b2ef82444f231b3a6b848/0x0C-python-almost_a_circle/tests/test_models/__pycache__/test_base.cpython-34.pyc -------------------------------------------------------------------------------- /0x0D-SQL_introduction/0-list_databases.sql: -------------------------------------------------------------------------------- 1 | -- Lists all databases of my MySQL server. 2 | SHOW DATABASES; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/1-create_database_if_missing.sql: -------------------------------------------------------------------------------- 1 | -- Creates the database hbtn_0c_0 in my MySQL server. 2 | CREATE DATABASE IF NOT EXISTS `hbtn_0c_0`; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/10-top_score.sql: -------------------------------------------------------------------------------- 1 | -- Lists all records of the table second_table. 2 | -- Records are ordered by descending score. 3 | SELECT `score`, `name` 4 | FROM `second_table` 5 | ORDER BY `score` DESC; 6 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/100-move_to_utf8.sql: -------------------------------------------------------------------------------- 1 | -- Converts the entire database hbtn_0c_0 to UTF8. 2 | USE `hbtn_0c_0` 3 | ALTER TABLE `first_table` 4 | CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; 5 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/101-avg_temperatures.sql: -------------------------------------------------------------------------------- 1 | -- Displays the average temperature (in Fahrenheit) by city ordered by descending temperature. 2 | SELECT `city`, AVG(`value`) AS `avg_temp` 3 | FROM `temperatures` 4 | GROUP BY `city` 5 | ORDER BY `avg_temp` DESC; 6 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/102-top_city.sql: -------------------------------------------------------------------------------- 1 | -- Displays the 3 cities with the highest average temperatures between July and August. 2 | SELECT `city`, AVG(`value`) AS `avg_temp` 3 | FROM `temperatures` 4 | WHERE `month` = 7 OR `month` = 8 5 | GROUP BY `city` 6 | ORDER BY `avg_temp` DESC 7 | LIMIT 3; 8 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/103-max_state.sql: -------------------------------------------------------------------------------- 1 | -- Displays the max temperature of each state, ordered by state name. 2 | SELECT `state`, MAX(`value`) AS `max_temp` 3 | FROM `temperatures` 4 | GROUP BY `state` 5 | ORDER BY `state`; 6 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/11-best_score.sql: -------------------------------------------------------------------------------- 1 | -- Lists all records in the table second_table with a score >= 10 in my MySQL server. 2 | -- Records are ordered by descending score. 3 | SELECT `score`, `name` 4 | FROM `second_table` 5 | WHERE `score` >= 10 6 | ORDER BY `score` DESC; 7 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/12-no_cheating.sql: -------------------------------------------------------------------------------- 1 | -- Updates the score of Bob to 10 in the table second_table in my MySQL server. 2 | UPDATE `second_table` 3 | SET `score` = 10 4 | WHERE `name` = "Bob"; 5 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/13-change_class.sql: -------------------------------------------------------------------------------- 1 | -- Removes all records with a score <= 5 in the table second_table in my MySQL server. 2 | DELETE FROM `second_table` 3 | WHERE `score` <= 5; 4 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/14-average.sql: -------------------------------------------------------------------------------- 1 | -- Computes the average score of all records in the table second_table in my MySQL server. 2 | SELECT AVG(`score`) AS `average` 3 | FROM `second_table`; 4 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/15-groups.sql: -------------------------------------------------------------------------------- 1 | -- Lists the number of records with the same score in the table second_table in my MySQL server. 2 | -- Records are ordered by descending count. 3 | SELECT `score`, COUNT(*) AS `number` 4 | FROM `second_table` 5 | GROUP BY `score` 6 | ORDER BY `number` DESC; 7 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/16-no_link.sql: -------------------------------------------------------------------------------- 1 | -- Lists all records of the table second_table having a name value in my MySQL server. 2 | -- Records are ordered by descending score. 3 | SELECT `score`, `name` 4 | FROM `second_table` 5 | WHERE `name` != "" 6 | ORDER BY `score` DESC 7 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/2-remove_database.sql: -------------------------------------------------------------------------------- 1 | -- Deletes the database hbtn_0c_0 from my MySQL server. 2 | DROP DATABASE IF EXISTS `hbtn_0c_0`; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/3-list_tables.sql: -------------------------------------------------------------------------------- 1 | -- Lists all tables of a database on my MySQL server. 2 | SHOW TABLES; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/4-first_table.sql: -------------------------------------------------------------------------------- 1 | -- Creates a table called first_table with values id and name in my MySQL server. 2 | CREATE TABLE IF NOT EXISTS `first_table` (`id` INT, `name` VARCHAR(256)); 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/5-full_table.sql: -------------------------------------------------------------------------------- 1 | -- Prints the full description of the table first_table in my MySQL server. 2 | SHOW CREATE TABLE `first_table`; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/6-list_values.sql: -------------------------------------------------------------------------------- 1 | -- Lists all rows of the table first_table in my MySQL server. 2 | SELECT * FROM `first_table`; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/7-insert_value.sql: -------------------------------------------------------------------------------- 1 | -- Inserts a new row into the table first_table in my MySQL server. 2 | INSERT INTO `first_table` (`id`, `name`) VALUES (89, "Best School"); 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/8-count_89.sql: -------------------------------------------------------------------------------- 1 | -- Displays the number of records with id = 89 in the table first_table in my MySQL server. 2 | SELECT COUNT(*) 3 | FROM `first_table` 4 | WHERE `id` = 89; 5 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/9-full_creation.sql: -------------------------------------------------------------------------------- 1 | -- Creates and fills a table second_table with attributes id, name and score in my MySQL server with multiple rows. 2 | CREATE TABLE IF NOT EXISTS `second_table` (`id` INT, `name` VARCHAR(256), `score` INT); 3 | INSERT INTO `second_table` (`id`, `name`, `score`) VALUES (1, "John", 10); 4 | INSERT INTO `second_table` (`id`, `name`, `score`) VALUES (2, "Alex", 3); 5 | INSERT INTO `second_table` (`id`, `name`, `score`) VALUES (3, "Bob", 14); 6 | INSERT INTO `second_table` (`id`, `name`, `score`) VALUES (4, "George", 8); 7 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/0-privileges.sql: -------------------------------------------------------------------------------- 1 | -- Lists all privileges of the MySQL users user_0d_1 and user_0d_2 2 | SHOW GRANTS FOR 'user_0d_1'@'localhost'; 3 | SHOW GRANTS FOR 'user_0d_2'@'localhost'; 4 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/1-create_user.sql: -------------------------------------------------------------------------------- 1 | -- creates the MySQL server user user_0d_1 and grant all priviledges 2 | CREATE USER IF NOT EXISTS user_0d_1@localhost IDENTIFIED BY 'user_0d_1_pwd'; 3 | GRANT ALL PRIVILEGES ON * . * TO user_0d_1@localhost; 4 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/10-genre_id_by_show.sql: -------------------------------------------------------------------------------- 1 | -- lists all shows contained in hbtn_0d_tvshows that have at least one genre linked 2 | -- lists all rows of a database that have one column in common 3 | SELECT tv_shows.title, tv_show_genres.genre_id FROM tv_shows INNER JOIN tv_show_genres ON tv_shows.id = tv_show_genres.show_id ORDER BY tv_shows.title ASC, tv_show_genres.genre_id ASC; 4 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/100-not_my_genres.sql: -------------------------------------------------------------------------------- 1 | -- uses the hbtn_0d_tvshows database to list all genres not linked to the show Dexter 2 | -- uses a database to list all rows not linked to one row 3 | SELECT name 4 | FROM tv_genres 5 | WHERE name NOT IN 6 | (SELECT name 7 | FROM tv_genres 8 | LEFT JOIN tv_show_genres ON tv_genres.id = tv_show_genres.genre_id 9 | LEFT JOIN tv_shows ON tv_show_genres.show_id = tv_shows.id 10 | WHERE tv_shows.title = 'Dexter') 11 | GROUP BY name 12 | ORDER BY name ASC; 13 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/101-not_a_comedy.sql: -------------------------------------------------------------------------------- 1 | -- lists all shows without the genre Comedy in the database hbtn_0d_tvshows 2 | -- uses a database to list all rows not linked to one row 3 | SELECT title 4 | FROM tv_shows 5 | WHERE title NOT IN 6 | (SELECT title 7 | FROM tv_shows 8 | LEFT JOIN tv_show_genres ON tv_shows.id = tv_show_genres.show_id 9 | LEFT JOIN tv_genres ON tv_show_genres.genre_id = tv_genres.id 10 | WHERE tv_genres.name = 'Comedy') 11 | GROUP BY title 12 | ORDER BY title ASC; 13 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/102-rating_shows.sql: -------------------------------------------------------------------------------- 1 | -- lists all shows from hbtn_0d_tvshows_rate by their rating 2 | -- lists all rows of a table by the sum of a linked row 3 | SELECT title, SUM(tv_show_ratings.rate) 'rating' 4 | FROM tv_shows 5 | LEFT JOIN tv_show_ratings ON tv_show_ratings.show_id = tv_shows.id 6 | GROUP BY title 7 | ORDER BY rating DESC; 8 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/103-rating_genres.sql: -------------------------------------------------------------------------------- 1 | -- lists all genres in the database hbtn_0d_tvshows_rate by their rating 2 | -- lists all rows in a database linked to a row in another table 3 | SELECT name, SUM(tv_show_ratings.rate) 'rating' 4 | FROM tv_genres 5 | INNER JOIN tv_show_genres ON tv_genres.id = tv_show_genres.genre_id 6 | INNER JOIN tv_show_ratings ON tv_show_genres.show_id = tv_show_ratings.show_id 7 | GROUP BY name 8 | ORDER BY rating DESC; 9 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/11-genre_id_all_shows.sql: -------------------------------------------------------------------------------- 1 | -- lists all shows contained in the database hbtn_0d_tvshows 2 | -- lists all rows of tables in a database 3 | SELECT tv_shows.title, tv_show_genres.genre_id 4 | FROM tv_shows LEFT JOIN tv_show_genres 5 | ON tv_shows.id = tv_show_genres.show_id 6 | ORDER BY tv_shows.title ASC, tv_show_genres.genre_id ASC; 7 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/12-no_genre.sql: -------------------------------------------------------------------------------- 1 | -- lists all shows contained in hbtn_0d_tvshows without a genre linked 2 | -- lists all rows of a database that don't have one column 3 | SELECT tv_shows.title, tv_show_genres.genre_id 4 | FROM tv_shows LEFT JOIN tv_show_genres 5 | ON tv_shows.id = tv_show_genres.show_id 6 | WHERE tv_show_genres.genre_id IS NULL 7 | ORDER BY tv_shows.title ASC, tv_show_genres.genre_id ASC; 8 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/13-count_shows_by_genre.sql: -------------------------------------------------------------------------------- 1 | -- lists all genres from hbtn_0d_tvshows and displays the number of shows linked to each 2 | -- lists all rows of a database meeting a condition 3 | SELECT tv_genres.name AS 'genre', COUNT(tv_show_genres.genre_id) AS 'number_of_shows' 4 | FROM tv_genres RIGHT JOIN tv_show_genres 5 | ON tv_genres.id = tv_show_genres.genre_id 6 | GROUP BY genre 7 | ORDER BY number_of_shows DESC; 8 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/14-my_genres.sql: -------------------------------------------------------------------------------- 1 | -- uses the hbtn_0d_tvshows database to lists all genres of the show Dexter 2 | -- uses a databse to lists all rows in a table corresponding to all rows in another 3 | SELECT name 4 | FROM tv_genres 5 | LEFT JOIN tv_show_genres ON tv_genres.id = tv_show_genres.genre_id 6 | LEFT JOIN tv_shows ON tv_show_genres.show_id = tv_shows.id 7 | WHERE tv_shows.title = 'Dexter' 8 | GROUP BY name 9 | ORDER BY name ASC; 10 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/15-comedy_only.sql: -------------------------------------------------------------------------------- 1 | -- lists all Comedy shows in the database hbtn_0d_tvshows 2 | -- lists all rows of a database corresponding to a column value 3 | SELECT title 4 | FROM tv_shows 5 | LEFT JOIN tv_show_genres ON tv_shows.id = tv_show_genres.show_id 6 | LEFT JOIN tv_genres ON tv_show_genres.genre_id = tv_genres.id 7 | WHERE tv_genres.name = 'Comedy' 8 | GROUP BY title 9 | ORDER BY title ASC; 10 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/16-shows_by_genre.sql: -------------------------------------------------------------------------------- 1 | -- lists all shows, and all genres linked to that show, from the database hbtn_0d_tvshows 2 | -- lists all rows of a table linked to another table 3 | SELECT title, name 4 | FROM tv_shows 5 | LEFT JOIN tv_show_genres ON tv_shows.id = tv_show_genres.show_id 6 | LEFT JOIN tv_genres ON tv_show_genres.genre_id = tv_genres.id 7 | ORDER BY title ASC, name ASC; 8 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/2-create_read_user.sql: -------------------------------------------------------------------------------- 1 | -- creates the database hbtn_0d_2 and the user user_0d_2 2 | -- creates a database 3 | CREATE DATABASE IF NOT EXISTS hbtn_0d_2; 4 | -- creates a user 5 | CREATE USER IF NOT EXISTS user_0d_2@localhost IDENTIFIED BY 'user_0d_2_pwd'; 6 | -- grants SELECT privileges to a user 7 | GRANT SELECT ON hbtn_0d_2.* TO user_0d_2@localhost; 8 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/3-force_name.sql: -------------------------------------------------------------------------------- 1 | -- creates the table force_name on your MySQL server 2 | -- creates a table in a database 3 | CREATE TABLE IF NOT EXISTS force_name (id INT, name VARCHAR(256) NOT NULL); 4 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/4-never_empty.sql: -------------------------------------------------------------------------------- 1 | -- creates the table id_not_null on your MySQL server 2 | -- creates a table 3 | CREATE TABLE IF NOT EXISTS id_not_null (id INT DEFAULT 1, name VARCHAR(256)); 4 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/5-unique_id.sql: -------------------------------------------------------------------------------- 1 | -- creates the table unique_id on your MySQL server 2 | -- creates a table 3 | CREATE TABLE IF NOT EXISTS unique_id (id INT DEFAULT 1 UNIQUE, name VARCHAR(256)); 4 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/6-states.sql: -------------------------------------------------------------------------------- 1 | -- creates the database hbtn_0d_usa and the table states (in the database hbtn_0d_usa) on your MySQL server 2 | -- creates a database 3 | CREATE DATABASE IF NOT EXISTS hbtn_0d_usa; 4 | -- use a database 5 | USE hbtn_0d_usa; 6 | -- creates a table 7 | CREATE TABLE IF NOT EXISTS states (id INT UNIQUE NOT NULL AUTO_INCREMENT, name VARCHAR(256) NOT NULL, PRIMARY KEY(id)); 8 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/7-cities.sql: -------------------------------------------------------------------------------- 1 | -- creates the database hbtn_0d_usa and the table cities (in the database hbtn_0d_usa) on your MySQL server 2 | -- creates a database 3 | CREATE DATABASE IF NOT EXISTS hbtn_0d_usa; 4 | -- use a database 5 | USE hbtn_0d_usa; 6 | -- creates a table 7 | CREATE TABLE IF NOT EXISTS cities (id INT UNIQUE AUTO_INCREMENT NOT NULL, 8 | state_id INT NOT NULL, 9 | name VARCHAR(256) NOT NULL, 10 | PRIMARY KEY(id), 11 | FOREIGN KEY(state_id) REFERENCES states(id)); 12 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/8-cities_of_california_subquery.sql: -------------------------------------------------------------------------------- 1 | -- lists all the cities of California that can be found in the database hbtn_0d_usa 2 | -- lists all rows of a column in a database 3 | SELECT id, name FROM cities WHERE state_id = (SELECT id FROM states WHERE name = 'California') ORDER BY id ASC; 4 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/9-cities_by_state_join.sql: -------------------------------------------------------------------------------- 1 | -- lists all cities contained in the database hbtn_0d_usa 2 | -- lists all rows of a particular column in a database 3 | SELECT cities.id, cities.name, states.name FROM cities LEFT JOIN states ON states.id = cities.state_id ORDER BY cities.id; 4 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/README.md: -------------------------------------------------------------------------------- 1 | # MORE QUERIES. 2 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/0-select_states.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 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/model_city.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Contains the class definition of a City 4 | """ 5 | from model_state import Base 6 | from sqlalchemy import Column, Integer, String, ForeignKey 7 | from sqlalchemy.ext.declarative import declarative_base 8 | 9 | 10 | class City(Base): 11 | """ 12 | Class that defines each city 13 | """ 14 | __tablename__ = 'cities' 15 | id = Column(Integer, unique=True, nullable=False, primary_key=True) 16 | name = Column(String(128), nullable=False) 17 | state_id = Column(Integer, ForeignKey("states.id"), nullable=False) 18 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/model_state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Contains State class and Base, an instance of declarative_base() 4 | """ 5 | from sqlalchemy import Column, Integer, String, MetaData 6 | from sqlalchemy.ext.declarative import declarative_base 7 | 8 | mymetadata = MetaData() 9 | Base = declarative_base(metadata=mymetadata) 10 | 11 | 12 | class State(Base): 13 | """ 14 | Class with id and name attributes of each state 15 | """ 16 | __tablename__ = 'states' 17 | id = Column(Integer, unique=True, nullable=False, primary_key=True) 18 | name = Column(String(128), nullable=False) 19 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/relationship_city.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Contains the class definition of a City 4 | """ 5 | from relationship_state import Base 6 | from sqlalchemy import Column, Integer, String, ForeignKey 7 | from sqlalchemy.ext.declarative import declarative_base 8 | 9 | 10 | class City(Base): 11 | """ 12 | Class that defines each city 13 | """ 14 | __tablename__ = 'cities' 15 | id = Column(Integer, unique=True, nullable=False, primary_key=True) 16 | name = Column(String(128), nullable=False) 17 | state_id = Column(Integer, ForeignKey("states.id"), nullable=False) 18 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/relationship_state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Contains State class and Base, an instance of declarative_base() 4 | """ 5 | from sqlalchemy import Column, Integer, String, MetaData 6 | from sqlalchemy.ext.declarative import declarative_base 7 | from sqlalchemy.orm import relationship 8 | 9 | mymetadata = MetaData() 10 | Base = declarative_base(metadata=mymetadata) 11 | 12 | 13 | class State(Base): 14 | """ 15 | Class with id and name attributes of each state 16 | """ 17 | __tablename__ = 'states' 18 | id = Column(Integer, unique=True, nullable=False, primary_key=True) 19 | name = Column(String(128), nullable=False) 20 | cities = relationship("City", backref="states") 21 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/tests/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 | 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 | 11 | INSERT INTO states (name) VALUES ("California"), ("Arizona"), ("Texas"), ("New York"), ("Nevada"); 12 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/tests/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 | SELECT * FROM states; 5 | SELECT * FROM cities; 6 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/tests/101-relationship_states_cities_list.sql: -------------------------------------------------------------------------------- 1 | -- Create states table in hbtn_0e_101_usa with some data 2 | CREATE DATABASE IF NOT EXISTS hbtn_0e_101_usa; 3 | USE hbtn_0e_101_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 | 10 | INSERT INTO states (name) VALUES ("California"), ("Arizona"), ("Texas"), ("New York"), ("Nevada"); 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/tests/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 | 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 | 10 | INSERT INTO states (name) VALUES ("California"), ("Arizona"), ("Texas"), ("New York"), ("Nevada"); 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 | 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/tests/4-cities_by_state.sql: -------------------------------------------------------------------------------- 1 | -- Create states table in hbtn_0e_4_usa with some data 2 | 3 | CREATE DATABASE IF NOT EXISTS hbtn_0e_4_usa; 4 | USE hbtn_0e_4_usa; 5 | 6 | CREATE TABLE IF NOT EXISTS states ( 7 | id INT NOT NULL AUTO_INCREMENT, 8 | name VARCHAR(256) NOT NULL, 9 | PRIMARY KEY (id) 10 | ); 11 | 12 | INSERT INTO states (name) VALUES ("California"), ("Arizona"), ("Texas"), ("New York"), ("Nevada"); 13 | 14 | CREATE TABLE IF NOT EXISTS cities ( 15 | id INT NOT NULL AUTO_INCREMENT, 16 | state_id INT NOT NULL, 17 | name VARCHAR(256) NOT NULL, 18 | PRIMARY KEY (id), 19 | FOREIGN KEY(state_id) REFERENCES states(id) 20 | ); 21 | 22 | INSERT INTO cities (state_id, name) VALUES (1, "San Francisco"), (1, "San Jose"), (1, "Los Angeles"), (1, "Fremont"), (1, "Livermore"); 23 | INSERT INTO cities (state_id, name) VALUES (2, "Page"), (2, "Phoenix"); 24 | INSERT INTO cities (state_id, name) VALUES (3, "Dallas"), (3, "Houston"), (3, "Austin"); 25 | INSERT INTO cities (state_id, name) VALUES (4, "New York"); 26 | INSERT INTO cities (state_id, name) VALUES (5, "Las Vegas"), (5, "Reno"), (5, "Henderson"), (5, "Carson City"); 27 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/tests/6-model_state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Start link class to table in database 3 | """ 4 | 5 | import sys 6 | from model_state import Base, State 7 | from sqlalchemy import (create_engine) 8 | 9 | if __name__ == "__main__": 10 | engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}' 11 | .format(sys.argv[1], sys.argv[2], sys.argv[3]), 12 | pool_pre_ping=True) 13 | Base.metadata.create_all(engine) 14 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/tests/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/tests/7-model_state_fetch_all.sql: -------------------------------------------------------------------------------- 1 | -- Insert states 2 | INSERT INTO states (name) VALUES ("California"), ("Arizona"), ("Texas"), ("New York"), ("Nevada"); 3 | -------------------------------------------------------------------------------- /0x10-python-network_0/0-body_size.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Get the byte size of the HTTP response header for a given URL. 3 | curl -s "$1" | wc -c 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/1-body.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Get the response body for a given URL for 200 status code responses. 3 | curl -sL "$1" 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/100-status_code.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Sends a GET request to a given URL and display the response status code. 3 | curl -s -o /dev/null -w "%{http_code}" "$1" 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/101-post_json.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Sends a JSON POST request to a given URL with a given JSON file. 3 | curl -s -H "Content-Type: application/json" -d "$(cat "$2")" "$1" 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/102-catch_me.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Makes a request to 0.0.0.0:5000/catch_me that gets the message "You got me!". 3 | curl -sL -X PUT -H "Origin: HolbertonSchool" -d "user_id=98" 0.0.0.0:5000/catch_me 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/2-delete.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Send a DELETE request to a given URL and display the response body. 3 | curl -sX DELETE "$1" 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/3-methods.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Display all HTTP methods the server of a given URL will accept. 3 | curl -sI "$1" | grep "Allow" | cut -d " " -f 2- 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/4-header.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Send a GET request to a given URL with a header variable. 3 | curl -sH "X-HolbertonSchool-User-Id: 98" "${1}" 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/5-post_params.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Bash scripts that sends a POST request to a given URL. 3 | curl -s -X POST -d "email=test@gmail.com&subject=I will always be here for PLD" "$1" 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/6-peak.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Finds a peak in a list of unsorted integers""" 3 | 4 | 5 | def find_peak(list_of_integers): 6 | """Finds a peak in list_of_integers""" 7 | 8 | if list_of_integers is None or list_of_integers == []: 9 | return None 10 | lo = 0 11 | hi = len(list_of_integers) 12 | mid = ((hi - lo) // 2) + lo 13 | mid = int(mid) 14 | if hi == 1: 15 | return list_of_integers[0] 16 | if hi == 2: 17 | return max(list_of_integers) 18 | if list_of_integers[mid] >= list_of_integers[mid - 1] and\ 19 | list_of_integers[mid] >= list_of_integers[mid + 1]: 20 | return list_of_integers[mid] 21 | if mid > 0 and list_of_integers[mid] < list_of_integers[mid + 1]: 22 | return find_peak(list_of_integers[mid:]) 23 | if mid > 0 and list_of_integers[mid] < list_of_integers[mid - 1]: 24 | return find_peak(list_of_integers[:mid]) 25 | -------------------------------------------------------------------------------- /0x10-python-network_0/6-peak.txt: -------------------------------------------------------------------------------- 1 | O(log(n)) 2 | -------------------------------------------------------------------------------- /0x11-python-network_1/0-hbtn_status.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """A script that 3 | - fetches https://alx-intranet.hbtn.io/status. 4 | - uses urlib package 5 | """ 6 | 7 | 8 | if __name__ == '__main__': 9 | import urllib.request 10 | 11 | with urllib.request.urlopen('https://alx-intranet.hbtn.io/status') as res: 12 | content = res.read() 13 | print("Body response:") 14 | print("\t- type: {}".format(type(content))) 15 | print("\t- content: {}".format(content)) 16 | print("\t- utf8 content: {}".format(content.decode('utf-8'))) 17 | -------------------------------------------------------------------------------- /0x11-python-network_1/1-hbtn_header.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """A script that: 3 | - takes in a URL, 4 | - sends a request to the URL and displays the value 5 | - of the X-Request-Id variable found in the header ofthe response. 6 | """ 7 | import sys 8 | import urllib.request 9 | 10 | if __name__ == "__main__": 11 | url = sys.argv[1] 12 | 13 | request = urllib.request.Request(url) 14 | with urllib.request.urlopen(request) as response: 15 | print(dict(response.headers).get("X-Request-Id")) 16 | -------------------------------------------------------------------------------- /0x11-python-network_1/10-my_github.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """A script that: 3 | - takes your GitHub credentials (username and password) 4 | - uses the GitHub API to display your id 5 | """ 6 | import sys 7 | import requests 8 | from requests.auth import HTTPBasicAuth 9 | 10 | 11 | if __name__ == "__main__": 12 | auth = HTTPBasicAuth(sys.argv[1], sys.argv[2]) 13 | r = requests.get("https://api.github.com/user", auth=auth) 14 | print(r.json().get("id")) 15 | -------------------------------------------------------------------------------- /0x11-python-network_1/100-github_commits.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """lists the 10 most recent commits on a given GitHub repository. 3 | """ 4 | import sys 5 | import requests 6 | 7 | 8 | if __name__ == "__main__": 9 | url = "https://api.github.com/repos/{}/{}/commits".format( 10 | sys.argv[2], sys.argv[1]) 11 | 12 | r = requests.get(url) 13 | commits = r.json() 14 | try: 15 | for i in range(10): 16 | print("{}: {}".format( 17 | commits[i].get("sha"), 18 | commits[i].get("commit").get("author").get("name"))) 19 | except IndexError: 20 | pass 21 | -------------------------------------------------------------------------------- /0x11-python-network_1/2-post_email.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """A script that: 3 | - takes in a URL 4 | - sends a POST request to the passed URL 5 | - takes email as a parameter 6 | - displays the body of the response 7 | """ 8 | import sys 9 | import urllib.parse 10 | import urllib.request 11 | 12 | 13 | if __name__ == "__main__": 14 | url = sys.argv[1] 15 | value = {"email": sys.argv[2]} 16 | data = urllib.parse.urlencode(value).encode("ascii") 17 | 18 | request = urllib.request.Request(url, data) 19 | with urllib.request.urlopen(request) as response: 20 | print(response.read().decode("utf-8")) 21 | -------------------------------------------------------------------------------- /0x11-python-network_1/3-error_code.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """A script that: 3 | - takes in a URL, 4 | - sends a request to the URL 5 | - displays the body of the response (decoded in utf-8). 6 | """ 7 | 8 | 9 | if __name__ == "__main__": 10 | import sys 11 | from urllib import request, error 12 | 13 | try: 14 | with request.urlopen(sys.argv[1]) as res: 15 | print(res.read().decode('UTF-8')) 16 | except error.HTTPError as er: 17 | print('Error code:', er.code) 18 | -------------------------------------------------------------------------------- /0x11-python-network_1/4-hbtn_status.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """fetches https://intranet.hbtn.io/status.""" 3 | import requests 4 | 5 | 6 | if __name__ == "__main__": 7 | r = requests.get("https://intranet.hbtn.io/status") 8 | print("Body response:") 9 | print("\t- type: {}".format(type(r.text))) 10 | print("\t- content: {}".format(r.text)) 11 | -------------------------------------------------------------------------------- /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 | """A script that: 3 | - takes in a URL, 4 | - sends a request to the URL and displays the value 5 | - of the X-Request-Id variable found in the header ofthe response. 6 | """ 7 | import sys 8 | import urllib.request 9 | 10 | if __name__ == "__main__": 11 | url = sys.argv[1] 12 | 13 | request = urllib.request.Request(url) 14 | with urllib.request.urlopen(request) as response: 15 | print(dict(response.headers).get("X-Request-Id")) 16 | -------------------------------------------------------------------------------- /0x11-python-network_1/7-error_code.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """A script that 3 | - takes in a URL 4 | - sends a request to the URL 5 | - displays the body of the response. 6 | """ 7 | import sys 8 | import requests 9 | 10 | 11 | if __name__ == "__main__": 12 | url = sys.argv[1] 13 | 14 | r = requests.get(url) 15 | if r.status_code >= 400: 16 | print("Error code: {}".format(r.status_code)) 17 | else: 18 | print(r.text) 19 | -------------------------------------------------------------------------------- /0x11-python-network_1/8-json_api.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """A script tha: 3 | - takes in a letter 4 | - sends POST request to http://0.0.0.0:5000/search_user 5 | with the letter as a parameter. 6 | """ 7 | import sys 8 | import requests 9 | 10 | 11 | if __name__ == "__main__": 12 | letter = "" if len(sys.argv) == 1 else sys.argv[1] 13 | payload = {"q": letter} 14 | 15 | r = requests.post("http://0.0.0.0:5000/search_user", data=payload) 16 | try: 17 | response = r.json() 18 | if response == {}: 19 | print("No result") 20 | else: 21 | print("[{}] {}".format(response.get("id"), response.get("name"))) 22 | except ValueError: 23 | print("Not a valid JSON") 24 | -------------------------------------------------------------------------------- /0x11-python-network_1/README.md: -------------------------------------------------------------------------------- 1 | # 0x11-python-network_1 2 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/0-javascript_is_amazing.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const myVar = 'JavaScript is amazing'; 3 | console.log(myVar); 4 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/1-multi_languages.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | console.log('C is fun'); 3 | console.log('Python is cool'); 4 | console.log('JavaScript is amazing'); 5 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/10-factorial.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | function factorial (n) { 3 | 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 | if (process.argv.length === 2) { 3 | console.log('No argument'); 4 | } else if (process.argv.length === 3) { 5 | console.log('Argument found'); 6 | } else { 7 | console.log('Arguments found'); 8 | } 9 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/3-value_argument.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | if (process.argv[2] === undefined) { 3 | console.log('No argument'); 4 | } else { 5 | console.log(process.argv[2]); 6 | } 7 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/4-concat.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | console.log(process.argv[2] + ' is ' + process.argv[3]); 3 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/5-to_integer.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | if (isNaN(process.argv[2]) || process.argv[2] === undefined) { 3 | console.log('Not a number'); 4 | } else { 5 | console.log('My number:', parseInt(process.argv[2])); 6 | } 7 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/6-multi_languages_loop.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | for (const line of ['C is fun', 'Python is cool', 'JavaScript is amazing']) { 3 | console.log(line); 4 | } 5 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/7-multi_c.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 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 | # 0x12. Javascript - Warm up 2 | 3 | ## Description 4 | The aim of this project is to get started with Javascript, learn all the syntax and its different uses. 5 | 6 | ## Table of contents 7 | Files | Description 8 | ----- | ----------- 9 | [0-javascript_is_amazing.js](./0-javascript_is_amazing.js) | JS script that prints “Javascript is amazing” 10 | [1-multi_languages.js](./1-multi_languages.js) | JS script that prints 3 lines 11 | [2-arguments.js](./2-arguments.js) | JS script that prints a message depending of the number of arguments passed 12 | [3-value_argument.js](./3-value_argument.js) | JS script that prints the first argument passed to it 13 | [4-concat.js](./4-concat.js) | JS script that prints two arguments passed to it, in the following format: “ is ” 14 | [5-to_integer.js](./5-to_integer.js) | JS script that prints My number: if the first argument can be converted to an integer 15 | [6-multi_languages_loop.js](./6-multi_languages_loop.js) | JS script that prints 3 lines: (like 1-multi_languages.js) but by using an array of string and a loop 16 | [7-multi_c.js](./7-multi_c.js) | JS script that prints x times “C is fun” 17 | [8-square.js](./8-square.js) | JS script that prints a square 18 | [9-add.js](./9-add.js) | JS script that prints the addition of 2 integers 19 | [10-factorial.js](./10-factorial.js) | JS script that computes and prints a factorial 20 | [11-second_biggest.js](./11-second_biggest.js) | JS script that searches the second biggest integer in the list of arguments 21 | [12-object.js](./12-object.js) | JS script to replace the value 12 with 89 22 | [13-add.js](./13-add.js) | JS function that returns the addition of 2 integers 23 | [100-let_me_const.js](./100-let_me_const.js) | JS file that modifies the value of myVar (in another file) to 333 24 | [101-call_me_moby.js](./101-call_me_moby.js) | JS function that executes x times a function 25 | [102-add_me_maybe.js](./102-add_me_maybe.js) | JS function that increments and calls a function 26 | [103-object_fct.js](./103-object_fct.js) | JS script that adds a new function incr that increments the integer value of the object myObject 27 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/0-rectangle.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | class Rectangle { 3 | } 4 | 5 | module.exports = Rectangle; 6 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/1-rectangle.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | class Rectangle { 3 | constructor (w, h) { 4 | this.width = w; 5 | this.height = h; 6 | } 7 | } 8 | 9 | module.exports = Rectangle; 10 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/10-converter.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | exports.converter = function (base) { 4 | return function (num) { 5 | return num.toString(base); 6 | }; 7 | }; 8 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/100-map.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const list = require('./100-data.js').list; 3 | console.log(list); 4 | console.log(list.map((item, index) => item * index)); 5 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/101-sorted.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const dict = require('./101-data').dict; 3 | 4 | const totalist = Object.entries(dict); 5 | const vals = Object.values(dict); 6 | const valsUniq = [...new Set(vals)]; 7 | const newDict = {}; 8 | for (const j in valsUniq) { 9 | const list = []; 10 | for (const k in totalist) { 11 | if (totalist[k][1] === valsUniq[j]) { 12 | list.unshift(totalist[k][0]); 13 | } 14 | } 15 | newDict[valsUniq[j]] = list; 16 | } 17 | console.log(newDict); 18 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/102-concat.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const fs = require('fs'); 3 | 4 | const fArg = fs.readFileSync(process.argv[2]).toString(); 5 | const sArg = fs.readFileSync(process.argv[3]).toString(); 6 | fs.writeFileSync(process.argv[4], fArg + sArg); 7 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/2-rectangle.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | class Rectangle { 3 | constructor (w, h) { 4 | if ((w > 0) && (h > 0)) { 5 | this.width = w; 6 | this.height = h; 7 | } 8 | } 9 | } 10 | 11 | module.exports = Rectangle; 12 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/3-rectangle.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | class Rectangle { 3 | constructor (w, h) { 4 | if ((w > 0) && (h > 0)) { 5 | this.width = w; 6 | this.height = h; 7 | } 8 | } 9 | 10 | print () { 11 | for (let i = 0; i < this.height; i++) { 12 | let s = ''; 13 | for (let j = 0; j < this.width; j++) { 14 | s += 'X'; 15 | } 16 | console.log(s); 17 | } 18 | } 19 | } 20 | 21 | module.exports = Rectangle; 22 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/4-rectangle.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | class Rectangle { 3 | constructor (w, h) { 4 | if ((w > 0) && (h > 0)) { 5 | this.width = w; 6 | this.height = h; 7 | } 8 | } 9 | 10 | print () { 11 | for (let i = 0; i < this.height; i++) { 12 | let s = ''; 13 | for (let j = 0; j < this.width; j++) { 14 | s += 'X'; 15 | } 16 | console.log(s); 17 | } 18 | } 19 | 20 | rotate () { 21 | const aux = this.width; 22 | this.width = this.height; 23 | this.height = aux; 24 | } 25 | 26 | double () { 27 | this.width *= 2; 28 | this.height *= 2; 29 | } 30 | } 31 | 32 | module.exports = Rectangle; 33 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/5-square.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const Rectangle = require('./4-rectangle'); 3 | 4 | class Square extends Rectangle { 5 | constructor (size) { 6 | super(size, size); 7 | } 8 | } 9 | 10 | module.exports = Square; 11 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/6-square.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const SquareP = require('./5-square'); 3 | 4 | class Square extends SquareP { 5 | charPrint (c) { 6 | if (c === undefined) { 7 | c = 'X'; 8 | } 9 | for (let i = 0; i < this.height; i++) { 10 | let s = ''; 11 | for (let j = 0; j < this.width; j++) { 12 | s += c; 13 | } 14 | console.log(s); 15 | } 16 | } 17 | } 18 | 19 | module.exports = Square; 20 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/7-occurrences.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | exports.nbOccurences = function (list, searchElement) { 3 | let nOccurrences = 0; 4 | for (let i = 0; i < list.length; i++) { 5 | if (searchElement === list[i]) { 6 | nOccurrences++; 7 | } 8 | } 9 | return nOccurrences; 10 | }; 11 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/8-esrever.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | exports.esrever = function (list) { 3 | let len = list.length - 1; 4 | let i = 0; 5 | while ((len - i) > 0) { 6 | const aux = list[len]; 7 | list[len] = list[i]; 8 | list[i] = aux; 9 | i++; 10 | len--; 11 | } 12 | return list; 13 | }; 14 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/9-logme.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | let narg = 0; 3 | 4 | exports.logMe = function (item) { 5 | console.log(narg + ': ' + item); 6 | narg++; 7 | }; 8 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/0-readme.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const fs = require('fs'); 3 | fs.readFile(process.argv[2], 'utf8', function (error, content) { 4 | console.log(error || content); 5 | }); 6 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/1-writeme.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const fs = require('fs'); 3 | fs.writeFile(process.argv[2], process.argv[3], error => { 4 | if (error) console.log(error); 5 | }); 6 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/100-starwars_characters.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | const req = require('request'); 4 | const id = process.argv[2]; 5 | const url = 'https://swapi-api.hbtn.io/api/films/'; 6 | req.get(url + id, function (error, res, body) { 7 | if (error) { 8 | console.log(error); 9 | } 10 | const data = JSON.parse(body); 11 | const dd = data.characters; 12 | for (const i of dd) { 13 | req.get(i, function (error, res, body1) { 14 | if (error) { 15 | console.log(error); 16 | } 17 | const data1 = JSON.parse(body1); 18 | console.log(data1.name); 19 | }); 20 | } 21 | }); 22 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/101-starwars_characters.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const request = require('request'); 3 | const url = 'https://swapi-api.hbtn.io/api/films/' + process.argv[2]; 4 | request(url, function (error, response, body) { 5 | if (!error) { 6 | const characters = JSON.parse(body).characters; 7 | printCharacters(characters, 0); 8 | } 9 | }); 10 | 11 | function printCharacters (characters, index) { 12 | request(characters[index], function (error, response, body) { 13 | if (!error) { 14 | console.log(JSON.parse(body).name); 15 | if (index + 1 < characters.length) { 16 | printCharacters(characters, index + 1); 17 | } 18 | } 19 | }); 20 | } 21 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/102-search_twitter.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const base64 = require('base-64'); 3 | const request = require('request'); 4 | const utf8 = require('utf8'); 5 | 6 | let promise = new Promise(function (resolve, reject) { 7 | const token = utf8.decode(base64.encode(`${process.argv[2]}:${process.argv[3]}`)); 8 | const options = { 9 | url: 'https://api.twitter.com/oauth2/token', 10 | headers: { 11 | Authorization: `Basic ${token}`, 12 | 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' 13 | }, 14 | form: { 15 | grant_type: 'client_credentials' 16 | } 17 | }; 18 | request.post(options, function (error, response, body) { 19 | if (!error) { 20 | resolve(JSON.parse(body).access_token); 21 | } 22 | }); 23 | }); 24 | 25 | promise.then( 26 | result => search(result), 27 | error => console.log(error) 28 | ); 29 | 30 | function search (bearer) { 31 | const options = { 32 | url: 'https://api.twitter.com/1.1/search/tweets.json', 33 | headers: { 34 | Authorization: `Bearer ${bearer}` 35 | }, 36 | qs: { 37 | q: process.argv[4], 38 | count: '5' 39 | } 40 | }; 41 | request.get(options, function (error, response, body) { 42 | if (!error) { 43 | const tweets = JSON.parse(body).statuses; 44 | tweets.forEach((t) => console.log(`[${t.id}] ${t.text} by ${t.user.name}`)); 45 | } 46 | }); 47 | } 48 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/0-script.js: -------------------------------------------------------------------------------- 1 | document.querySelector('HEADER').style.color = '#FF0000'; 2 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/1-script.js: -------------------------------------------------------------------------------- 1 | $('HEADER').css('color', '#FF0000'); 2 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/100-script.js: -------------------------------------------------------------------------------- 1 | document.addEventListener('DOMContentLoaded', function () { 2 | document.querySelector('HEADER').style.color = '#FF0000'; 3 | }); 4 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/101-script.js: -------------------------------------------------------------------------------- 1 | $('document').ready(function () { 2 | $('DIV#add_item').click(function () { 3 | $('UL.my_list').append('
  • Item
  • '); 4 | }); 5 | $('DIV#remove_item').click(function () { 6 | $('UL.my_list li:last').remove(); 7 | }); 8 | $('DIV#clear_list').click(function () { 9 | $('UL.my_list').empty(); 10 | }); 11 | }); 12 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/102-script.js: -------------------------------------------------------------------------------- 1 | $('document').ready(function () { 2 | const url = 'https://www.fourtonfish.com/hellosalut/?'; 3 | $('INPUT#btn_translate').click(function () { 4 | $.get(url + $.param({ lang: $('INPUT#language_code').val() }), function (data) { 5 | $('DIV#hello').html(data.hello); 6 | }); 7 | }); 8 | }); 9 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/103-script.js: -------------------------------------------------------------------------------- 1 | $('document').ready(function () { 2 | $('INPUT#btn_translate').click(translate); 3 | $('INPUT#language_code').focus(function () { 4 | $(this).keydown(function (e) { 5 | if (e.keyCode === 13) { 6 | translate(); 7 | } 8 | }); 9 | }); 10 | }); 11 | 12 | function translate () { 13 | const url = 'https://www.fourtonfish.com/hellosalut/?'; 14 | $.get(url + $.param({ lang: $('INPUT#language_code').val() }), function (data) { 15 | $('DIV#hello').html(data.hello); 16 | }); 17 | } 18 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/2-script.js: -------------------------------------------------------------------------------- 1 | $('DIV#red_header').click(function () { 2 | $('HEADER').css('color', '#FF0000'); 3 | }); 4 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/3-script.js: -------------------------------------------------------------------------------- 1 | $('DIV#red_header').click(function () { 2 | $('HEADER').addClass('red'); 3 | }); 4 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/4-script.js: -------------------------------------------------------------------------------- 1 | $('DIV#toggle_header').click(function () { 2 | $('HEADER').toggleClass('green red'); 3 | }); 4 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/5-script.js: -------------------------------------------------------------------------------- 1 | $('DIV#add_item').click(function () { 2 | $('UL.my_list').append('
  • Item
  • '); 3 | }); 4 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/6-script.js: -------------------------------------------------------------------------------- 1 | $('DIV#update_header').click(function () { 2 | $('HEADER').text('New Header!!!'); 3 | }); 4 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/7-script.js: -------------------------------------------------------------------------------- 1 | $.get('https://swapi.co/api/people/5/?format=json', function (data) { 2 | $('DIV#character').text(data.name); 3 | }); 4 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/8-script.js: -------------------------------------------------------------------------------- 1 | $.get('https://swapi.co/api/films/?format=json', function (data) { 2 | $('UL#list_movies').append(...data.results.map(movie => `
  • ${movie.title}
  • `)); 3 | }); 4 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/9-script.js: -------------------------------------------------------------------------------- 1 | $('document').ready(function () { 2 | $.get('https://fourtonfish.com/hellosalut/?lang=fr', function (data) { 3 | $('DIV#hello').text(data.hello); 4 | }); 5 | }); 6 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/README.md: -------------------------------------------------------------------------------- 1 | # 0x15-javascript-web_jquery 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Higher Level Programming Projects 2 | This repo contains all the projects that I have done in the alx-Holberton curriculum on Higher level programming. 3 | 4 | 5 | ## What Does High-Level Language (HLL) Mean? 6 | A high-level language is any programming language that enables development of a program in a much more user-friendly programming context and is generally independent of the computer's hardware architecture. 7 | 8 | A high-level language has a higher level of abstraction from the computer, and focuses more on the programming logic rather than the underlying hardware components such as memory addressing and register utilization. 9 | 10 | | Projects | Description | 11 | | -------- | ----------- | 12 | | [0x00-python-hello_world](0x00-python-hello_world) | All about introduction to python. A bit about Technical interview prep | 13 | . 14 | --------------------------------------------------------------------------------