├── 0-run ├── 0x00-python-hello_world ├── 0-run ├── 1-run_inline ├── 10-check_cycle.c ├── 100-write.py ├── 101-compile ├── 102-magic_calculation.py ├── 2-print.py ├── 3-print_number.py ├── 4-print_float.py ├── 5-print_string.py ├── 6-concat.py ├── 7-edges.py ├── 8-concat_edges.py ├── 9-easter_egg.py ├── README.md └── lists.h ├── 0x01-python-if_else_loops_functions ├── 0-positive_or_negative.py ├── 1-last_digit.py ├── 10-add.py ├── 100-print_tebahpla.py ├── 101-remove_char_at.py ├── 102-magic_calculation.py ├── 11-pow.py ├── 12-fizzbuzz.py ├── 13-insert_number.c ├── 2-print_alphabet.py ├── 3-print_alphabt.py ├── 4-print_hexa.py ├── 5-print_comb2.py ├── 6-print_comb3.py ├── 7-islower.py ├── 8-uppercase.py ├── 9-print_last_digit.py ├── README.md └── lists.h ├── 0x02-python-import_modules ├── 0-add.py ├── 0-import_add.py ├── 1-calculation.py ├── 100-my_calculator.py ├── 101-easy_print.py ├── 102-magic_calculation.py ├── 103-fast_alphabet.py ├── 2-args.py ├── 3-infinite_add.py ├── 4-hidden_discovery.py ├── 5-variable_load.py └── README.md ├── 0x03-python-data_structures ├── 0-print_list_integer.py ├── 1-element_at.py ├── 10-divisible_by_2.py ├── 100-print_python_list_info.c ├── 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 └── switch.py ├── 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-main.py ├── 11-multiply_list_map.py ├── 12-roman_to_int.py ├── 2-uniq_add.py ├── 3-common_elements.py ├── 4-only_diff_elements.py ├── 5-number_keys.py ├── 6-print_sorted_dictionary.py ├── 7-update_dictionary.py ├── 8-simple_delete.py ├── 9-multiply_by_2.py └── README.md ├── 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 └── REAME.md ├── 0x07-python-test_driven_development ├── 0-add_integer.py ├── 100-matrix_mul.py ├── 101-lazy_matrix_mul.py ├── 102-python.c ├── 2-matrix_divided.py ├── 3-say_my_name.py ├── 4-print_square.py ├── 5-text_indentation.py ├── README.md └── tests │ ├── 0-add_integer.txt │ ├── 100-matrix_mul.txt │ ├── 101-lazy_matrix_mul.txt │ ├── 2-matrix_divided.txt │ ├── 3-say_my_name.txt │ ├── 4-print_square.txt │ ├── 5-text_indentation.txt │ └── 6-max_integer_test.py ├── 0x08-python-more_classes ├── .swp ├── 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 ├── 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 └── vi ├── 0x0A-python-inheritance ├── 0-lookup.py ├── 1-my_list.py ├── 10-square.py ├── 100-my_int.py ├── 101-add_attribute.py ├── 11-square.py ├── 2-is_same_class.py ├── 3-is_kind_of_class.py ├── 4-inherits_from.py ├── 5-base_geometry.py ├── 6-base_geometry.py ├── 7-base_geometry.py ├── 8-rectangle.py ├── 9-rectangle.py ├── README.md └── tests │ ├── 1-my_list.txt │ └── 7-base_geometry.txt ├── 0x0B-python-input_output ├── 0-read_file.py ├── 1-write_file.py ├── 10-student.py ├── 100-append_after.py ├── 101-generator.py ├── 101-stats.py ├── 11-student.py ├── 12-pascal_triangle.py ├── 2-append_write.py ├── 3-to_json_string.py ├── 4-from_json_string.py ├── 5-save_to_json_file.py ├── 6-load_from_json_file.py ├── 7-add_item.py ├── 8-class_to_json.py ├── 9-student.py └── README.md ├── 0x0C-python-almost_a_circle ├── README.md ├── models │ ├── __init__.py │ ├── base.py │ ├── rectangle.py │ └── square.py └── tests │ ├── __init__.py │ ├── test_base.py │ ├── test_rectangle.py │ └── test_square.py ├── 0x0D-SQL_introduction ├── 0-list_databases.sql ├── 1-create_database_if_missing.sql ├── 10-top_score.sql ├── 100-move_to_utf8.sql ├── 101-avg_temperatures.sql ├── 102-top_city.sql ├── 103-max_state.sql ├── 11-best_score.sql ├── 12-no_cheating.sql ├── 13-change_class.sql ├── 14-average.sql ├── 15-groups.sql ├── 16-no_link.sql ├── 2-remove_database.sql ├── 3-list_tables.sql ├── 4-first_table.sql ├── 5-full_table.sql ├── 6-list_values.sql ├── 7-insert_value.sql ├── 8-count_89.sql ├── 9-full_creation.sql └── README.md ├── 0x0E-SQL_more_queries ├── .101-not_a_comedy.sql.swp ├── .hbtn_0d_tvshows_rate.sql.swp ├── 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 ├── hbtn_0d_tvshows.sql └── hbtn_0d_tvshows_rate.sql ├── 0x0F-python-object_relational_mapping ├── .1-filter_states.py.swp ├── 0-select_states.py ├── 1-filter_states.py ├── 10-model_state_my_get.py ├── 100-relationship_states_cities.py ├── 101-relationship_states_cities_list.py ├── 102-relationship_cities_states_list.py ├── 11-model_state_insert.py ├── 12-model_state_update_id_2.py ├── 13-model_state_delete_a.py ├── 14-model_city_fetch_by_state.py ├── 2-my_filter_states.py ├── 3-my_safe_filter_states.py ├── 4-cities_by_state.py ├── 5-filter_cities.py ├── 7-model_state_fetch_all.py ├── 8-model_state_fetch_first.py ├── 9-model_state_filter_a.py ├── README.md ├── model_city.py ├── model_state.py ├── relationship_city.py └── relationship_state.py ├── 0x10-python-network_0 ├── 0-body_size.sh ├── 1-body.sh ├── 100-status_code.sh ├── 101-post_json.sh ├── 102-catch_me.sh ├── 2-delete.sh ├── 3-methods.sh ├── 4-header.sh ├── 5-post_params.sh ├── 6-peak.py ├── 6-peak.txt └── README.md ├── 0x11-python-network_1 ├── 0-hbtn_status.py ├── 1-hbtn_header.py ├── 10-my_github.py ├── 100-github_commits.py ├── 2-post_email.py ├── 3-error_code.py ├── 4-hbtn_status.py ├── 5-hbtn_header.py ├── 6-post_email.py ├── 7-error_code.py ├── 8-json_api.py └── README.md ├── 0x12-javascript-warm_up ├── 0-javascript_is_amazing.js ├── 1-multi_languages.js ├── 10-factorial.js ├── 100-let_me_const.js ├── 101-call_me_moby.js ├── 102-add_me_maybe.js ├── 103-object_fct.js ├── 11-second_biggest.js ├── 12-object.js ├── 13-add.js ├── 2-arguments.js ├── 3-value_argument.js ├── 4-concat.js ├── 5-to_integer.js ├── 6-multi_languages_loop.js ├── 7-multi_c.js ├── 8-square.js ├── 9-add.js └── README.md ├── 0x13-javascript_objects_scopes_closures ├── 0-rectangle.js ├── 1-rectangle.js ├── 10-converter.js ├── 100-map.js ├── 101-sorted.js ├── 102-concat.js ├── 2-rectangle.js ├── 3-rectangle.js ├── 4-rectangle.js ├── 5-square.js ├── 6-square.js ├── 7-occurrences.js ├── 8-esrever.js ├── 9-logme.js └── README.md ├── 0x14-javascript-web_scraping ├── 0-readme.js ├── 1-writeme.js ├── 100-starwars_characters.js ├── 101-starwars_characters.js ├── 2-statuscode.js ├── 3-starwars_title.js ├── 4-starwars_count.js ├── 5-request_store.js ├── 6-completed_tasks.js └── README.md ├── 0x15-javascript-web_jquery ├── 0-script.js ├── 1-script.js ├── 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 ├── 0x1C-makefiles ├── 0-Makefile ├── 1-Makefile ├── 100-Makefile ├── 2-Makefile ├── 3-Makefile ├── 4-Makefile ├── README.md ├── m.h ├── main.c └── school.c ├── 1-run_inline └── README.md /0-run: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | python3 $PYFILE 3 | -------------------------------------------------------------------------------- /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 - checks if a singly linked list has 5 | * a cycle in it 6 | * @list: pointer to the list 7 | * Return: 0 if there is no cycle, 8 | * 1 if there is a cycle 9 | */ 10 | int check_cycle(listint_t *list) 11 | { 12 | listint_t *p2; 13 | listint_t *prev; 14 | 15 | p2 = list; 16 | prev = list; 17 | while (list && p2 && p2->next) 18 | { 19 | list = list->next; 20 | p2 = p2->next->next; 21 | 22 | if (list == p2) 23 | { 24 | list = prev; 25 | prev = p2; 26 | while (1) 27 | { 28 | p2 = prev; 29 | while (p2->next != list && p2->next != prev) 30 | { 31 | p2 = p2->next; 32 | } 33 | if (p2->next == list) 34 | break; 35 | 36 | list = list->next; 37 | } 38 | return (1); 39 | } 40 | } 41 | 42 | return (0); 43 | } 44 | -------------------------------------------------------------------------------- /0x00-python-hello_world/100-write.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import sys 3 | sys.stderr.write("and that piece of art is useful - Dora Korpar, 2015-10-19\n") 4 | sys.exit(1) 5 | -------------------------------------------------------------------------------- /0x00-python-hello_world/101-compile: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | python3 -m compileall -b "$PYFILE" 3 | -------------------------------------------------------------------------------- /0x00-python-hello_world/102-magic_calculation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | # comments 4 | 5 | def magic_calculation(a, b): 6 | return (98 + a ** b) 7 | -------------------------------------------------------------------------------- /0x00-python-hello_world/2-print.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | # print hello world 4 | 5 | print("\"Programming is like building a multilingual puzzle") 6 | -------------------------------------------------------------------------------- /0x00-python-hello_world/3-print_number.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | # print number 4 | 5 | number = 98 6 | print(f"{number:d} Battery street") 7 | -------------------------------------------------------------------------------- /0x00-python-hello_world/4-print_float.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | # comments 4 | 5 | number = 3.14159 6 | print(f"Float: {number:.2f}") 7 | -------------------------------------------------------------------------------- /0x00-python-hello_world/5-print_string.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # comments 3 | str = "Holberton School" 4 | print(str*3) 5 | print(str[0:9]) 6 | -------------------------------------------------------------------------------- /0x00-python-hello_world/6-concat.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | str1 = "Holberton" 3 | str2 = "School" 4 | two = str1 + " " + str2 5 | print(f"Welcome to {two}!") 6 | -------------------------------------------------------------------------------- /0x00-python-hello_world/7-edges.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | word = "Holberton" 3 | word_first_3 = word[0:3] 4 | word_last_2 = word[-2:] 5 | middle_word = word[1:-1] 6 | print(f"First 3 letters: {word_first_3}") 7 | print(f"Last 2 letters: {word_last_2}") 8 | print(f"Middle word: {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 | 3 | # comments 4 | 5 | import this 6 | -------------------------------------------------------------------------------- /0x00-python-hello_world/README.md: -------------------------------------------------------------------------------- 1 | # Hello World 2 | * 0-run-inline -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | print(f"{number}", end=" ") 5 | if number > 0: 6 | print("is positive") 7 | elif number < 0: 8 | print("is negative") 9 | else: 10 | print("is zero") 11 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/1-last_digit.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import random 3 | number = random.randint(-10000, 10000) 4 | if number < 0 and str(number)[-1] != "0": 5 | sign = "-" 6 | else: 7 | sign = "" 8 | number = f"{number}" 9 | print(f"Last digit of {number} is {sign}{number[-1]}", end=" ") 10 | if int(sign+number[-1]) > 5: 11 | print("and is greater than 5") 12 | elif int(sign+number[-1]) < 6 and int(number[-1]) != 0: 13 | print("and is less than 6 and not 0") 14 | else: 15 | print("and is 0") 16 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/10-add.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def add(a, b): return a + b 3 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/100-print_tebahpla.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for ch in reversed(range(97, 123)): 3 | print("{:c}".format(ch if (ch % 2 == 0) else (ch - 32)), end='') 4 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/101-remove_char_at.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def remove_char_at(str, n): 3 | i = 0 4 | new_str = "" 5 | for ch in str: 6 | if i != n: 7 | new_str += ch 8 | i += 1 9 | return new_str 10 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/102-magic_calculation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def magic_calculation(a, b, c): 3 | if a < b: 4 | return c 5 | else: 6 | if c > b: 7 | return a + b 8 | return (a * b) - c 9 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/11-pow.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def pow(a, b): return a ** b 3 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/12-fizzbuzz.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def fizzbuzz(): 3 | for num in range(1, 101): 4 | if num % 3 == 0 and num % 5 == 0: 5 | print("FizzBuzz ", end="") 6 | elif num % 5 == 0: 7 | print("Buzz ", end="") 8 | elif num % 3 == 0: 9 | print("Fizz ", end="") 10 | else: 11 | print(f"{num} ", end="") 12 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/13-insert_number.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "lists.h" 3 | 4 | /** 5 | * insert_node - Inserts a number into a sorted singly linked list. 6 | * 7 | * @head: Double pointer to a singly linked list 8 | * 9 | * @number: Value of the new node. 10 | * 11 | * Return: The address of the new node, or NULL if it failed. 12 | */ 13 | 14 | listint_t *insert_node(listint_t **head, int number) 15 | { 16 | int flag = 0; 17 | listint_t *new_node = NULL, *actual = NULL, *after = NULL; 18 | 19 | if (head == NULL) 20 | return (NULL); 21 | new_node = malloc(sizeof(listint_t)); 22 | if (!new_node) 23 | return (NULL); 24 | new_node->n = number, new_node->next = NULL; 25 | if (*head == NULL) 26 | { 27 | *head = new_node; 28 | return (*head); 29 | } 30 | actual = *head; 31 | if (number <= actual->n) 32 | { 33 | new_node->next = actual, *head = new_node; 34 | return (*head); 35 | } 36 | if (number > actual->n && !actual->next) 37 | { 38 | actual->next = new_node; 39 | return (new_node); 40 | } 41 | after = actual->next; 42 | while (actual) 43 | { 44 | if (!after) 45 | actual->next = new_node, flag = 1; 46 | else if (after->n == number) 47 | actual->next = new_node, new_node->next = after, flag = 1; 48 | else if (after->n > number && actual->n < number) 49 | actual->next = new_node, new_node->next = after, flag = 1; 50 | if (flag) 51 | break; 52 | after = after->next, actual = actual->next; 53 | } 54 | return (new_node); 55 | } 56 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/2-print_alphabet.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for i in range(97, 123): 3 | print(f"{chr(i)}".format(), end="") 4 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/3-print_alphabt.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for i in range(97, 123): 3 | if chr(i) == "q" or chr(i) == "e": 4 | continue 5 | print(f"{chr(i)}".format(), end="") 6 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/4-print_hexa.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for i in range(99): 3 | print(f"{i} = {hex(i)}".format()) 4 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/5-print_comb2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for number in range(100): 3 | if (number != 99): 4 | print("{}{}, ".format(int(number / 10), number % 10), end="") 5 | else: 6 | print("{}{}".format(int(number / 10), number % 10)) 7 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/6-print_comb3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for number in range(100): 3 | if int(number / 10) != number % 10 and int(number / 10) < number % 10: 4 | print("{}{}".format(int(number / 10), number % 10), end="") 5 | if (number != 89): 6 | print(", ", end="") 7 | print("") 8 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/7-islower.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def islower(c): 3 | ascii_num = ord(c) 4 | if ascii_num >= 97 and ascii_num <= 122: 5 | return True 6 | return False 7 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/8-uppercase.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def uppercase(str): 3 | for i in range(len(str)): 4 | if ord(str[i]) >= 97 and ord(str[i]) <= 122: 5 | num = 32 6 | else: 7 | num = 0 8 | print("{:c}".format(ord(str[i]) - num), end='') 9 | print() 10 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/9-print_last_digit.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def print_last_digit(number): 3 | last_digit = number % 10 if number >= 0 else -number % 10 4 | print(f"{last_digit}", end="") 5 | return last_digit 6 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/README.md: -------------------------------------------------------------------------------- 1 | # If Else While -------------------------------------------------------------------------------- /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 | */ 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_end(listint_t **head, const int n); 22 | void free_listint(listint_t *head); 23 | 24 | listint_t *insert_node(listint_t **head, int number); 25 | 26 | #endif /* LISTS_H */ 27 | -------------------------------------------------------------------------------- /0x02-python-import_modules/0-add.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | if __name__ == "__main__": 4 | from add_0 import add 5 | a = 1 6 | b = 2 7 | print("{} + {} = {}".format(a, b, add(a, b))) 8 | -------------------------------------------------------------------------------- /0x02-python-import_modules/0-import_add.py: -------------------------------------------------------------------------------- 1 | __import__("0-add") 2 | -------------------------------------------------------------------------------- /0x02-python-import_modules/1-calculation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | if __name__ == "__main__": 4 | from calculator_1 import add, sub, mul, div 5 | a = 10 6 | b = 5 7 | print("{} + {} = {}".format(a, b, add(a, b))) 8 | print("{} - {} = {}".format(a, b, sub(a, b))) 9 | print("{} * {} = {}".format(a, b, mul(a, b))) 10 | print("{} / {} = {}".format(a, b, div(a, b))) 11 | -------------------------------------------------------------------------------- /0x02-python-import_modules/100-my_calculator.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | from sys import argv 3 | from calculator_1 import add, sub, mul, div 4 | 5 | if (__name__ == "__main__"): 6 | argc = len(argv) 7 | result = 0 8 | operators = ["+", "-", "*", "/"] 9 | 10 | if (argc != 4): 11 | print(f"Usage: {argv[0]} ") 12 | exit(1) 13 | 14 | if (argv[2] not in operators): 15 | print("Unknown operator. Available operators: +, -, * and /") 16 | exit(1) 17 | 18 | num1 = int(argv[1]) 19 | operator = argv[2] 20 | num2 = int(argv[3]) 21 | 22 | if (operator == "+"): 23 | result = add(num1, num2) 24 | elif (operator == "-"): 25 | result = sub(num1, num2) 26 | elif (operator == "*"): 27 | result = mul(num1, num2) 28 | else: 29 | result = div(num1, num2) 30 | print(f"{num1} {operator} {num2} = {result}") 31 | -------------------------------------------------------------------------------- /0x02-python-import_modules/101-easy_print.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | __import__("sys").stdout.write("#pythoniscool\n") 3 | -------------------------------------------------------------------------------- /0x02-python-import_modules/102-magic_calculation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def magic_calculation(a, b): 3 | from magic_calculation_102 import add, sub 4 | if (a < b): 5 | c = add(a, b) 6 | for i in range(4, 6): 7 | c = add(c, i) 8 | return (c) 9 | else: 10 | return (sub(a, b)) 11 | -------------------------------------------------------------------------------- /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 | from sys import argv 5 | i = 1 6 | args = len(argv) - 1 7 | 8 | print(f"{args} {'argument' if args == 1 else 'arguments'}", end="") 9 | print(f"{'.' if args == 0 else ':'}") 10 | while (i <= args): 11 | print(f"{i}: {argv[i]}") 12 | i += 1 13 | -------------------------------------------------------------------------------- /0x02-python-import_modules/3-infinite_add.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | from sys import argv 3 | 4 | if __name__ == "__main__": 5 | i = 1 6 | result = 0 7 | arguments = len(argv) - 1 8 | 9 | if (arguments != 0): 10 | while (i <= arguments): 11 | result += int(argv[i]) 12 | i += 1 13 | print(result) 14 | -------------------------------------------------------------------------------- /0x02-python-import_modules/4-hidden_discovery.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import hidden_4 3 | 4 | if __name__ == "__main__": 5 | for function in dir(hidden_4): 6 | if (function[0] != "_"): 7 | print(function) 8 | -------------------------------------------------------------------------------- /0x02-python-import_modules/5-variable_load.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | from variable_load_5 import a 3 | 4 | if __name__ == "__main__": 5 | print(a) 6 | -------------------------------------------------------------------------------- /0x02-python-import_modules/README.md: -------------------------------------------------------------------------------- 1 | # Importing Modules -------------------------------------------------------------------------------- /0x03-python-data_structures/0-print_list_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def print_list_integer(my_list=[]): 4 | for i in my_list: 5 | print("{:d}".format(i)) 6 | -------------------------------------------------------------------------------- /0x03-python-data_structures/1-element_at.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def element_at(my_list, idx): 4 | if idx > len(my_list)-1 or idx < 0: 5 | return None 6 | else: 7 | return my_list[idx] 8 | -------------------------------------------------------------------------------- /0x03-python-data_structures/10-divisible_by_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def divisible_by_2(my_list=[]): 3 | check_div = [] 4 | 5 | for i in range(len(my_list)): 6 | if my_list[i] % 2 == 0: 7 | check_div.append(True) 8 | else: 9 | check_div.append(False) 10 | 11 | return (check_div) 12 | -------------------------------------------------------------------------------- /0x03-python-data_structures/100-print_python_list_info.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /** 5 | * print_python_list_info - prints python list info 6 | * 7 | * @p: PyObject 8 | * Return: no return 9 | */ 10 | void print_python_list_info(PyObject *p) 11 | { 12 | long int size, i; 13 | PyListObject *list; 14 | PyObject *item; 15 | 16 | size = Py_SIZE(p); 17 | printf("[*] Size of the Python List = %ld\n", size); 18 | 19 | list = (PyListObject *)p; 20 | printf("[*] Allocated = %ld\n", list->allocated); 21 | 22 | for (i = 0; i < size; i++) 23 | { 24 | item = PyList_GetItem(p, i); 25 | printf("Element %ld: %s\n", i, Py_TYPE(item)->tp_name); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /0x03-python-data_structures/11-delete_at.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def delete_at(my_list=[], idx=0): 3 | length = len(my_list) 4 | 5 | if idx < 0 or idx >= length: 6 | return (my_list) 7 | 8 | del my_list[idx] 9 | 10 | return (my_list) 11 | -------------------------------------------------------------------------------- /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 - reverses the second half of the list 5 | * 6 | * @h_r: head of the second half 7 | * Return: no return 8 | */ 9 | void reverse(listint_t **h_r) 10 | { 11 | listint_t *prv; 12 | listint_t *crr; 13 | listint_t *nxt; 14 | 15 | prv = NULL; 16 | crr = *h_r; 17 | 18 | while (crr != NULL) 19 | { 20 | nxt = crr->next; 21 | crr->next = prv; 22 | prv = crr; 23 | crr = nxt; 24 | } 25 | 26 | *h_r = prv; 27 | } 28 | 29 | /** 30 | * compare - compares each int of the list 31 | * 32 | * @h1: head of the first half 33 | * @h2: head of the second half 34 | * Return: 1 if are equals, 0 if not 35 | */ 36 | int compare(listint_t *h1, listint_t *h2) 37 | { 38 | listint_t *tmp1; 39 | listint_t *tmp2; 40 | 41 | tmp1 = h1; 42 | tmp2 = h2; 43 | 44 | while (tmp1 != NULL && tmp2 != NULL) 45 | { 46 | if (tmp1->n == tmp2->n) 47 | { 48 | tmp1 = tmp1->next; 49 | tmp2 = tmp2->next; 50 | } 51 | else 52 | { 53 | return (0); 54 | } 55 | } 56 | 57 | if (tmp1 == NULL && tmp2 == NULL) 58 | { 59 | return (1); 60 | } 61 | 62 | return (0); 63 | } 64 | 65 | /** 66 | * is_palindrome - checks if a singly linked list 67 | * is a palindrome 68 | * @head: pointer to head of list 69 | * Return: 0 if it is not a palindrome, 70 | * 1 if it is a palndrome 71 | */ 72 | int is_palindrome(listint_t **head) 73 | { 74 | listint_t *slow, *fast, *prev_slow; 75 | listint_t *scn_half, *middle; 76 | int isp; 77 | 78 | slow = fast = prev_slow = *head; 79 | middle = NULL; 80 | isp = 1; 81 | 82 | if (*head != NULL && (*head)->next != NULL) 83 | { 84 | while (fast != NULL && fast->next != NULL) 85 | { 86 | fast = fast->next->next; 87 | prev_slow = slow; 88 | slow = slow->next; 89 | } 90 | 91 | if (fast != NULL) 92 | { 93 | middle = slow; 94 | slow = slow->next; 95 | } 96 | 97 | scn_half = slow; 98 | prev_slow->next = NULL; 99 | reverse(&scn_half); 100 | isp = compare(*head, scn_half); 101 | 102 | if (middle != NULL) 103 | { 104 | prev_slow->next = middle; 105 | middle->next = scn_half; 106 | } 107 | else 108 | { 109 | prev_slow->next = scn_half; 110 | } 111 | } 112 | 113 | return (isp); 114 | } 115 | -------------------------------------------------------------------------------- /0x03-python-data_structures/2-replace_in_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def replace_in_list(my_list, idx, element): 4 | if idx > len(my_list)-1 or idx < 0: 5 | pass 6 | else: 7 | my_list[idx] = element 8 | return my_list 9 | -------------------------------------------------------------------------------- /0x03-python-data_structures/3-print_reversed_list_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def print_reversed_list_integer(my_list=[]): 3 | if not my_list: 4 | pass 5 | else: 6 | my_list.reverse() 7 | for i in range(len(my_list)): 8 | print("{:d}".format(my_list[i])) 9 | -------------------------------------------------------------------------------- /0x03-python-data_structures/4-new_in_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def new_in_list(my_list, idx, element): 3 | 4 | new_list = my_list[:] 5 | 6 | if 0 <= idx < len(my_list): 7 | new_list[idx] = element 8 | return new_list 9 | -------------------------------------------------------------------------------- /0x03-python-data_structures/5-no_c.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def no_c(my_string): 4 | 5 | new_string = "" 6 | 7 | for i in my_string: 8 | if i == 'c' or i == "C": 9 | pass 10 | else: 11 | new_string += i 12 | return new_string 13 | -------------------------------------------------------------------------------- /0x03-python-data_structures/6-print_matrix_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def print_matrix_integer(matrix=[[]]): 3 | for i in range(len(matrix)): 4 | for j in range(len(matrix[i])): 5 | if j != 0: 6 | print(" ", end='') 7 | print("{:d}".format(matrix[i][j]), end='') 8 | print() 9 | -------------------------------------------------------------------------------- /0x03-python-data_structures/7-add_tuple.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def add_tuple(tuple_a=(), tuple_b=()): 3 | len_a = len(tuple_a) 4 | len_b = len(tuple_b) 5 | 6 | if len_a == 0: 7 | a1 = 0 8 | a2 = 0 9 | elif len_a == 1: 10 | a1 = tuple_a[0] 11 | a2 = 0 12 | else: 13 | a1 = tuple_a[0] 14 | a2 = tuple_a[1] 15 | 16 | if len_b == 0: 17 | b1 = 0 18 | b2 = 0 19 | elif len_b == 1: 20 | b1 = tuple_b[0] 21 | b2 = 0 22 | else: 23 | b1 = tuple_b[0] 24 | b2 = tuple_b[1] 25 | 26 | new_tuple = (a1 + b1, a2 + b2) 27 | 28 | return (new_tuple) 29 | -------------------------------------------------------------------------------- /0x03-python-data_structures/8-multiple_returns.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def multiple_returns(sentence): 3 | len_sen = len(sentence) 4 | 5 | if (len_sen == 0): 6 | new_tuple = (len_sen, None) 7 | else: 8 | new_tuple = (len_sen, sentence[0]) 9 | 10 | return (new_tuple) 11 | -------------------------------------------------------------------------------- /0x03-python-data_structures/9-max_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def max_integer(my_list=[]): 3 | length = len(my_list) 4 | 5 | if length == 0: 6 | return (None) 7 | 8 | max_int = my_list[0] 9 | 10 | for i in range(1, length): 11 | if my_list[i] > max_int: 12 | max_int = my_list[i] 13 | 14 | return (max_int) 15 | -------------------------------------------------------------------------------- /0x03-python-data_structures/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_end(listint_t **head, const int n); 22 | void free_listint(listint_t *head); 23 | 24 | int is_palindrome(listint_t **head); 25 | 26 | #endif /* LISTS_H */ 27 | -------------------------------------------------------------------------------- /0x03-python-data_structures/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 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/0-square_matrix_simple.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def square_matrix_simple(matrix=[]): 4 | matrix_2 = [] 5 | for i in matrix: 6 | tmp = [] 7 | for j in i: 8 | tmp.append(j * j) 9 | matrix_2.append(tmp) 10 | return matrix_2 11 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/1-search_replace.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def search_replace(my_list, search, replace): 4 | new_list = [] 5 | for i in my_list: 6 | if search == i: 7 | new_list.append(replace) 8 | else: 9 | new_list.append(i) 10 | return (new_list) 11 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/10-best_score.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def best_score(a_dictionary): 4 | if not a_dictionary: 5 | return None 6 | else: 7 | return (max(a_dictionary, key=a_dictionary.get)) 8 | -------------------------------------------------------------------------------- /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 | num = 0 6 | den = 0 7 | for tup in my_list: 8 | num += tup[0] * tup[1] 9 | den += tup[1] 10 | return (num / den) 11 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/101-square_matrix_map.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def square_matrix_map(matrix=[]): 3 | return (list(map(lambda x: list(map(lambda 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 | for value_dic in list_keys: 5 | if value == a_dictionary.get(value_dic): 6 | del a_dictionary[value_dic] 7 | return (a_dictionary) 8 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/103-python.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | 5 | /** 6 | * print_python_bytes - Prints bytes information 7 | * 8 | * @p: Python Object 9 | * Return: no return 10 | */ 11 | void print_python_bytes(PyObject *p) 12 | { 13 | char *string; 14 | long int size, i, limit; 15 | 16 | printf("[.] bytes object info\n"); 17 | if (!PyBytes_Check(p)) 18 | { 19 | printf(" [ERROR] Invalid Bytes Object\n"); 20 | return; 21 | } 22 | 23 | size = ((PyVarObject *)(p))->ob_size; 24 | string = ((PyBytesObject *)p)->ob_sval; 25 | 26 | printf(" size: %ld\n", size); 27 | printf(" trying string: %s\n", string); 28 | 29 | if (size >= 10) 30 | limit = 10; 31 | else 32 | limit = size + 1; 33 | 34 | printf(" first %ld bytes:", limit); 35 | 36 | for (i = 0; i < limit; i++) 37 | if (string[i] >= 0) 38 | printf(" %02x", string[i]); 39 | else 40 | printf(" %02x", 256 + string[i]); 41 | 42 | printf("\n"); 43 | } 44 | 45 | /** 46 | * print_python_list - Prints list information 47 | * 48 | * @p: Python Object 49 | * Return: no return 50 | */ 51 | void print_python_list(PyObject *p) 52 | { 53 | long int size, i; 54 | PyListObject *list; 55 | PyObject *obj; 56 | 57 | size = ((PyVarObject *)(p))->ob_size; 58 | list = (PyListObject *)p; 59 | 60 | printf("[*] Python list info\n"); 61 | printf("[*] Size of the Python List = %ld\n", size); 62 | printf("[*] Allocated = %ld\n", list->allocated); 63 | 64 | for (i = 0; i < size; i++) 65 | { 66 | obj = ((PyListObject *)p)->ob_item[i]; 67 | printf("Element %ld: %s\n", i, ((obj)->ob_type)->tp_name); 68 | if (PyBytes_Check(obj)) 69 | print_python_bytes(obj); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/11-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | multiply_list_map = __import__('11-multiply_list_map').multiply_list_map 3 | my_list = [1, 2, 3, 4, 6] 4 | new_list = multiply_list_map(my_list, 4) 5 | print(new_list) 6 | print(my_list) 7 | -------------------------------------------------------------------------------- /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 | def uniq_add(my_list=[]): 3 | uniq_list = set(my_list) 4 | num = 0 5 | for i in uniq_list: 6 | num += i 7 | return (num) 8 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/3-common_elements.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def common_elements(set_1, set_2): 3 | return (set_1 & set_2) 4 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/4-only_diff_elements.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def only_diff_elements(set_1, set_2): 3 | return (set_1 ^ set_2) 4 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/5-number_keys.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def number_keys(a_dictionary): 4 | num = 0 5 | list_keys = list(a_dictionary.keys()) 6 | for i in list_keys: 7 | num += 1 8 | return num 9 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/6-print_sorted_dictionary.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def print_sorted_dictionary(a_dictionary): 4 | list_ord = list(a_dictionary.keys()) 5 | list_ord.sort() 6 | for i in list_ord: 7 | print(f"{i}: {a_dictionary.get(i)}") 8 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/7-update_dictionary.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def update_dictionary(a_dictionary, key, value): 4 | a_dictionary[key] = value 5 | return (a_dictionary) 6 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/8-simple_delete.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def simple_delete(a_dictionary, key=""): 4 | if a_dictionary.get(key) is not None: 5 | del a_dictionary[key] 6 | return (a_dictionary) 7 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/9-multiply_by_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def multiply_by_2(a_dictionary): 4 | new = {} 5 | for i in a_dictionary: 6 | new[i] = a_dictionary[i] * 2 7 | return new 8 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/README.md: -------------------------------------------------------------------------------- 1 | # 0x04-python-more_data_structures 2 | 3 | * Matrix Squares -------------------------------------------------------------------------------- /0x05-python-exceptions/0-safe_print_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def safe_print_list(my_list=[], x=0): 3 | counter = 0 4 | for idx in range(x): 5 | try: 6 | print(f'{my_list[idx]}', end='') 7 | except (IndexError): 8 | continue 9 | counter += 1 10 | print() 11 | return (counter) 12 | -------------------------------------------------------------------------------- /0x05-python-exceptions/1-safe_print_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def safe_print_integer(value): 3 | try: 4 | print('{:d}'.format(value)) 5 | except (Exception): 6 | return (False) 7 | return True 8 | -------------------------------------------------------------------------------- /0x05-python-exceptions/100-safe_print_integer_err.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import sys 3 | 4 | 5 | def safe_print_integer_err(value): 6 | try: 7 | print("{:d}".format(value)) 8 | except (Exception) as err: 9 | sys.stderr.write('Exception: ' + str(err) + '\n') 10 | return (False) 11 | return (True) 12 | -------------------------------------------------------------------------------- /0x05-python-exceptions/101-safe_function.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import sys 3 | 4 | 5 | def safe_function(fct, *args): 6 | try: 7 | result = fct(*args) 8 | except (Exception) as err: 9 | sys.stderr.write(f'Exception: {str(err)}\n') 10 | result = None 11 | return (result) 12 | -------------------------------------------------------------------------------- /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 | else: 9 | 10 | result = (((a ** b) / i) + result) 11 | except (Exception): 12 | result = (b + a) 13 | break 14 | return (result) 15 | -------------------------------------------------------------------------------- /0x05-python-exceptions/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 | setbuf(stdout, NULL); 16 | 17 | printf("[.] bytes object info\n"); 18 | if (!PyBytes_Check(p)) 19 | { 20 | printf(" [ERROR] Invalid Bytes Object\n"); 21 | setbuf(stdout, NULL); 22 | return; 23 | } 24 | 25 | size = ((PyVarObject *)(p))->ob_size; 26 | string = ((PyBytesObject *)p)->ob_sval; 27 | 28 | printf(" size: %ld\n", size); 29 | printf(" trying string: %s\n", string); 30 | 31 | if (size >= 10) 32 | limit = 10; 33 | else 34 | limit = size + 1; 35 | 36 | printf(" first %ld bytes:", limit); 37 | 38 | for (i = 0; i < limit; i++) 39 | if (string[i] >= 0) 40 | printf(" %02x", string[i]); 41 | else 42 | printf(" %02x", 256 + string[i]); 43 | 44 | printf("\n"); 45 | setbuf(stdout, NULL); 46 | } 47 | 48 | /** 49 | * print_python_float - Prints float information 50 | * 51 | * @p: Python Object 52 | * Return: no return 53 | */ 54 | void print_python_float(PyObject *p) 55 | { 56 | double val; 57 | char *nf; 58 | 59 | setbuf(stdout, NULL); 60 | printf("[.] float object info\n"); 61 | 62 | if (!PyFloat_Check(p)) 63 | { 64 | printf(" [ERROR] Invalid Float Object\n"); 65 | setbuf(stdout, NULL); 66 | return; 67 | } 68 | 69 | val = ((PyFloatObject *)(p))->ob_fval; 70 | nf = PyOS_double_to_string(val, 'r', 0, Py_DTSF_ADD_DOT_0, Py_DTST_FINITE); 71 | 72 | printf(" value: %s\n", nf); 73 | setbuf(stdout, NULL); 74 | } 75 | 76 | /** 77 | * print_python_list - Prints list information 78 | * 79 | * @p: Python Object 80 | * Return: no return 81 | */ 82 | void print_python_list(PyObject *p) 83 | { 84 | long int size, i; 85 | PyListObject *list; 86 | PyObject *obj; 87 | 88 | setbuf(stdout, NULL); 89 | printf("[*] Python list info\n"); 90 | 91 | if (!PyList_Check(p)) 92 | { 93 | printf(" [ERROR] Invalid List Object\n"); 94 | setbuf(stdout, NULL); 95 | return; 96 | } 97 | 98 | size = ((PyVarObject *)(p))->ob_size; 99 | list = (PyListObject *)p; 100 | 101 | printf("[*] Size of the Python List = %ld\n", size); 102 | printf("[*] Allocated = %ld\n", list->allocated); 103 | 104 | for (i = 0; i < size; i++) 105 | { 106 | obj = list->ob_item[i]; 107 | printf("Element %ld: %s\n", i, ((obj)->ob_type)->tp_name); 108 | 109 | if (PyBytes_Check(obj)) 110 | print_python_bytes(obj); 111 | if (PyFloat_Check(obj)) 112 | print_python_float(obj); 113 | } 114 | setbuf(stdout, NULL); 115 | } 116 | -------------------------------------------------------------------------------- /0x05-python-exceptions/2-safe_print_list_integers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def safe_print_list_integers(my_list=[], x=0): 3 | counter = 0 4 | for idx in range(x): 5 | try: 6 | print("{:d}".format(my_list[idx]), end='') 7 | except (ValueError, TypeError): 8 | continue 9 | counter += 1 10 | print() 11 | return (counter) 12 | -------------------------------------------------------------------------------- /0x05-python-exceptions/3-safe_print_division.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def safe_print_division(a, b): 3 | try: 4 | result = a / b 5 | except (ZeroDivisionError): 6 | result = None 7 | finally: 8 | print("Inside result: {}".format(result)) 9 | return (result) 10 | -------------------------------------------------------------------------------- /0x05-python-exceptions/4-list_division.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def list_division(my_list_1, my_list_2, list_length): 3 | new_list = [] 4 | for idx in range(list_length): 5 | result = 0 6 | try: 7 | result = my_list_1[idx] / my_list_2[idx] 8 | except (ZeroDivisionError): 9 | print('division by 0') 10 | except (TypeError): 11 | print('wrong type') 12 | except (IndexError): 13 | print('out of range') 14 | finally: 15 | new_list.append(result) 16 | return (new_list) 17 | -------------------------------------------------------------------------------- /0x05-python-exceptions/5-raise_exception.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def raise_exception(): 3 | raise TypeError 4 | -------------------------------------------------------------------------------- /0x05-python-exceptions/6-raise_exception_msg.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def raise_exception_msg(message=""): 3 | raise (NameError(message)) 4 | -------------------------------------------------------------------------------- /0x05-python-exceptions/README.md: -------------------------------------------------------------------------------- 1 | # Python Exceptons 2 | -------------------------------------------------------------------------------- /0x06-python-classes/0-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Empty Class Square""" 3 | 4 | 5 | class Square: 6 | """Empty Class Square""" 7 | pass 8 | -------------------------------------------------------------------------------- /0x06-python-classes/1-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Class Square with size""" 3 | 4 | 5 | class Square: 6 | """Class to create a square with it size""" 7 | 8 | def __init__(self, square_size): 9 | """Constructor of the Square""" 10 | self.__size = square_size 11 | -------------------------------------------------------------------------------- /0x06-python-classes/100-singly_linked_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """This module contains a class that defines a square. 3 | In the Square class we initialize each object by the 4 | __init__ method with a private instance variable called 5 | __size that takes the size variable's value passed as 6 | argument. Also checks if the size arg has a valid value. 7 | """ 8 | 9 | 10 | class Node(): 11 | """Node Class.""" 12 | 13 | def __init__(self, data, next_node=None): 14 | """Initialization of Node Class""" 15 | self.data = data 16 | self.next_node = next_node 17 | 18 | @property 19 | def data(self): 20 | """Data""" 21 | return self.__data 22 | 23 | @data.setter 24 | def data(self, DataValue): 25 | """Set data""" 26 | if type(DataValue) != int: 27 | raise TypeError("data must be an integer") 28 | self.__data = DataValue 29 | 30 | @property 31 | def next_node(self): 32 | """Node""" 33 | return self.__next_node 34 | 35 | @next_node.setter 36 | def next_node(self, NodeValue): 37 | """set Node""" 38 | if NodeValue is not None and not isinstance(NodeValue, Node): 39 | raise TypeError("next_node must be a Node object") 40 | self.__next_node = NodeValue 41 | 42 | 43 | class SinglyLinkedList(): 44 | """Class SinglyLinkedList""" 45 | def __init__(self): 46 | """Initialization of SinglyLinkedList""" 47 | self.__head = None 48 | 49 | def sorted_insert(self, DataValue): 50 | """Inserts a nodes""" 51 | NewNode = Node(DataValue) 52 | if self.__head is None: 53 | self.__head = NewNode 54 | return 55 | if DataValue < self.__head.data: 56 | NewNode.next_node = self.__head 57 | self.__head = NewNode 58 | return 59 | actual = self.__head 60 | while DataValue >= actual.data: 61 | prev = actual 62 | if actual.next_node: 63 | actual = actual.next_node 64 | else: 65 | actual.next_node = NewNode 66 | return 67 | prev.next_node = NewNode 68 | NewNode.next_node = actual 69 | 70 | def __str__(self): 71 | """Class As a String""" 72 | strg = "" 73 | actual = self.__head 74 | while actual: 75 | strg += str(actual.data) + "\n" 76 | actual = actual.next_node 77 | return strg[:-1] 78 | -------------------------------------------------------------------------------- /0x06-python-classes/101-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Create a Class Square with: 4 | - size, position private propreties 5 | - method of area and method of print_square 6 | - getters & setters. 7 | """ 8 | 9 | 10 | class Square: 11 | """Class - Square""" 12 | 13 | def __init__(self, size=0, position=(0, 0)): 14 | """Constructor of a Square with the size and position""" 15 | if (type(size) is not int): 16 | raise (TypeError("size must be an integer")) 17 | elif (size < 0): 18 | raise (ValueError("size must be >= 0")) 19 | else: 20 | self.__size = size 21 | 22 | if (len(position) != 2) or (type(position) is not tuple)\ 23 | or (type(position[0]) is not int)\ 24 | or (type(position[1]) is not int)\ 25 | or (position[0] < 0) or (position[1] < 0): 26 | raise TypeError("position must be a tuple of 2 positive integers") 27 | else: 28 | self.__position = position 29 | 30 | def area(self): 31 | """Method to get the area of the Square""" 32 | return (self.__size ** 2) 33 | 34 | def my_print(self): 35 | """Method to print a Square with spaces""" 36 | if (self.__size == 0): 37 | print() 38 | else: 39 | for blank in range(self.position[1]): 40 | print() 41 | for rows in range(self.__size): 42 | print(" " * self.position[0], end='') 43 | print("#" * self.__size) 44 | 45 | def __str__(self): 46 | str = "" 47 | if (self.__size == 0): 48 | return str 49 | else: 50 | for blank in range(self.position[1]): 51 | str += "\n" 52 | for rows in range(self.__size): 53 | str += (" " * self.position[0]) 54 | str += ("#" * self.__size) 55 | if (rows != self.__size - 1): 56 | str += "\n" 57 | return (str) 58 | 59 | @property 60 | def size(self): 61 | """Getter of the private attribute size""" 62 | return (self.__size) 63 | 64 | @size.setter 65 | def size(self, value): 66 | """Setter for the size private attribute""" 67 | if (type(value) is not int): 68 | raise (TypeError("size must be an integer")) 69 | elif (value < 0): 70 | raise (ValueError("size must be >= 0")) 71 | else: 72 | self.__size = value 73 | 74 | @property 75 | def position(self): 76 | """Getter of Position""" 77 | return (self.__position) 78 | 79 | @position.setter 80 | def position(self, value): 81 | """Setter of position""" 82 | if (len(value) != 2) or (type(value) is not tuple) \ 83 | or (type(value[0]) is not int) \ 84 | or (type(value[1]) is not int) \ 85 | or (value[0] < 0) or (value[1] < 0): 86 | raise TypeError("position must be a tuple of 2 positive integers") 87 | else: 88 | self.__position = value 89 | -------------------------------------------------------------------------------- /0x06-python-classes/102-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Create a Class Square with size, method of area and getters & setters""" 3 | 4 | 5 | class Square: 6 | """Class - Square""" 7 | 8 | def __init__(self, size=0): 9 | """Constructor of a Square with the size""" 10 | if (type(size) is not int): 11 | raise (TypeError("size must be an integer")) 12 | elif (size < 0): 13 | raise (ValueError("size must be >= 0")) 14 | else: 15 | self.__size = size 16 | 17 | def __lt__(self, other): 18 | """Compare operator <""" 19 | return (self.area() < other.area()) 20 | 21 | def __le__(self, other): 22 | """Compare operator <=""" 23 | return (self.area() <= other.area()) 24 | 25 | def __gt__(self, other): 26 | """Compare operator >""" 27 | return (self.area() > other.area()) 28 | 29 | def __ge__(self, other): 30 | """Compare operator >=""" 31 | return (self.area() >= other.area()) 32 | 33 | def __eq__(self, other): 34 | """Compare operator ==""" 35 | return (self.area() == other.area()) 36 | 37 | def __ne__(self, other): 38 | """Compare operator !=""" 39 | return (self.area() != other.area()) 40 | 41 | def area(self): 42 | """Method to get the area of the Square""" 43 | return (self.__size ** 2) 44 | 45 | @property 46 | def size(self): 47 | """Getter of the private attribute size""" 48 | return (self.__size) 49 | 50 | @size.setter 51 | def size(self, value): 52 | """Setter for the size private attribute""" 53 | if ((type(value) is int) or (type(value) is float)): 54 | if (value < 0): 55 | raise (ValueError("size must be >= 0")) 56 | else: 57 | self.__size = value 58 | else: 59 | raise (TypeError("size must be a number")) 60 | -------------------------------------------------------------------------------- /0x06-python-classes/103-magic_class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Class MagicClass""" 3 | import math 4 | 5 | 6 | class MagicClass: 7 | """Defines MagicClass""" 8 | def __init__(self, radius=0): 9 | """Initializes Data""" 10 | self.__radius = 0 11 | if type(radius) is not int and type(radius) is not float: 12 | raise TypeError("radius must be a number") 13 | self.__radius = radius 14 | 15 | def area(self): 16 | """Get area""" 17 | return (self.__radius ** 2) * math.pi 18 | 19 | def circumference(self): 20 | """Get Circumference""" 21 | return (2 * math.pi * self.__radius) 22 | -------------------------------------------------------------------------------- /0x06-python-classes/2-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Create a Class Square with size""" 3 | 4 | 5 | class Square: 6 | """Class - Square""" 7 | 8 | def __init__(self, size=0): 9 | """Constructor of a Square with the size""" 10 | if (type(size) is not int): 11 | raise (TypeError("size must be an integer")) 12 | elif (size < 0): 13 | raise (ValueError("size must be >= 0")) 14 | else: 15 | self.__size = size 16 | -------------------------------------------------------------------------------- /0x06-python-classes/3-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Create a Class Square with size and method of area""" 3 | 4 | 5 | class Square: 6 | """Class - Square""" 7 | 8 | def __init__(self, size=0): 9 | """Constructor of a Square with the size""" 10 | if (type(size) is not int): 11 | raise (TypeError("size must be an integer")) 12 | elif (size < 0): 13 | raise (ValueError("size must be >= 0")) 14 | else: 15 | self.__size = size 16 | 17 | def area(self): 18 | """Method to get the area of the Square""" 19 | return (self.__size ** 2) 20 | -------------------------------------------------------------------------------- /0x06-python-classes/4-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Create a Class Square with size, method of area and getters & setters""" 3 | 4 | 5 | class Square: 6 | """Class - Square""" 7 | 8 | def __init__(self, size=0): 9 | """Constructor of a Square with the size""" 10 | if (type(size) is not int): 11 | raise (TypeError("size must be an integer")) 12 | elif (size < 0): 13 | raise (ValueError("size must be >= 0")) 14 | else: 15 | self.__size = size 16 | 17 | def area(self): 18 | """Method to get the area of the Square""" 19 | return (self.__size ** 2) 20 | 21 | @property 22 | def size(self): 23 | """Getter of the private attribute size""" 24 | return (self.__size) 25 | 26 | @size.setter 27 | def size(self, value): 28 | """Setter for the size private attribute""" 29 | if (type(value) is not int): 30 | raise (TypeError("size must be an integer")) 31 | elif (value < 0): 32 | raise (ValueError("size must be >= 0")) 33 | else: 34 | self.__size = value 35 | -------------------------------------------------------------------------------- /0x06-python-classes/5-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Create a Class Square with: 4 | - size proprety 5 | - method of area and method of print_square 6 | - getters & setters. 7 | """ 8 | 9 | 10 | class Square: 11 | """Class - Square""" 12 | 13 | def __init__(self, size=0): 14 | """Constructor of a Square with the size""" 15 | if (type(size) is not int): 16 | raise (TypeError("size must be an integer")) 17 | elif (size < 0): 18 | raise (ValueError("size must be >= 0")) 19 | else: 20 | self.__size = size 21 | 22 | def area(self): 23 | """Method to get the area of the Square""" 24 | return (self.__size ** 2) 25 | 26 | def my_print(self): 27 | """Method to print a Square""" 28 | if (self.__size == 0): 29 | print() 30 | else: 31 | for rows in range(self.__size): 32 | print("#" * self.__size) 33 | 34 | @property 35 | def size(self): 36 | """Getter of the private attribute size""" 37 | return (self.__size) 38 | 39 | @size.setter 40 | def size(self, value): 41 | """Setter for the size private attribute""" 42 | if (type(value) is not int): 43 | raise (TypeError("size must be an integer")) 44 | elif (value < 0): 45 | raise (ValueError("size must be >= 0")) 46 | else: 47 | self.__size = value 48 | -------------------------------------------------------------------------------- /0x06-python-classes/6-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Create a Class Square with: 4 | - size, position private propreties 5 | - method of area and method of print_square 6 | - getters & setters. 7 | """ 8 | 9 | 10 | class Square: 11 | """Class - Square""" 12 | 13 | def __init__(self, size=0, position=(0, 0)): 14 | """Constructor of a Square with the size and position""" 15 | self.size = size 16 | self.position = position 17 | 18 | def area(self): 19 | """Method to get the area of the Square""" 20 | return (self.__size ** 2) 21 | 22 | def my_print(self): 23 | """Method to print a Square with spaces""" 24 | if (self.__size == 0): 25 | print() 26 | else: 27 | for blank in range(self.position[1]): 28 | print() 29 | for rows in range(self.__size): 30 | print(" " * self.position[0], end='') 31 | print("#" * self.__size) 32 | 33 | @property 34 | def size(self): 35 | """Getter of the private attribute size""" 36 | return (self.__size) 37 | 38 | @size.setter 39 | def size(self, value): 40 | """Setter for the size private attribute""" 41 | if (type(value) is not int): 42 | raise (TypeError("size must be an integer")) 43 | elif (value < 0): 44 | raise (ValueError("size must be >= 0")) 45 | else: 46 | self.__size = value 47 | 48 | @property 49 | def position(self): 50 | """Getter of Position""" 51 | return (self.__position) 52 | 53 | @position.setter 54 | def position(self, value): 55 | """Setter of position""" 56 | if (len(value) != 2) or (type(value) is not tuple) \ 57 | or (type(value[0]) is not int) \ 58 | or (type(value[1]) is not int) \ 59 | or (value[0] < 0) or (value[1] < 0): 60 | raise TypeError("position must be a tuple of 2 positive integers") 61 | else: 62 | self.__position = value 63 | -------------------------------------------------------------------------------- /0x06-python-classes/REAME.md: -------------------------------------------------------------------------------- 1 | python classes 2 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/0-add_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Integers addition""" 3 | 4 | 5 | def add_integer(a, b=98): 6 | """Adds two numbers 7 | Args: 8 | a - first number input 9 | b - second number input 10 | """ 11 | if type(a) not in [int, float]: 12 | raise TypeError("a must be an integer") 13 | if type(b) not in [int, float]: 14 | raise TypeError("b must be an integer") 15 | return int(a) + int(b) 16 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/100-matrix_mul.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | 4 | def matrix_mul(m_a, m_b): 5 | """Multiplies two matricies 6 | """ 7 | 8 | # check if the two matrix's aren't empty 9 | if type(m_a) != list: 10 | raise TypeError("m_a must be a list") 11 | if type(m_b) != list: 12 | raise TypeError("m_b must be a list") 13 | if len(m_a) == 0: 14 | raise ValueError("m_a can't be empty") 15 | # check the validity of the content of each elemtent 16 | # for matrix a 17 | if not all(type(row) == list for row in m_a): 18 | raise TypeError("m_a must be a list of lists") 19 | if len(m_a[0]) == 0: 20 | raise ValueError("m_a can't be empty") 21 | 22 | # check the validity of the content of each elemtent 23 | # for matrix b 24 | if not all(type(row) == list for row in m_b): 25 | raise TypeError("m_b must be a list of lists") 26 | if len(m_b) == 0: 27 | raise ValueError("m_b can't be empty") 28 | if len(m_b[0]) == 0: 29 | raise ValueError("m_b can't be empty") 30 | 31 | # Check the validity of the content of each list 32 | # inside each list of matrix a 33 | row_len = len(m_a[0]) 34 | if not all(len(row) == row_len for row in m_a): 35 | raise TypeError("each row of m_a must be of the same size") 36 | 37 | if not all(type(num) in [int, float] for row in m_a for num in row): 38 | raise TypeError("m_a should contain only integers or floats") 39 | # Check the validity of the content of each list 40 | # inside each list of matrix a 41 | row_len = len(m_b[0]) 42 | if not all(len(row) == row_len for row in m_b): 43 | raise TypeError("each row of m_b must be of the same size") 44 | 45 | if not all(type(num) in [int, float] for row in m_b for num in row): 46 | raise TypeError("m_b should contain only integers or floats") 47 | # check if the two vectors are multipliable 48 | acols = len(m_a[0]) 49 | arows = len(m_a) 50 | brows = len(m_b) 51 | bcols = len(m_b[0]) 52 | if acols != brows: 53 | raise ValueError("m_a and m_b can't be multiplied") 54 | 55 | product = [[0 for x in range(bcols)] for y in range(arows)] 56 | for row_i in range(len(m_a)): 57 | col_b = 0 58 | while (col_b < bcols): 59 | sum_t = 0 60 | for col_i in range(len(m_a[row_i])): 61 | sum_t += m_a[row_i][col_i] * m_b[col_i][col_b] 62 | product[row_i][col_b] = sum_t 63 | col_b += 1 64 | return product 65 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/101-lazy_matrix_mul.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This program takes two matrices and multiply them with the library numpy 4 | """ 5 | import numpy as np 6 | 7 | 8 | def lazy_matrix_mul(m_a, m_b): 9 | """ 10 | Takes two matrices and multiply them with numpy 11 | Args: 12 | m_a: list of lists (int or float) 13 | m_b: list of lists (int or float) 14 | """ 15 | return np.matmul(m_a, m_b) 16 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/102-python.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | /** 6 | * print_python_string - Prints string information 7 | * 8 | * @p: Python Object 9 | * Return: no return 10 | */ 11 | void print_python_string(PyObject *p) 12 | { 13 | 14 | PyObject *str, *repr; 15 | 16 | (void)repr; 17 | printf("[.] string object info\n"); 18 | 19 | if (strcmp(p->ob_type->tp_name, "str")) 20 | { 21 | printf(" [ERROR] Invalid String Object\n"); 22 | return; 23 | } 24 | 25 | if (PyUnicode_IS_COMPACT_ASCII(p)) 26 | printf(" type: compact ascii\n"); 27 | else 28 | printf(" type: compact unicode object\n"); 29 | 30 | repr = PyObject_Repr(p); 31 | str = PyUnicode_AsEncodedString(p, "utf-8", "~E~"); 32 | printf(" length: %ld\n", PyUnicode_GET_SIZE(p)); 33 | printf(" value: %s\n", PyBytes_AsString(str)); 34 | } 35 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/2-matrix_divided.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Matrix division""" 3 | 4 | 5 | def matrix_divided(matrix, div): 6 | """Divides every element of a matrix 7 | Args: 8 | matrix (list): A list of lists of integers 9 | or floats div (int/float): The divisor. 10 | """ 11 | 12 | if type(div) not in [int, float]: 13 | raise TypeError("div must be a number") 14 | if div == 0: 15 | raise ZeroDivisionError( 16 | "Each row of the matrix must have the same size") 17 | 18 | if not all(len(row) == len(matrix[0]) for row in matrix): 19 | raise TypeError("Each row of the matrix must have the same size") 20 | if not all(type(num) in [int, float] for row in matrix for num in row): 21 | raise TypeError("matrix must be a matrix (list of lists)" 22 | " of integers/floats") 23 | 24 | new_matrix = [[eval("{:.2f}".format(num / div)) for num in row] 25 | for row in matrix] 26 | return new_matrix 27 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/3-say_my_name.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """String manipulations""" 3 | 4 | 5 | def say_my_name(first_name, last_name=""): 6 | """Prints a string. 7 | Validates string inputs, the display 8 | the full name 9 | """ 10 | if type(first_name) != str: 11 | raise TypeError("first name must be a string") 12 | if type(last_name) != str: 13 | raise TypeError("last name must be a string") 14 | print("My name is {} {}".format(first_name, last_name)) 15 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/4-print_square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Printing square""" 3 | 4 | 5 | def print_square(size): 6 | """Prints a square with the character '#'""" 7 | if type(size) != int: 8 | raise TypeError("size must be an integer") 9 | if size < 0: 10 | raise ValueError("size must be >= 0") 11 | for x in range(size): 12 | for y in range(size): 13 | print("#", end='') 14 | print() 15 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/5-text_indentation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Text indentations""" 3 | 4 | 5 | def text_indentation(text): 6 | """Prints a text with 2 new lines 7 | Args: 8 | text (string): The text to print. 9 | Raises: 10 | TypeError: If text is not a string. 11 | """ 12 | special = ['.', '?', ':'] 13 | if type(text) != str: 14 | raise TypeError("text must be string") 15 | for x in text: 16 | print(x, end='') 17 | if x in special: 18 | print('\n\n', end='') 19 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/README.md: -------------------------------------------------------------------------------- 1 | 0x07. Python - Test-driven development 2 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/0-add_integer.txt: -------------------------------------------------------------------------------- 1 | A test to for adding two inteter 2 | 3 | Import Python module + collections 4 | >>> import sys 5 | >>> sys.path.insert(1, '../') 6 | >>> lib = __import__("0-add_integer") 7 | >>> add_integer = lib.add_integer 8 | 9 | # Normal addition test 10 | >>> add_integer(0) 11 | 98 12 | >>> add_integer(-1) 13 | 97 14 | >>> add_integer(10.5) 15 | 108 16 | 17 | # Type Errors 18 | >>> add_integer(10+5j) 19 | Traceback (most recent call last): 20 | ... 21 | TypeError: a must be an integer 22 | >>> add_integer([]) 23 | Traceback (most recent call last): 24 | ... 25 | TypeError: a must be an integer 26 | >>> add_integer({}) 27 | Traceback (most recent call last): 28 | ... 29 | TypeError: a must be an integer 30 | >>> add_integer(set()) 31 | Traceback (most recent call last): 32 | ... 33 | TypeError: a must be an integer 34 | 35 | >>> add_integer("") 36 | Traceback (most recent call last): 37 | ... 38 | TypeError: a must be an integer 39 | 40 | # Two input addition type errors 41 | >>> add_integer(10, 10+5j) 42 | Traceback (most recent call last): 43 | ... 44 | TypeError: b must be an integer 45 | >>> add_integer(10, []) 46 | Traceback (most recent call last): 47 | ... 48 | TypeError: b must be an integer 49 | >>> add_integer(10, {}) 50 | Traceback (most recent call last): 51 | ... 52 | TypeError: b must be an integer 53 | >>> add_integer(10, set()) 54 | Traceback (most recent call last): 55 | ... 56 | TypeError: b must be an integer 57 | 58 | >>> add_integer(10, "") 59 | Traceback (most recent call last): 60 | ... 61 | TypeError: b must be an integer 62 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/101-lazy_matrix_mul.txt: -------------------------------------------------------------------------------- 1 | # doctest_101-lazy_matrix_mul.txt 2 | =============================== 3 | Tests to 101-lazy_matrix_mul.txt 4 | =============================== 5 | 6 | This library is for multiply two matrix 7 | ``lazy_matrix_mul(m_a, m_b):``. 8 | 9 | File ``101-lazy-matrix_mul.py`` 10 | 11 | Return: New matrix with the result 12 | 13 | Importing the function: 14 | 15 | >>> lazy_matrix_mul = __import__('101-lazy_matrix_mul').lazy_matrix_mul 16 | 17 | Test to realize: 18 | 19 | >>> print(lazy_matrix_mul([[1, 2], [3, 4]], [[1, 2], [3, 4]])) 20 | [[ 7 10] 21 | [15 22]] 22 | 23 | >>> print(lazy_matrix_mul([[1, 2]], [[3, 4], [5, 6]])) 24 | [[13 16]] 25 | 26 | >>> print(lazy_matrix_mul([[3, -2], [1, 2]], [[1, 1], [1, 1]])) 27 | [[1 1] 28 | [3 3]] 29 | 30 | >>> print(lazy_matrix_mul([[1.0, 1.0], [2.0, 2.0]], [[1, 1], [1, 1]])) 31 | [[2. 2.] 32 | [4. 4.]] 33 | 34 | >>> print(lazy_matrix_mul("JavaScript", [[2, 5]])) 35 | Traceback (most recent call last): 36 | ... 37 | ValueError: Scalar operands are not allowed, use '*' instead 38 | 39 | >>> print(lazy_matrix_mul([[2], [5]], "JavaScript")) 40 | Traceback (most recent call last): 41 | ... 42 | ValueError: Scalar operands are not allowed, use '*' instead 43 | 44 | >>> print(lazy_matrix_mul(["C is", "Fun"], [[50, 25]])) 45 | Traceback (most recent call last): 46 | ... 47 | ValueError: shapes (2,) and (1,2) not aligned: 2 (dim 0) != 1 (dim 0) 48 | 49 | >>> print(lazy_matrix_mul([[7.5, 30]], ["C is", "Fun"])) 50 | Traceback (most recent call last): 51 | ... 52 | TypeError: invalid data type for einsum 53 | 54 | >>> print(lazy_matrix_mul([], [[1.9, 90]])) 55 | Traceback (most recent call last): 56 | ... 57 | ValueError: shapes (0,) and (1,2) not aligned: 0 (dim 0) != 1 (dim 0) 58 | 59 | >>> print(lazy_matrix_mul([[2, 1]], [[]])) 60 | Traceback (most recent call last): 61 | ... 62 | ValueError: shapes (1,2) and (1,0) not aligned: 2 (dim 1) != 1 (dim 0) 63 | 64 | >>> print(lazy_matrix_mul([[3, (1, )], [9, 5]], [[2, 0], [4, 0]])) 65 | Traceback (most recent call last): 66 | ... 67 | ValueError: setting an array element with a sequence. 68 | 69 | >>> print(lazy_matrix_mul([[3, 1], [9, 5]], [[2, "Diego"], [5, []]])) 70 | Traceback (most recent call last): 71 | ... 72 | ValueError: setting an array element with a sequence 73 | 74 | >>> print(lazy_matrix_mul([[3, 8], [0.5]], [[3, 1], [5.2, 51]])) 75 | Traceback (most recent call last): 76 | ... 77 | ValueError: setting an array element with a sequence. 78 | 79 | >>> print(lazy_matrix_mul([[1, 0], [50, 9.5]], [[5], [10, 80]])) 80 | Traceback (most recent call last): 81 | ... 82 | ValueError: setting an array element with a sequence. 83 | 84 | >>> print(lazy_matrix_mul([[3, 1, 9], [5, 2, 0]], [[2, 1], [10, 4]])) 85 | Traceback (most recent call last): 86 | ... 87 | ValueError: shapes (2,3) and (2,2) not aligned: 3 (dim 1) != 2 (dim 0) 88 | 89 | >>> print(lazy_matrix_mul([[1, 2], [3, 4]])) 90 | Traceback (most recent call last): 91 | ... 92 | TypeError: lazy_matrix_mul() missing 1 required positional argument: 'm_b' 93 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/2-matrix_divided.txt: -------------------------------------------------------------------------------- 1 | Test the matrix divided function 2 | 3 | >>> import sys 4 | >>> sys.path.insert(1, '../') 5 | >>> lib = __import__("2-matrix_divided") 6 | >>> func = lib.matrix_divided 7 | 8 | #Define test matricies 9 | >>> x = [[0,2],[1,2],[4,4],[7,8],[-54,3.2]] 10 | >>> y = [[1,9 + 1j,3],[1.2, "", 1.5]] 11 | >>> z = [[1,2,3],[4,5]] 12 | 13 | #Normal checks 14 | >>> func(x, 1) 15 | [[0.0, 2.0], [1.0, 2.0], [4.0, 4.0], [7.0, 8.0], [-54.0, 3.2]] 16 | >>> func(x, 2) 17 | [[0.0, 1.0], [0.5, 1.0], [2.0, 2.0], [3.5, 4.0], [-27.0, 1.6]] 18 | 19 | 20 | #Type Errors 21 | >>> func(x, "") 22 | Traceback (most recent call last): 23 | ... 24 | TypeError: div must be a number 25 | 26 | >>> func(y, 2) 27 | Traceback (most recent call last): 28 | ... 29 | TypeError: matrix must be a matrix (list of lists) of integers/floats 30 | 31 | 32 | #unbalanced rows 33 | >>> func(z, 1) 34 | Traceback (most recent call last): 35 | ... 36 | TypeError: Each row of the matrix must have the same size 37 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/3-say_my_name.txt: -------------------------------------------------------------------------------- 1 | A test for the say_my_name function 2 | 3 | Import the module 4 | >>> import sys 5 | >>> sys.path.insert(1, '../') 6 | >>> lib = __import__("3-say_my_name") 7 | >>> func = lib.say_my_name 8 | >>> fn1 = "Musa" 9 | >>> ln1 = "Kanneh" 10 | >>> fn2 = 4 11 | >>> ln2 = 5 12 | 13 | 14 | #Normal Test 15 | >>> func(fn1, ln1) 16 | My name is Musa Kanneh 17 | 18 | #Type Errors 19 | >>> func(fn1, ln2) 20 | Traceback (most recent call last): 21 | ... 22 | TypeError: last_name must be a string 23 | >>> func(fn2, ln1) 24 | Traceback (most recent call last): 25 | ... 26 | TypeError: first_name must be a string 27 | 28 | 29 | >>> fn2 = 4.3 30 | >>> ln2 = 5.7 31 | 32 | 33 | >>> func(fn1, ln2) 34 | Traceback (most recent call last): 35 | ... 36 | TypeError: last name must be a string 37 | >>> func(fn2, ln1) 38 | Traceback (most recent call last): 39 | ... 40 | TypeError: first name must be a string 41 | 42 | 43 | 44 | >>> fn2 = 3 + 1j 45 | >>> ln2 = [] 46 | 47 | 48 | >>> func(fn1, ln2) 49 | Traceback (most recent call last): 50 | ... 51 | TypeError: last_name must be a string 52 | >>> func(fn2, ln1) 53 | Traceback (most recent call last): 54 | ... 55 | TypeError: first_name must be a string 56 | 57 | >>> fn2 = {} 58 | >>> ln2 = 3 + 1j 59 | 60 | 61 | >>> func(fn1, ln2) 62 | Traceback (most recent call last): 63 | ... 64 | TypeError: last name must be a string 65 | >>> func(fn2, ln1) 66 | Traceback (most recent call last): 67 | ... 68 | TypeError: first name must be a string 69 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/4-print_square.txt: -------------------------------------------------------------------------------- 1 | A test to for the print_square function 2 | 3 | Import the module 4 | >>> import sys 5 | >>> sys.path.insert(1, '../') 6 | >>> lib = __import__("4-print_square") 7 | >>> func = lib.print_square 8 | 9 | #Normal addition test 10 | ''' 11 | >>> func(3) 12 | ### 13 | ### 14 | ### 15 | 16 | 17 | #Type Errors 18 | 19 | >>> func("") 20 | Traceback (most recent call last): 21 | ... 22 | TypeError: size must be an integer 23 | >>> func(12.3) 24 | Traceback (most recent call last): 25 | ... 26 | TypeError: size must be an integer 27 | >>> func([]) 28 | Traceback (most recent call last): 29 | ... 30 | TypeError: size must be an integer 31 | >>> func({}) 32 | Traceback (most recent call last): 33 | ... 34 | TypeError: size must be an integer 35 | >>> func(1j) 36 | Traceback (most recent call last): 37 | ... 38 | TypeError: size must be an integer 39 | 40 | 41 | 42 | #value Errors 43 | >>> func(-1) 44 | Traceback (most recent call last): 45 | ... 46 | ValueError: size must be >= 0 47 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/5-text_indentation.txt: -------------------------------------------------------------------------------- 1 | A test to for the text_indenation function 2 | 3 | Import the module 4 | >>> import sys 5 | >>> sys.path.insert(1, '../') 6 | >>> lib = __import__("5-text_indentation") 7 | >>> func = lib.text_indentation 8 | 9 | #Normal addition test 10 | >>> func("Lorem Ipsum.?:") 11 | Lorem Ipsum. 12 | 13 | ? 14 | 15 | : 16 | 17 | 18 | 19 | #Type Errors 20 | 21 | >>> func(4) 22 | Traceback (most recent call last): 23 | ... 24 | TypeError: text must be string 25 | >>> func(12.3) 26 | Traceback (most recent call last): 27 | ... 28 | TypeError: text must be string 29 | >>> func([]) 30 | Traceback (most recent call last): 31 | ... 32 | TypeError: text must be string 33 | >>> func({}) 34 | Traceback (most recent call last): 35 | ... 36 | TypeError: text must be string 37 | >>> func(1j) 38 | Traceback (most recent call last): 39 | ... 40 | TypeError: text must be string 41 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/6-max_integer_test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Unittest for max_integer([..])""" 3 | import unittest 4 | max_integer = __import__('6-max_integer').max_integer 5 | 6 | 7 | class TestMaxInteger(unittest.TestCase): 8 | """Test case for the max_integer_function 9 | """ 10 | 11 | def test_typeErrors(self): 12 | self.assertRaises(TypeError, max_integer, 1) 13 | self.assertRaises(TypeError, max_integer, 1.3) 14 | self.assertRaises(TypeError, max_integer, -3) 15 | self.assertRaises(TypeError, max_integer, 2j) 16 | self.assertRaises(TypeError, max_integer, [2j, 3]) 17 | self.assertRaises(TypeError, max_integer, [-2, "90"]) 18 | 19 | def test_normalResults(self): 20 | self.assertEqual(max_integer([1, 2, 3]), 3) 21 | self.assertEqual(max_integer([-1000000, 1, 2, 3]), 3) 22 | self.assertEqual(max_integer([-1000000, 10000, 2.5, 3, 10000000000]), 23 | 10000000000) 24 | -------------------------------------------------------------------------------- /0x08-python-more_classes/.swp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hardope/alx-higher_level_programming/d4d2ff7523c88c169e798a619251b6552c02ba86/0x08-python-more_classes/.swp -------------------------------------------------------------------------------- /0x08-python-more_classes/0-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """This program create an empty Rectangle Class""" 3 | 4 | 5 | class Rectangle(): 6 | """Do nothing""" 7 | pass 8 | -------------------------------------------------------------------------------- /0x08-python-more_classes/1-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """This program define a class Rectangle with it attributes""" 3 | 4 | 5 | class Rectangle(): 6 | """ 7 | A Rectangle Class with the private instance attributes width and height 8 | """ 9 | 10 | def __init__(self, width=0, height=0): 11 | """ 12 | Constructor of the class Rectangle 13 | Args: 14 | - width (default = 0): int 15 | - heigth (default = 0): int 16 | """ 17 | self.height = height 18 | self.width = width 19 | 20 | @property 21 | def width(self): 22 | """Getter of the property width""" 23 | return self.__width 24 | 25 | @width.setter 26 | def width(self, value): 27 | """ 28 | Getter of the property value 29 | Args: 30 | - value: int 31 | """ 32 | if not isinstance(value, int): 33 | raise TypeError('width must be an integer') 34 | 35 | if value < 0: 36 | raise ValueError('width must be >= 0') 37 | 38 | self.__width = value 39 | 40 | @property 41 | def height(self): 42 | """Getter of the property height""" 43 | return self.__height 44 | 45 | @height.setter 46 | def height(self, value): 47 | """ 48 | Getter of the property value 49 | Args: 50 | - value: int 51 | """ 52 | if not isinstance(value, int): 53 | raise TypeError('height must be an integer') 54 | 55 | if value < 0: 56 | raise ValueError('height must be >= 0') 57 | 58 | self.__height = value 59 | -------------------------------------------------------------------------------- /0x08-python-more_classes/101-nqueens.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This module contains an algorithm that resolves the N-Queen puzzle 4 | using backtracking 5 | """ 6 | 7 | 8 | def isSafe(m_queen, nqueen): 9 | """ Method that determines if the queens can or can't kill each other 10 | Args: 11 | m_queen: array that has the queens positions 12 | nqueen: queen number 13 | Returns: 14 | True: when queens can't kill each other 15 | False: when some of the queens can kill 16 | """ 17 | 18 | for i in range(nqueen): 19 | 20 | if m_queen[i] == m_queen[nqueen]: 21 | return False 22 | 23 | if abs(m_queen[i] - m_queen[nqueen]) == abs(i - nqueen): 24 | return False 25 | 26 | return True 27 | 28 | 29 | def print_result(m_queen, nqueen): 30 | """ Method that prints the list with the Queens positions 31 | Args: 32 | m_queen: array that has the queens positions 33 | nqueen: queen number 34 | """ 35 | 36 | res = [] 37 | 38 | for i in range(nqueen): 39 | res.append([i, m_queen[i]]) 40 | 41 | print(res) 42 | 43 | 44 | def Queen(m_queen, nqueen): 45 | """ Recursive function that executes the Backtracking algorithm 46 | Args: 47 | m_queen: array that has the queens positions 48 | nqueen: queen number 49 | """ 50 | 51 | if nqueen is len(m_queen): 52 | print_result(m_queen, nqueen) 53 | return 54 | 55 | m_queen[nqueen] = -1 56 | 57 | while((m_queen[nqueen] < len(m_queen) - 1)): 58 | 59 | m_queen[nqueen] += 1 60 | 61 | if isSafe(m_queen, nqueen) is True: 62 | 63 | if nqueen is not len(m_queen): 64 | Queen(m_queen, nqueen + 1) 65 | 66 | 67 | def solveNQueen(size): 68 | """ Function that invokes the Backtracking algorithm 69 | Args: 70 | size: size of the chessboard 71 | """ 72 | 73 | m_queen = [-1 for i in range(size)] 74 | 75 | Queen(m_queen, 0) 76 | 77 | 78 | if __name__ == '__main__': 79 | 80 | import sys 81 | 82 | if len(sys.argv) == 1 or len(sys.argv) > 2: 83 | print("Usage: nqueens N") 84 | sys.exit(1) 85 | 86 | try: 87 | size = int(sys.argv[1]) 88 | except Exception as e: 89 | print("N must be a number") 90 | sys.exit(1) 91 | 92 | if size < 4: 93 | print("N must be at least 4") 94 | sys.exit(1) 95 | 96 | solveNQueen(size) 97 | -------------------------------------------------------------------------------- /0x08-python-more_classes/2-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """This program define a class Rectangle with private attributes and methods""" 3 | 4 | 5 | class Rectangle(): 6 | """ 7 | A Rectangle Class with the private instance attributes width and height 8 | and public methods 9 | """ 10 | 11 | def __init__(self, width=0, height=0): 12 | """ 13 | Constructor of the class Rectangle 14 | Args: 15 | - width (default = 0): int 16 | - heigth (default = 0): int 17 | """ 18 | self.height = height 19 | self.width = width 20 | 21 | def area(self): 22 | """Calculate the area of a Rectangle""" 23 | return self.__width * self.__height 24 | 25 | def perimeter(self): 26 | """Get the perimeter of a Rectangle""" 27 | if (self.__width == 0 or self.__height == 0): 28 | return 0 29 | 30 | return (self.__width * 2) + (self.__height * 2) 31 | 32 | @property 33 | def width(self): 34 | """Getter of the property width""" 35 | return self.__width 36 | 37 | @width.setter 38 | def width(self, value): 39 | """ 40 | Getter of the property value 41 | Args: 42 | - value: int 43 | """ 44 | if not isinstance(value, int): 45 | raise TypeError('width must be an integer') 46 | 47 | if value < 0: 48 | raise ValueError('width must be >= 0') 49 | 50 | self.__width = value 51 | 52 | @property 53 | def height(self): 54 | """Getter of the property height""" 55 | return self.__height 56 | 57 | @height.setter 58 | def height(self, value): 59 | """ 60 | Getter of the property value 61 | Args: 62 | - value: int 63 | """ 64 | if not isinstance(value, int): 65 | raise TypeError('height must be an integer') 66 | 67 | if value < 0: 68 | raise ValueError('height must be >= 0') 69 | 70 | self.__height = value 71 | -------------------------------------------------------------------------------- /0x08-python-more_classes/3-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | A Rectangle Class with the private instance attributes width, height 4 | and public methods 5 | """ 6 | 7 | 8 | class Rectangle(): 9 | """ 10 | A Rectangle Class with the private instance attributes width and height 11 | """ 12 | 13 | def __init__(self, width=0, height=0): 14 | """ 15 | Constructor of the class Rectangle 16 | Args: 17 | - width (default = 0): int 18 | - heigth (default = 0): int 19 | """ 20 | self.height = height 21 | self.width = width 22 | 23 | def area(self): 24 | """Calculate the area of a Rectangle""" 25 | return self.__width * self.__height 26 | 27 | def perimeter(self): 28 | """Get the perimeter of a Rectangle""" 29 | if (self.__width == 0 or self.__height == 0): 30 | return 0 31 | 32 | return (self.__width * 2) + (self.__height * 2) 33 | 34 | def __str__(self): 35 | """ 36 | Function to print a Square with # 37 | """ 38 | 39 | if self.__width == 0 or self.__height == 0: 40 | return "" 41 | 42 | final = ['#' * self.__width for line in range(self.__height)] 43 | 44 | return '\n'.join(final) 45 | 46 | @property 47 | def width(self): 48 | """Getter of the property width""" 49 | return self.__width 50 | 51 | @width.setter 52 | def width(self, value): 53 | """ 54 | Getter of the property value 55 | Args: 56 | - value: int 57 | """ 58 | if not isinstance(value, int): 59 | raise TypeError('width must be an integer') 60 | 61 | if value < 0: 62 | raise ValueError('width must be >= 0') 63 | 64 | self.__width = value 65 | 66 | @property 67 | def height(self): 68 | """Getter of the property height""" 69 | return self.__height 70 | 71 | @height.setter 72 | def height(self, value): 73 | """ 74 | Getter of the property value 75 | Args: 76 | - value: int 77 | """ 78 | if not isinstance(value, int): 79 | raise TypeError('height must be an integer') 80 | 81 | if value < 0: 82 | raise ValueError('height must be >= 0') 83 | 84 | self.__height = value 85 | -------------------------------------------------------------------------------- /0x08-python-more_classes/4-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | A Rectangle Class with the private instance attributes width, height 4 | , public methods and special methods 5 | """ 6 | 7 | 8 | class Rectangle(): 9 | """ 10 | A Rectangle Class with the private instance attributes width, height, 11 | public methods and special methods 12 | """ 13 | 14 | def __init__(self, width=0, height=0): 15 | """ 16 | Constructor of the class Rectangle 17 | Args: 18 | - width (default = 0): int 19 | - heigth (default = 0): int 20 | """ 21 | self.height = height 22 | self.width = width 23 | 24 | def area(self): 25 | """Calculate the area of a Rectangle""" 26 | return self.__width * self.__height 27 | 28 | def perimeter(self): 29 | """Get the perimeter of a Rectangle""" 30 | if (self.__width == 0 or self.__height == 0): 31 | return 0 32 | 33 | return (self.__width * 2) + (self.__height * 2) 34 | 35 | def __str__(self): 36 | """ 37 | Function to print a Square with # 38 | """ 39 | 40 | if self.__width == 0 or self.__height == 0: 41 | return "" 42 | 43 | final = [character * self.__width for character in '#' * self.__height] 44 | 45 | return '\n'.join(final) 46 | 47 | def __repr__(self): 48 | """Returns an “official” string representation of a Rectangle""" 49 | return f'Rectangle({self.__width}, {self.__height})' 50 | 51 | @property 52 | def width(self): 53 | """Getter of the property width""" 54 | return self.__width 55 | 56 | @width.setter 57 | def width(self, value): 58 | """ 59 | Getter of the property value 60 | Args: 61 | - value: int 62 | """ 63 | if not isinstance(value, int): 64 | raise TypeError('width must be an integer') 65 | 66 | if value < 0: 67 | raise ValueError('width must be >= 0') 68 | 69 | self.__width = value 70 | 71 | @property 72 | def height(self): 73 | """Getter of the property height""" 74 | return self.__height 75 | 76 | @height.setter 77 | def height(self, value): 78 | """ 79 | Getter of the property value 80 | Args: 81 | - value: int 82 | """ 83 | if not isinstance(value, int): 84 | raise TypeError('height must be an integer') 85 | 86 | if value < 0: 87 | raise ValueError('height must be >= 0') 88 | 89 | self.__height = value 90 | -------------------------------------------------------------------------------- /0x08-python-more_classes/5-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | A Rectangle Class with the private instance attributes width, height 4 | , public methods and special methods 5 | """ 6 | 7 | 8 | class Rectangle(): 9 | """ 10 | A Rectangle Class with the private instance attributes width, height, 11 | public methods and special methods 12 | """ 13 | 14 | def __init__(self, width=0, height=0): 15 | """ 16 | Constructor of the class Rectangle 17 | Args: 18 | - width (default = 0): int 19 | - heigth (default = 0): int 20 | """ 21 | self.height = height 22 | self.width = width 23 | 24 | def area(self): 25 | """Calculate the area of a Rectangle""" 26 | return self.__width * self.__height 27 | 28 | def perimeter(self): 29 | """Get the perimeter of a Rectangle""" 30 | if (self.__width == 0 or self.__height == 0): 31 | return 0 32 | 33 | return (self.__width * 2) + (self.__height * 2) 34 | 35 | def __str__(self): 36 | """ 37 | Function to print a Square with # 38 | """ 39 | 40 | if self.__width == 0 or self.__height == 0: 41 | return "" 42 | 43 | final = [character * self.__width for character in '#' * self.__height] 44 | 45 | return '\n'.join(final) 46 | 47 | def __repr__(self): 48 | """Returns an “official” string representation of a Rectangle""" 49 | return f'Rectangle({self.__width}, {self.__height})' 50 | 51 | def __del__(self): 52 | """Prints a message when a Rectangle instance is deleted""" 53 | print('Bye rectangle...') 54 | 55 | @property 56 | def width(self): 57 | """Getter of the property width""" 58 | return self.__width 59 | 60 | @width.setter 61 | def width(self, value): 62 | """ 63 | Getter of the property value 64 | Args: 65 | - value: int 66 | """ 67 | if not isinstance(value, int): 68 | raise TypeError('width must be an integer') 69 | 70 | if value < 0: 71 | raise ValueError('width must be >= 0') 72 | 73 | self.__width = value 74 | 75 | @property 76 | def height(self): 77 | """Getter of the property height""" 78 | return self.__height 79 | 80 | @height.setter 81 | def height(self, value): 82 | """ 83 | Getter of the property value 84 | Args: 85 | - value: int 86 | """ 87 | if not isinstance(value, int): 88 | raise TypeError('height must be an integer') 89 | 90 | if value < 0: 91 | raise ValueError('height must be >= 0') 92 | 93 | self.__height = value 94 | -------------------------------------------------------------------------------- /0x08-python-more_classes/6-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Area and Perimeter""" 3 | 4 | 5 | class Rectangle: 6 | """Defines the implementation of a rectangle 7 | Attribute: 8 | number_of_instances (int): The number of Rectangle instances. 9 | """ 10 | 11 | number_of_instances = 0 12 | 13 | def __init__(self, width=0, height=0): 14 | type(self).number_of_instances += 1 15 | self.width = width 16 | self.height = height 17 | 18 | @property 19 | def width(self): 20 | """Property retriever, for retreiving""" 21 | return self.__width 22 | 23 | @width.setter 24 | def width(self, value): 25 | """Property setter, for setting""" 26 | if not isinstance(value, int): 27 | raise TypeError("width must be an integer") 28 | if value < 0: 29 | raise ValueError("width must be >= 0") 30 | self.__width = value 31 | 32 | @property 33 | def height(self): 34 | """Property retriever, for retreiving 35 | the rectangle height 36 | """ 37 | return self.__height 38 | 39 | @height.setter 40 | def height(self, value): 41 | if not isinstance(value, int): 42 | raise TypeError("height must be an integer") 43 | if value < 0: 44 | raise ValueError("height must be >= 0") 45 | self.__height = value 46 | 47 | def area(self): 48 | """Public instance method that returns 49 | the rectangle area 50 | """ 51 | rectangle_area = self.__height * self.__width 52 | return rectangle_area 53 | 54 | def perimeter(self): 55 | """Public instance method that returns the 56 | rectangle perimeter 57 | """ 58 | if self.__width == 0 or self.__height == 0: 59 | return (0) 60 | rectangle_params = ((2 * self.__height) + (2 * self.__width)) 61 | return rectangle_params 62 | 63 | def __str__(self): 64 | """Returns the rectangle with the # character.""" 65 | if self.__width == 0 or self.__height == 0: 66 | return ("") 67 | 68 | rectangle = [] 69 | for i in range(self.__height): 70 | [rectangle.append('#') for j in range(self.__width)] 71 | if i != self.__height - 1: 72 | rectangle.append("\n") 73 | return ("".join(rectangle)) 74 | 75 | def __repr__(self): 76 | """Returns the string representation of the Rectangle.""" 77 | rectangle = "Rectangle(" + str(self.__width) 78 | rectangle += ", " + str(self.__height) + ")" 79 | return (rectangle) 80 | 81 | def __del__(self): 82 | """Print a message for every deletion of 83 | the rectangle. 84 | """ 85 | type(self).number_of_instances -= 1 86 | print("Bye rectangle...") 87 | -------------------------------------------------------------------------------- /0x08-python-more_classes/7-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Area and Perimeter""" 3 | 4 | 5 | class Rectangle: 6 | """Defines the implementation of a rectangle 7 | Attributes: 8 | number_of_instances (int): The number of Rectangle instances. 9 | print_symbol (any): The symbol used for string representation. 10 | """ 11 | 12 | number_of_instances = 0 13 | print_symbol = "#" 14 | 15 | def __init__(self, width=0, height=0): 16 | type(self).number_of_instances += 1 17 | self.width = width 18 | self.height = height 19 | 20 | @property 21 | def width(self): 22 | """Property retriever, for retreiving""" 23 | return self.__width 24 | 25 | @width.setter 26 | def width(self, value): 27 | """Property setter, for setting""" 28 | if not isinstance(value, int): 29 | raise TypeError("width must be an integer") 30 | if value < 0: 31 | raise ValueError("width must be >= 0") 32 | self.__width = value 33 | 34 | @property 35 | def height(self): 36 | """Property retriever, for retreiving 37 | the rectangle height 38 | """ 39 | return self.__height 40 | 41 | @height.setter 42 | def height(self, value): 43 | if not isinstance(value, int): 44 | raise TypeError("height must be an integer") 45 | if value < 0: 46 | raise ValueError("height must be >= 0") 47 | self.__height = value 48 | 49 | def area(self): 50 | """Public instance method that returns 51 | the rectangle area 52 | """ 53 | rectangle_area = self.__height * self.__width 54 | return rectangle_area 55 | 56 | def perimeter(self): 57 | """Public instance method that returns the 58 | rectangle perimeter 59 | """ 60 | if self.__width == 0 or self.__height == 0: 61 | return (0) 62 | rectangle_params = ((2 * self.__height) + (2 * self.__width)) 63 | return rectangle_params 64 | 65 | def __str__(self): 66 | """Returns the rectangle with the # character.""" 67 | if self.__width == 0 or self.__height == 0: 68 | return ("") 69 | 70 | rectangle = [] 71 | for i in range(self.__height): 72 | [rectangle.append(str(self.print_symbol)) 73 | for j in range(self.__width)] 74 | if i != self.__height - 1: 75 | rectangle.append("\n") 76 | return ("".join(rectangle)) 77 | 78 | def __repr__(self): 79 | """Returns the string representation of the Rectangle.""" 80 | rectangle = "Rectangle(" + str(self.__width) 81 | rectangle += ", " + str(self.__height) + ")" 82 | return (rectangle) 83 | 84 | def __del__(self): 85 | """Print a message for every deletion of 86 | the rectangle. 87 | """ 88 | type(self).number_of_instances -= 1 89 | print("Bye rectangle...") 90 | -------------------------------------------------------------------------------- /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 | 3 | """Defines a locked class.""" 4 | 5 | 6 | class LockedClass: 7 | """ 8 | Prevent the user from instantiating new LockedClass attributes 9 | for anything but attributes called 'first_name'. 10 | """ 11 | 12 | __slots__ = ["first_name"] 13 | -------------------------------------------------------------------------------- /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(ll): 3 | return ll.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/vi: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/0-lookup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """This program return a list withh the methods of the obj""" 3 | 4 | 5 | def lookup(obj): 6 | """Gets the methods of the obj""" 7 | return dir(obj) 8 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/1-my_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This program creates a class called MyList that inherits of the class List 4 | """ 5 | 6 | 7 | class MyList(list): 8 | """ 9 | This class inherits form the class list an can print it's elements sorted 10 | """ 11 | 12 | def print_sorted(self): 13 | print(sorted(self)) 14 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/10-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This program create a Square from a Rectangle 4 | """ 5 | 6 | 7 | Rectangle = __import__('9-rectangle').Rectangle 8 | 9 | 10 | class Square(Rectangle): 11 | """Class Squared based from Rectangle""" 12 | def __init__(self, size): 13 | """Constructor of Square""" 14 | self.integer_validator("size", size) 15 | self.__size = size 16 | super().__init__(size, size) 17 | 18 | def area(self): 19 | """Calculate the area of a Square""" 20 | return self.__size ** 2 21 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/100-my_int.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """This program create a new int called MyInt and is rebel!!!""" 3 | 4 | 5 | class MyInt(int): 6 | """Class MyInt is like an int but Rebel""" 7 | 8 | def __eq__(self, other_num): 9 | """Rebel!!! equal is not equal""" 10 | return super().__ne__(other_num) 11 | 12 | def __ne__(self, other_num): 13 | """Rebel!!! not equal is equal""" 14 | return super().__eq__(other_num) 15 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/101-add_attribute.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This program will try to add attributes to classes if it possible 4 | """ 5 | 6 | 7 | def add_attribute(obj, key, value): 8 | """ 9 | This function will try to add a new attribute 10 | to a class if it possible, throws an Exception if can't 11 | """ 12 | 13 | if not hasattr(obj, '__dict__'): 14 | raise TypeError("can't add new attribute") 15 | 16 | setattr(obj, key, value) 17 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/11-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This program improves a previous Square 4 | """ 5 | 6 | 7 | PrevSquare = __import__('10-square').Square 8 | 9 | 10 | class Square(PrevSquare): 11 | """ 12 | Improved Class Square 13 | """ 14 | 15 | def __init__(self, size): 16 | """Constructor of the improved Square""" 17 | super().__init__(size) 18 | 19 | def __str__(self): 20 | """String representation of Square""" 21 | return '[Square] {0:d}/{0:d}'.format(self.__size) 22 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/2-is_same_class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This program validate if the obj is the same with other class 4 | """ 5 | 6 | 7 | def is_same_class(obj, a_class): 8 | """ 9 | This function validate if obj is the same class of a_clas 10 | Args: 11 | - obj 12 | - a_class 13 | """ 14 | return type(obj) == a_class 15 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/3-is_kind_of_class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This program validate the kind of class of an obj 4 | """ 5 | 6 | 7 | def is_kind_of_class(obj, a_class): 8 | """ 9 | Returns True if the object is an instance of, 10 | or if the object is an instance of a class that inherited from, 11 | the specified class; otherwise False. 12 | """ 13 | return isinstance(obj, a_class) 14 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/4-inherits_from.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Validate if a class inherits from a_class 4 | """ 5 | 6 | 7 | def inherits_from(obj, a_class): 8 | """ 9 | Returns True if the object is an instance of a class that inherited 10 | (directly or indirectly) from the specified class; otherwise False. 11 | """ 12 | if type(obj) == a_class: 13 | return (False) 14 | return isinstance(obj, a_class) 15 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/5-base_geometry.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This program creates a empty class 4 | """ 5 | 6 | 7 | class BaseGeometry(): 8 | """BaseGeometry is a empty class""" 9 | pass 10 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/6-base_geometry.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This program have an incompleted class 4 | """ 5 | 6 | 7 | class BaseGeometry(): 8 | """ 9 | This class contain a method not implemented 10 | """ 11 | 12 | def area(self): 13 | """ 14 | This function raise an exception 15 | """ 16 | raise Exception('area() is not implemented') 17 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/7-base_geometry.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This program have a class with a validator and an error 4 | """ 5 | 6 | 7 | class BaseGeometry(): 8 | """ 9 | This class contain a method not implemented and a validator 10 | """ 11 | 12 | def area(self): 13 | """ 14 | This function raise an exception 15 | """ 16 | raise Exception('area() is not implemented') 17 | 18 | def integer_validator(self, name, value): 19 | """ 20 | Validate if value is a integer. 21 | Args: 22 | - name: str 23 | - value: int 24 | """ 25 | if not isinstance(value, int): 26 | raise TypeError('{:s} must be an integer'.format(name)) 27 | 28 | if value <= 0: 29 | raise ValueError('{:s} must be greater than 0'.format(name)) 30 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/8-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This program use the inherit for create Rectangle 4 | """ 5 | 6 | 7 | BaseGeometry = __import__('7-base_geometry').BaseGeometry 8 | 9 | 10 | class Rectangle(BaseGeometry): 11 | """ 12 | Class Rectangle based in BaseGeometry 13 | """ 14 | 15 | def __init__(self, width, height): 16 | """Constructor of Retangle""" 17 | BaseGeometry.integer_validator(self, 'width', width) 18 | self.__width = width 19 | BaseGeometry.integer_validator(self, 'height', height) 20 | self.__height = height 21 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/9-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This program use the inherit for create a new Rectangle 4 | """ 5 | 6 | 7 | prevRectangle = __import__('8-rectangle').Rectangle 8 | 9 | 10 | class Rectangle(prevRectangle): 11 | """ 12 | Class Rectangle based in BaseGeometry and other rectangle 13 | """ 14 | 15 | def __init__(self, width, height): 16 | """Constructor of new Retangle""" 17 | self.integer_validator('width', width) 18 | self.__width = width 19 | self.integer_validator('height', height) 20 | self.__height = height 21 | 22 | def area(self): 23 | """This method return the area of the Rectangle""" 24 | return self.__width * self.__height 25 | 26 | def __str__(self): 27 | """This method return the representation of the Rectangle""" 28 | return '[Rectangle] {:d}/{:d}'.format(self.__width, self.__height) 29 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/1-my_list.txt: -------------------------------------------------------------------------------- 1 | >>> MyList = __import__('1-my_list').MyList 2 | 3 | >>> my_list = MyList() 4 | >>> my_list.append(1) 5 | >>> my_list.append(4) 6 | >>> my_list.append(2) 7 | >>> my_list.append(3) 8 | >>> my_list.append(5) 9 | >>> print(my_list) 10 | [1, 4, 2, 3, 5] 11 | >>> my_list.print_sorted() 12 | [1, 2, 3, 4, 5] 13 | >>> print(my_list) 14 | [1, 4, 2, 3, 5] 15 | 16 | >>> my_list = MyList() 17 | >>> my_list.append(0) 18 | >>> my_list.append(0) 19 | >>> my_list.append(0) 20 | >>> my_list.append(0) 21 | >>> my_list.append(0) 22 | >>> print(my_list) 23 | [0, 0, 0, 0, 0] 24 | >>> my_list.print_sorted() 25 | [0, 0, 0, 0, 0] 26 | >>> print(my_list) 27 | [0, 0, 0, 0, 0] 28 | 29 | >>> my_list = MyList() 30 | >>> print(my_list) 31 | [] 32 | >>> my_list.print_sorted() 33 | [] 34 | >>> print(my_list) 35 | [] 36 | 37 | >>> my_list = MyList() 38 | >>> my_list.append(1) 39 | >>> print(my_list) 40 | [1] 41 | >>> my_list.print_sorted() 42 | [1] 43 | >>> print(my_list) 44 | [1] 45 | 46 | >>> my_list = MyList() 47 | >>> my_list.append(-1) 48 | >>> print(my_list) 49 | [-1] 50 | >>> my_list.print_sorted() 51 | [-1] 52 | >>> print(my_list) 53 | [-1] 54 | 55 | >>> my_list = MyList() 56 | >>> my_list.append(50) 57 | >>> my_list.append(-1) 58 | >>> my_list.append(1) 59 | >>> my_list.append(90) 60 | >>> print(my_list) 61 | [50, -1, 1, 90] 62 | >>> my_list.print_sorted() 63 | [-1, 1, 50, 90] 64 | >>> print(my_list) 65 | [50, -1, 1, 90] 66 | 67 | >>> my_list = MyList() 68 | >>> my_list.append(90) 69 | >>> my_list.append(0) 70 | >>> my_list.append(0) 71 | >>> my_list.append(0) 72 | >>> print(my_list) 73 | [90, 0, 0, 0] 74 | >>> my_list.print_sorted() 75 | [0, 0, 0, 90] 76 | >>> print(my_list) 77 | [90, 0, 0, 0] 78 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/7-base_geometry.txt: -------------------------------------------------------------------------------- 1 | >>> BaseGeometry = __import__('7-base_geometry').BaseGeometry 2 | >>> bg = BaseGeometry() 3 | 4 | >>> modulo_doc = __import__('7-base_geometry').__doc__ 5 | >>> print(len(modulo_doc) > 0) 6 | True 7 | 8 | >>> class_doc = __import__('7-base_geometry').BaseGeometry.__doc__ 9 | >>> print(len(class_doc) > 0) 10 | True 11 | 12 | >>> area_doc = __import__('7-base_geometry').BaseGeometry.area.__doc__ 13 | >>> print(len(area_doc) > 0) 14 | True 15 | 16 | >>> validate_doc = __import__('7-base_geometry').BaseGeometry.integer_validator.__doc__ 17 | >>> print(len(validate_doc) > 0) 18 | True 19 | 20 | >>> bg.integer_validator("my_int", 12) 21 | >>> 22 | 23 | >>> bg.integer_validator("width", 89) 24 | >>> 25 | 26 | >>> bg.integer_validator("uno", 0) 27 | Traceback (most recent call last): 28 | ... 29 | ValueError: uno must be greater than 0 30 | 31 | >>> bg.integer_validator("dos", -1) 32 | Traceback (most recent call last): 33 | ... 34 | ValueError: dos must be greater than 0 35 | 36 | >>> bg.integer_validator("tres", []) 37 | Traceback (most recent call last): 38 | ... 39 | TypeError: tres must be an integer 40 | 41 | >>> bg.integer_validator("cuatro", {}) 42 | Traceback (most recent call last): 43 | ... 44 | TypeError: cuatro must be an integer 45 | 46 | >>> bg.integer_validator("cinco", (1, 0)) 47 | Traceback (most recent call last): 48 | ... 49 | TypeError: cinco must be an integer 50 | 51 | >>> bg.integer_validator("seis", "") 52 | Traceback (most recent call last): 53 | ... 54 | TypeError: seis must be an integer 55 | 56 | >>> bg.integer_validator("siete", 5.2) 57 | Traceback (most recent call last): 58 | ... 59 | TypeError: siete must be an integer 60 | 61 | >>> bg.integer_validator("ocho", 5j) 62 | Traceback (most recent call last): 63 | ... 64 | TypeError: ocho must be an integer 65 | 66 | >>> bg.integer_validator("nueve", float('nan')) 67 | Traceback (most recent call last): 68 | ... 69 | TypeError: nueve must be an integer 70 | 71 | >>> bg.integer_validator("diez", float('inf')) 72 | Traceback (most recent call last): 73 | ... 74 | TypeError: diez must be an integer 75 | 76 | >>> bg.integer_validator("once", 100e319) 77 | Traceback (most recent call last): 78 | ... 79 | TypeError: once must be an integer 80 | 81 | >>> bg.integer_validator("doce", -5.2) 82 | Traceback (most recent call last): 83 | ... 84 | TypeError: doce must be an integer 85 | 86 | >>> bg.integer_validator("trece", 0b010101) 87 | >>> 88 | 89 | >>> bg.integer_validator("catorce", 0xAF56) 90 | >>> 91 | -------------------------------------------------------------------------------- /0x0B-python-input_output/0-read_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This program reads files 4 | """ 5 | 6 | 7 | def read_file(filename=""): 8 | """ 9 | This function read a file and print it's content 10 | """ 11 | 12 | with open(filename, encoding="utf-8") as _file: 13 | print(_file.read(), end="") 14 | -------------------------------------------------------------------------------- /0x0B-python-input_output/1-write_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This program writes in a file if doesn't exists create the file 4 | """ 5 | 6 | 7 | def write_file(filename="", text=""): 8 | """ 9 | Write in a file, if doesn't exists create the file 10 | Args: 11 | - filename: string 12 | - text: string 13 | """ 14 | 15 | with open(filename, mode="w", encoding="utf-8") as _file: 16 | _file.write(text) 17 | 18 | return (len(text)) 19 | -------------------------------------------------------------------------------- /0x0B-python-input_output/10-student.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This program define a Student in a class 4 | """ 5 | 6 | 7 | class Student(): 8 | """ 9 | Class of a student 10 | """ 11 | 12 | def __init__(self, first_name, last_name, age): 13 | """ 14 | Constructor of a student 15 | Args: 16 | - first_name: str 17 | - last_name: str 18 | - age: int 19 | """ 20 | self.first_name = first_name 21 | self.last_name = last_name 22 | self.age = age 23 | 24 | def to_json(self, attrs=None): 25 | """ 26 | Return the dict representation of the instance 27 | Args: 28 | - attrs: list (None default) 29 | """ 30 | 31 | result = {} 32 | 33 | if attrs is None: 34 | return (self.__dict__) 35 | 36 | for attr in attrs: 37 | value = self.__dict__.get(attr) 38 | if value is not None: 39 | result[attr] = value 40 | 41 | return (result) 42 | -------------------------------------------------------------------------------- /0x0B-python-input_output/100-append_after.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This program take a file and read it, search a string 4 | and add other string on the next line 5 | """ 6 | 7 | 8 | def append_after(filename="", search_string="", new_string=""): 9 | """ 10 | Open and reads a file, search a string in all the file. 11 | and after each ocurrence add other string (new_string) 12 | Args: 13 | - filename: string 14 | - search_string: string 15 | - new_string: string 16 | """ 17 | 18 | with open(filename, mode="r+", encoding="utf-8") as _file: 19 | all_text = _file.readlines() 20 | new_text = "" 21 | 22 | for line in all_text: 23 | new_text += line 24 | if (search_string in line): 25 | new_text += new_string 26 | 27 | # This method position the cursor to the beginning of the file 28 | _file.seek(0) 29 | _file.write(new_text) 30 | -------------------------------------------------------------------------------- /0x0B-python-input_output/101-generator.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Module for log parsing scripts. 4 | """ 5 | 6 | 7 | import sys 8 | 9 | 10 | if __name__ == "__main__": 11 | size = [0] 12 | codes = {200: 0, 301: 0, 400: 0, 401: 0, 403: 0, 404: 0, 405: 0, 500: 0} 13 | 14 | def check_match(line): 15 | '''Checks for regexp match in line.''' 16 | try: 17 | line = line[:-1] 18 | words = line.split(" ") 19 | size[0] += int(words[-1]) 20 | code = int(words[-2]) 21 | if code in codes: 22 | codes[code] += 1 23 | except Exception as e: 24 | pass 25 | 26 | def print_stats(): 27 | '''Prints accumulated statistics.''' 28 | print("File size: {}".format(size[0])) 29 | for k in sorted(codes.keys()): 30 | if codes[k]: 31 | print("{}: {}".format(k, codes[k])) 32 | i = 1 33 | try: 34 | for line in sys.stdin: 35 | check_match(line) 36 | if i % 10 == 0: 37 | print_stats() 38 | i += 1 39 | except KeyboardInterrupt: 40 | print_stats() 41 | raise 42 | print_stats() 43 | -------------------------------------------------------------------------------- /0x0B-python-input_output/101-stats.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """This documents gather stats from stdin""" 3 | import sys 4 | 5 | 6 | def print_pretty(size, code_dict): 7 | """parse important data""" 8 | print("File size: {}".format(size)) 9 | for key, value in sorted(code_dict.items()): 10 | if (value != 0): 11 | print("{}: {}".format(key, value)) 12 | 13 | if __name__ == '__main__': 14 | """init code to print the parsed data""" 15 | size = 0 16 | code_dict = { 17 | "200": 0, 18 | "301": 0, 19 | "400": 0, 20 | "401": 0, 21 | "403": 0, 22 | "404": 0, 23 | "405": 0, 24 | "500": 0 25 | } 26 | try: 27 | line_counter = 0 28 | for line in sys.stdin: 29 | line_counter += 1 30 | code = line.split()[7] 31 | size += int(line.split()[8]) 32 | if code in code_dict: 33 | code_dict[code] += 1 34 | if (line_counter % 10 == 0): 35 | print_pretty(size, code_dict) 36 | print_pretty(size, code_dict) 37 | except KeyboardInterrupt: 38 | print_pretty(size, code_dict) 39 | raise 40 | -------------------------------------------------------------------------------- /0x0B-python-input_output/11-student.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This program define a Student in a class 4 | """ 5 | 6 | 7 | class Student(): 8 | """ 9 | Class of a student 10 | """ 11 | 12 | def __init__(self, first_name, last_name, age): 13 | """ 14 | Constructor of a student 15 | Args: 16 | - first_name: str 17 | - last_name: str 18 | - age: int 19 | """ 20 | self.first_name = first_name 21 | self.last_name = last_name 22 | self.age = age 23 | 24 | def to_json(self, attrs=None): 25 | """ 26 | Return the dict representation of the instance 27 | Args: 28 | - attrs: list (None default) 29 | """ 30 | 31 | result = {} 32 | 33 | if attrs is None: 34 | return (self.__dict__) 35 | 36 | for attr in attrs: 37 | value = self.__dict__.get(attr) 38 | if value is not None: 39 | result[attr] = value 40 | 41 | return (result) 42 | 43 | def reload_from_json(self, json): 44 | """ 45 | Update all public instance attributes 46 | Args: 47 | - json: dict 48 | """ 49 | dict_des = self.__dict__ 50 | 51 | for key, value in json.items(): 52 | if (dict_des.get(key) == self.first_name): 53 | self.first_name = value 54 | elif (dict_des.get(key) == self.last_name): 55 | self.last_name = value 56 | elif (dict_des.get(key) == self.age): 57 | self.age = value 58 | -------------------------------------------------------------------------------- /0x0B-python-input_output/12-pascal_triangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This program makes a pascal triangle 4 | """ 5 | 6 | 7 | def pascal_triangle(n): 8 | """ 9 | Makes a list of lists in representation of a 10 | pascal triangle. 11 | n: Levels of the triangle 12 | Args: 13 | - n: int 14 | """ 15 | if (n <= 0): 16 | return ([]) 17 | elif (n == 1): 18 | return ([[1]]) 19 | elif (n == 2): 20 | return ([[1], [1, 1]]) 21 | 22 | pascal = [[1], [1, 1]] 23 | 24 | for i in range(1, n - 1): 25 | new_list = [] 26 | new_list.append(1) 27 | for j in range(1, len(pascal)): 28 | new_list.append(pascal[i][j - 1] + pascal[i][j]) 29 | new_list.append(1) 30 | pascal.append(new_list) 31 | 32 | return (pascal) 33 | -------------------------------------------------------------------------------- /0x0B-python-input_output/2-append_write.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This program can append text in a file, 4 | create the file if doesn't exists 5 | """ 6 | 7 | 8 | def append_write(filename="", text=""): 9 | """ 10 | Append text to the end of file, and created if doesn't exists. 11 | Args: 12 | - filename: string 13 | - text: string 14 | """ 15 | 16 | with open(filename, mode="a", encoding="utf-8") as _file: 17 | _file.write(text) 18 | 19 | return (len(text)) 20 | -------------------------------------------------------------------------------- /0x0B-python-input_output/3-to_json_string.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This program converts dictionaries to JSON 4 | """ 5 | 6 | 7 | import json 8 | 9 | 10 | def to_json_string(my_obj): 11 | """ 12 | Convert a dict to JSON format 13 | Args: 14 | - my_obj: dict 15 | """ 16 | 17 | return (json.dumps(my_obj)) 18 | -------------------------------------------------------------------------------- /0x0B-python-input_output/4-from_json_string.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This program converts JSON to dictionaries 4 | """ 5 | 6 | 7 | import json 8 | 9 | 10 | def from_json_string(my_str): 11 | """ 12 | Returns an object (Python data structure) represented by a JSON stringx 13 | Args: 14 | - my_str: str 15 | """ 16 | return (json.loads(my_str)) 17 | -------------------------------------------------------------------------------- /0x0B-python-input_output/5-save_to_json_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This program writes in a file with a JSON format 4 | """ 5 | 6 | 7 | import json 8 | 9 | 10 | def save_to_json_file(my_obj, filename): 11 | """ 12 | Save in a file data with JSON format, if the files doesn't exists 13 | create it. 14 | Args: 15 | - my_obj 16 | - filename: str 17 | """ 18 | 19 | with open(filename, mode="w", encoding="utf-8") as _file: 20 | _file.write(json.dumps(my_obj)) 21 | -------------------------------------------------------------------------------- /0x0B-python-input_output/6-load_from_json_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This program reads files .json and convert to types of python 4 | """ 5 | 6 | 7 | import json 8 | 9 | 10 | def load_from_json_file(filename): 11 | """ 12 | Read a file and convert the content (JSON) to python types 13 | Args: 14 | - filename: path 15 | """ 16 | 17 | with open(filename, mode="r", encoding="utf-8") as _file: 18 | return (json.loads(_file.read())) 19 | -------------------------------------------------------------------------------- /0x0B-python-input_output/7-add_item.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This program take the file add_item.json, and add the 4 | parameters to the list inside this file. 5 | - If the file doesn't exist create it. 6 | - If no exist parameters do nothing or create the list if the file is empty. 7 | """ 8 | 9 | from sys import argv 10 | from os.path import exists 11 | 12 | save_to_json_file = __import__("5-save_to_json_file").save_to_json_file 13 | load_from_json_file = __import__("6-load_from_json_file").load_from_json_file 14 | 15 | namefile = "add_item.json" 16 | argc = len(argv) 17 | 18 | file_list = [] 19 | 20 | if exists(namefile): 21 | file_list = load_from_json_file(namefile) 22 | 23 | if (argc == 1): 24 | save_to_json_file(file_list, namefile) 25 | else: 26 | for index in range(1, argc): 27 | file_list.append(argv[index]) 28 | save_to_json_file(file_list, namefile) 29 | -------------------------------------------------------------------------------- /0x0B-python-input_output/8-class_to_json.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This program return the dict representation of a instance of Class. 4 | """ 5 | 6 | 7 | def class_to_json(obj): 8 | """ 9 | Returns the dictionary description with simple data structure 10 | Args: 11 | - obj: instance of class 12 | """ 13 | 14 | return (obj.__dict__) 15 | -------------------------------------------------------------------------------- /0x0B-python-input_output/9-student.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This program define a Student in a class 4 | """ 5 | 6 | 7 | class Student(): 8 | """ 9 | Class of a student 10 | """ 11 | 12 | def __init__(self, first_name, last_name, age): 13 | """ 14 | Constructor of a student 15 | Args: 16 | - first_name: str 17 | - last_name: str 18 | - age: int 19 | """ 20 | self.first_name = first_name 21 | self.last_name = last_name 22 | self.age = age 23 | 24 | def to_json(self): 25 | """ 26 | Return the dict representation of the instance 27 | """ 28 | return (self.__dict__) 29 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/models/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hardope/alx-higher_level_programming/d4d2ff7523c88c169e798a619251b6552c02ba86/0x0C-python-almost_a_circle/models/__init__.py -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/models/square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | '''Module for Square class.''' 3 | from models.rectangle import Rectangle 4 | 5 | 6 | class Square(Rectangle): 7 | '''A Square class.''' 8 | 9 | def __init__(self, size, x=0, y=0, id=None): 10 | '''Constructor.''' 11 | super().__init__(size, size, x, y, id) 12 | 13 | def __str__(self): 14 | '''Returns string info about this square.''' 15 | return '[{}] ({}) {}/{} - {}'.\ 16 | format(type(self).__name__, self.id, self.x, self.y, self.width) 17 | 18 | @property 19 | def size(self): 20 | '''Size of this square.''' 21 | return self.width 22 | 23 | @size.setter 24 | def size(self, value): 25 | self.width = value 26 | self.height = value 27 | 28 | def __update(self, id=None, size=None, x=None, y=None): 29 | '''Internal method that updates instance attributes via */**args.''' 30 | if id is not None: 31 | self.id = id 32 | if size is not None: 33 | self.size = size 34 | if x is not None: 35 | self.x = x 36 | if y is not None: 37 | self.y = y 38 | 39 | def update(self, *args, **kwargs): 40 | '''Updates instance attributes via no-keyword & keyword args.''' 41 | if args: 42 | self.__update(*args) 43 | elif kwargs: 44 | self.__update(**kwargs) 45 | 46 | def to_dictionary(self): 47 | '''Returns dictionary representation of this class.''' 48 | return {"id": self.id, "size": self.width, 49 | "x": self.x, "y": self.y} 50 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hardope/alx-higher_level_programming/d4d2ff7523c88c169e798a619251b6552c02ba86/0x0C-python-almost_a_circle/tests/__init__.py -------------------------------------------------------------------------------- /0x0D-SQL_introduction/0-list_databases.sql: -------------------------------------------------------------------------------- 1 | -- Displays all databases 2 | -- Query to display databases 3 | SHOW DATABASES; 4 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/1-create_database_if_missing.sql: -------------------------------------------------------------------------------- 1 | -- Creates a new database 2 | -- Query to create the database hbtn_0c_0 in MySQL server 3 | CREATE DATABASE IF NOT EXISTS hbtn_0c_0; 4 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/10-top_score.sql: -------------------------------------------------------------------------------- 1 | -- Script that lists all records in a table 2 | -- Query to lists all records in the table second_table of a database 3 | SELECT score, name FROM second_table ORDER BY score DESC; 4 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/100-move_to_utf8.sql: -------------------------------------------------------------------------------- 1 | -- Script that converts hbtn_0c_0 database to UTF8 2 | -- Query to convert hbtn_0c_0 database to UTF8 3 | ALTER DATABASE hbtn_0c_0 CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; 4 | USE hbtn_0c_0; 5 | ALTER TABLE first_table CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; 6 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/101-avg_temperatures.sql: -------------------------------------------------------------------------------- 1 | -- Script that displays the average temperature 2 | -- Query to display the average temperature by city ordered by temperature 3 | SELECT city, AVG(value) AS avg_temp 4 | FROM temperatures 5 | GROUP BY city 6 | ORDER BY avg_temp DESC; 7 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/102-top_city.sql: -------------------------------------------------------------------------------- 1 | -- Script that displays the average temperature 2 | -- Query to display the average temperature by city ordered by temperature 3 | SELECT city, AVG(value) AS avg_temp 4 | FROM temperatures 5 | WHERE month = 7 OR month = 8 6 | GROUP BY city 7 | ORDER BY avg_temp DESC 8 | LIMIT 3; 9 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/103-max_state.sql: -------------------------------------------------------------------------------- 1 | -- Displays the max temperature of each state (ordered by State name). 2 | 3 | SELECT state, MAX(value) as max_temp FROM temperatures 4 | GROUP BY state 5 | ORDER BY state 6 | limit 3; 7 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/11-best_score.sql: -------------------------------------------------------------------------------- 1 | -- Script that lists all records with a score >= 10 2 | -- Query to lists all records with a score >= 10 in the table second_table of a database 3 | SELECT score, name FROM second_table WHERE score >= 10 ORDER BY score DESC; 4 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/12-no_cheating.sql: -------------------------------------------------------------------------------- 1 | -- Script that updates the attribute value of a table 2 | -- Query to update the score of Bob to 10 in the table second_table 3 | UPDATE second_table 4 | SET score = 10 5 | WHERE name = "Bob" 6 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/13-change_class.sql: -------------------------------------------------------------------------------- 1 | -- Script that removes records 2 | -- Query to remove all records with a score <= 5 in the table second_table 3 | DELETE FROM second_table WHERE score <= 5; 4 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/14-average.sql: -------------------------------------------------------------------------------- 1 | -- Script that computes the score average of all records in a table 2 | -- Query to computes the score average of all records in the table second_table 3 | SELECT AVG(score) AS average FROM second_table; 4 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/15-groups.sql: -------------------------------------------------------------------------------- 1 | -- Script that lists the number of records with the same score 2 | -- Query to lists the number of records with the same score 3 | SELECT score, COUNT(*) AS number 4 | FROM second_table 5 | GROUP BY score 6 | ORDER BY score DESC; 7 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/16-no_link.sql: -------------------------------------------------------------------------------- 1 | -- Script that lists all records of a table 2 | -- Query to lists all records of the table second_table who have name value 3 | SELECT score, name FROM second_table WHERE name IS NOT NULL ORDER BY score DESC; 4 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/2-remove_database.sql: -------------------------------------------------------------------------------- 1 | -- Deletes a database 2 | -- Query to delete the database hbtn_0c_0 in MySQL server 3 | DROP DATABASE IF EXISTS hbtn_0c_0; 4 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/3-list_tables.sql: -------------------------------------------------------------------------------- 1 | -- Lists all the tables of a database 2 | -- Query to list all tables of a database 3 | SHOW TABLES; 4 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/4-first_table.sql: -------------------------------------------------------------------------------- 1 | -- Creates a table in the current database 2 | -- Query to create a table called first_table in the current database in your MySQL server 3 | CREATE TABLE IF NOT EXISTS first_table ( 4 | id INT, 5 | name VARCHAR(256)); 6 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/5-full_table.sql: -------------------------------------------------------------------------------- 1 | -- Prints the full description of the table first_table from the database 2 | -- Query to print full description of a table 3 | SHOW CREATE TABLE first_table; 4 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/6-list_values.sql: -------------------------------------------------------------------------------- 1 | -- Lists all rows of a table 2 | -- Lists all rows of the table first_table from the database hbtn_0c_0 3 | SELECT * FROM first_table; 4 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/7-insert_value.sql: -------------------------------------------------------------------------------- 1 | -- Inserts a new row in a table 2 | -- Query to insert a new row in the table first_table 3 | INSERT INTO first_table (id, name) VALUES (89, "Best School"); 4 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/8-count_89.sql: -------------------------------------------------------------------------------- 1 | -- Displays the number of records 2 | -- Query to display the number of records with id = 89 in a table 3 | SELECT COUNT(*) as id FROM first_table WHERE id=89; 4 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/9-full_creation.sql: -------------------------------------------------------------------------------- 1 | -- Creates a table in a database 2 | -- Query to create a table second_table in the database hbtn_0c_0 3 | CREATE TABLE IF NOT EXISTS second_table ( 4 | id INT, 5 | name VARCHAR(256), 6 | score INT); 7 | INSERT INTO second_table (id, name, score) VALUES (1, "John", 10); 8 | INSERT INTO second_table (id, name, score) VALUES (2, "Alex", 3); 9 | INSERT INTO second_table (id, name, score) VALUES (3, "Bob", 14); 10 | INSERT INTO second_table (id, name, score) VALUES (4, "George", 8); 11 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/.101-not_a_comedy.sql.swp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hardope/alx-higher_level_programming/d4d2ff7523c88c169e798a619251b6552c02ba86/0x0E-SQL_more_queries/.101-not_a_comedy.sql.swp -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/.hbtn_0d_tvshows_rate.sql.swp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hardope/alx-higher_level_programming/d4d2ff7523c88c169e798a619251b6552c02ba86/0x0E-SQL_more_queries/.hbtn_0d_tvshows_rate.sql.swp -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/0-privileges.sql: -------------------------------------------------------------------------------- 1 | -- Lists all privileges of the 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 | -- script that creates the MySQL server user user_0d_1 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 in hbtn_0d_tvshows that have at least one genre linked. 2 | -- Records are sorted by ascending tv_shows.title and tv_show_genres.genre_id. 3 | SELECT s.`title`, g.`genre_id` 4 | FROM `tv_shows` AS s 5 | INNER JOIN `tv_show_genres` AS g 6 | ON s.`id` = g.`show_id` 7 | ORDER BY s.`title`, g.`genre_id`; 8 | 9 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/100-not_my_genres.sql: -------------------------------------------------------------------------------- 1 | -- Lists all genres of the database hbtn_0d_tvshows 2 | -- not linked to the show Dexter. 3 | -- Records are sorted by ascending genre name. 4 | SELECT DISTINCT `name` 5 | FROM `tv_genres` AS g 6 | INNER JOIN `tv_show_genres` AS s 7 | ON g.`id` = s.`genre_id` 8 | 9 | INNER JOIN `tv_shows` AS t 10 | ON s.`show_id` = t.`id` 11 | WHERE g.`name` NOT IN 12 | (SELECT `name` 13 | FROM `tv_genres` AS g 14 | INNER JOIN `tv_show_genres` AS s 15 | ON g.`id` = s.`genre_id` 16 | 17 | INNER JOIN `tv_shows` AS t 18 | ON s.`show_id` = t.`id` 19 | WHERE t.`title` = "Dexter") 20 | ORDER BY g.`name`; 21 | 22 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/101-not_a_comedy.sql: -------------------------------------------------------------------------------- 1 | -- Lists all shows without the comedy genre in the database hbtn_0d_tvshows. 2 | -- Records are ordered by ascending show title. 3 | SELECT DISTINCT `title` 4 | FROM `tv_shows` AS t 5 | LEFT JOIN `tv_show_genres` AS s 6 | ON s.`show_id` = t.`id` 7 | 8 | LEFT JOIN `tv_genres` AS g 9 | ON g.`id` = s.`genre_id` 10 | WHERE t.`title` NOT IN 11 | (SELECT `title` 12 | FROM `tv_shows` AS t 13 | INNER JOIN `tv_show_genres` AS s 14 | ON s.`show_id` = t.`id` 15 | 16 | INNER JOIN `tv_genres` AS g 17 | ON g.`id` = s.`genre_id` 18 | WHERE g.`name` = "Comedy") 19 | ORDER BY `title`; 20 | 21 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/102-rating_shows.sql: -------------------------------------------------------------------------------- 1 | -- Lists all shows from hbtn_0d_tvshows_rate by their rating. 2 | -- Records are ordered by descending rating. 3 | SELECT `title`, SUM(`rate`) AS `rating` 4 | FROM `tv_shows` AS t 5 | INNER JOIN `tv_show_ratings` AS r 6 | ON t.`id` = r.`show_id` 7 | GROUP BY `title` 8 | ORDER BY `rating` DESC; 9 | 10 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/103-rating_genres.sql: -------------------------------------------------------------------------------- 1 | -- Lists all genres in the database hbtn_0d_tvshows_rate by their rating. 2 | -- Records are ordered by descending rating. 3 | SELECT `name`, SUM(`rate`) AS `rating` 4 | FROM `tv_genres` AS g 5 | INNER JOIN `tv_show_genres` AS s 6 | ON s.`genre_id` = g.`id` 7 | 8 | INNER JOIN `tv_show_ratings` AS r 9 | ON r.`show_id` = s.`show_id` 10 | GROUP BY `name` 11 | ORDER BY `rating` DESC; 12 | 13 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/11-genre_id_all_shows.sql: -------------------------------------------------------------------------------- 1 | -- Lists all shows contained in the database hbtn_0d_tvshows. 2 | -- Displays NULL for shows without genres. 3 | -- Records are ordered by ascending tv_shows.title and tv_show_genres.genre_id. 4 | SELECT s.`title`, g.`genre_id` 5 | FROM `tv_shows` AS s 6 | LEFT JOIN `tv_show_genres` AS g 7 | ON s.`id` = g.`show_id` 8 | ORDER BY s.`title`, g.`genre_id`; 9 | 10 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/12-no_genre.sql: -------------------------------------------------------------------------------- 1 | -- Lists all shows in the database hbtn_0d_tvshows without a genre linked. 2 | -- Records are ordered by ascending tv_shows.title and tv_show_genres.genre_id. 3 | SELECT s.`title`, g.`genre_id` 4 | FROM `tv_shows` AS s 5 | LEFT JOIN `tv_show_genres` AS g 6 | ON s.`id` = g.`show_id` 7 | WHERE g.`genre_id` IS NULL 8 | ORDER BY s.`title`, g.`genre_id`; 9 | 10 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/13-count_shows_by_genre.sql: -------------------------------------------------------------------------------- 1 | -- Lists all genres from the database hbtn_0d_tvshows along with the number of 2 | -- shows linked to each. 3 | -- Does not display genres without linked shows. 4 | -- Records are ordered by descending number of shows linked. 5 | SELECT g.`name` AS `genre`, 6 | COUNT(*) AS `number_of_shows` 7 | FROM `tv_genres` AS g 8 | INNER JOIN `tv_show_genres` AS t 9 | ON g.`id` = t.`genre_id` 10 | GROUP BY g.`name` 11 | ORDER BY `number_of_shows` DESC; 12 | 13 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/14-my_genres.sql: -------------------------------------------------------------------------------- 1 | -- Lists all genres of the show Dexter in the database hbtn_0d_tvshows. 2 | -- Records are ordered by ascending genre name. 3 | SELECT g.`name` 4 | FROM `tv_genres` AS g 5 | INNER JOIN `tv_show_genres` AS s 6 | ON g.`id` = s.`genre_id` 7 | 8 | INNER JOIN `tv_shows` AS t 9 | ON t.`id` = s.`show_id` 10 | WHERE t.`title` = "Dexter" 11 | ORDER BY g.`name`; 12 | 13 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/15-comedy_only.sql: -------------------------------------------------------------------------------- 1 | -- Lists all comedy shows in the database hbtn_0d_tvshows. 2 | -- Records are ordered by descending show title. 3 | SELECT t.`title` 4 | FROM `tv_shows` AS t 5 | INNER JOIN `tv_show_genres` AS s 6 | ON t.`id` = s.`show_id` 7 | 8 | INNER JOIN `tv_genres` AS g 9 | ON g.`id` = s.`genre_id` 10 | WHERE g.`name` = "Comedy" 11 | ORDER BY t.`title`; 12 | 13 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/16-shows_by_genre.sql: -------------------------------------------------------------------------------- 1 | -- Lists all shows and genres linked to the show from the 2 | -- database hbtn_0d_tvshows. 3 | -- Records are ordered by ascending show title and genre name. 4 | SELECT t.`title`, g.`name` 5 | FROM `tv_shows` AS t 6 | LEFT JOIN `tv_show_genres` AS s 7 | ON t.`id` = s.`show_id` 8 | 9 | LEFT JOIN `tv_genres` AS g 10 | ON s.`genre_id` = g.`id` 11 | ORDER BY t.`title`, g.`name`; 12 | 13 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/2-create_read_user.sql: -------------------------------------------------------------------------------- 1 | -- script that creates the database hbtn_0d_2 and the user user_0d_2 2 | CREATE DATABASE IF NOT EXISTS hbtn_0d_2; 3 | CREATE USER IF NOT EXISTS 'user_0d_2'@'localhost' IDENTIFIED BY 'user_0d_2_pwd'; 4 | GRANT SELECT ON hbtn_0d_2 . * TO 'user_0d_2'@'localhost'; 5 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/3-force_name.sql: -------------------------------------------------------------------------------- 1 | -- Creates the table force_name. 2 | CREATE TABLE IF NOT EXISTS `force_name` ( 3 | `id` INT, 4 | `name` VARCHAR(256) NOT NULL 5 | ); 6 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/4-never_empty.sql: -------------------------------------------------------------------------------- 1 | -- Creates the table id_not_null 2 | CREATE TABLE IF NOT EXISTS `id_not_null` ( 3 | `id` INT DEFAULT 1, 4 | `name` VARCHAR(256) 5 | ); 6 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/5-unique_id.sql: -------------------------------------------------------------------------------- 1 | -- Creates the table unique_id. 2 | CREATE TABLE IF NOT EXISTS `unique_id` ( 3 | `id` INT DEFAULT 1 UNIQUE, 4 | `name` VARCHAR(256) 5 | ); 6 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/6-states.sql: -------------------------------------------------------------------------------- 1 | -- Creates the table hbtn_0d_usa with table states. 2 | CREATE DATABASE IF NOT EXISTS `hbtn_0d_usa`; 3 | CREATE TABLE IF NOT EXISTS `hbtn_0d_usa`.`states` ( 4 | PRIMARY KEY(`id`), 5 | `id` INT NOT NULL AUTO_INCREMENT, 6 | `name` VARCHAR(256) NOT NULL 7 | ); 8 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/7-cities.sql: -------------------------------------------------------------------------------- 1 | -- Creates the database hbtn_0d_usa with the table cities. 2 | CREATE DATABASE IF NOT EXISTS `hbtn_0d_usa`; 3 | CREATE TABLE IF NOT EXISTS `hbtn_0d_usa`.`cities` ( 4 | PRIMARY KEY(`id`), 5 | `id` INT NOT NULL AUTO_INCREMENT, 6 | `state_id` INT NOT NULL, 7 | `name` VARCHAR(256) NOT NULL, 8 | FOREIGN KEY(`state_id`) 9 | REFERENCES `hbtn_0d_usa`.`states`(`id`) 10 | ); 11 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/8-cities_of_california_subquery.sql: -------------------------------------------------------------------------------- 1 | -- Lists all cities of CA in the database hbtn_0d_usa. 2 | -- Results are ordered by ascending cities.id. 3 | SELECT `id`, `name` 4 | FROM `cities` 5 | WHERE `state_id` IN 6 | (SELECT `id` 7 | FROM `states` 8 | WHERE `name` = "California") 9 | ORDER BY `id`; 10 | 11 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/9-cities_by_state_join.sql: -------------------------------------------------------------------------------- 1 | -- Lists all cities in the database hbtn_0d_usa. 2 | -- Records are sorted in order of ascending cities.id. 3 | SELECT c.`id`, c.`name`, s.`name` 4 | FROM `cities` AS c 5 | INNER JOIN `states` AS s 6 | ON c.`state_id` = s.`id` 7 | ORDER BY c.`id`; 8 | 9 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/.1-filter_states.py.swp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hardope/alx-higher_level_programming/d4d2ff7523c88c169e798a619251b6552c02ba86/0x0F-python-object_relational_mapping/.1-filter_states.py.swp -------------------------------------------------------------------------------- /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 | 4 | if __name__ == '__main__': 5 | from sys import argv 6 | import MySQLdb as mysql 7 | 8 | try: 9 | db = mysql.connect(host='localhost', port=3306, user=argv[1], 10 | passwd=argv[2], db=argv[3]) 11 | except Exception: 12 | print('Failed to connect to the database') 13 | exit(0) 14 | 15 | cursor = db.cursor() 16 | 17 | cursor.execute("SELECT * FROM states ORDER BY id ASC;") 18 | 19 | result_query = cursor.fetchall() 20 | 21 | for row in result_query: 22 | print(row) 23 | 24 | cursor.close() 25 | db.close() 26 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/1-filter_states.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Lists all states with a name starting with 4 | N (upper N) from the database hbtn_0e_0_usa 5 | """ 6 | 7 | if __name__ == '__main__': 8 | from sys import argv 9 | import MySQLdb as mysql 10 | 11 | try: 12 | db = mysql.connect(host='localhost', port=3306, user=argv[1], 13 | passwd=argv[2], db=argv[3]) 14 | except Exception: 15 | print('Failed to connect to the database') 16 | exit(0) 17 | 18 | cursor = db.cursor() 19 | 20 | cursor.execute("SELECT * FROM states \ 21 | WHERE name LIKE BINARY 'N%' ORDER BY id ASC;") 22 | 23 | result_query = cursor.fetchall() 24 | 25 | for row in result_query: 26 | print(row) 27 | 28 | cursor.close() 29 | db.close() 30 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/10-model_state_my_get.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Prints the State object with the name passed as argument 4 | from the database hbtn_0e_6_usa 5 | """ 6 | 7 | if __name__ == "__main__": 8 | from sqlalchemy.orm import sessionmaker 9 | from sqlalchemy import create_engine 10 | from model_state import Base, State 11 | from sys import argv 12 | import re 13 | 14 | if (len(argv) != 5): 15 | print('Use: username, password, database_name, state') 16 | exit(1) 17 | 18 | searched = ' '.join(argv[4].split()) 19 | 20 | if (re.search('^[a-zA-Z ]+$', searched) is None): 21 | print('Enter a valid name state (example: Arizona)') 22 | exit(1) 23 | 24 | engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}'.format( 25 | argv[1], argv[2], argv[3]), pool_pre_ping=True) 26 | Base.metadata.create_all(engine) 27 | 28 | Session = sessionmaker(bind=engine) 29 | session = Session() 30 | 31 | states = session.query(State).where(State.name == searched) 32 | 33 | if (states.count() == 0): 34 | print('Not found') 35 | else: 36 | for row in states: 37 | print(row.id) 38 | session.close() 39 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/100-relationship_states_cities.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Creates the State "California" with the City "San Francisco" from a DB 4 | """ 5 | import sys 6 | from relationship_state import Base, State 7 | from relationship_city import City 8 | from sqlalchemy import create_engine 9 | from sqlalchemy.orm import sessionmaker 10 | 11 | 12 | if __name__ == '__main__': 13 | engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}'. 14 | format(sys.argv[1], sys.argv[2], sys.argv[3]), 15 | pool_pre_ping=True) 16 | Base.metadata.create_all(engine) 17 | 18 | Session = sessionmaker(bind=engine) 19 | session = Session() 20 | 21 | newState = State(name='California') 22 | newCity = City(name='San Francisco') 23 | newState.cities.append(newCity) 24 | 25 | session.add(newState) 26 | session.add(newCity) 27 | session.commit() 28 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/101-relationship_states_cities_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Lists all State objects and corresponding City objects contained in the DB 4 | """ 5 | import sys 6 | from relationship_state import Base, State 7 | from relationship_city import City 8 | from sqlalchemy import create_engine 9 | from sqlalchemy.orm import sessionmaker 10 | 11 | 12 | if __name__ == '__main__': 13 | engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}'. 14 | format(sys.argv[1], sys.argv[2], sys.argv[3]), 15 | pool_pre_ping=True) 16 | Base.metadata.create_all(engine) 17 | 18 | Session = sessionmaker(bind=engine) 19 | session = Session() 20 | 21 | st = session.query(State).outerjoin(City).order_by(State.id, City.id).all() 22 | 23 | for state in st: 24 | print("{}: {}".format(state.id, state.name)) 25 | for city in state.cities: 26 | print(" {}: {}".format(city.id, city.name)) 27 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/102-relationship_cities_states_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Lists all City objects from the database hbtn_0e_101_usa 4 | """ 5 | import sys 6 | from relationship_state import Base, State 7 | from relationship_city import City 8 | from sqlalchemy import create_engine 9 | from sqlalchemy.orm import sessionmaker 10 | 11 | 12 | if __name__ == '__main__': 13 | engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}'. 14 | format(sys.argv[1], sys.argv[2], sys.argv[3]), 15 | pool_pre_ping=True) 16 | 17 | Session = sessionmaker(bind=engine) 18 | session = Session() 19 | 20 | st = session.query(State).join(City).order_by(City.id).all() 21 | 22 | for state in st: 23 | for city in state.cities: 24 | print("{}: {} -> {}".format(city.id, city.name, state.name)) 25 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/11-model_state_insert.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Adds the State object “Louisiana” to the database hbtn_0e_6_usa 4 | """ 5 | 6 | 7 | if __name__ == "__main__": 8 | from sqlalchemy.orm import sessionmaker 9 | from sqlalchemy import create_engine 10 | from model_state import Base, State 11 | from sys import argv 12 | 13 | if (len(argv) != 4): 14 | print('Use: username, password database_name') 15 | exit(1) 16 | 17 | engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}'.format( 18 | argv[1], argv[2], argv[3]), pool_pre_ping=True) 19 | Base.metadata.create_all(engine) 20 | 21 | Session = sessionmaker(bind=engine) 22 | session = Session() 23 | 24 | new_row = State(name='Louisiana') 25 | session.add(new_row) 26 | session.commit() 27 | 28 | states = session.query(State).where(State.name == 'Louisiana') 29 | 30 | for row in states: 31 | print(row.id) 32 | session.close() 33 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/12-model_state_update_id_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Changes the name of a State object from the database hbtn_0e_6_usa 4 | """ 5 | 6 | 7 | if __name__ == "__main__": 8 | from sqlalchemy.orm import sessionmaker 9 | from sqlalchemy import create_engine 10 | from model_state import Base, State 11 | from sys import argv 12 | 13 | if (len(argv) != 4): 14 | print('Use: username, password database_name') 15 | exit(1) 16 | 17 | engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}'.format( 18 | argv[1], argv[2], argv[3]), pool_pre_ping=True) 19 | Base.metadata.create_all(engine) 20 | 21 | Session = sessionmaker(bind=engine) 22 | session = Session() 23 | 24 | states = session.query(State).where(State.id == 2)\ 25 | .update({'name': 'New Mexico'}) 26 | session.commit() 27 | session.close() 28 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/13-model_state_delete_a.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Deletes all State objects with a name containing the letter a 4 | from the database hbtn_0e_6_usa 5 | """ 6 | 7 | 8 | if __name__ == "__main__": 9 | from sqlalchemy.orm import sessionmaker 10 | from sqlalchemy import create_engine 11 | from model_state import Base, State 12 | from sys import argv 13 | 14 | engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}'.format( 15 | argv[1], argv[2], argv[3]), pool_pre_ping=True) 16 | 17 | Base.metadata.create_all(engine) 18 | Session = sessionmaker(bind=engine) 19 | session = Session() 20 | 21 | states = session.query(State).filter(State.name.like('%a%')) 22 | 23 | for state in states: 24 | session.delete(state) 25 | 26 | session.commit() 27 | session.close() 28 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/14-model_city_fetch_by_state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Prints all City objects from the database hbtn_0e_14_usa 4 | """ 5 | 6 | if __name__ == "__main__": 7 | from sqlalchemy.orm import sessionmaker 8 | from sqlalchemy import create_engine 9 | from model_state import Base, State 10 | from model_city import City 11 | from sys import argv 12 | 13 | if (len(argv) != 4): 14 | print('Use: username, password database_name') 15 | exit(1) 16 | 17 | engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}'.format( 18 | argv[1], argv[2], argv[3]), pool_pre_ping=True) 19 | Base.metadata.create_all(engine) 20 | 21 | Session = sessionmaker(bind=engine) 22 | session = Session() 23 | 24 | result = session.query(State, City.id, City).filter( 25 | City.state_id == State.id).order_by(City.id).all() 26 | 27 | for row in result: 28 | print(f'{row.State.name}: ({row.id}) {row.City.name}') 29 | session.close() 30 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/2-my_filter_states.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Displays all values in the states table of 4 | hbtn_0e_0_usa where name matches the argument. 5 | """ 6 | 7 | if __name__ == '__main__': 8 | from sys import argv 9 | import MySQLdb as mysql 10 | 11 | try: 12 | db = mysql.connect(host='localhost', port=3306, user=argv[1], 13 | passwd=argv[2], db=argv[3]) 14 | except Exception: 15 | print('Failed to connect to the database') 16 | exit(0) 17 | 18 | searched = argv[4] 19 | 20 | cursor = db.cursor() 21 | 22 | cursor.execute("SELECT * FROM states WHERE name = BINARY '{:s}' \ 23 | ORDER BY id ASC;".format(searched)) 24 | 25 | result_query = cursor.fetchall() 26 | 27 | for row in result_query: 28 | print(row) 29 | 30 | cursor.close() 31 | db.close() 32 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/3-my_safe_filter_states.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Displays all values in the states table of 4 | hbtn_0e_0_usa where name matches the argument. 5 | (Safe from SQL Injection) 6 | """ 7 | 8 | if __name__ == '__main__': 9 | from sys import argv 10 | import MySQLdb as mysql 11 | import re 12 | 13 | if (len(argv) != 5): 14 | print('Use: username, password, database name, state name') 15 | exit(1) 16 | 17 | searched = ' '.join(argv[4].split()) 18 | 19 | if (re.search('^[a-zA-Z ]+$', searched) is None): 20 | print('Enter a valid name state (example: Arizona)') 21 | exit(1) 22 | 23 | try: 24 | db = mysql.connect(host='localhost', port=3306, user=argv[1], 25 | passwd=argv[2], db=argv[3]) 26 | except Exception: 27 | print('Failed to connect to the database') 28 | exit(0) 29 | 30 | cursor = db.cursor() 31 | 32 | cursor.execute("SELECT * FROM states \ 33 | WHERE name = '{:s}' ORDER BY id ASC;".format(searched)) 34 | 35 | result_query = cursor.fetchall() 36 | 37 | for row in result_query: 38 | print(row) 39 | 40 | cursor.close() 41 | db.close() 42 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/4-cities_by_state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Lists all cities from the database hbtn_0e_4_usa""" 3 | 4 | if __name__ == '__main__': 5 | from sys import argv 6 | import MySQLdb as mysql 7 | 8 | if (len(argv) != 4): 9 | print('Use: username, password, database name') 10 | exit(1) 11 | 12 | try: 13 | db = mysql.connect(host='localhost', port=3306, user=argv[1], 14 | passwd=argv[2], db=argv[3]) 15 | except Exception: 16 | print('Failed to connect to the database') 17 | exit(0) 18 | 19 | cursor = db.cursor() 20 | 21 | cursor.execute("""SELECT c.id, c.name, s.name FROM cities as c 22 | INNER JOIN states as s 23 | ON c.state_id = s.id 24 | ORDER BY c.id ASC;""") 25 | 26 | result_query = cursor.fetchall() 27 | 28 | for row in result_query: 29 | print(row) 30 | 31 | cursor.close() 32 | db.close() 33 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/5-filter_cities.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Takes in the name of a state as an argument and 4 | lists all cities of that state, using 5 | the database hbtn_0e_4_usa 6 | """ 7 | 8 | if __name__ == '__main__': 9 | from sys import argv 10 | import MySQLdb as mysql 11 | import re 12 | 13 | if (len(argv) != 5): 14 | print('Use: username, password, database name, state name') 15 | exit(1) 16 | 17 | state_name = ' '.join(argv[4].split()) 18 | 19 | if (re.search('^[a-zA-Z ]+$', state_name) is None): 20 | print('Enter a valid name state (example: California)') 21 | exit(1) 22 | 23 | try: 24 | db = mysql.connect(host='localhost', port=3306, user=argv[1], 25 | passwd=argv[2], db=argv[3]) 26 | except Exception: 27 | print('Failed to connect to the database') 28 | exit(0) 29 | 30 | cursor = db.cursor() 31 | 32 | cuantity = cursor.execute("""SELECT c.name FROM cities as c 33 | INNER JOIN states as s 34 | ON c.state_id = s.id 35 | WHERE s.name = '{:s}' 36 | ORDER BY c.id ASC;""".format(state_name)) 37 | 38 | result_query = cursor.fetchall() 39 | 40 | final = [] 41 | 42 | for i in range(cuantity): 43 | final.append(result_query[i][0]) 44 | 45 | print(', '.join(final)) 46 | 47 | cursor.close() 48 | db.close() 49 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/7-model_state_fetch_all.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Lists all State objects from the database hbtn_0e_6_usa 4 | """ 5 | 6 | if __name__ == "__main__": 7 | from sqlalchemy.orm import sessionmaker 8 | from sqlalchemy import create_engine 9 | from model_state import Base, State 10 | from sys import argv 11 | 12 | if (len(argv) != 4): 13 | print('Use: username, password database_name') 14 | exit(1) 15 | 16 | engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}'.format( 17 | argv[1], argv[2], argv[3]), pool_pre_ping=True) 18 | Base.metadata.create_all(engine) 19 | 20 | Session = sessionmaker(bind=engine) 21 | session = Session() 22 | 23 | states = session.query(State).order_by(State.id) 24 | 25 | for row in states: 26 | print(f'{row.id}: {row.name}') 27 | session.close() 28 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/8-model_state_fetch_first.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Prints the first State object from the database hbtn_0e_6_usa 4 | """ 5 | 6 | if __name__ == "__main__": 7 | from sqlalchemy.orm import sessionmaker 8 | from sqlalchemy import create_engine 9 | from model_state import Base, State 10 | from sys import argv 11 | 12 | if (len(argv) != 4): 13 | print('Use: username, password database_name') 14 | exit(1) 15 | 16 | engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}'.format( 17 | argv[1], argv[2], argv[3]), pool_pre_ping=True) 18 | Base.metadata.create_all(engine) 19 | 20 | Session = sessionmaker(bind=engine) 21 | session = Session() 22 | 23 | state = session.query(State).order_by(State.id).first() 24 | 25 | if (state is None): 26 | print('Nothing') 27 | else: 28 | print('{:d}: {:s}'.format(state.id, state.name)) 29 | session.close() 30 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/9-model_state_filter_a.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Lists all State objects that contain the letter a 4 | from the database hbtn_0e_6_usa 5 | """ 6 | 7 | if __name__ == "__main__": 8 | from sqlalchemy.orm import sessionmaker 9 | from sqlalchemy import create_engine 10 | from model_state import Base, State 11 | from sys import argv 12 | 13 | if (len(argv) != 4): 14 | print('Use: username, password database_name') 15 | exit(1) 16 | 17 | engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}'.format( 18 | argv[1], argv[2], argv[3]), pool_pre_ping=True) 19 | Base.metadata.create_all(engine) 20 | 21 | Session = sessionmaker(bind=engine) 22 | session = Session() 23 | 24 | states = session.query(State).filter(State.name.like('%a%')).order_by( 25 | State.id) 26 | 27 | for row in states: 28 | print(f'{row.id}: {row.name}') 29 | session.close() 30 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/model_city.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Contains the class definition of a City 4 | """ 5 | 6 | from sqlalchemy import Column, Integer, String, ForeignKey 7 | from model_state import Base 8 | 9 | 10 | class City(Base): 11 | """ 12 | Representation of the table cities 13 | """ 14 | __tablename__ = 'cities' 15 | 16 | id = Column(Integer, primary_key=True) 17 | name = Column(String(128), nullable=False) 18 | state_id = Column(Integer, ForeignKey('states.id'), nullable=False) 19 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/model_state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Contains the class definition of a State 4 | """ 5 | 6 | from sqlalchemy import Column, Integer, String 7 | from sqlalchemy.ext.declarative import declarative_base 8 | 9 | Base = declarative_base() 10 | 11 | 12 | class State(Base): 13 | """ 14 | Representation of the table states 15 | """ 16 | __tablename__ = 'states' 17 | 18 | id = Column(Integer, primary_key=True) 19 | name = Column(String(128), nullable=False) 20 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/relationship_city.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Contains the class definition of a City 4 | """ 5 | from relationship_state import Base 6 | from sqlalchemy import Column, Integer, String, ForeignKey 7 | from sqlalchemy.ext.declarative import declarative_base 8 | 9 | 10 | class City(Base): 11 | """ 12 | Class that defines each city 13 | """ 14 | __tablename__ = 'cities' 15 | id = Column(Integer, unique=True, nullable=False, primary_key=True) 16 | name = Column(String(128), nullable=False) 17 | state_id = Column(Integer, ForeignKey("states.id"), nullable=False) 18 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/relationship_state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Contains State class and Base, an instance of declarative_base() 4 | """ 5 | from sqlalchemy import Column, Integer, String, MetaData 6 | from sqlalchemy.ext.declarative import declarative_base 7 | from sqlalchemy.orm import relationship 8 | 9 | mymetadata = MetaData() 10 | Base = declarative_base(metadata=mymetadata) 11 | 12 | 13 | class State(Base): 14 | """ 15 | Class with id and name attributes of each state 16 | """ 17 | __tablename__ = 'states' 18 | id = Column(Integer, unique=True, nullable=False, primary_key=True) 19 | name = Column(String(128), nullable=False) 20 | cities = relationship("City", backref="states") 21 | -------------------------------------------------------------------------------- /0x10-python-network_0/0-body_size.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Sends a request to that URL, and displays the size of the body of the response 3 | curl -s "${1}" | wc -c 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/1-body.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Sends a GET request to the URL, and displays the body of the response 3 | curl -s -L "${1}" 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/100-status_code.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Script that sends a request to a URL passed as an argument, and displays only the status code of the response 3 | curl -so /dev/null -w "%{http_code}" "$1" 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/101-post_json.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Script that sends a JSON POST request to a URL passed as the first argument, and displays the body of the response 3 | curl -s "$1" -d "@$2" -X POST -H "Content-Type: application/json" 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/102-catch_me.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Script that makes a request to causes an specific response 3 | curl -sL 0.0.0.0:5000/catch_me_3 -X PUT -H "Origin:HolbertonSchool" 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/2-delete.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Sends a DELETE request to the URL passed as the first argument and displays the body of the respons 3 | curl -s -X DELETE "${1}" 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/3-methods.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Displays all HTTP methods the server will accept. 3 | curl -s -I "${1}" | grep "^Allow: .*" | cut -d " " -f 2- 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/4-header.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Sends a GET request to the URL, and displays the body of the response 3 | curl -sH "X-HolbertonSchool-User-Id: 98" "${1}" 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/5-post_params.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Sends a POST request to the passed URL, and displays the body of the response 3 | curl -s -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 | """Algorithms for list of integers.""" 3 | 4 | 5 | def find_peak(list_of_integers): 6 | """Finds a peak in a list of unsorted integers.""" 7 | if list_of_integers: 8 | list_of_integers.sort(reverse=True) 9 | return list_of_integers[0] 10 | -------------------------------------------------------------------------------- /0x10-python-network_0/6-peak.txt: -------------------------------------------------------------------------------- 1 | O(log(n)) 2 | 3 | -------------------------------------------------------------------------------- /0x10-python-network_0/README.md: -------------------------------------------------------------------------------- 1 | ## 0x10. Python - Network #0 2 | 3 | 4 | **0-body_size.sh:** Writing a Bash script that takes in a URL, sends a request to that URL, and displays the size of the body of the response 5 | The size must be displayed in bytes. 6 | You have to use curl. 7 | 8 | 9 | **1-body.sh:** Writing a Bash script that takes in a URL, sends a GET request to the URL, and displays the body of the response. 10 | Display only body of a 200 status code response. 11 | You have to use curl. 12 | 13 | 14 | **2-delete.sh:** Writing a Bash script that sends a DELETE request to the URL passed as the first argument and displays the body of the response. 15 | You have to use curl. 16 | 17 | 18 | **3-methods.sh:** Writing a Bash script that takes in a URL and displays all HTTP methods the server will accept. 19 | You have to use curl. 20 | 21 | 22 | **4-header.sh:** Writing a Bash script that takes in a URL as an argument, sends a GET request to the URL, and displays the body of the response. 23 | A header variable X-School-User-Id must be sent with the value 98. 24 | You have to use curl. 25 | 26 | 27 | **5-post_params.sh:** Writing a Bash script that takes in a URL, sends a POST request to the passed URL, and displays the body of the response. 28 | A variable email must be sent with the value test@gmail.com. 29 | A variable subject must be sent with the value I will always be here for PLD. 30 | You have to use curl. 31 | 32 | 33 | **6-peak.py, 6-peak.txt:** Technical interview preparation: 34 | You are not allowed to google anything 35 | Whiteboard first 36 | Writing a function that finds a peak in a list of unsorted integers. 37 | Prototype: def find_peak(list_of_integers): 38 | You are not allowed to import any module. 39 | Your algorithm must have the lowest complexity (hint: you don’t need to go through all numbers to find a peak). 40 | 6-peak.py must contain the function. 41 | 6-peak.txt must contain the complexity of your algorithm: O(log(n)), O(n), O(nlog(n)) or O(n2). 42 | Note: there may be more than one peak in the list. 43 | 44 | 45 | **100-status_code.sh:** Writing a Bash script that sends a request to a URL passed as an argument, and displays only the status code of the response. 46 | You are not allowed to use any pipe, redirection, etc. 47 | You are not allowed to use ; and &&. 48 | You have to use curl. 49 | 50 | 51 | **101-post_json.sh:** Writing a Bash script that sends a JSON POST request to a URL passed as the first argument, and displays the body of the response. 52 | Your script must send a POST request with the contents of a file, passed with the filename as the second argument of the script, in the body of the request 53 | You have to use curl. 54 | 55 | 56 | **102-catch_me.sh:** Writing a Bash script that makes a request to 0.0.0.0:5000/catch_me that causes the server to respond with a message containing You got me!, in the body of the response. 57 | You have to use curl. 58 | You are not allow to use echo, cat, etc. to display the final result. 59 | 60 | 61 | 62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /0x11-python-network_1/0-hbtn_status.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Fetches https://alx-intranet.hbtn.io/status""" 3 | import urllib.request 4 | 5 | 6 | if __name__ == "__main__": 7 | request = urllib.request.Request("https://alx-intranet.hbtn.io/status") 8 | with urllib.request.urlopen(request) as response: 9 | body = response.read() 10 | print("Body response:") 11 | print("\t- type: {}".format(type(body))) 12 | print("\t- content: {}".format(body)) 13 | print("\t- utf8 content: {}".format(body.decode("utf-8"))) 14 | -------------------------------------------------------------------------------- /0x11-python-network_1/1-hbtn_header.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Displays the value of the X-Request-Id variable 4 | found in the header of the response. 5 | """ 6 | 7 | 8 | if __name__ == "__main__": 9 | import sys 10 | import urllib.request 11 | 12 | with urllib.request.urlopen(sys.argv[1]) as response: 13 | print(response.headers["X-Request-Id"]) 14 | -------------------------------------------------------------------------------- /0x11-python-network_1/10-my_github.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Takes your GitHub credentials (username and password) and uses the GitHub API 4 | to display your id 5 | """ 6 | 7 | if __name__ == '__main__': 8 | from requests import get 9 | from sys import argv 10 | 11 | username = argv[1] 12 | password = argv[2] 13 | 14 | URL = "https://api.github.com/user" 15 | response = get(URL, auth=(username, password)) 16 | json = response.json() 17 | 18 | print(json.get('id')) 19 | -------------------------------------------------------------------------------- /0x11-python-network_1/100-github_commits.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Please list 10 commits (from the most recent to oldest) of the repository 4 | “rails” by the user “rails” 5 | You must use the GitHub API, here is the documentation 6 | https://developer.github.com/v3/repos/commits/ 7 | Print all commits by: `: ` (one by line) 8 | """ 9 | 10 | 11 | if __name__ == '__main__': 12 | from requests import get 13 | from sys import argv 14 | 15 | repo = argv[1] 16 | owner = argv[2] 17 | i = 0 18 | 19 | URL = "https://api.github.com/repos/{}/{}/commits".format(owner, repo) 20 | 21 | response = get(URL) 22 | json = response.json() 23 | 24 | for element in json: 25 | if i > 9: 26 | break 27 | sha = element.get('sha') 28 | author = element.get('commit').get('author').get('name') 29 | print("{}: {}".format(sha, author)) 30 | i += 1 31 | -------------------------------------------------------------------------------- /0x11-python-network_1/2-post_email.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Sends a POST request to the passed URL with the email as a parameter, 4 | and displays the body of the response (decoded in utf-8) 5 | """ 6 | 7 | if __name__ == '__main__': 8 | import urllib.request 9 | import urllib.parse 10 | import sys 11 | 12 | argv = sys.argv 13 | url = argv[1] 14 | email = argv[2] 15 | DATA = urllib.parse.urlencode({"email": email}) 16 | DATA = DATA.encode('ascii') 17 | 18 | with urllib.request.urlopen(url, DATA) as response: 19 | print(response.read().decode('utf-8')) 20 | -------------------------------------------------------------------------------- /0x11-python-network_1/3-error_code.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Sends a request to the URL and displays the body of the response 4 | (decoded in utf-8). 5 | """ 6 | 7 | 8 | if __name__ == '__main__': 9 | import sys 10 | from urllib import request, error 11 | 12 | argv = sys.argv 13 | url = argv[1] 14 | try: 15 | with request.urlopen(url) as response: 16 | print(response.read().decode('utf-8')) 17 | except error.HTTPError as err: 18 | print("Error code: {}".format(err.status)) 19 | -------------------------------------------------------------------------------- /0x11-python-network_1/4-hbtn_status.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Python script that fetches an URL with requests package 4 | """ 5 | import requests 6 | 7 | 8 | if __name__ == "__main__": 9 | r = requests.get('https://alx-intranet.hbtn.io/status') 10 | t = r.text 11 | print('Body response:\n\t- type: {}\n\t- content: {}'.format(type(t), t)) 12 | -------------------------------------------------------------------------------- /0x11-python-network_1/5-hbtn_header.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Sends a request to the URL and displays the value of the variable X-Request-Id 4 | in the response header""" 5 | 6 | if __name__ == '__main__': 7 | from requests import get 8 | from sys import argv 9 | 10 | res = get(argv[1]) 11 | print(res.headers.get('X-Request-Id')) 12 | -------------------------------------------------------------------------------- /0x11-python-network_1/6-post_email.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Sends a POST request to the passed URL with the email as a parameter, 4 | and finally displays the body of the response.""" 5 | 6 | 7 | if __name__ == '__main__': 8 | from sys import argv 9 | from requests import post 10 | 11 | url = argv[1] 12 | email = argv[2] 13 | res = post(url, {'email': email}) 14 | print(res.text) 15 | -------------------------------------------------------------------------------- /0x11-python-network_1/7-error_code.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Sends a request to the URL and displays the body of the response.""" 3 | 4 | 5 | if __name__ == '__main__': 6 | from sys import argv 7 | from requests import get 8 | 9 | url = argv[1] 10 | 11 | response = get(url) 12 | ERR_TXT = 'Error code: {}' 13 | status = response.status_code 14 | print(ERR_TXT.format(status) if (status >= 400) else response.text) 15 | -------------------------------------------------------------------------------- /0x11-python-network_1/8-json_api.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Sends a request to the URL and displays the body of the response.""" 3 | 4 | 5 | if __name__ == '__main__': 6 | from requests import post 7 | from sys import argv 8 | 9 | URL = 'http://0.0.0.0:5000/search_user' 10 | data = {'q': argv[1] if len(argv) >= 2 else ""} 11 | response = post(URL, data) 12 | 13 | type_res = response.headers['content-type'] 14 | 15 | if type_res == 'application/json': 16 | result = response.json() 17 | _id = result.get('id') 18 | name = result.get('name') 19 | if (result != {} and _id and name): 20 | print("[{}] {}".format(_id, name)) 21 | else: 22 | print('No result') 23 | else: 24 | print('Not a valid JSON') 25 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/0-javascript_is_amazing.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | const myVar = 'JavaScript is amazing'; 4 | console.log(myVar); 5 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/1-multi_languages.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | console.log('C is fun'); 4 | console.log('Python is cool'); 5 | console.log('JavaScript is amazing'); 6 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/10-factorial.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | const { argv } = require('process'); 4 | 5 | function factorial (num) { 6 | if (num <= 1) return (1); 7 | 8 | return (factorial(num - 1) * num); 9 | } 10 | 11 | const parsed = parseInt(argv[2]); 12 | console.log(Number.isNaN(parsed) ? 1 : factorial(parsed)); 13 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/100-let_me_const.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | myVar = 333; 4 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/101-call_me_moby.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | const callMeMoby = (x, theFunction) => { 4 | for (; x > 0; x--) { 5 | theFunction(); 6 | } 7 | }; 8 | 9 | module.exports = { callMeMoby }; 10 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/102-add_me_maybe.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | const addMeMaybe = (number, theFunction) => { 4 | theFunction(number + 1); 5 | }; 6 | 7 | module.exports = { addMeMaybe }; 8 | -------------------------------------------------------------------------------- /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 | 8 | myObject.incr = () => myObject.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 | 3 | const { argv } = require('process'); 4 | const args = argv.slice(2); 5 | let result = 0; 6 | let finalArray = []; 7 | 8 | if (args.length > 1) { 9 | finalArray = [...new Set(args.map((e) => parseInt(e)).sort((a, b) => b - a))]; 10 | result = finalArray.length > 1 ? finalArray[1] : finalArray[0]; 11 | } 12 | 13 | console.log(result); 14 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/12-object.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | const myObject = { 4 | type: 'object', 5 | value: 12 6 | }; 7 | console.log(myObject); 8 | 9 | myObject.value = 89; 10 | 11 | console.log(myObject); 12 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/13-add.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | const add = (a, b) => a + b; 4 | 5 | module.exports = { add }; 6 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/2-arguments.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | const { argv } = require('process'); 4 | const argc = argv.length; 5 | 6 | if (argc === 2) { 7 | console.log('No argument'); 8 | } else if (argc === 3) { 9 | console.log('Argument found'); 10 | } else { 11 | console.log('Arguments found'); 12 | } 13 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/3-value_argument.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const { argv } = require('process'); 3 | let len = 0; 4 | 5 | argv.forEach(() => len++); 6 | 7 | console.log(len === 2 ? 'No argument' : argv[2]); 8 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/4-concat.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | const { argv } = require('process'); 4 | 5 | console.log(`${argv[2]} is ${argv[3]}`); 6 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/5-to_integer.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | const { argv } = require('process'); 4 | const num = parseInt(argv[2]); 5 | 6 | console.log(Number.isInteger(num) ? `My number: ${num}` : 'Not a number'); 7 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/6-multi_languages_loop.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | // ['C is fun', 'Python is cool', 'JavaScript is amazing'].forEach((e) => console.log(e)); 4 | 5 | const msg = ['C is fun', 'Python is cool', 'JavaScript is amazing']; 6 | 7 | msg.forEach((element) => console.log(element)); 8 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/7-multi_c.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | const { argv } = require('process'); 4 | const num = parseInt(argv[2]); 5 | const printC = (cuantity) => { 6 | for (; cuantity > 0; cuantity--) console.log('C is fun'); 7 | }; 8 | 9 | Number.isInteger(num) ? printC(num) : console.log('Missing number of occurrences'); 10 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/8-square.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | const { argv } = require('process'); 4 | const size = parseInt(argv[2]); 5 | 6 | const printSquare = (size) => { 7 | const row = 'X'.repeat(size); 8 | for (let i = 0; i < size; i++) console.log(row); 9 | }; 10 | 11 | Number.isInteger(size) ? printSquare(size) : console.log('Missing size'); 12 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/9-add.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | function add (a, b) { 4 | return (a + b); 5 | } 6 | 7 | const { argv } = require('process'); 8 | const num1 = parseInt(argv[2]); 9 | const num2 = parseInt(argv[3]); 10 | 11 | console.log(add(num1, num2)); 12 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/0-rectangle.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | class Rectangle {} 4 | 5 | module.exports = Rectangle; 6 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/1-rectangle.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | class Rectangle { 4 | constructor (w, h) { 5 | this.width = w; 6 | this.height = h; 7 | } 8 | } 9 | 10 | module.exports = Rectangle; 11 | -------------------------------------------------------------------------------- /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 | 3 | const { list } = require('./100-data'); 4 | 5 | console.log(list); 6 | console.log(list.map((element, idx) => element * idx)); 7 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/101-sorted.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | const { dict } = require('./101-data'); 4 | 5 | const convertedArr = Object.entries(dict); 6 | 7 | const newObj = {}; 8 | 9 | convertedArr.forEach(element => { 10 | newObj[element[1]] ? newObj[element[1]].push(element[0]) : newObj[element[1]] = [element[0]]; 11 | }); 12 | 13 | console.log(newObj); 14 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/102-concat.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | const fs = require('fs').promises; 4 | const { argv } = require('process'); 5 | 6 | fs.readFile(argv[2], 'utf8') 7 | .then(data => fs.writeFile(argv[4], data, 'utf8')) 8 | .catch(err => console.error(err)); 9 | 10 | fs.readFile(argv[3], 'utf8') 11 | .then(data => fs.writeFile(argv[4], data, { flag: 'a' }, 'utf8')) 12 | .catch(err => console.error(err)); 13 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/2-rectangle.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | class Rectangle { 4 | constructor (w, h) { 5 | if (w > 0 && h > 0) { 6 | this.width = w; 7 | this.height = h; 8 | } 9 | } 10 | } 11 | 12 | module.exports = Rectangle; 13 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/3-rectangle.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | class Rectangle { 4 | constructor (w, h) { 5 | if (w > 0 && h > 0) { 6 | this.width = w; 7 | this.height = h; 8 | } 9 | } 10 | 11 | print () { 12 | for (let i = 0; i < this.height; i++) { 13 | console.log('X'.repeat(this.width)); 14 | } 15 | } 16 | } 17 | 18 | module.exports = Rectangle; 19 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/4-rectangle.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | class Rectangle { 4 | constructor (w, h) { 5 | if (w > 0 && h > 0) { 6 | this.width = w; 7 | this.height = h; 8 | } 9 | } 10 | 11 | print () { 12 | for (let i = 0; i < this.height; i++) { 13 | console.log('X'.repeat(this.width)); 14 | } 15 | } 16 | 17 | rotate () { 18 | const tmp = this.height; 19 | this.height = this.width; 20 | this.width = tmp; 21 | } 22 | 23 | double () { 24 | this.height *= 2; 25 | this.width *= 2; 26 | } 27 | } 28 | 29 | module.exports = Rectangle; 30 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/5-square.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | const Rectangle = require('./4-rectangle'); 4 | 5 | class Square extends Rectangle { 6 | constructor (size) { 7 | super(size, size); 8 | } 9 | } 10 | 11 | module.exports = Square; 12 | -------------------------------------------------------------------------------- /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 | 3 | const nbOccurences = (list, searchElement) => list.filter((element) => searchElement === element).length; 4 | 5 | module.exports = { nbOccurences }; 6 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/8-esrever.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | const esrever = (list) => { 4 | const reversedArray = []; 5 | list.forEach((element) => reversedArray.unshift(element)); 6 | return (reversedArray); 7 | }; 8 | 9 | module.exports = { esrever }; 10 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/9-logme.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | let cuantity = 0; 4 | 5 | const logMe = (item) => { 6 | console.log(`${cuantity}: ${item}`); 7 | cuantity++; 8 | }; 9 | 10 | module.exports = { logMe }; 11 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/0-readme.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | // Read from file 3 | 4 | const filesys = require('fs'); 5 | filesys.readFile(process.argv[2], 'utf-8', 6 | function (err, data) { 7 | if (err) { 8 | console.log(err); 9 | return; 10 | } 11 | console.log(data); 12 | }); 13 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/1-writeme.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | const fs = require('fs'); 4 | 5 | fs.writeFile(process.argv[2], process.argv[3], 'utf-8', 6 | function (err) { 7 | if (err) { 8 | console.log(err); 9 | } 10 | }); 11 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/100-starwars_characters.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | const request = require('request'); 4 | const id = process.argv[2]; 5 | const url = `https://swapi-api.alx-tools.com/api/films/${id}`; 6 | 7 | request.get(url, (error, response, body) => { 8 | if (error) { 9 | console.log(error); 10 | } else { 11 | const content = JSON.parse(body); 12 | const characters = content.characters; 13 | // console.log(characters); 14 | for (const character of characters) { 15 | request.get(character, (error, response, body) => { 16 | if (error) { 17 | console.log(error); 18 | } else { 19 | const names = JSON.parse(body); 20 | console.log(names.name); 21 | } 22 | }); 23 | } 24 | } 25 | }); 26 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/101-starwars_characters.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | const request = require('request'); 4 | const id = process.argv[2]; 5 | const url = `https://swapi-api.alx-tools.com/api/films/${id}`; 6 | 7 | request.get(url, (error, response, body) => { 8 | if (error) { 9 | console.log(error); 10 | } else { 11 | const content = JSON.parse(body); 12 | const characters = content.characters; 13 | // console.log(characters); 14 | for (const character of characters) { 15 | request.get(character, (error, response, body) => { 16 | if (error) { 17 | console.log(error); 18 | } else { 19 | const names = JSON.parse(body); 20 | console.log(names.name); 21 | } 22 | }); 23 | } 24 | } 25 | }); 26 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/2-statuscode.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | // Status Of Get request 3 | 4 | const request = require('request'); 5 | const url = process.argv[2]; 6 | request.get(url, function (error, response) { 7 | if (error) { 8 | console.log(error); 9 | } else { 10 | console.log('code:' + ' ' + response.statusCode); 11 | } 12 | }); 13 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/3-starwars_title.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | // Star Wars 3 | 4 | const request = require('request'); 5 | const url = 'https://swapi-api.alx-tools.com/api/films/' + process.argv[2]; 6 | 7 | request.get(url, (error, response, body) => { 8 | if (error) { 9 | console.log(error); 10 | } else { 11 | const content = JSON.parse(body); 12 | console.log(content.title); 13 | } 14 | }); 15 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/4-starwars_count.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | // Number of films with the given character ID 3 | const request = require('request'); 4 | let num = 0; 5 | 6 | request.get(process.argv[2], (error, response, body) => { 7 | if (error) { 8 | console.log(error); 9 | } else { 10 | const content = JSON.parse(body); 11 | content.results.forEach((film) => { 12 | film.characters.forEach((character) => { 13 | if (character.includes(18)) { 14 | num += 1; 15 | } 16 | }); 17 | }); 18 | console.log(num); 19 | } 20 | }); 21 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/5-request_store.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | // lorem ipsum 3 | 4 | const request = require('request'); 5 | const fs = require('fs'); 6 | 7 | request.get(process.argv[2], (error, response, body) => { 8 | if (error) { 9 | console.log(error); 10 | } else { 11 | fs.writeFile(process.argv[3], body, 'utf-8', (error) => { 12 | if (error) { 13 | console.log(error); 14 | } 15 | }); 16 | } 17 | }); 18 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/6-completed_tasks.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | // web scrapper 3 | 4 | const request = require('request'); 5 | 6 | request.get(process.argv[2], { json: true }, (error, response, body) => { 7 | if (error) { 8 | console.log(error); 9 | return; 10 | } 11 | 12 | const tasksCompleted = {}; 13 | body.forEach((todo) => { 14 | if (todo.completed) { 15 | if (!tasksCompleted[todo.userId]) { 16 | tasksCompleted[todo.userId] = 1; 17 | } else { 18 | tasksCompleted[todo.userId] += 1; 19 | } 20 | } 21 | }); 22 | console.log(tasksCompleted); 23 | }); 24 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/README.md: -------------------------------------------------------------------------------- 1 | # Web Scrapping 2 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/0-script.js: -------------------------------------------------------------------------------- 1 | // Update text color of the HTML tag HEADER to red 2 | 3 | document.querySelector('head').style.color = '#FF0000'; 4 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/1-script.js: -------------------------------------------------------------------------------- 1 | // Use jQuery API to change color of header tag to red 2 | 3 | $('header').css('color', '#FF0000'); 4 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/2-script.js: -------------------------------------------------------------------------------- 1 | // Uses jQuery API to change color of div#red_header to red on click 2 | 3 | $('div#red_header').click(function () { 4 | $('header').css('color', '#FF0000'); 5 | }); 6 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/3-script.js: -------------------------------------------------------------------------------- 1 | // Uses the jQuery API to add a red class to the header tag and turn it 2 | // red when the div#red_header tag is clicked 3 | 4 | $('div#red_header').click(function () { 5 | $('header').addClass('red'); 6 | }); 7 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/4-script.js: -------------------------------------------------------------------------------- 1 | // Toggles the class of HTML tag 'HEADER' when user clicks the 2 | // div#toggle_header tag 3 | 4 | $('div#toggle_header').click(function () { 5 | $('header').ToggleClass('red'); 6 | }); 7 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/5-script.js: -------------------------------------------------------------------------------- 1 | // Adds an LI element to the list when the div#add_item tag is clicked 2 | // The new element must be
  • Item
  • and must be added to UL.my_list 3 | 4 | $('div#add_item').click(function () { 5 | let element = '
  • Item
  • '; 6 | $('ul.my_list').append(element); 7 | }); 8 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/6-script.js: -------------------------------------------------------------------------------- 1 | // Updates the text of the header tag with a new header when the 2 | // DIV#update_header tag is clicked 3 | 4 | $('div#update_header').click(function () { 5 | $('header').text('New Header!!!'); 6 | }); 7 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/7-script.js: -------------------------------------------------------------------------------- 1 | // Fetches and replaces the name of the API data then replaces the name 2 | // of the character in the DIV#character tag text 3 | 4 | let url = 'https://swapi.co/api/people/5/?format=json'; 5 | $.get(url, function (data, stat) { 6 | $('div#character').text(data.name); 7 | }); 8 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/8-script.js: -------------------------------------------------------------------------------- 1 | // Queries an API and fetches all movie titles then inserts them 2 | // into the UL#list_movies tag 3 | 4 | let url = 'https://swapi.co/api/films/?format=json'; 5 | $.get(url, function (data) { 6 | let films = data.results; 7 | for (let film of films) { 8 | $('ul#list_movies').append(`
  • ${film.title}
  • `); 9 | } 10 | }); 11 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/9-script.js: -------------------------------------------------------------------------------- 1 | // Queries an API for wind speed in SF and replaces the text of the 2 | // div#sf_wind_speed tag with the speed 3 | 4 | let url = 'https://query.yahooapis.com/v1/public/yql?q=select%20wind%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22San%20Francisco%2C%20CA%22)&format=json'; 5 | $.get(url, function (data) { 6 | let wind = data.query.results.channel.wind.speed; 7 | $('div#sf_wind_speed').text(wind); 8 | }); 9 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/README.md: -------------------------------------------------------------------------------- 1 | # J Query 2 | -------------------------------------------------------------------------------- /0x1C-makefiles/0-Makefile: -------------------------------------------------------------------------------- 1 | all: main.c school.c 2 | gcc main.c school.c -o school 3 | -------------------------------------------------------------------------------- /0x1C-makefiles/1-Makefile: -------------------------------------------------------------------------------- 1 | CC = gcc 2 | SRC = main.c school.c 3 | 4 | all: $(SRC) 5 | $(CC) $(SRC) -o school 6 | -------------------------------------------------------------------------------- /0x1C-makefiles/100-Makefile: -------------------------------------------------------------------------------- 1 | CC = gcc 2 | SRC = main.c school.c 3 | OBJ = $(SRC:.c=.o) 4 | NAME = holberton 5 | CFLAGS = -Wall -Werror -Wextra -pedantic 6 | 7 | .PHONY: all clean oclean fclean re 8 | 9 | all: m.h $(OBJ) 10 | $(CC) $(OBJ) -o $(NAME) 11 | 12 | clean: 13 | $(RM) *~ $(NAME) 14 | 15 | oclean: 16 | $(RM) $(OBJ) 17 | 18 | fclean: clean oclean 19 | 20 | re: fclean all 21 | -------------------------------------------------------------------------------- /0x1C-makefiles/2-Makefile: -------------------------------------------------------------------------------- 1 | CC = gcc 2 | SRC = main.c school.c 3 | OBJ = $(SRC:.c=.o) 4 | NAME = school 5 | 6 | all: $(OBJ) 7 | $(CC) $(OBJ) -o $(NAME) 8 | -------------------------------------------------------------------------------- /0x1C-makefiles/3-Makefile: -------------------------------------------------------------------------------- 1 | CC = gcc 2 | SRC = main.c school.c 3 | OBJ = $(SRC:.c=.o) 4 | NAME = school 5 | RM = rm -f 6 | 7 | all: $(OBJ) 8 | $(CC) $(OBJ) -o $(NAME) 9 | 10 | clean: 11 | $(RM) *~ $(NAME) 12 | 13 | oclean: 14 | $(RM) $(OBJ) 15 | 16 | fclean: clean oclean 17 | 18 | re: fclean all 19 | -------------------------------------------------------------------------------- /0x1C-makefiles/4-Makefile: -------------------------------------------------------------------------------- 1 | CC = gcc 2 | SRC = main.c school.c 3 | OBJ = $(SRC:.c=.o) 4 | NAME = school 5 | RM = rm -f 6 | CFLAGS = -Wall -Werror -Wextra -pedantic 7 | 8 | all: $(OBJ) 9 | $(CC) $(CLFAGS) $(OBJ) -o $(NAME) 10 | 11 | clean: 12 | $(RM) *~ $(NAME) 13 | 14 | oclean: 15 | $(RM) $(OBJ) 16 | 17 | fclean: clean oclean 18 | 19 | re: fclean all 20 | -------------------------------------------------------------------------------- /0x1C-makefiles/README.md: -------------------------------------------------------------------------------- 1 | 0x1C. C - Makefiles 2 | -------------------------------------------------------------------------------- /0x1C-makefiles/m.h: -------------------------------------------------------------------------------- 1 | #ifndef __M_H__ 2 | #define __M_H__ 3 | 4 | #include 5 | #include 6 | 7 | void print_school(void); 8 | 9 | #endif 10 | -------------------------------------------------------------------------------- /0x1C-makefiles/main.c: -------------------------------------------------------------------------------- 1 | #include "m.h" 2 | 3 | /** 4 | * main - Entry point 5 | * 6 | * Return: Always 7 | */ 8 | int main(void) 9 | { 10 | print_school(); 11 | return (EXIT_SUCCESS); 12 | } 13 | /* Holberton */ 14 | -------------------------------------------------------------------------------- /0x1C-makefiles/school.c: -------------------------------------------------------------------------------- 1 | #include "m.h" 2 | 3 | /** 4 | * print_holberton - print the logo of Holberton 5 | * 6 | * Return: Nothing 7 | * 8 | * Learn more: https://www.holbertonschool.com 9 | */ 10 | void print_school(void) 11 | { 12 | printf("j#0000000000000000000000000000000000000\n"); 13 | printf("j#000000000000000000@Q**g00000000000000\n"); 14 | printf("j#0000000000000000*]++]4000000000000000\n"); 15 | printf("j#000000000000000k]++]++*N#000000000000\n"); 16 | printf("j#0000000000000*C+++]++]++]J*0000000000\n"); 17 | printf("j#00000000000@+]++qwwwp=]++++]*00000000\n"); 18 | printf("j#0000000000*+++]q#0000k+]+]++]4#000000\n"); 19 | printf("j#00000000*C+]+]w#0000*]+++]+]++0000000\n"); 20 | printf("j#0000we+]wW000***C++]++]+]++++40000000\n"); 21 | printf("j#000000000*C+]+]]+]++]++]++]+q#0000000\n"); 22 | printf("j#0000000*]+]+++++++]++]+++]+++J0000000\n"); 23 | printf("j#000000C++]=]+]+]+]++]++]+]+]+]=000000\n"); 24 | printf("j#00000k+]++]+++]+]++qwW0000000AgW00000\n"); 25 | printf("j#00000k++]++]+]+++qW#00000000000000000\n"); 26 | printf("j#00000A]++]++]++]++J**0000000000000000\n"); 27 | printf("j#000000e]++]+++]++]++]J000000000000000\n"); 28 | printf("j#0000000A]++]+]++]++]++000000000000000\n"); 29 | printf("j#000000000w]++]+]++]+qW#00000000000000\n"); 30 | printf("j#00000000000w]++++]*0##000000000000000\n"); 31 | printf("j#0000000000000Ag]+]++*0000000000000000\n"); 32 | printf("j#00000000000000000we]+]Q00000000000000\n"); 33 | printf("j#0000000000000@@+wgdA]+J00000000000000\n"); 34 | printf("j#0000000000000k?qwgdC=]4#0000000000000\n"); 35 | printf("j#00000000000000w]+]++qw#00000000000000\n"); 36 | printf("\"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"); 37 | } 38 | -------------------------------------------------------------------------------- /1-run_inline: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | python3 -c "$PYCODE" 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ALX Higher level programming 2 | * Python Hello world 3 | * If else conditions 4 | * Loops 5 | * Functions 6 | * Import Modules 7 | * Data Structures 8 | * Tuples 9 | * Lists 10 | --------------------------------------------------------------------------------