├── 0x00-python-hello_world ├── 0-run ├── 1-run_inline ├── 10-check_cycle.c ├── 100-write.py ├── 101-compile ├── 102-magic_calculation.py ├── 2-print.py ├── 3-print_number.py ├── 4-print_float.py ├── 5-print_string.py ├── 6-concat.py ├── 7-edges.py ├── 8-concat_edges.py ├── 9-easter_egg.py ├── README.md └── lists.h ├── 0x01-python-if_else_loops_functions ├── 0-positive_or_negative.py ├── 1-last_digit.py ├── 10-add.py ├── 100-print_tebahpla.py ├── 101-remove_char_at.py ├── 102-magic_calculation.py ├── 11-pow.py ├── 12-fizzbuzz.py ├── 13-insert_number.c ├── 2-print_alphabet.py ├── 3-print_alphabt.py ├── 4-print_hexa.py ├── 5-print_comb2.py ├── 6-print_comb3.py ├── 7-islower.py ├── 8-uppercase.py ├── 9-print_last_digit.py ├── README.md └── lists.h ├── 0x02-python-import_modules ├── 0-add.py ├── 0-import_add.py ├── 1-calculation.py ├── 100-my_calculator.py ├── 101-easy_print.py ├── 102-magic_calculation.py ├── 103-fast_alphabet.py ├── 2-args.py ├── 3-infinite_add.py ├── 4-hidden_discovery.py ├── 5-variable_load.py ├── README.md ├── add_0.py ├── calculator_1.py ├── easy_print_101.py ├── fast_alphabet_103.py └── variable_load_5.py ├── 0x03-python-data_structures ├── 0-print_list_integer.py ├── 1-element_at.py ├── 10-divisible_by_2.py ├── 100-print_python_list_info.c ├── 11-delete_at.py ├── 12-switch.py ├── 13-is_palindrome.c ├── 2-replace_in_list.py ├── 3-print_reversed_list_integer.py ├── 4-new_in_list.py ├── 5-no_c.py ├── 6-print_matrix_integer.py ├── 7-add_tuple.py ├── 8-multiple_returns.py ├── 9-max_integer.py ├── README.md └── lists.h ├── 0x04-python-more_data_structures ├── 0-square_matrix_simple.py ├── 1-search_replace.py ├── 10-best_score.py ├── 100-weight_average.py ├── 101-square_matrix_map.py ├── 102-complex_delete.py ├── 103-python.c ├── 11-multiply_list_map.py ├── 12-roman_to_int.py ├── 2-uniq_add.py ├── 3-common_elements.py ├── 4-only_diff_elements.py ├── 5-number_keys.py ├── 6-print_sorted_dictionary.py ├── 7-update_dictionary.py ├── 8-simple_delete.py ├── 9-multiply_by_2.py └── README.md ├── 0x05-python-exceptions ├── 0-safe_print_list.py ├── 1-safe_print_integer.py ├── 100-safe_print_integer_err.py ├── 101-safe_function.py ├── 102-magic_calculation.py ├── 103-python.c ├── 2-safe_print_list_integers.py ├── 3-safe_print_division.py ├── 4-list_division.py ├── 5-raise_exception.py ├── 6-raise_exception_msg.py └── README.md ├── 0x06-python-classes ├── 0-square.py ├── 1-square.py ├── 100-singly_linked_list.py ├── 101-square.py ├── 102-square.py ├── 103-magic_class.py ├── 2-square.py ├── 3-square.py ├── 4-square.py ├── 5-square.py ├── 6-square.py └── README.md ├── 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 ├── 0-rectangle.py ├── 1-rectangle.py ├── 101-nqueens.py ├── 2-rectangle.py ├── 3-rectangle.py ├── 4-rectangle.py ├── 5-rectangle.py ├── 6-rectangle.py ├── 7-rectangle.py ├── 8-rectangle.py ├── 9-rectangle.py ├── README.md └── tests │ ├── 0-main.py │ ├── 1-main.py │ ├── 2-main.py │ ├── 3-main.py │ ├── 4-main.py │ ├── 5-main.py │ ├── 6-main.py │ ├── 7-main.py │ ├── 8-main.py │ └── 9-main.py ├── 0x09-python-everything_is_object ├── 0-answer.txt ├── 1-answer.txt ├── 10-answer.txt ├── 100-magic_string.py ├── 101-locked_class.py ├── 103-line1.txt ├── 103-line2.txt ├── 104-line1.txt ├── 104-line2.txt ├── 104-line3.txt ├── 104-line4.txt ├── 104-line5.txt ├── 105-line1.txt ├── 106-line1.txt ├── 106-line2.txt ├── 106-line3.txt ├── 106-line4.txt ├── 106-line5.txt ├── 11-answer.txt ├── 12-answer.txt ├── 13-answer.txt ├── 14-answer.txt ├── 15-answer.txt ├── 16-answer.txt ├── 17-answer.txt ├── 18-answer.txt ├── 19-copy_list.py ├── 2-answer.txt ├── 20-answer.txt ├── 21-answer.txt ├── 22-answer.txt ├── 23-answer.txt ├── 24-answer.txt ├── 25-answer.txt ├── 26-answer.txt ├── 27-answer.txt ├── 28-answer.txt ├── 3-answer.txt ├── 4-answer.txt ├── 5-answer.txt ├── 6-answer.txt ├── 7-answer.txt ├── 8-answer.txt ├── 9-answer.txt ├── README.md └── tests │ ├── 100-main.py │ ├── 101-main.py │ └── 19-main.py ├── 0x0A-python-inheritance ├── 0-lookup.py ├── 1-my_list.py ├── 10-square.py ├── 100-my_int.py ├── 101-add_attribute.py ├── 11-square.py ├── 2-is_same_class.py ├── 3-is_kind_of_class.py ├── 4-inherits_from.py ├── 5-base_geometry.py ├── 6-base_geometry.py ├── 7-base_geometry.py ├── 8-rectangle.py ├── 9-rectangle.py ├── README.md └── tests │ ├── 0-main.py │ ├── 1-main.py │ ├── 1-my_list.txt │ ├── 10-main.py │ ├── 100-main.py │ ├── 101-main.py │ ├── 11-main.py │ ├── 2-main.py │ ├── 3-main.py │ ├── 4-main.py │ ├── 5-main.py │ ├── 6-main.py │ ├── 7-base_geometry.txt │ ├── 7-main.py │ ├── 8-main.py │ └── 9-main.py ├── 0x0B-python-input_output ├── 0-read_file.py ├── 1-write_file.py ├── 10-student.py ├── 100-append_after.py ├── 101-stats.py ├── 11-student.py ├── 12-pascal_triangle.py ├── 2-append_write.py ├── 3-to_json_string.py ├── 4-from_json_string.py ├── 5-save_to_json_file.py ├── 6-load_from_json_file.py ├── 7-add_item.py ├── 8-class_to_json.py ├── 9-student.py ├── README.md └── tests │ ├── 0-main.py │ ├── 1-main.py │ ├── 10-main.py │ ├── 100-main.py │ ├── 12-main.py │ ├── 2-main.py │ ├── 3-main.py │ ├── 4-main.py │ ├── 8-main.py │ └── 9-main.py ├── 0x0C-python-almost_a_circle ├── 0-main.py ├── 1-main.py ├── 10-main.py ├── 100-main.py ├── 101-main.py ├── 11-main.py ├── 12-main.py ├── 13-main.py ├── 14-main.py ├── 15-main.py ├── 16-main.py ├── 17-main.py ├── 18-main.py ├── 2-main.py ├── 3-main.py ├── 4-main.py ├── 5-main.py ├── 6-main.py ├── 7-main.py ├── 8-main.py ├── 9-main.py ├── README.md ├── models │ ├── __init__.py │ ├── base.py │ ├── rectangle.py │ └── square.py └── tests │ └── test_models │ ├── __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 ├── 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 ├── 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 ├── 6-model_state.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 └── tests │ ├── 0-select_states.sql │ ├── 100-relationship_states_cities.sql │ ├── 101-relationship_states_cities_list.sql │ ├── 14-model_city_fetch_by_state.sql │ ├── 4-cities_by_state.sql │ ├── 6-model_state.py │ ├── 6-model_state.sql │ └── 7-model_state_fetch_all.sql ├── 0x10-python-network_0 ├── 0-body_size.sh ├── 1-body.sh ├── 100-status_code.sh ├── 101-post_json.sh ├── 102-catch_me.sh ├── 2-delete.sh ├── 3-methods.sh ├── 4-header.sh ├── 5-post_params.sh ├── 6-peak.py ├── 6-peak.txt ├── README.md └── tests │ └── 6-main.py ├── 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-data.js ├── 100-map.js ├── 101-data.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 └── tests │ ├── 0-main.js │ ├── 1-main.js │ ├── 10-main.js │ ├── 2-main.js │ ├── 3-main.js │ ├── 4-main.js │ ├── 5-main.js │ ├── 6-main.js │ ├── 7-main.js │ ├── 8-main.js │ └── 9-main.js ├── 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-main.html ├── 0-script.js ├── 1-main.html ├── 1-script.js ├── 100-main.html ├── 100-script.js ├── 101-main.html ├── 101-script.js ├── 102-main.html ├── 102-script.js ├── 103-main.html ├── 103-script.js ├── 2-main.html ├── 2-script.js ├── 3-main.html ├── 3-script.js ├── 4-main.html ├── 4-script.js ├── 5-main.html ├── 5-script.js ├── 6-main.html ├── 6-script.js ├── 7-main.html ├── 7-script.js ├── 8-main.html ├── 8-script.js ├── 9-main.html ├── 9-script.js └── README.md └── README.md /0x00-python-hello_world/0-run: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | python3 $PYFILE 3 | -------------------------------------------------------------------------------- /0x00-python-hello_world/1-run_inline: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | python3 -c "$PYCODE" 3 | -------------------------------------------------------------------------------- /0x00-python-hello_world/10-check_cycle.c: -------------------------------------------------------------------------------- 1 | #include "lists.h" 2 | 3 | /** 4 | * check_cycle - 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 | def magic_calculation(a, b): 3 | return (98 + a ** b) 4 | -------------------------------------------------------------------------------- /0x00-python-hello_world/2-print.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | print("\"Programming is like building a multilingual puzzle") 3 | -------------------------------------------------------------------------------- /0x00-python-hello_world/3-print_number.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | number = 98 3 | print(f"{number:d} Battery street") 4 | -------------------------------------------------------------------------------- /0x00-python-hello_world/4-print_float.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | number = 3.14159 3 | print(f"Float: {number:.2f}") 4 | -------------------------------------------------------------------------------- /0x00-python-hello_world/5-print_string.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | str = "Holberton School" 3 | print(str*3) 4 | print(str[:9]) 5 | -------------------------------------------------------------------------------- /0x00-python-hello_world/6-concat.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | str1 = "Holberton" 3 | str2 = "School" 4 | str1 = str1 + " " + str2 5 | print("Welcome to {}!".format(str1)) 6 | -------------------------------------------------------------------------------- /0x00-python-hello_world/7-edges.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | word = "Holberton" 3 | word_first_3 = word[:3] 4 | word_last_2 = word[-2:] 5 | middle_word = word[1:-1] 6 | print("First 3 letters: {}".format(word_first_3)) 7 | print("Last 2 letters: {}".format(word_last_2)) 8 | print("Middle word: {}".format(middle_word)) 9 | -------------------------------------------------------------------------------- /0x00-python-hello_world/8-concat_edges.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | str = "Python is an interpreted, interactive, object-oriented programming\ 3 | language that combines remarkable power with very clear syntax" 4 | str = str[39:67] + str[107:112] + str[:6] 5 | print(str) 6 | -------------------------------------------------------------------------------- /0x00-python-hello_world/9-easter_egg.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import this 3 | -------------------------------------------------------------------------------- /0x00-python-hello_world/lists.h: -------------------------------------------------------------------------------- 1 | #ifndef LISTS_H 2 | #define LISTS_H 3 | 4 | #include 5 | 6 | /** 7 | * struct listint_s - singly linked list 8 | * @n: integer 9 | * @next: points to the next node 10 | * 11 | * Description: singly linked list node structure 12 | * for ALX 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 | if number > 0: 5 | print("{:d} is positive".format(number)) 6 | elif number == 0: 7 | print("{:d} is zero".format(number)) 8 | else: 9 | print("{:d} is negative".format(number)) 10 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/1-last_digit.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import random 3 | number = random.randint(-10000, 10000) 4 | 5 | if number >= 0: 6 | l_digit = number % 10 7 | else: 8 | l_digit = number % -10 9 | 10 | print("Last digit of {} is {}".format(number, l_digit), end='') 11 | 12 | if l_digit > 5: 13 | print(" and is greater than 5") 14 | elif l_digit == 0: 15 | print(" and is 0") 16 | else: 17 | print(" and is less than 6 and not 0") 18 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/10-add.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def add(a, b): 3 | return (a + b) 4 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/100-print_tebahpla.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for 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 | s = "" 4 | for i in range(len(str)): 5 | if i != n: 6 | s = s + str[i] 7 | return (s) 8 | -------------------------------------------------------------------------------- /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 | elif (c > b): 6 | return (a + b) 7 | else: 8 | return (a * b - c) 9 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/11-pow.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def pow(a, b): 3 | return (a ** b) 4 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/12-fizzbuzz.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def fizzbuzz(): 3 | for i in range(1, 101): 4 | if i % 3 == 0 and i % 5 == 0: 5 | print("FizzBuzz", end='') 6 | elif i % 3 == 0: 7 | print("Fizz", end='') 8 | elif i % 5 == 0: 9 | print("Buzz", end='') 10 | else: 11 | print(i, end='') 12 | 13 | print(" ", end='') 14 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/13-insert_number.c: -------------------------------------------------------------------------------- 1 | #include "lists.h" 2 | 3 | /** 4 | * insert_node - inserts a new node 5 | * at a given position. 6 | * @head: head of a list. 7 | * @number: index of the list where the new node is 8 | * added. 9 | * Return: the address of the new node, or NULL if it 10 | * failed. 11 | */ 12 | listint_t *insert_node(listint_t **head, int number) 13 | { 14 | listint_t *new; 15 | listint_t *h; 16 | listint_t *h_prev; 17 | 18 | h = *head; 19 | new = malloc(sizeof(listint_t)); 20 | 21 | if (new == NULL) 22 | return (NULL); 23 | 24 | while (h != NULL) 25 | { 26 | if (h->n > number) 27 | break; 28 | h_prev = h; 29 | h = h->next; 30 | } 31 | 32 | new->n = number; 33 | 34 | if (*head == NULL) 35 | { 36 | new->next = NULL; 37 | *head = new; 38 | } 39 | else 40 | { 41 | new->next = h; 42 | if (h == *head) 43 | *head = new; 44 | else 45 | h_prev->next = new; 46 | } 47 | 48 | return (new); 49 | } 50 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/2-print_alphabet.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for i in range(97, 123): 3 | print("{:c}".format(i), end='') 4 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/3-print_alphabt.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for i in range(97, 123): 3 | if i != 101 and i != 113: 4 | print("{:c}".format(i), end='') 5 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/4-print_hexa.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for i in range(0, 99): 3 | print("{:d} =".format(i), hex(i)) 4 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/5-print_comb2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for i in range(0, 99): 3 | print("{:02d}".format(i), end=", ") 4 | print(i + 1) 5 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/6-print_comb3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for digit1 in range(0, 9): 3 | for digit2 in range(digit1 + 1, 10): 4 | if digit1 == 8: 5 | print("{:d}{:d}".format(digit1, digit2)) 6 | break 7 | print("{:d}{:d}".format(digit1, digit2), end=", ") 8 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/7-islower.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def islower(c): 3 | if ord(c) >= 97 and ord(c) <= 122: 4 | return (True) 5 | else: 6 | return (False) 7 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/8-uppercase.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def uppercase(str): 3 | for i in 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 | if number >= 0: 4 | l_digit = number % 10 5 | else: 6 | l_digit = number % -10 7 | l_digit *= -1 8 | 9 | print("{:d}".format(l_digit), end='') 10 | return (l_digit) 11 | -------------------------------------------------------------------------------- /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 | * for ALX 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 | 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 | if __name__ == "__main__": 3 | from add_0 import add 4 | a = 1 5 | b = 2 6 | print("{} + {} = {}".format(a, b, add(a, b))) 7 | -------------------------------------------------------------------------------- /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 | if __name__ == "__main__": 3 | from calculator_1 import add, sub, mul, div 4 | a = 10 5 | b = 5 6 | print("{} + {} = {}".format(a, b, add(a, b))) 7 | print("{} - {} = {}".format(a, b, sub(a, b))) 8 | print("{} * {} = {}".format(a, b, mul(a, b))) 9 | print("{} / {} = {}".format(a, b, div(a, b))) 10 | -------------------------------------------------------------------------------- /0x02-python-import_modules/100-my_calculator.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | if __name__ == "__main__": 3 | import sys 4 | 5 | nargs = len(sys.argv) - 1 6 | if nargs != 3: 7 | print("Usage: ./100-my_calculator.py ") 8 | sys.exit(1) 9 | 10 | op = sys.argv[2] 11 | if op != '+' and op != '-' and op != '*' and op != '/': 12 | print("Unknown operator. Available operators: +, -, * and /") 13 | sys.exit(1) 14 | 15 | from calculator_1 import add, sub, mul, div 16 | a = int(sys.argv[1]) 17 | b = int(sys.argv[3]) 18 | 19 | if op == '+': 20 | print("{} + {} = {}".format(a, b, add(a, b))) 21 | elif op == '-': 22 | print("{} - {} = {}".format(a, b, sub(a, b))) 23 | elif op == '*': 24 | print("{} * {} = {}".format(a, b, mul(a, b))) 25 | else: 26 | print("{} / {} = {}".format(a, b, div(a, b))) 27 | -------------------------------------------------------------------------------- /0x02-python-import_modules/101-easy_print.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import easy_print_101 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 fast_alphabet_103 3 | -------------------------------------------------------------------------------- /0x02-python-import_modules/2-args.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | if __name__ == "__main__": 3 | import sys 4 | i = len(sys.argv) - 1 5 | 6 | if i == 0: 7 | print("{} arguments.".format(i)) 8 | elif i == 1: 9 | print("{} argument:".format(i)) 10 | else: 11 | print("{} arguments:".format(i)) 12 | 13 | if i >= 1: 14 | i = 0 15 | for arg in sys.argv: 16 | if i != 0: 17 | print("{}: {}".format(i, arg)) 18 | i += 1 19 | -------------------------------------------------------------------------------- /0x02-python-import_modules/3-infinite_add.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | if __name__ == "__main__": 3 | import sys 4 | result = 0 5 | for arg in sys.argv: 6 | if arg != sys.argv[0]: 7 | result += int(arg) 8 | print(result) 9 | -------------------------------------------------------------------------------- /0x02-python-import_modules/4-hidden_discovery.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | if __name__ == "__main__": 3 | import hidden_4 4 | for name in dir(hidden_4): 5 | if name[0] != '_' and name[1] != '_': 6 | print(name) 7 | -------------------------------------------------------------------------------- /0x02-python-import_modules/5-variable_load.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | if __name__ == "__main__": 3 | from variable_load_5 import a 4 | print(a) 5 | -------------------------------------------------------------------------------- /0x02-python-import_modules/add_0.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def add(a, b): 3 | """My addition function 4 | 5 | Args: 6 | a: first integer 7 | b: second integer 8 | 9 | Returns: 10 | The return value. a + b 11 | """ 12 | return (a + b) 13 | -------------------------------------------------------------------------------- /0x02-python-import_modules/calculator_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def add(a, b): 3 | """My addition function 4 | 5 | Args: 6 | a: first integer 7 | b: second integer 8 | 9 | Returns: 10 | The return value. a + b 11 | """ 12 | return (a + b) 13 | 14 | 15 | def sub(a, b): 16 | """My subtraction function 17 | 18 | Args: 19 | a: first integer 20 | b: second integer 21 | 22 | Returns: 23 | The return value. a - b 24 | """ 25 | return (a - b) 26 | 27 | 28 | def mul(a, b): 29 | """My multiplication function 30 | 31 | Args: 32 | a: first integer 33 | b: second integer 34 | 35 | Returns: 36 | The return value. a * b 37 | """ 38 | return (a * b) 39 | 40 | 41 | def div(a, b): 42 | """My division function 43 | 44 | Args: 45 | a: first integer 46 | b: second integer 47 | 48 | Returns: 49 | The return value. a / b 50 | """ 51 | return int(a / b) 52 | -------------------------------------------------------------------------------- /0x02-python-import_modules/easy_print_101.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | print("#pythoniscool") 3 | -------------------------------------------------------------------------------- /0x02-python-import_modules/fast_alphabet_103.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | print(u"\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F", end='') 3 | print(u"\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A") 4 | -------------------------------------------------------------------------------- /0x02-python-import_modules/variable_load_5.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | a = 98 3 | """Simple variable 4 | """ 5 | -------------------------------------------------------------------------------- /0x03-python-data_structures/0-print_list_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def print_list_integer(my_list=[]): 3 | for i in range(len(my_list)): 4 | print("{:d}".format(my_list[i])) 5 | -------------------------------------------------------------------------------- /0x03-python-data_structures/1-element_at.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def element_at(my_list, idx): 3 | if idx < 0: 4 | return (None) 5 | 6 | length = len(my_list) 7 | 8 | if idx > length - 1: 9 | return (None) 10 | 11 | return(my_list[idx]) 12 | -------------------------------------------------------------------------------- /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/2-replace_in_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def replace_in_list(my_list, idx, element): 3 | if idx < 0: 4 | return (my_list) 5 | 6 | length = len(my_list) 7 | 8 | if idx > length - 1: 9 | return (my_list) 10 | 11 | my_list[idx] = element 12 | 13 | return (my_list) 14 | -------------------------------------------------------------------------------- /0x03-python-data_structures/3-print_reversed_list_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def print_reversed_list_integer(my_list=[]): 3 | 4 | if not my_list: 5 | pass 6 | else: 7 | my_list.reverse() 8 | for i in range(len(my_list)): 9 | print("{:d}".format(my_list[i])) 10 | -------------------------------------------------------------------------------- /0x03-python-data_structures/4-new_in_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def new_in_list(my_list, idx, element): 3 | length = len(my_list) 4 | 5 | new_list = my_list[:] 6 | 7 | if 0 <= idx < length: 8 | new_list[idx] = element 9 | 10 | return (new_list) 11 | -------------------------------------------------------------------------------- /0x03-python-data_structures/5-no_c.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def no_c(my_string): 3 | length = len(my_string) 4 | 5 | j = 0 6 | 7 | new_string = my_string[:] 8 | 9 | for i in range(length): 10 | if (my_string[i] == 'c' or my_string[i] == 'C'): 11 | new_string = new_string[:(i - j)] + my_string[(i + 1):] 12 | j += 1 13 | 14 | return (new_string) 15 | -------------------------------------------------------------------------------- /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 ALX 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 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/0-square_matrix_simple.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def square_matrix_simple(matrix=[]): 3 | new_matrix = matrix.copy() 4 | 5 | for i in range(len(matrix)): 6 | new_matrix[i] = list(map(lambda x: x**2, matrix[i])) 7 | 8 | return (new_matrix) 9 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/1-search_replace.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def search_replace(my_list, search, replace): 3 | new_list = list(map(lambda x: replace if x == search else x, my_list)) 4 | return (new_list) 5 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/10-best_score.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def best_score(a_dictionary): 3 | if not a_dictionary: 4 | return (None) 5 | 6 | return (max(a_dictionary, key=a_dictionary.get)) 7 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/100-weight_average.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def weight_average(my_list=[]): 3 | if not my_list: 4 | return 0 5 | 6 | num = 0 7 | den = 0 8 | 9 | for tup in my_list: 10 | num += tup[0] * tup[1] 11 | den += tup[1] 12 | 13 | return (num / den) 14 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/101-square_matrix_map.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def square_matrix_map(matrix=[]): 3 | return (list(map(lambda x: list(map(lambda y: y**2, x)), matrix))) 4 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/102-complex_delete.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def complex_delete(a_dictionary, value): 3 | list_keys = list(a_dictionary.keys()) 4 | 5 | for value_dic in list_keys: 6 | if value == a_dictionary.get(value_dic): 7 | del a_dictionary[value_dic] 8 | 9 | return (a_dictionary) 10 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/103-python.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /** 5 | * print_python_bytes - Prints bytes information 6 | * 7 | * @p: Python Object 8 | * Return: no return 9 | */ 10 | void print_python_bytes(PyObject *p) 11 | { 12 | char *string; 13 | long int size, i, limit; 14 | 15 | printf("[.] bytes object info\n"); 16 | if (!PyBytes_Check(p)) 17 | { 18 | printf(" [ERROR] Invalid Bytes Object\n"); 19 | return; 20 | } 21 | 22 | size = ((PyVarObject *)(p))->ob_size; 23 | string = ((PyBytesObject *)p)->ob_sval; 24 | 25 | printf(" size: %ld\n", size); 26 | printf(" trying string: %s\n", string); 27 | 28 | if (size >= 10) 29 | limit = 10; 30 | else 31 | limit = size + 1; 32 | 33 | printf(" first %ld bytes:", limit); 34 | 35 | for (i = 0; i < limit; i++) 36 | if (string[i] >= 0) 37 | printf(" %02x", string[i]); 38 | else 39 | printf(" %02x", 256 + string[i]); 40 | 41 | printf("\n"); 42 | } 43 | 44 | /** 45 | * print_python_list - Prints list information 46 | * 47 | * @p: Python Object 48 | * Return: no return 49 | */ 50 | void print_python_list(PyObject *p) 51 | { 52 | long int size, i; 53 | PyListObject *list; 54 | PyObject *obj; 55 | 56 | size = ((PyVarObject *)(p))->ob_size; 57 | list = (PyListObject *)p; 58 | 59 | printf("[*] Python list info\n"); 60 | printf("[*] Size of the Python List = %ld\n", size); 61 | printf("[*] Allocated = %ld\n", list->allocated); 62 | 63 | for (i = 0; i < size; i++) 64 | { 65 | obj = ((PyListObject *)p)->ob_item[i]; 66 | printf("Element %ld: %s\n", i, ((obj)->ob_type)->tp_name); 67 | if (PyBytes_Check(obj)) 68 | print_python_bytes(obj); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/11-multiply_list_map.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def multiply_list_map(my_list=[], number=0): 3 | return (list(map((lambda i: i * number), my_list))) 4 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/12-roman_to_int.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def to_subtract(list_num): 3 | to_sub = 0 4 | max_list = max(list_num) 5 | 6 | for n in list_num: 7 | if max_list > n: 8 | to_sub += n 9 | 10 | return (max_list - to_sub) 11 | 12 | 13 | def roman_to_int(roman_string): 14 | if not roman_string: 15 | return 0 16 | 17 | if not isinstance(roman_string, str): 18 | return 0 19 | 20 | rom_n = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} 21 | list_keys = list(rom_n.keys()) 22 | 23 | num = 0 24 | last_rom = 0 25 | list_num = [0] 26 | 27 | for ch in roman_string: 28 | for r_num in list_keys: 29 | if r_num == ch: 30 | if rom_n.get(ch) <= last_rom: 31 | num += to_subtract(list_num) 32 | list_num = [rom_n.get(ch)] 33 | else: 34 | list_num.append(rom_n.get(ch)) 35 | 36 | last_rom = rom_n.get(ch) 37 | 38 | num += to_subtract(list_num) 39 | 40 | return (num) 41 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/2-uniq_add.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def uniq_add(my_list=[]): 3 | uniq_list = set(my_list) 4 | num = 0 5 | 6 | for i in uniq_list: 7 | num += i 8 | 9 | return (num) 10 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/3-common_elements.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def common_elements(set_1, set_2): 3 | return (set_1 & set_2) 4 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/4-only_diff_elements.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def only_diff_elements(set_1, set_2): 3 | return (set_1 ^ set_2) 4 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/5-number_keys.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def number_keys(a_dictionary): 3 | num = 0 4 | list_keys = list(a_dictionary.keys()) 5 | 6 | for i in list_keys: 7 | num += 1 8 | 9 | return (num) 10 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/6-print_sorted_dictionary.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def print_sorted_dictionary(a_dictionary): 3 | list_ord = list(a_dictionary.keys()) 4 | list_ord.sort() 5 | for i in list_ord: 6 | print("{}: {}".format(i, a_dictionary.get(i))) 7 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/7-update_dictionary.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def update_dictionary(a_dictionary, key, value): 3 | a_dictionary[key] = value 4 | return (a_dictionary) 5 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/8-simple_delete.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def simple_delete(a_dictionary, key=""): 3 | if a_dictionary.get(key) is not None: 4 | del a_dictionary[key] 5 | return (a_dictionary) 6 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/9-multiply_by_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def multiply_by_2(a_dictionary): 3 | new_dir = a_dictionary.copy() 4 | list_keys = list(new_dir.keys()) 5 | 6 | for i in list_keys: 7 | new_dir[i] *= 2 8 | 9 | return (new_dir) 10 | -------------------------------------------------------------------------------- /0x05-python-exceptions/0-safe_print_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def safe_print_list(my_list=[], x=0): 4 | """Print x elememts of a list. 5 | 6 | Args: 7 | my_list (list): The list to print elements from. 8 | x (int): The number of elements of my_list to print. 9 | 10 | Returns: 11 | The number of elements printed. 12 | """ 13 | ret = 0 14 | for i in range(x): 15 | try: 16 | print("{}".format(my_list[i]), end="") 17 | ret += 1 18 | except IndexError: 19 | break 20 | print("") 21 | return (ret) 22 | -------------------------------------------------------------------------------- /0x05-python-exceptions/1-safe_print_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def safe_print_integer(value): 3 | """Print an integer with "{:d}".format(). 4 | 5 | Args: 6 | value (int): The integer to print. 7 | 8 | Returns: 9 | If a TypeError or ValueError occurs - False. 10 | Otherwise - True. 11 | """ 12 | try: 13 | print("{:d}".format(value)) 14 | return (True) 15 | except (TypeError, ValueError): 16 | return (False) 17 | -------------------------------------------------------------------------------- /0x05-python-exceptions/100-safe_print_integer_err.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def safe_print_integer_err(value): 3 | import sys 4 | try: 5 | print("{:d}".format(value)) 6 | except Exception as i: 7 | sys.stderr.write("Exception: {}\n".format(i)) 8 | return (False) 9 | else: 10 | return (True) 11 | -------------------------------------------------------------------------------- /0x05-python-exceptions/101-safe_function.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def safe_function(fct, *args): 3 | import sys 4 | try: 5 | result = fct(*args) 6 | except Exception as i: 7 | sys.stderr.write("Exception: {}\n".format(i)) 8 | result = None 9 | 10 | return (result) 11 | -------------------------------------------------------------------------------- /0x05-python-exceptions/102-magic_calculation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def magic_calculation(a, b): 3 | result = 0 4 | for i in range(1, 3): 5 | try: 6 | if i > a: 7 | raise Exception('Too far') 8 | result += a ** b / i 9 | except Exception: 10 | result = b + a 11 | break 12 | return result 13 | -------------------------------------------------------------------------------- /0x05-python-exceptions/2-safe_print_list_integers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def safe_print_list_integers(my_list=[], x=0): 3 | count = 0 4 | 5 | for i in range(x): 6 | try: 7 | print("{:d}".format(my_list[i]), end='') 8 | except TypeError: 9 | pass 10 | except ValueError: 11 | pass 12 | else: 13 | count += 1 14 | 15 | print() 16 | return (count) 17 | -------------------------------------------------------------------------------- /0x05-python-exceptions/3-safe_print_division.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def safe_print_division(a, b): 4 | """Returns the division of a by b.""" 5 | try: 6 | div = a / b 7 | except (TypeError, ZeroDivisionError): 8 | div = None 9 | finally: 10 | print("Inside result: {}".format(div)) 11 | return (div) 12 | -------------------------------------------------------------------------------- /0x05-python-exceptions/4-list_division.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def list_division(my_list_1, my_list_2, list_length): 3 | new_list = [] 4 | for i in range(list_length): 5 | try: 6 | result = my_list_1[i] / my_list_2[i] 7 | except ZeroDivisionError: 8 | print("division by 0") 9 | result = 0 10 | except TypeError: 11 | print("wrong type") 12 | result = 0 13 | except IndexError: 14 | print("out of range") 15 | result = 0 16 | finally: 17 | new_list.append(result) 18 | 19 | return (new_list) 20 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /0x06-python-classes/0-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Empty class Square that defines a square""" 3 | 4 | 5 | class Square: 6 | """Empty class Square that defines a square""" 7 | pass 8 | -------------------------------------------------------------------------------- /0x06-python-classes/1-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ class Square that defines a square""" 3 | 4 | 5 | class Square: 6 | """ class Square that defines a square""" 7 | def __init__(self, size): 8 | """initialize square 9 | Args: 10 | size (int): size of the square 11 | """ 12 | self.__size = size #: size of the square 13 | -------------------------------------------------------------------------------- /0x06-python-classes/102-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ class Square that defines a square""" 3 | 4 | 5 | class Square: 6 | """ class Square that defines a square""" 7 | def __init__(self, size=0): 8 | """ init square 9 | 10 | Args: 11 | value (int): size of the square. 12 | """ 13 | self.size = size 14 | 15 | @property 16 | def size(self): 17 | """int: private size. 18 | 19 | Returns: 20 | Private size. 21 | """ 22 | return self.__size 23 | 24 | @size.setter 25 | def size(self, value): 26 | """Sets value into size, must be int. 27 | 28 | Args: 29 | value (int): size of the square. 30 | """ 31 | if type(value) is not int and type(value) is not float: 32 | raise TypeError('size must be a number') 33 | elif value < 0: 34 | raise ValueError('size must be >= 0') 35 | else: 36 | self.__size = value #: size of the square 37 | 38 | def area(self): 39 | """returns the area 40 | 41 | Returns: 42 | area. 43 | """ 44 | return self.__size**2 45 | 46 | def __lt__(self, other): 47 | return self.size < other.size 48 | 49 | def __le__(self, other): 50 | return self.size <= other.size 51 | 52 | def __eq__(self, other): 53 | return self.size == other.size 54 | 55 | def __ne__(self, other): 56 | return self.size != other.size 57 | 58 | def __ge__(self, other): 59 | return self.size >= other.size 60 | -------------------------------------------------------------------------------- /0x06-python-classes/103-magic_class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Define a MagicClass matching exactly a bytecode provided by ALX.""" 3 | 4 | import math 5 | 6 | 7 | class MagicClass: 8 | """Represent a circle.""" 9 | 10 | def __init__(self, radius=0): 11 | """Initialize a MagicClass. 12 | 13 | Arg: 14 | radius (float or int): The radius of the new MagicClass. 15 | """ 16 | self.__radius = 0 17 | if type(radius) is not int and type(radius) is not float: 18 | raise TypeError("radius must be a number") 19 | self.__radius = radius 20 | 21 | def area(self): 22 | """Return the area of the MagicClass.""" 23 | return (self.__radius ** 2 * math.pi) 24 | 25 | def circumference(self): 26 | """Return The circumference of the MagicClass.""" 27 | return (2 * math.pi * self.__radius) 28 | -------------------------------------------------------------------------------- /0x06-python-classes/2-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ class Square that defines a square""" 3 | 4 | 5 | class Square: 6 | """ class Square that defines a square""" 7 | 8 | def __init__(self, size=0): 9 | """initialize square 10 | Args: 11 | size (int): size of the square 12 | """ 13 | if type(size) is not int: 14 | raise TypeError('size must be an integer') 15 | elif size < 0: 16 | raise ValueError('size must be >= 0') 17 | else: 18 | self.__size = size #: size of the square 19 | -------------------------------------------------------------------------------- /0x06-python-classes/3-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ class Square that defines a square""" 3 | 4 | 5 | class Square: 6 | """ class Square that defines a square""" 7 | 8 | def __init__(self, size=0): 9 | """initialize square 10 | Args: 11 | size (int): size of the square 12 | """ 13 | if type(size) is not int: 14 | raise TypeError('size must be an integer') 15 | elif size < 0: 16 | raise ValueError('size must be >= 0') 17 | else: 18 | self.__size = size #: size of the square 19 | 20 | def area(self): 21 | """returns the area. 22 | 23 | Returns: 24 | ares. 25 | """ 26 | return self.__size**2 27 | -------------------------------------------------------------------------------- /0x06-python-classes/4-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ class Square that defines a square""" 3 | 4 | 5 | class Square: 6 | """ class Square that defines a square""" 7 | def __init__(self, size=0): 8 | """ init square 9 | 10 | Args: 11 | value (int): size of the square. 12 | """ 13 | self.size = size 14 | 15 | @property 16 | def size(self): 17 | """int: private size. 18 | 19 | Returns: 20 | Private size. 21 | """ 22 | return self.__size 23 | 24 | @size.setter 25 | def size(self, value): 26 | """Sets value into size, must be int. 27 | 28 | Args: 29 | value (int): size of the square. 30 | """ 31 | if type(value) is not int: 32 | raise TypeError('size must be an integer') 33 | elif value < 0: 34 | raise ValueError('size must be >= 0') 35 | else: 36 | self.__size = value #: size of the square 37 | 38 | def area(self): 39 | """returns the area 40 | 41 | Returns: 42 | area. 43 | """ 44 | return self.__size**2 45 | -------------------------------------------------------------------------------- /0x06-python-classes/5-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ class Square that defines a square""" 3 | 4 | 5 | class Square: 6 | """ class Square that defines a square""" 7 | def __init__(self, size=0): 8 | """ init square 9 | 10 | Args: 11 | value (int): size of the square. 12 | """ 13 | self.size = size 14 | 15 | @property 16 | def size(self): 17 | """int: private size. 18 | 19 | Returns: 20 | Private size. 21 | """ 22 | return self.__size 23 | 24 | @size.setter 25 | def size(self, value): 26 | """Sets value into size, must be int. 27 | 28 | Args: 29 | value (int): size of the square. 30 | """ 31 | if type(value) is not int: 32 | raise TypeError('size must be an integer') 33 | elif value < 0: 34 | raise ValueError('size must be >= 0') 35 | else: 36 | self.__size = value #: size of the square 37 | 38 | def area(self): 39 | """returns the area 40 | 41 | Returns: 42 | area. 43 | """ 44 | return self.__size**2 45 | 46 | def my_print(self): 47 | """prints in stdout the square with the character #""" 48 | 49 | if self.__size != 0: 50 | for i in range(self.__size): 51 | for j in range(self.__size): 52 | print('#', end='') 53 | print() 54 | else: 55 | print() 56 | -------------------------------------------------------------------------------- /0x06-python-classes/6-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Define a class Square.""" 3 | 4 | 5 | class Square: 6 | """Represent a square.""" 7 | 8 | def __init__(self, size=0, position=(0, 0)): 9 | """Initialize a new square. 10 | 11 | Args: 12 | size (int): The size of the new square. 13 | position (int, int): The position of the new square. 14 | """ 15 | self.size = size 16 | self.position = position 17 | 18 | @property 19 | def size(self): 20 | """Get/set the current size of the square.""" 21 | return (self.__size) 22 | 23 | @size.setter 24 | def size(self, value): 25 | if not isinstance(value, int): 26 | raise TypeError("size must be an integer") 27 | elif value < 0: 28 | raise ValueError("size must be >= 0") 29 | self.__size = value 30 | 31 | @property 32 | def position(self): 33 | """Get/set the current position of the square.""" 34 | return (self.__position) 35 | 36 | @position.setter 37 | def position(self, value): 38 | if (not isinstance(value, tuple) or 39 | len(value) != 2 or 40 | not all(isinstance(num, int) for num in value) or 41 | not all(num >= 0 for num in value)): 42 | raise TypeError("position must be a tuple of 2 positive integers") 43 | self.__position = value 44 | 45 | def area(self): 46 | """Return the current area of the square.""" 47 | return (self.__size * self.__size) 48 | 49 | def my_print(self): 50 | """Print the square with the # character.""" 51 | if self.__size == 0: 52 | print("") 53 | return 54 | 55 | [print("") for i in range(0, self.__position[1])] 56 | for i in range(0, self.__size): 57 | [print(" ", end="") for j in range(0, self.__position[0])] 58 | [print("#", end="") for k in range(0, self.__size)] 59 | print("") 60 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/0-add_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | 4 | This module is composed by a function that adds two numbers 5 | 6 | """ 7 | 8 | 9 | def add_integer(a, b=98): 10 | """ Function that adds two integer and/or float numbers 11 | 12 | Args: 13 | a: first number 14 | b: second number 15 | 16 | Returns: 17 | The addition of the two given numbers 18 | 19 | Raises: 20 | TypeError: If a or b aren't integer and/or float numbers 21 | 22 | """ 23 | 24 | if not isinstance(a, int) and not isinstance(a, float): 25 | raise TypeError("a must be an integer") 26 | if not isinstance(b, int) and not isinstance(b, float): 27 | raise TypeError("b must be an integer") 28 | a = int(a) 29 | b = int(b) 30 | return (a + b) 31 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/101-lazy_matrix_mul.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3.5 2 | """ 3 | 4 | Module composed by a function that multiplies 2 matrices 5 | 6 | """ 7 | import numpy as np 8 | 9 | 10 | def lazy_matrix_mul(m_a, m_b): 11 | """ Function that multiplies 2 matrices 12 | 13 | Args: 14 | m_a: matrix a 15 | m_b: matrix b 16 | 17 | Returns: 18 | result of the multiplication 19 | 20 | 21 | """ 22 | 23 | return (np.matmul(m_a, m_b)) 24 | -------------------------------------------------------------------------------- /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 | """ 3 | 4 | This module is composed by a function that divides the numbers of a matrix 5 | 6 | """ 7 | 8 | 9 | def matrix_divided(matrix, div): 10 | """ Function that divides the integer/float numbers of a matrix 11 | 12 | Args: 13 | matrix: list of a lists of integers/floats 14 | div: number which divides the matrix 15 | 16 | Returns: 17 | A new matrix with the result of the division 18 | 19 | Raises: 20 | TypeError: If the elements of the matrix aren't lists 21 | If the elemetns of the lists aren't integers/floats 22 | If div is not an integer/float number 23 | If the lists of the matrix don't have the same size 24 | 25 | ZeroDivisionError: If div is zero 26 | 27 | 28 | """ 29 | 30 | if not type(div) in (int, float): 31 | raise TypeError("div must be a number") 32 | 33 | if div == 0: 34 | raise ZeroDivisionError("division by zero") 35 | 36 | msg_type = "matrix must be a matrix (list of lists) of integers/floats" 37 | 38 | if not matrix or not isinstance(matrix, list): 39 | raise TypeError(msg_type) 40 | 41 | len_e = 0 42 | msg_size = "Each row of the matrix must have the same size" 43 | 44 | for elems in matrix: 45 | if not elems or not isinstance(elems, list): 46 | raise TypeError(msg_type) 47 | 48 | if len_e != 0 and len(elems) != len_e: 49 | raise TypeError(msg_size) 50 | 51 | for num in elems: 52 | if not type(num) in (int, float): 53 | raise TypeError(msg_type) 54 | 55 | len_e = len(elems) 56 | 57 | m = list(map(lambda x: list(map(lambda y: round(y / div, 2), x)), matrix)) 58 | return (m) 59 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/3-say_my_name.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | 4 | This module is composed by a function prints a message 5 | 6 | """ 7 | 8 | 9 | def say_my_name(first_name, last_name=""): 10 | """ Function that prints "My name is " 11 | 12 | Args: 13 | first_name: first name 14 | last_name: last name 15 | 16 | Returns: 17 | No return 18 | 19 | Raises: 20 | TypeError: If first_name or last_name is not a string 21 | 22 | 23 | """ 24 | 25 | if type(first_name) is not str: 26 | raise TypeError("first_name must be a string") 27 | 28 | if type(last_name) is not str: 29 | raise TypeError("last_name must be a string") 30 | 31 | print("My name is {} {}".format(first_name, last_name)) 32 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/4-print_square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | 4 | This module is composed by a function that prints a square with the character # 5 | 6 | """ 7 | 8 | 9 | def print_square(size): 10 | """ Function that prints a square with the character # 11 | 12 | Args: 13 | size: size of the square printed 14 | 15 | Returns: 16 | No return 17 | 18 | Raises: 19 | TypeError: If size is not an integer number 20 | 21 | 22 | """ 23 | 24 | if not isinstance(size, int): 25 | raise TypeError("size must be an integer") 26 | if size < 0: 27 | raise ValueError("size must be >= 0") 28 | 29 | for i in range(size): 30 | print("#" * size) 31 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/5-text_indentation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | 4 | Module composed by a function that prints 2 new lines after ".?:" characters 5 | 6 | """ 7 | 8 | 9 | def text_indentation(text): 10 | """ Function that prints 2 new lines after ".?:" characters 11 | 12 | Args: 13 | text: input string 14 | 15 | Returns: 16 | No return 17 | 18 | Raises: 19 | TypeError: If text is not a string 20 | 21 | 22 | """ 23 | 24 | if type(text) is not str: 25 | raise TypeError("text must be a string") 26 | 27 | s = text[:] 28 | 29 | for d in ".?:": 30 | list_text = s.split(d) 31 | s = "" 32 | for i in list_text: 33 | i = i.strip(" ") 34 | s = i + d if s is "" else s + "\n\n" + i + d 35 | 36 | print(s[:-3], end="") 37 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/3-say_my_name.txt: -------------------------------------------------------------------------------- 1 | The ``3-say_my_name`` module 2 | ============================ 3 | 4 | Using ``say_my_name`` 5 | --------------------- 6 | 7 | Importing function from the module: 8 | 9 | >>> say_my_name = __import__('3-say_my_name').say_my_name 10 | 11 | Passing first_name and last_name correctly 12 | 13 | >>> say_my_name("Betty", "Holberton") 14 | My name is Betty Holberton 15 | 16 | Passing first_name and last_name correctly 2 17 | 18 | >>> say_my_name("Luis") 19 | My name is Luis 20 | 21 | Passing None as the last_name 22 | 23 | >>> say_my_name("John", None) 24 | Traceback (most recent call last): 25 | ... 26 | TypeError: last_name must be a string 27 | 28 | Passing None as the first_name 29 | 30 | >>> say_my_name(None) 31 | Traceback (most recent call last): 32 | ... 33 | TypeError: first_name must be a string 34 | 35 | Passing a number as the first_name 36 | 37 | >>> say_my_name(1) 38 | Traceback (most recent call last): 39 | ... 40 | TypeError: first_name must be a string 41 | 42 | Passing a number as the last_name 43 | 44 | >>> say_my_name("Betty", 0) 45 | Traceback (most recent call last): 46 | ... 47 | TypeError: last_name must be a string 48 | 49 | Missing two arguments 50 | 51 | >>> say_my_name() 52 | Traceback (most recent call last): 53 | ... 54 | TypeError: say_my_name() missing 1 required positional argument: 'first_name' 55 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/4-print_square.txt: -------------------------------------------------------------------------------- 1 | The ``4-print_square`` module 2 | ============================ 3 | 4 | Using ``print_square`` 5 | --------------------- 6 | 7 | Importing function from the module: 8 | 9 | >>> print_square = __import__('4-print_square').print_square 10 | 11 | Printing a square with a size of 5 12 | 13 | >>> print_square(5) 14 | ##### 15 | ##### 16 | ##### 17 | ##### 18 | ##### 19 | 20 | Passing 0 as the size of the square 21 | 22 | >>> print_square(0) 23 | 24 | Passing a float number as the size of the square 25 | 26 | >>> print_square(1.0) 27 | Traceback (most recent call last): 28 | ... 29 | TypeError: size must be an integer 30 | 31 | Passing a string as the size of the square 32 | 33 | >>> print_square('2') 34 | Traceback (most recent call last): 35 | ... 36 | TypeError: size must be an integer 37 | 38 | Passing a negative number as the size of the square 39 | 40 | >>> print_square(-2) 41 | Traceback (most recent call last): 42 | ... 43 | ValueError: size must be >= 0 44 | 45 | Passing None as the size of the square 46 | 47 | >>> print_square(None) 48 | Traceback (most recent call last): 49 | ... 50 | TypeError: size must be an integer 51 | 52 | Missing argument 53 | 54 | >>> print_square() 55 | Traceback (most recent call last): 56 | ... 57 | TypeError: print_square() missing 1 required positional argument: 'size' 58 | -------------------------------------------------------------------------------- /0x08-python-more_classes/0-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ empty class Rectangle that defines a rectangle 3 | """ 4 | 5 | 6 | class Rectangle: 7 | """ class rectangle""" 8 | pass 9 | -------------------------------------------------------------------------------- /0x08-python-more_classes/1-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ empty class Rectangle that defines a rectangle 3 | """ 4 | 5 | 6 | class Rectangle: 7 | """ class rectangle""" 8 | def __init__(self, width=0, height=0): 9 | """ Instantiation with optional width and height""" 10 | self.width = width 11 | self.height = height 12 | 13 | @property 14 | def width(self): 15 | """ width 16 | """ 17 | return self.__width 18 | 19 | @property 20 | def height(self): 21 | """height 22 | """ 23 | return self.__height 24 | 25 | @width.setter 26 | def width(self, value): 27 | """ width setter 28 | """ 29 | if type(value) is not int: 30 | raise TypeError("width must be an integer") 31 | if value < 0: 32 | raise ValueError("width must be >= 0") 33 | self.__width = value 34 | 35 | @height.setter 36 | def height(self, value): 37 | """ height setter 38 | """ 39 | if type(value) is not int: 40 | raise TypeError("height must be an integer") 41 | if value < 0: 42 | raise ValueError("height must be >= 0") 43 | self.__height = value 44 | -------------------------------------------------------------------------------- /0x08-python-more_classes/2-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ empty class Rectangle that defines a rectangle 3 | """ 4 | 5 | 6 | class Rectangle: 7 | """ class rectangle""" 8 | def __init__(self, width=0, height=0): 9 | """ Instantiation with optional width and height""" 10 | self.width = width 11 | self.height = height 12 | 13 | @property 14 | def width(self): 15 | """ width 16 | """ 17 | return self.__width 18 | 19 | @property 20 | def height(self): 21 | """ height 22 | """ 23 | return self.__height 24 | 25 | @width.setter 26 | def width(self, value): 27 | """ width setter 28 | """ 29 | if type(value) is not int: 30 | raise TypeError("width must be an integer") 31 | if value < 0: 32 | raise ValueError("width must be >= 0") 33 | self.__width = value 34 | 35 | @height.setter 36 | def height(self, value): 37 | """ height setter 38 | """ 39 | if type(value) is not int: 40 | raise TypeError("height must be an integer") 41 | if value < 0: 42 | raise ValueError("height must be >= 0") 43 | self.__height = value 44 | 45 | def area(self): 46 | """ returns rectangle area""" 47 | return self.__width * self.__height 48 | 49 | def perimeter(self): 50 | """ returns rectangle perimiter""" 51 | if self.__width is 0 or self.__height is 0: 52 | return 0 53 | return self.__width * 2 + self.__height * 2 54 | -------------------------------------------------------------------------------- /0x08-python-more_classes/3-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ empty class Rectangle that defines a rectangle 3 | """ 4 | 5 | 6 | class Rectangle: 7 | """ class rectangle""" 8 | def __init__(self, width=0, height=0): 9 | """ Instantiation with optional width and height""" 10 | self.width = width 11 | self.height = height 12 | 13 | @property 14 | def width(self): 15 | """ width 16 | """ 17 | return self.__width 18 | 19 | @property 20 | def height(self): 21 | """ height 22 | """ 23 | return self.__height 24 | 25 | @width.setter 26 | def width(self, value): 27 | """ width setter 28 | """ 29 | if type(value) is not int: 30 | raise TypeError("width must be an integer") 31 | if value < 0: 32 | raise ValueError("width must be >= 0") 33 | self.__width = value 34 | 35 | @height.setter 36 | def height(self, value): 37 | """ height setter 38 | """ 39 | if type(value) is not int: 40 | raise TypeError("height must be an integer") 41 | if value < 0: 42 | raise ValueError("height must be >= 0") 43 | self.__height = value 44 | 45 | def area(self): 46 | """ returns rectangle area""" 47 | return self.__width * self.__height 48 | 49 | def perimeter(self): 50 | """ returns rectangle perimiter""" 51 | if self.__width is 0 or self.__height is 0: 52 | return 0 53 | return self.__width * 2 + self.__height * 2 54 | 55 | def __str__(self): 56 | """ return the rectangle with the character # 57 | """ 58 | if self.__width is 0 or self.__height is 0: 59 | return "" 60 | return ("\n".join(["".join(["#" for i in range(self.__width)]) 61 | for j in range(self.__height)])) 62 | -------------------------------------------------------------------------------- /0x08-python-more_classes/4-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ empty class Rectangle that defines a rectangle 3 | """ 4 | 5 | 6 | class Rectangle: 7 | """ class rectangle""" 8 | def __init__(self, width=0, height=0): 9 | """ Instantiation with optional width and height""" 10 | self.width = width 11 | self.height = height 12 | 13 | @property 14 | def width(self): 15 | """ width 16 | """ 17 | return self.__width 18 | 19 | @property 20 | def height(self): 21 | """ height 22 | """ 23 | return self.__height 24 | 25 | @width.setter 26 | def width(self, value): 27 | """ width setter 28 | """ 29 | if type(value) is not int: 30 | raise TypeError("width must be an integer") 31 | if value < 0: 32 | raise ValueError("width must be >= 0") 33 | self.__width = value 34 | 35 | @height.setter 36 | def height(self, value): 37 | """ height setter 38 | """ 39 | if type(value) is not int: 40 | raise TypeError("height must be an integer") 41 | if value < 0: 42 | raise ValueError("height must be >= 0") 43 | self.__height = value 44 | 45 | def area(self): 46 | """ returns rectangle area""" 47 | return self.__width * self.__height 48 | 49 | def perimeter(self): 50 | """ returns rectangle perimiter""" 51 | if self.__width is 0 or self.__height is 0: 52 | return 0 53 | return self.__width * 2 + self.__height * 2 54 | 55 | def __str__(self): 56 | """ return the rectangle with the character # 57 | """ 58 | if self.__width is 0 or self.__height is 0: 59 | return "" 60 | return ("\n".join(["".join(["#" for i in range(self.__width)]) 61 | for j in range(self.__height)])) 62 | 63 | def __repr__(self): 64 | """ return a string representation of the rectangle 65 | """ 66 | return "Rectangle({}, {})".format(self.__width, self.__height) 67 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/0-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('0-rectangle').Rectangle 3 | 4 | my_rectangle = Rectangle() 5 | print(type(my_rectangle)) 6 | print(my_rectangle.__dict__) 7 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/1-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('1-rectangle').Rectangle 3 | 4 | my_rectangle = Rectangle(2, 4) 5 | print(my_rectangle.__dict__) 6 | 7 | my_rectangle.width = 10 8 | my_rectangle.height = 3 9 | print(my_rectangle.__dict__) 10 | 11 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/2-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('2-rectangle').Rectangle 3 | 4 | my_rectangle = Rectangle(2, 4) 5 | print("Area: {} - Perimeter: {}".format(my_rectangle.area(), my_rectangle.perimeter())) 6 | 7 | print("--") 8 | 9 | my_rectangle.width = 10 10 | my_rectangle.height = 3 11 | print("Area: {} - Perimeter: {}".format(my_rectangle.area(), my_rectangle.perimeter())) 12 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/3-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('3-rectangle').Rectangle 3 | 4 | my_rectangle = Rectangle(2, 4) 5 | print("Area: {} - Perimeter: {}".format(my_rectangle.area(), my_rectangle.perimeter())) 6 | 7 | print(str(my_rectangle)) 8 | print(repr(my_rectangle)) 9 | 10 | print("--") 11 | 12 | my_rectangle.width = 10 13 | my_rectangle.height = 3 14 | print(my_rectangle) 15 | print(repr(my_rectangle)) 16 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/4-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('4-rectangle').Rectangle 3 | 4 | my_rectangle = Rectangle(2, 4) 5 | print(str(my_rectangle)) 6 | print("--") 7 | print(my_rectangle) 8 | print("--") 9 | print(repr(my_rectangle)) 10 | print("--") 11 | print(hex(id(my_rectangle))) 12 | print("--") 13 | 14 | # create new instance based on representation 15 | new_rectangle = eval(repr(my_rectangle)) 16 | print(str(new_rectangle)) 17 | print("--") 18 | print(new_rectangle) 19 | print("--") 20 | print(repr(new_rectangle)) 21 | print("--") 22 | print(hex(id(new_rectangle))) 23 | print("--") 24 | 25 | print(new_rectangle is my_rectangle) 26 | print(type(new_rectangle) is type(my_rectangle)) 27 | 28 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/5-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('5-rectangle').Rectangle 3 | 4 | my_rectangle = Rectangle(2, 4) 5 | print("Area: {} - Perimeter: {}".format(my_rectangle.area(), my_rectangle.perimeter())) 6 | 7 | del my_rectangle 8 | 9 | try: 10 | print(my_rectangle) 11 | except Exception as e: 12 | print("[{}] {}".format(e.__class__.__name__, e)) 13 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/6-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('6-rectangle').Rectangle 3 | 4 | my_rectangle_1 = Rectangle(2, 4) 5 | my_rectangle_2 = Rectangle(2, 4) 6 | print("{:d} instances of Rectangle".format(Rectangle.number_of_instances)) 7 | del my_rectangle_1 8 | print("{:d} instances of Rectangle".format(Rectangle.number_of_instances)) 9 | del my_rectangle_2 10 | print("{:d} instances of Rectangle".format(Rectangle.number_of_instances)) 11 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/7-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('7-rectangle').Rectangle 3 | 4 | my_rectangle_1 = Rectangle(8, 4) 5 | print(my_rectangle_1) 6 | print("--") 7 | my_rectangle_1.print_symbol = "&" 8 | print(my_rectangle_1) 9 | print("--") 10 | 11 | my_rectangle_2 = Rectangle(2, 1) 12 | print(my_rectangle_2) 13 | print("--") 14 | Rectangle.print_symbol = "C" 15 | print(my_rectangle_2) 16 | print("--") 17 | 18 | my_rectangle_3 = Rectangle(7, 3) 19 | print(my_rectangle_3) 20 | 21 | print("--") 22 | 23 | my_rectangle_3.print_symbol = ["C", "is", "fun!"] 24 | print(my_rectangle_3) 25 | 26 | print("--") 27 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/8-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('8-rectangle').Rectangle 3 | 4 | my_rectangle_1 = Rectangle(8, 4) 5 | my_rectangle_2 = Rectangle(2, 3) 6 | 7 | if my_rectangle_1 is Rectangle.bigger_or_equal(my_rectangle_1, my_rectangle_2): 8 | print("my_rectangle_1 is bigger or equal to my_rectangle_2") 9 | else: 10 | print("my_rectangle_2 is bigger than my_rectangle_1") 11 | 12 | 13 | my_rectangle_2.width = 10 14 | my_rectangle_2.height = 5 15 | if my_rectangle_1 is Rectangle.bigger_or_equal(my_rectangle_1, my_rectangle_2): 16 | print("my_rectangle_1 is bigger or equal to my_rectangle_2") 17 | else: 18 | print("my_rectangle_2 is bigger than my_rectangle_1") 19 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/9-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('9-rectangle').Rectangle 3 | 4 | my_square = Rectangle.square(5) 5 | print("Area: {} - Perimeter: {}".format(my_square.area(), my_square.perimeter())) 6 | print(my_square) 7 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/0-answer.txt: -------------------------------------------------------------------------------- 1 | type 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/1-answer.txt: -------------------------------------------------------------------------------- 1 | id 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/10-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/100-magic_string.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def magic_string(): 3 | magic_string.n = getattr(magic_string, 'n', 0) + 1 4 | return ("BestSchool, " * (magic_string.n - 1) + "BestSchool") 5 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/101-locked_class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ LockedClass 3 | """ 4 | 5 | 6 | class LockedClass: 7 | __slots__= ['first_name'] 8 | -------------------------------------------------------------------------------- /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(l): 3 | return l[:] 4 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/2-answer.txt: -------------------------------------------------------------------------------- 1 | No 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/20-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/21-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/22-answer.txt: -------------------------------------------------------------------------------- 1 | No 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/23-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/24-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/25-answer.txt: -------------------------------------------------------------------------------- 1 | False 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/26-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/27-answer.txt: -------------------------------------------------------------------------------- 1 | No 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/28-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/3-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/4-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/5-answer.txt: -------------------------------------------------------------------------------- 1 | No 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/6-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/7-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/8-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/9-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/tests/100-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | magic_string = __import__('100-magic_string').magic_string 3 | 4 | for i in range(10): 5 | print(magic_string()) 6 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/tests/101-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | LockedClass = __import__('101-locked_class').LockedClass 3 | 4 | lc = LockedClass() 5 | lc.first_name = "John" 6 | try: 7 | lc.last_name = "Snow" 8 | except Exception as e: 9 | print("[{}] {}".format(e.__class__.__name__, e)) 10 | 11 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/tests/19-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | copy_list = __import__('19-copy_list').copy_list 3 | 4 | my_list = [1, 2, 3] 5 | print(my_list) 6 | 7 | new_list = copy_list(my_list) 8 | 9 | print(my_list) 10 | print(new_list) 11 | 12 | print(new_list == my_list) 13 | print(new_list is my_list) 14 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/0-lookup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ returns the list of available attributes 3 | and methods of an object 4 | """ 5 | 6 | 7 | def lookup(obj): 8 | """returns the list of available attributes""" 9 | return dir(obj) 10 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/1-my_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """class MyList that inherits from list 3 | """ 4 | 5 | 6 | class MyList(list): 7 | """inherits from list""" 8 | def print_sorted(self): 9 | """prints the list, but sorted 10 | (ascending sort) 11 | """ 12 | print(sorted(self)) 13 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/10-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a Rectangle subclass Square.""" 3 | Rectangle = __import__('9-rectangle').Rectangle 4 | 5 | 6 | class Square(Rectangle): 7 | """Represent a square.""" 8 | 9 | def __init__(self, size): 10 | """Initialize a new square. 11 | 12 | Args: 13 | size (int): The size of the new square. 14 | """ 15 | self.integer_validator("size", size) 16 | super().__init__(size, size) 17 | self.__size = size 18 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/100-my_int.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ class MyInt that inherits from int: 3 | """ 4 | 5 | 6 | class MyInt(int): 7 | """ Class """ 8 | def __eq__(self, other): 9 | return int(str(self)) != other 10 | 11 | def __ne__(self, other): 12 | return int(str(self)) == other 13 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/101-add_attribute.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """dds a new attribute to an object 3 | if it’s possible 4 | """ 5 | 6 | 7 | def add_attribute(obj, attribute, value): 8 | """dds a new attribute""" 9 | if '__dict__' not in dir(obj): 10 | raise TypeError("can't add new attribute") 11 | if '__slots__' in dir(obj): 12 | raise TypeError("can't add new attribute") 13 | else: 14 | setattr(obj, attribute, value) 15 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/11-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Fri May 29 15:13:37 2020 5 | 6 | @author: Robinson Montes 7 | """ 8 | 9 | 10 | BaseGeometry = __import__('7-base_geometry').BaseGeometry 11 | 12 | 13 | class Square(BaseGeometry): 14 | """ 15 | A Square class shape, inheirts from BaseGeometry 16 | """ 17 | def __init__(self, size): 18 | """" 19 | Init function for Square 20 | 21 | Attributes: 22 | size (int): The size of the square 23 | """ 24 | self.integer_validator("size", size) 25 | self.__size = size 26 | 27 | def __str__(self): 28 | """ 29 | str funtion to print with/height 30 | 31 | Returns: 32 | Return width/height 33 | """ 34 | return '[Square] ' + str(self.__size) + '/' + str(self.__size) 35 | 36 | def area(self): 37 | """ 38 | A function that calculates the area of the Square 39 | """ 40 | return self.__size ** 2 41 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/2-is_same_class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """returns True if the object is exactly an instance of the specified class 3 | ; otherwise False. 4 | """ 5 | 6 | 7 | def is_same_class(obj, a_class): 8 | """returns True if the object is exactly an instance""" 9 | return True if type(obj) == a_class else False 10 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/3-is_kind_of_class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Module check class ans subclass 3 | """ 4 | 5 | 6 | def is_kind_of_class(obj, a_class): 7 | """ 8 | returns True if the object is an instance of, or if the object 9 | is an instance 10 | of a class that inherited from, the specified class ; otherwise False 11 | """ 12 | return isinstance(obj, a_class) 13 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/4-inherits_from.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | module only sub class of 4 | """ 5 | 6 | 7 | def inherits_from(obj, a_class): 8 | """returns True if the object is an instance of a class 9 | that inherited (directly or indirectly) from the specified class; 10 | otherwise False. 11 | """ 12 | if type(obj) != a_class: 13 | return issubclass(type(obj), a_class) 14 | else: 15 | return False 16 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/5-base_geometry.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ Module base geometry 3 | """ 4 | 5 | 6 | class BaseGeometry: 7 | """ empty class""" 8 | pass 9 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/6-base_geometry.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ Module base geometry 3 | """ 4 | 5 | 6 | class BaseGeometry: 7 | """ empty class""" 8 | def area(self): 9 | raise Exception('area() is not implemented') 10 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/7-base_geometry.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | """Defines a base geometry class BaseGeometry.""" 4 | 5 | 6 | class BaseGeometry: 7 | """Reprsent base geometry.""" 8 | 9 | def area(self): 10 | """Not yet implemented.""" 11 | raise Exception("area() is not implemented") 12 | 13 | def integer_validator(self, name, value): 14 | """Validate a parameter as an integer. 15 | 16 | Args: 17 | name (str): The name of the parameter. 18 | value (int): The parameter to validate. 19 | Raises: 20 | TypeError: If value is not an integer. 21 | ValueError: If value is <= 0. 22 | """ 23 | if type(value) != int: 24 | raise TypeError("{} must be an integer".format(name)) 25 | if value <= 0: 26 | raise ValueError("{} must be greater than 0".format(name)) 27 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/8-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ module subclass rectangle 3 | """ 4 | BaseGeometry = __import__('7-base_geometry').BaseGeometry 5 | 6 | 7 | class Rectangle(BaseGeometry): 8 | """Rectangle that inherits from BaseGeometry""" 9 | def __init__(self, width, height): 10 | BaseGeometry.integer_validator(self, 'height', height) 11 | self.__height = height 12 | BaseGeometry.integer_validator(self, 'width', width) 13 | self.__width = width 14 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/9-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ module subclass rectangle 3 | """ 4 | BaseGeometry = __import__('7-base_geometry').BaseGeometry 5 | 6 | 7 | class Rectangle(BaseGeometry): 8 | """Rectangle that inherits from BaseGeometry""" 9 | def __init__(self, width, height): 10 | BaseGeometry.integer_validator(self, 'height', height) 11 | self.__height = height 12 | BaseGeometry.integer_validator(self, 'width', width) 13 | self.__width = width 14 | 15 | def area(self): 16 | return self.__width * self.__height 17 | 18 | def __str__(self): 19 | 20 | return "[Rectangle] {}/{}".format(self.__width, self.__height) 21 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/0-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | lookup = __import__('0-lookup').lookup 3 | 4 | class MyClass1(object): 5 | pass 6 | 7 | class MyClass2(object): 8 | my_attr1 = 3 9 | def my_meth(self): 10 | pass 11 | 12 | print(lookup(MyClass1)) 13 | print(lookup(MyClass2)) 14 | print(lookup(int)) 15 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/1-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | MyList = __import__('1-my_list').MyList 3 | 4 | my_list = MyList() 5 | my_list.append(1) 6 | my_list.append(4) 7 | my_list.append(2) 8 | my_list.append(3) 9 | my_list.append(5) 10 | print(my_list) 11 | my_list.print_sorted() 12 | print(my_list) 13 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/10-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Square = __import__('10-square').Square 3 | 4 | s = Square("Error") 5 | 6 | print(s) 7 | print(s.area()) 8 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/100-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | MyInt = __import__('100-my_int').MyInt 3 | 4 | my_i = MyInt(3) 5 | print(my_i) 6 | print(my_i == 3) 7 | print(my_i != 3) 8 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/101-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | add_attribute = __import__('101-add_attribute').add_attribute 3 | 4 | class MyClass(): 5 | pass 6 | 7 | mc = MyClass() 8 | add_attribute(mc, "name", "John") 9 | print(mc.name) 10 | 11 | try: 12 | a = "My String" 13 | add_attribute(a, "name", "Bob") 14 | print(a.name) 15 | except Exception as e: 16 | print("[{}] {}".format(e.__class__.__name__, e)) 17 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/11-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Square = __import__('11-square').Square 3 | 4 | s = Square("erroR") 5 | 6 | print(s) 7 | print(s.area()) 8 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/2-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | is_same_class = __import__('2-is_same_class').is_same_class 3 | 4 | a = 1 5 | if is_same_class(a, int): 6 | print("{} is an instance of the class {}".format(a, int.__name__)) 7 | if is_same_class(a, float): 8 | print("{} is an instance of the class {}".format(a, float.__name__)) 9 | if is_same_class(a, object): 10 | print("{} is an instance of the class {}".format(a, object.__name__)) 11 | """ 12 | class MyClass1(object): 13 | pass 14 | 15 | class MyClass2(object): 16 | my_attr1 = 3 17 | def my_meth(self): 18 | pass 19 | 20 | Myinstance = MyClass1() 21 | if is_same_class(Myinstance, MyClass2): 22 | print("{} is an instance of the class {}".format(Myinstance.__class__.name, Myclass1.__name__)) 23 | """ 24 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/3-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | is_kind_of_class = __import__('3-is_kind_of_class').is_kind_of_class 3 | 4 | a = 1 5 | if is_kind_of_class(a, int): 6 | print("{} comes from {}".format(a, int.__name__)) 7 | if is_kind_of_class(a, float): 8 | print("{} comes from {}".format(a, float.__name__)) 9 | if is_kind_of_class(a, object): 10 | print("{} comes from {}".format(a, object.__name__)) 11 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/4-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | inherits_from = __import__('4-inherits_from').inherits_from 3 | 4 | a = True 5 | if inherits_from(a, int): 6 | print("{} inherited from class {}".format(a, int.__name__)) 7 | if inherits_from(a, bool): 8 | print("{} inherited from class {}".format(a, bool.__name__)) 9 | if inherits_from(a, object): 10 | print("{} inherited from class {}".format(a, object.__name__)) 11 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/5-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | BaseGeometry = __import__('5-base_geometry').BaseGeometry 3 | 4 | bg = BaseGeometry() 5 | 6 | print(bg) 7 | print(dir(bg)) 8 | print(dir(BaseGeometry)) 9 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/6-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | BaseGeometry = __import__('6-base_geometry').BaseGeometry 3 | 4 | bg = BaseGeometry() 5 | 6 | try: 7 | print(bg.area()) 8 | except Exception as e: 9 | print("[{}] {}".format(e.__class__.__name__, e)) 10 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/7-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | BaseGeometry = __import__('7-base_geometry').BaseGeometry 3 | 4 | bg = BaseGeometry() 5 | 6 | bg.integer_validator("my_int", 12) 7 | bg.integer_validator("width", 89) 8 | 9 | try: 10 | bg.integer_validator("name", "John") 11 | except Exception as e: 12 | print("[{}] {}".format(e.__class__.__name__, e)) 13 | 14 | try: 15 | bg.integer_validator("age", 0) 16 | except Exception as e: 17 | print("[{}] {}".format(e.__class__.__name__, e)) 18 | 19 | try: 20 | bg.integer_validator("distance", -4) 21 | except Exception as e: 22 | print("[{}] {}".format(e.__class__.__name__, e)) 23 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/8-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('8-rectangle').Rectangle 3 | 4 | r = Rectangle(3, 5) 5 | 6 | print(r) 7 | print(dir(r)) 8 | 9 | try: 10 | print("Rectangle: {} - {}".format(r.width, r.height)) 11 | except Exception as e: 12 | print("[{}] {}".format(e.__class__.__name__, e)) 13 | 14 | try: 15 | r2 = Rectangle(4, True) 16 | except Exception as e: 17 | print("[{}] {}".format(e.__class__.__name__, e)) 18 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/9-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('9-rectangle').Rectangle 3 | 4 | r = Rectangle(3, 5) 5 | 6 | print(r) 7 | print(r.area()) 8 | -------------------------------------------------------------------------------- /0x0B-python-input_output/0-read_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ Module that contains a function that reads from a file """ 3 | 4 | 5 | def read_file(filename=""): 6 | """ Function that reads from a file 7 | 8 | Args: 9 | filename: filename 10 | 11 | Raises 12 | Exception: when the file can be opened 13 | 14 | """ 15 | 16 | with open(filename, 'r', encoding="utf-8") as f: 17 | read_data = f.read() 18 | print(read_data, end='') 19 | -------------------------------------------------------------------------------- /0x0B-python-input_output/1-write_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ Module that contains a function that writes to a text file 3 | """ 4 | 5 | 6 | def write_file(filename="", text=""): 7 | """ Function that writes to a text file 8 | 9 | Args: 10 | filename: filename 11 | text: text to write 12 | 13 | Raises 14 | Exception: when the file can be opened 15 | 16 | """ 17 | 18 | with open(filename, 'w', encoding="utf-8") as f: 19 | return f.write(text) 20 | -------------------------------------------------------------------------------- /0x0B-python-input_output/10-student.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ Module that defines the class Student 3 | """ 4 | 5 | 6 | class Student: 7 | """ Class to create student instances """ 8 | 9 | def __init__(self, first_name, last_name, age): 10 | """ Special method to initialize """ 11 | self.first_name = first_name 12 | self.last_name = last_name 13 | self.age = age 14 | 15 | def to_json(self, attrs=None): 16 | """ Method that returns directory description """ 17 | obj = self.__dict__.copy() 18 | if type(attrs) is list: 19 | 20 | for item in attrs: 21 | if type(item) is not str: 22 | return obj 23 | 24 | d_list = {} 25 | 26 | for iatr in range(len(attrs)): 27 | for satr in obj: 28 | if attrs[iatr] == satr: 29 | d_list[satr] = obj[satr] 30 | return d_list 31 | 32 | return obj 33 | -------------------------------------------------------------------------------- /0x0B-python-input_output/100-append_after.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ Module that executes a function that appends a line """ 3 | 4 | 5 | def append_after(filename="", search_string="", new_string=""): 6 | """ Function that appends a new line when a string is found 7 | 8 | Args: 9 | filename: filename 10 | search_string: string to search 11 | new_string: string to append 12 | 13 | """ 14 | 15 | res_line = [] 16 | with open(filename, 'r', encoding="utf-8") as f: 17 | for line in f: 18 | res_line += [line] 19 | if line.find(search_string) != -1: 20 | res_line += [new_string] 21 | 22 | with open(filename, 'w', encoding="utf-8") as f: 23 | f.write("".join(res_line)) 24 | -------------------------------------------------------------------------------- /0x0B-python-input_output/101-stats.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Reads from standard input and computes metrics. 3 | 4 | After every ten lines or the input of a keyboard interruption (CTRL + C), 5 | prints the following statistics: 6 | - Total file size up to that point. 7 | - Count of read status codes up to that point. 8 | """ 9 | 10 | 11 | def print_stats(size, status_codes): 12 | """Print accumulated metrics. 13 | 14 | Args: 15 | size (int): The accumulated read file size. 16 | status_codes (dict): The accumulated count of status codes. 17 | """ 18 | print("File size: {}".format(size)) 19 | for key in sorted(status_codes): 20 | print("{}: {}".format(key, status_codes[key])) 21 | 22 | 23 | if __name__ == "__main__": 24 | import sys 25 | 26 | size = 0 27 | status_codes = {} 28 | valid_codes = ['200', '301', '400', '401', '403', '404', '405', '500'] 29 | count = 0 30 | 31 | try: 32 | for line in sys.stdin: 33 | if count == 10: 34 | print_stats(size, status_codes) 35 | count = 1 36 | else: 37 | count += 1 38 | 39 | line = line.split() 40 | 41 | try: 42 | size += int(line[-1]) 43 | except (IndexError, ValueError): 44 | pass 45 | 46 | try: 47 | if line[-2] in valid_codes: 48 | if status_codes.get(line[-2], -1) == -1: 49 | status_codes[line[-2]] = 1 50 | else: 51 | status_codes[line[-2]] += 1 52 | except IndexError: 53 | pass 54 | 55 | print_stats(size, status_codes) 56 | 57 | except KeyboardInterrupt: 58 | print_stats(size, status_codes) 59 | raise 60 | -------------------------------------------------------------------------------- /0x0B-python-input_output/11-student.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ Module that defines the class Student 3 | """ 4 | 5 | 6 | class Student: 7 | """ Class to create student instances """ 8 | 9 | def __init__(self, first_name, last_name, age): 10 | """ Special method to initialize """ 11 | self.first_name = first_name 12 | self.last_name = last_name 13 | self.age = age 14 | 15 | def to_json(self, attrs=None): 16 | """ Method that returns directory description """ 17 | obj = self.__dict__.copy() 18 | if type(attrs) is list: 19 | 20 | for item in attrs: 21 | if type(item) is not str: 22 | return obj 23 | 24 | d_list = {} 25 | 26 | for iatr in range(len(attrs)): 27 | for satr in obj: 28 | if attrs[iatr] == satr: 29 | d_list[satr] = obj[satr] 30 | return d_list 31 | 32 | return obj 33 | 34 | def reload_from_json(self, json): 35 | """ Replaces all attributes of the Student instance """ 36 | for atr in json: 37 | self.__dict__[atr] = json[atr] 38 | -------------------------------------------------------------------------------- /0x0B-python-input_output/12-pascal_triangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a Pascal's Triangle function.""" 3 | 4 | 5 | def pascal_triangle(n): 6 | """Represent Pascal's Triangle of size n. 7 | 8 | Returns a list of lists of integers representing the triangle. 9 | """ 10 | if n <= 0: 11 | return [] 12 | 13 | triangles = [[1]] 14 | while len(triangles) != n: 15 | tri = triangles[-1] 16 | tmp = [1] 17 | for i in range(len(tri) - 1): 18 | tmp.append(tri[i] + tri[i + 1]) 19 | tmp.append(1) 20 | triangles.append(tmp) 21 | return triangles 22 | -------------------------------------------------------------------------------- /0x0B-python-input_output/2-append_write.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ Module that contains a function that appends to a text file 3 | """ 4 | 5 | 6 | def append_write(filename="", text=""): 7 | """ Function that appends to a text file 8 | 9 | Args: 10 | filename: filename 11 | text: text to write 12 | 13 | Raises 14 | Exception: when the file can be opened 15 | 16 | """ 17 | 18 | with open(filename, 'a', encoding="utf-8") as f: 19 | return f.write(text) 20 | -------------------------------------------------------------------------------- /0x0B-python-input_output/3-to_json_string.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ Module that contains a function that returns the JSON 3 | representation of an object 4 | """ 5 | import json 6 | 7 | 8 | def to_json_string(my_obj): 9 | """ Function that returns the JSON representation of an object 10 | 11 | Args: 12 | my_obj: object 13 | 14 | Raises: 15 | Exception: when the object can't be encoded 16 | 17 | """ 18 | return json.dumps(my_obj) 19 | -------------------------------------------------------------------------------- /0x0B-python-input_output/4-from_json_string.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ Module that contains a function that returns an object by 3 | a JSON representation 4 | """ 5 | import json 6 | 7 | 8 | def from_json_string(my_str): 9 | """ Function that returns an object by a JSON representation 10 | 11 | Args: 12 | my_str: JSON representation 13 | 14 | Raises: 15 | Exception: when the string can't be decoded 16 | 17 | """ 18 | return json.loads(my_str) 19 | -------------------------------------------------------------------------------- /0x0B-python-input_output/5-save_to_json_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ Module that writes an Object to a text file using 3 | a JSON representation 4 | """ 5 | import json 6 | 7 | 8 | def save_to_json_file(my_obj, filename): 9 | """ Function that writes an object to a text file 10 | by a JSON representation 11 | 12 | Args: 13 | my_obj: object 14 | filename: textfile name 15 | 16 | Raises: 17 | Exception: when the object can't be encoded 18 | 19 | """ 20 | with open(filename, 'w', encoding="utf-8") as f: 21 | json.dump(my_obj, f) 22 | -------------------------------------------------------------------------------- /0x0B-python-input_output/6-load_from_json_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ Module that creates an Object from a JSON file 3 | """ 4 | import json 5 | 6 | 7 | def load_from_json_file(filename): 8 | """ Function that creates an Object from a JSON file 9 | 10 | Args: 11 | filename: textfile name 12 | 13 | Raises: 14 | Exception: when the object can't be encoded 15 | 16 | """ 17 | with open(filename, 'r', encoding="utf-8") as f: 18 | return json.load(f) 19 | -------------------------------------------------------------------------------- /0x0B-python-input_output/7-add_item.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Add all arguments to a Python list and save them to a file.""" 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | save_to_json_file = __import__('5-save_to_json_file').save_to_json_file 7 | load_from_json_file = \ 8 | __import__('6-load_from_json_file').load_from_json_file 9 | 10 | try: 11 | items = load_from_json_file("add_item.json") 12 | except FileNotFoundError: 13 | items = [] 14 | items.extend(sys.argv[1:]) 15 | save_to_json_file(items, "add_item.json") 16 | -------------------------------------------------------------------------------- /0x0B-python-input_output/8-class_to_json.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ Module that returns the dictionary description with a simple 3 | data structure for a JSON serialization of an object 4 | """ 5 | 6 | 7 | def class_to_json(obj): 8 | """ Function that retuns the dictionary description of an obj """ 9 | 10 | res = {} 11 | if hasattr(obj, "__dict__"): 12 | res = obj.__dict__.copy() 13 | return res 14 | -------------------------------------------------------------------------------- /0x0B-python-input_output/9-student.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ Module that defines the class Student 3 | """ 4 | 5 | 6 | class Student: 7 | """ Class to create student instances """ 8 | 9 | def __init__(self, first_name, last_name, age): 10 | """ Special method to initialize """ 11 | self.first_name = first_name 12 | self.last_name = last_name 13 | self.age = age 14 | 15 | def to_json(self): 16 | """ Method that returns directory description """ 17 | return self.__dict__.copy() 18 | -------------------------------------------------------------------------------- /0x0B-python-input_output/tests/0-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | read_file = __import__('0-read_file').read_file 3 | 4 | read_file("my_file_0.txt") 5 | -------------------------------------------------------------------------------- /0x0B-python-input_output/tests/1-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | write_file = __import__('3-write_file').write_file 3 | 4 | nb_characters = write_file("my_first_file.txt", "School is so cool!\n") 5 | print(nb_characters) 6 | -------------------------------------------------------------------------------- /0x0B-python-input_output/tests/10-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Student = __import__('12-student').Student 3 | 4 | student_1 = Student("John", "Doe", 23) 5 | student_2 = Student("Bob", "Dylan", 27) 6 | 7 | j_student_1 = student_1.to_json() 8 | j_student_2 = student_2.to_json(['first_name', 'age']) 9 | j_student_3 = student_2.to_json(['middle_name', 'age']) 10 | 11 | print(j_student_1) 12 | print(j_student_2) 13 | print(j_student_3) 14 | -------------------------------------------------------------------------------- /0x0B-python-input_output/tests/100-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | append_after = __import__('100-append_after').append_after 3 | 4 | append_after("append_after_100.txt", "Python", "\"C is fun!\"\n") 5 | -------------------------------------------------------------------------------- /0x0B-python-input_output/tests/12-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | 14-main 4 | """ 5 | pascal_triangle = __import__('14-pascal_triangle').pascal_triangle 6 | 7 | def print_triangle(triangle): 8 | """ 9 | Print the triangle 10 | """ 11 | for row in triangle: 12 | print("[{}]".format(",".join([str(x) for x in row]))) 13 | 14 | 15 | if __name__ == "__main__": 16 | print_triangle(pascal_triangle(5)) 17 | -------------------------------------------------------------------------------- /0x0B-python-input_output/tests/2-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | append_write = __import__('4-append_write').append_write 3 | 4 | nb_characters_added = append_write("file_append.txt", "School is so cool!\n") 5 | print(nb_characters_added) 6 | -------------------------------------------------------------------------------- /0x0B-python-input_output/tests/3-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | to_json_string = __import__('5-to_json_string').to_json_string 3 | 4 | my_list = [1, 2, 3] 5 | s_my_list = to_json_string(my_list) 6 | print(s_my_list) 7 | print(type(s_my_list)) 8 | 9 | my_dict = { 10 | 'id': 12, 11 | 'name': "John", 12 | 'places': [ "San Francisco", "Tokyo" ], 13 | 'is_active': True, 14 | 'info': { 15 | 'age': 36, 16 | 'average': 3.14 17 | } 18 | } 19 | s_my_dict = to_json_string(my_dict) 20 | print(s_my_dict) 21 | print(type(s_my_dict)) 22 | 23 | try: 24 | my_set = { 132, 3 } 25 | s_my_set = to_json_string(my_set) 26 | print(s_my_set) 27 | print(type(s_my_set)) 28 | except Exception as e: 29 | print("[{}] {}".format(e.__class__.__name__, e)) 30 | -------------------------------------------------------------------------------- /0x0B-python-input_output/tests/4-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | from_json_string = __import__('6-from_json_string').from_json_string 3 | 4 | s_my_list = "[1, 2, 3]" 5 | my_list = from_json_string(s_my_list) 6 | print(my_list) 7 | print(type(my_list)) 8 | 9 | s_my_dict = """ 10 | {"is_active": true, "info": {"age": 36, "average": 3.14}, 11 | "id": 12, "name": "John", "places": ["San Francisco", "Tokyo"]} 12 | """ 13 | my_dict = from_json_string(s_my_dict) 14 | print(my_dict) 15 | print(type(my_dict)) 16 | 17 | try: 18 | s_my_dict = """ 19 | {"is_active": true, 12 } 20 | """ 21 | my_dict = from_json_string(s_my_dict) 22 | print(my_dict) 23 | print(type(my_dict)) 24 | except Exception as e: 25 | print("[{}] {}".format(e.__class__.__name__, e)) 26 | -------------------------------------------------------------------------------- /0x0B-python-input_output/tests/8-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | MyClass = __import__('10-my_class').MyClass 3 | class_to_json = __import__('10-class_to_json').class_to_json 4 | 5 | m = MyClass("John") 6 | m.number = 89 7 | print(type(m)) 8 | print(m) 9 | 10 | mj = class_to_json(m) 11 | print(type(mj)) 12 | print(mj) 13 | -------------------------------------------------------------------------------- /0x0B-python-input_output/tests/9-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Student = __import__('11-student').Student 3 | 4 | students = [Student("John", "Doe", 23), Student("Bob", "Dylan", 27)] 5 | 6 | for student in students: 7 | j_student = student.to_json() 8 | print(type(j_student)) 9 | print(j_student['first_name']) 10 | print(type(j_student['first_name'])) 11 | print(j_student['age']) 12 | print(type(j_student['age'])) 13 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/0-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 0-main """ 3 | from models.base import Base 4 | 5 | if __name__ == "__main__": 6 | 7 | b1 = Base() 8 | print(b1.id) 9 | 10 | b2 = Base() 11 | print(b2.id) 12 | 13 | b3 = Base() 14 | print(b3.id) 15 | 16 | b4 = Base(12) 17 | print(b4.id) 18 | 19 | b5 = Base() 20 | print(b5.id) 21 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/1-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 1-main """ 3 | from models.rectangle import Rectangle 4 | 5 | if __name__ == "__main__": 6 | 7 | r1 = Rectangle(10, 2) 8 | print(r1.id) 9 | 10 | r2 = Rectangle(2, 10) 11 | print(r2.id) 12 | 13 | r3 = Rectangle(10, 2, 0, 0, 12) 14 | print(r3.id) 15 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/10-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 10-main """ 3 | from models.square import Square 4 | 5 | if __name__ == "__main__": 6 | 7 | s1 = Square(5) 8 | print(s1) 9 | print(s1.size) 10 | s1.size = 10 11 | print(s1) 12 | 13 | try: 14 | s1.size = "9" 15 | except Exception as e: 16 | print("[{}] {}".format(e.__class__.__name__, e)) 17 | 18 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/100-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 100-main """ 3 | from models.rectangle import Rectangle 4 | from models.square import Square 5 | 6 | if __name__ == "__main__": 7 | 8 | r1 = Rectangle(10, 7, 2, 8) 9 | r2 = Rectangle(2, 4) 10 | list_rectangles_input = [r1, r2] 11 | 12 | Rectangle.save_to_file_csv(list_rectangles_input) 13 | 14 | list_rectangles_output = Rectangle.load_from_file_csv() 15 | 16 | for rect in list_rectangles_input: 17 | print("[{}] {}".format(id(rect), rect)) 18 | 19 | print("---") 20 | 21 | for rect in list_rectangles_output: 22 | print("[{}] {}".format(id(rect), rect)) 23 | 24 | print("---") 25 | print("---") 26 | 27 | s1 = Square(5) 28 | s2 = Square(7, 9, 1) 29 | list_squares_input = [s1, s2] 30 | 31 | Square.save_to_file_csv(list_squares_input) 32 | 33 | list_squares_output = Square.load_from_file_csv() 34 | 35 | for square in list_squares_input: 36 | print("[{}] {}".format(id(square), square)) 37 | 38 | print("---") 39 | 40 | for square in list_squares_output: 41 | print("[{}] {}".format(id(square), square)) 42 | 43 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/101-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 101-main """ 3 | from models.base import Base 4 | from models.rectangle import Rectangle 5 | from models.square import Square 6 | 7 | if __name__ == "__main__": 8 | 9 | list_rectangles = [Rectangle(100, 40), Rectangle(90, 110, 30, 10), Rectangle(20, 25, 110, 80)] 10 | list_squares = [Square(35), Square(15, 70, 50), Square(80, 30, 70)] 11 | 12 | Base.draw(list_rectangles, list_squares) 13 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/11-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 11-main """ 3 | from models.square import Square 4 | 5 | if __name__ == "__main__": 6 | 7 | s1 = Square(5) 8 | print(s1) 9 | 10 | s1.update(10) 11 | print(s1) 12 | 13 | s1.update(1, 2) 14 | print(s1) 15 | 16 | s1.update(1, 2, 3) 17 | print(s1) 18 | 19 | s1.update(1, 2, 3, 4) 20 | print(s1) 21 | 22 | s1.update(x=12) 23 | print(s1) 24 | 25 | s1.update(size=7, y=1) 26 | print(s1) 27 | 28 | s1.update(size=7, id=89, y=1) 29 | print(s1) 30 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/12-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 12-main """ 3 | from models.rectangle import Rectangle 4 | 5 | if __name__ == "__main__": 6 | 7 | r1 = Rectangle(10, 2, 1, 9) 8 | print(r1) 9 | r1_dictionary = r1.to_dictionary() 10 | print(r1_dictionary) 11 | print(type(r1_dictionary)) 12 | 13 | r2 = Rectangle(1, 1) 14 | print(r2) 15 | r2.update(**r1_dictionary) 16 | print(r2) 17 | print(r1 == r2) 18 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/13-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 13-main """ 3 | from models.square import Square 4 | 5 | if __name__ == "__main__": 6 | 7 | s1 = Square(10, 2, 1) 8 | print(s1) 9 | s1_dictionary = s1.to_dictionary() 10 | print(s1_dictionary) 11 | print(type(s1_dictionary)) 12 | 13 | s2 = Square(1, 1) 14 | print(s2) 15 | s2.update(**s1_dictionary) 16 | print(s2) 17 | print(s1 == s2) 18 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/14-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 14-main """ 3 | from models.base import Base 4 | from models.rectangle import Rectangle 5 | 6 | if __name__ == "__main__": 7 | 8 | r1 = Rectangle(10, 7, 2, 8) 9 | dictionary = r1.to_dictionary() 10 | #json_dictionary = Base.to_json_string([dictionary]) 11 | j = Base.to_json_string([{'y': 3, 'id': 1, 'x': 53, 'height': 39, 'width': 89}, {'size': 13, 'id': 2, 'x': 99, 'y': 19}, {'y': 99, 'id': 2, 'x': 99, 'height': 71, 'width': 17}, {'size': 13, 'id': 3, 'x': 81, 'y': 27}, {'y': 39, 'id': 3, 'x': 67, 'height': 17, 'width': 27}, {'size': 41, 'id': 4, 'x': 77, 'y': 83}, {'y': 21, 'id': 4, 'x': 49, 'height': 19, 'width': 39}, {'size': 19, 'id': 5, 'x': 61, 'y': 71}, {'y': 25, 'id': 5, 'x': 15, 'height': 93, 'width': 1}, {'size': 97, 'id': 6, 'x': 19, 'y': 43}, {'id': 20, 'name': '2454fee4-3a3f-4b4d-923d-a6ff745c36b4'}, {'id': 21, 'name': 'e262513a-b537-440a-ac08-4600ea4df5e6'}, {'id': 22, 'name': 'a4245a05-526e-4b18-8d8c-cda29a512414'}, {'id': 23, 'name': '6f5bb2fd-fc61-478e-a739-94bed72edd76'}, {'id': 24, 'name': '5c554f55-57f7-42e3-b00a-bbbe5b4215f5'}]) 12 | print(dictionary) 13 | print(type(dictionary)) 14 | print(j) 15 | print(type(j)) 16 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/15-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 15-main """ 3 | from models.rectangle import Rectangle 4 | from models.base import Base 5 | 6 | 7 | if __name__ == "__main__": 8 | 9 | r1 = Rectangle(10, 7, 2, 8) 10 | r2 = Rectangle(2, 4) 11 | Rectangle.save_to_file([r1, r2]) 12 | 13 | with open("Rectangle.json", "r") as file: 14 | print(file.read()) 15 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/16-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 16-main """ 3 | from models.rectangle import Rectangle 4 | 5 | if __name__ == "__main__": 6 | 7 | list_input = [ 8 | {'id': 89, 'width': 10, 'height': 4}, 9 | {'id': 7, 'width': 1, 'height': 7} 10 | ] 11 | json_list_input = Rectangle.to_json_string(list_input) 12 | list_output = Rectangle.from_json_string(json_list_input) 13 | print("[{}] {}".format(type(list_input), list_input)) 14 | print("[{}] {}".format(type(json_list_input), json_list_input)) 15 | print("[{}] {}".format(type(list_output), list_output)) 16 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/17-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 17-main """ 3 | from models.rectangle import Rectangle 4 | 5 | if __name__ == "__main__": 6 | 7 | r1 = Rectangle(3, 5, 1) 8 | r1_dictionary = r1.to_dictionary() 9 | r2 = Rectangle.create(**r1_dictionary) 10 | print(r1) 11 | print(r2) 12 | print(r1 is r2) 13 | print(r1 == r2) 14 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/18-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 18-main """ 3 | from models.rectangle import Rectangle 4 | from models.square import Square 5 | 6 | if __name__ == "__main__": 7 | 8 | r1 = Rectangle(10, 7, 2, 8) 9 | r2 = Rectangle(2, 4) 10 | list_rectangles_input = [r1, r2] 11 | 12 | Rectangle.save_to_file(list_rectangles_input) 13 | 14 | list_rectangles_output = Rectangle.load_from_file() 15 | 16 | for rect in list_rectangles_input: 17 | print("[{}] {}".format(id(rect), rect)) 18 | 19 | print("---") 20 | 21 | for rect in list_rectangles_output: 22 | print("[{}] {}".format(id(rect), rect)) 23 | 24 | print("---") 25 | print("---") 26 | 27 | s1 = Square(5) 28 | s2 = Square(7, 9, 1) 29 | list_squares_input = [s1, s2] 30 | 31 | Square.save_to_file(list_squares_input) 32 | 33 | list_squares_output = Square.load_from_file() 34 | 35 | for square in list_squares_input: 36 | print("[{}] {}".format(id(square), square)) 37 | 38 | print("---") 39 | 40 | for square in list_squares_output: 41 | print("[{}] {}".format(id(square), square)) 42 | 43 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/2-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 2-main """ 3 | from models.rectangle import Rectangle 4 | 5 | if __name__ == "__main__": 6 | 7 | try: 8 | Rectangle(10, "2") 9 | except Exception as e: 10 | print("[{}] {}".format(e.__class__.__name__, e)) 11 | 12 | try: 13 | r = Rectangle(10, 2) 14 | r.width = -10 15 | except Exception as e: 16 | print("[{}] {}".format(e.__class__.__name__, e)) 17 | 18 | try: 19 | r = Rectangle(10, 2) 20 | r.x = {} 21 | except Exception as e: 22 | print("[{}] {}".format(e.__class__.__name__, e)) 23 | 24 | try: 25 | Rectangle(10, 2, 3, -1) 26 | except Exception as e: 27 | print("[{}] {}".format(e.__class__.__name__, e)) 28 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/3-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3-main """ 3 | from models.rectangle import Rectangle 4 | 5 | if __name__ == "__main__": 6 | 7 | r1 = Rectangle(3, 2) 8 | print(r1.area()) 9 | 10 | r2 = Rectangle(2, 10) 11 | print(r2.area()) 12 | 13 | r3 = Rectangle(8, 7, 0, 0, 12) 14 | print(r3.area()) 15 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/4-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 4-main """ 3 | from models.rectangle import Rectangle 4 | 5 | if __name__ == "__main__": 6 | 7 | r1 = Rectangle(4, 6) 8 | r1.display() 9 | 10 | print("---") 11 | 12 | r1 = Rectangle(2, 2) 13 | r1.display() 14 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/5-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 5-main """ 3 | from models.rectangle import Rectangle 4 | 5 | if __name__ == "__main__": 6 | 7 | r1 = Rectangle(4, 6, 2, 1, 12) 8 | print(r1) 9 | 10 | r2 = Rectangle(5, 5, 1) 11 | print(r2) 12 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/6-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 6-main """ 3 | from models.rectangle import Rectangle 4 | 5 | if __name__ == "__main__": 6 | 7 | r1 = Rectangle(2, 3, 2, 2) 8 | r1.display() 9 | 10 | print("---") 11 | 12 | r2 = Rectangle(3, 2, 1, 0) 13 | r2.display() 14 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/7-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ Doc """ 3 | from models.rectangle import Rectangle 4 | 5 | if __name__ == "__main__": 6 | 7 | r1 = Rectangle(10, 10, 10, 10) 8 | print(r1) 9 | 10 | r1.update(89) 11 | print(r1) 12 | 13 | r1.update(89, 2) 14 | print(r1) 15 | 16 | r1.update(89, 2, 3) 17 | print(r1) 18 | 19 | r1.update(89, 2, 3, 4) 20 | print(r1) 21 | 22 | r1.update(89, 2, 3, 4, 5) 23 | print(r1) 24 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/8-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 8-main """ 3 | from models.rectangle import Rectangle 4 | 5 | if __name__ == "__main__": 6 | 7 | r1 = Rectangle(10, 10, 10, 10) 8 | print(r1) 9 | 10 | r1.update(6, height=1) 11 | print(r1) 12 | 13 | r1.update(width=1, x=2) 14 | print(r1) 15 | 16 | r1.update(y=1, width=2, x=3, id=89) 17 | print(r1) 18 | 19 | r1.update(x=1, height=2, y=3, width=4) 20 | print(r1) 21 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/9-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 9-main """ 3 | from models.square import Square 4 | 5 | if __name__ == "__main__": 6 | 7 | s1 = Square(5) 8 | print(s1) 9 | print(s1.area()) 10 | s1.display() 11 | 12 | print("---") 13 | 14 | s2 = Square(2, 2) 15 | print(s2) 16 | print(s2.area()) 17 | s2.display() 18 | 19 | print("---") 20 | 21 | s3 = Square(3, 1, 3) 22 | print(s3) 23 | print(s3.area()) 24 | s3.display() 25 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/models/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Aysuarex/alx-higher_level_programming/abf5a90359aa9f6492e9377276dea79820bf2d86/0x0C-python-almost_a_circle/models/__init__.py -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/tests/test_models/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Aysuarex/alx-higher_level_programming/abf5a90359aa9f6492e9377276dea79820bf2d86/0x0C-python-almost_a_circle/tests/test_models/__init__.py -------------------------------------------------------------------------------- /0x0D-SQL_introduction/0-list_databases.sql: -------------------------------------------------------------------------------- 1 | -- Lists all databases of my MySQL server 2 | SHOW DATABASES; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/1-create_database_if_missing.sql: -------------------------------------------------------------------------------- 1 | -- creates the database hbtn_0c_0 in my MySQL server. 2 | CREATE DATABASE IF NOT EXISTS `hbtn_0c_0`; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/10-top_score.sql: -------------------------------------------------------------------------------- 1 | -- Lists all records of the table second_table. 2 | -- Records are ordered by descending score. 3 | SELECT `score`, `name` 4 | FROM `second_table` 5 | ORDER BY `score` DESC; 6 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/100-move_to_utf8.sql: -------------------------------------------------------------------------------- 1 | -- Converts the entire database hbtn_0c_0 to UTF8. 2 | USE `hbtn_0c_0` 3 | ALTER TABLE `first_table` 4 | CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; 5 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/101-avg_temperatures.sql: -------------------------------------------------------------------------------- 1 | -- Displays the average temperature (in Fahrenheit) 2 | -- by city ordered by descending 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 | -- Displays the 3 cities with the highest average 2 | -- temperatures between July and August. 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 | SELECT `state`, MAX(`value`) AS `max_temp` 3 | FROM `temperatures` 4 | GROUP BY `state` 5 | ORDER BY `state`; 6 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/11-best_score.sql: -------------------------------------------------------------------------------- 1 | -- Lists all records in the table second_table with a score >= 10. 2 | -- Records are ordered by descending score. 3 | SELECT `score`, `name` 4 | FROM `second_table` 5 | WHERE `score` >= 10 6 | ORDER BY `score` DESC; 7 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/12-no_cheating.sql: -------------------------------------------------------------------------------- 1 | -- Updates the score of Bob to 10 in the table second_table. 2 | UPDATE `second_table` 3 | SET `score` = 10 4 | WHERE `name` = "Bob"; 5 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/13-change_class.sql: -------------------------------------------------------------------------------- 1 | -- Removes all records with a score <= 5 in the table second_table. 2 | DELETE FROM `second_table` 3 | WHERE `score` <= 5; 4 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/14-average.sql: -------------------------------------------------------------------------------- 1 | -- Computes the average score of all records in the table second_table. 2 | SELECT AVG(`score`) AS `average` 3 | FROM `second_table`; 4 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/15-groups.sql: -------------------------------------------------------------------------------- 1 | -- Lists the number of records with the same score in the table second_table. 2 | -- Records are ordered by descending count. 3 | SELECT `score`, COUNT(*) AS `number` 4 | FROM `second_table` 5 | GROUP BY `score` 6 | ORDER BY `number` DESC; 7 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/16-no_link.sql: -------------------------------------------------------------------------------- 1 | -- Lists all records of the table second_table having a name value. 2 | -- Records are ordered by descending score. 3 | SELECT `score`, `name` 4 | FROM `second_table` 5 | WHERE `name` != "" 6 | ORDER BY `score` DESC 7 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/2-remove_database.sql: -------------------------------------------------------------------------------- 1 | -- deletes the database hbtn_0c_0 in my MySQL server 2 | DROP DATABASE IF EXISTS `hbtn_0c_0`; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/3-list_tables.sql: -------------------------------------------------------------------------------- 1 | -- Lists all the tables of my database in my MySQL server 2 | SHOW TABLES; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/4-first_table.sql: -------------------------------------------------------------------------------- 1 | -- creates a table called first_table in my current DB 2 | CREATE TABLE IF NOT EXISTS `first_table` (`id` INT, `name` VARCHAR(256)); 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/5-full_table.sql: -------------------------------------------------------------------------------- 1 | -- Prints the full description of the table first_table. 2 | SHOW CREATE TABLE `first_table`; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/6-list_values.sql: -------------------------------------------------------------------------------- 1 | -- Lists all rows of the table first_table. 2 | SELECT * FROM `first_table`; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/7-insert_value.sql: -------------------------------------------------------------------------------- 1 | -- Inserts a new row into the table first_table. 2 | INSERT INTO `first_table` (`id`, `name`) VALUES (89, "Best School"); 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/8-count_89.sql: -------------------------------------------------------------------------------- 1 | -- Displays the number of records with id = 89 in the table first_table. 2 | SELECT COUNT(*) 3 | FROM `first_table` 4 | WHERE `id` = 89; 5 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/9-full_creation.sql: -------------------------------------------------------------------------------- 1 | -- Creates and fills a table second_table with attributes id, name and score. 2 | CREATE TABLE IF NOT EXISTS `second_table` (`id` INT, `name` VARCHAR(256), `score` INT); 3 | INSERT INTO `second_table` (`id`, `name`, `score`) VALUES (1, "John", 10); 4 | INSERT INTO `second_table` (`id`, `name`, `score`) VALUES (2, "Alex", 3); 5 | INSERT INTO `second_table` (`id`, `name`, `score`) VALUES (3, "Bob", 14); 6 | INSERT INTO `second_table` (`id`, `name`, `score`) VALUES (4, "George", 8); 7 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/0-privileges.sql: -------------------------------------------------------------------------------- 1 | -- Lists all privileges of the users user_0d_1 and user_0d_2 2 | SHOW GRANTS FOR 'user_0d_1'@'localhost'; 3 | SHOW GRANTS FOR 'user_0d_2'@'localhost'; 4 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/1-create_user.sql: -------------------------------------------------------------------------------- 1 | -- Creates the user user_0d_1 with all privileges. 2 | CREATE USER 3 | IF NOT EXISTS 'user_0d_1'@'localhost' 4 | IDENTIFIED BY 'user_0d_1_pwd'; 5 | GRANT ALL PRIVILEGES 6 | ON *.* 7 | TO 'user_0d_1'@'localhost'; 8 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/2-create_read_user.sql: -------------------------------------------------------------------------------- 1 | -- Creates the database hbtn_0d_2 and the user user_0d_2 2 | -- The user_0d_2 has SELECT privilege on hbtn_0d_2 with password user_0d_2_pwd 3 | CREATE DATABASE 4 | IF NOT EXISTS `hbtn_0d_2`; 5 | CREATE USER 6 | IF NOT EXISTS 'user_0d_2'@'localhost' 7 | IDENTIFIED BY 'user_0d_2_pwd'; 8 | GRANT SELECT 9 | ON `hbtn_0d_2`.* 10 | TO 'user_0d_2'@'localhost'; 11 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/0-select_states.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ lists all states from the database hbtn_0e_0_usa """ 3 | import MySQLdb 4 | import sys 5 | 6 | 7 | if __name__ == "__main__": 8 | db = MySQLdb.connect(host="localhost", user=sys.argv[1], 9 | passwd=sys.argv[2], db=sys.argv[3], port=3306) 10 | cur = db.cursor() 11 | cur.execute("SELECT * FROM states") 12 | rows = cur.fetchall() 13 | for row in rows: 14 | print(row) 15 | cur.close() 16 | db.close() 17 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/1-filter_states.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ lists all states from the database hbtn_0e_0_usa """ 3 | import MySQLdb 4 | import sys 5 | 6 | 7 | if __name__ == "__main__": 8 | db = MySQLdb.connect(host="localhost", user=sys.argv[1], 9 | passwd=sys.argv[2], db=sys.argv[3], port=3306) 10 | cur = db.cursor() 11 | cur.execute("""SELECT * FROM states WHERE name 12 | LIKE BINARY 'N%' ORDER BY states.id""") 13 | rows = cur.fetchall() 14 | for row in rows: 15 | print(row) 16 | cur.close() 17 | db.close() 18 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/10-model_state_my_get.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ prints the State object with the name passed as argument from the database 3 | """ 4 | import sys 5 | from model_state import Base, State 6 | from sqlalchemy import (create_engine) 7 | from sqlalchemy.orm import sessionmaker 8 | 9 | 10 | if __name__ == "__main__": 11 | engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}' 12 | .format(sys.argv[1], sys.argv[2], sys.argv[3])) 13 | Base.metadata.create_all(engine) 14 | Session = sessionmaker(bind=engine) 15 | session = Session() 16 | instance = session.query(State).filter(State.name == (sys.argv[4],)) 17 | try: 18 | print(instance[0].id) 19 | except IndexError: 20 | print("Not found") 21 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/100-relationship_states_cities.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Creates the State "California" with the City "San Francisco" from a DB 4 | """ 5 | import sys 6 | from relationship_state import Base, State 7 | from relationship_city import City 8 | from sqlalchemy import create_engine 9 | from sqlalchemy.orm import sessionmaker 10 | 11 | 12 | if __name__ == '__main__': 13 | engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}'. 14 | format(sys.argv[1], sys.argv[2], sys.argv[3]), 15 | pool_pre_ping=True) 16 | Base.metadata.create_all(engine) 17 | 18 | Session = sessionmaker(bind=engine) 19 | session = Session() 20 | 21 | newState = State(name='California') 22 | newCity = City(name='San Francisco') 23 | newState.cities.append(newCity) 24 | 25 | session.add(newState) 26 | session.add(newCity) 27 | session.commit() 28 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/101-relationship_states_cities_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ prints the State object with the name passed as argument from the database 3 | """ 4 | import sys 5 | from relationship_state import Base, State 6 | from relationship_city import City 7 | from sqlalchemy import (create_engine) 8 | from sqlalchemy.orm import sessionmaker 9 | from sqlalchemy.orm import relationship 10 | 11 | 12 | if __name__ == "__main__": 13 | engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}' 14 | .format(sys.argv[1], sys.argv[2], sys.argv[3])) 15 | Base.metadata.create_all(engine) 16 | Session = sessionmaker(bind=engine) 17 | session = Session() 18 | for instance in session.query(State).order_by(State.id): 19 | print(instance.id, instance.name, sep=": ") 20 | for city_ins in instance.cities: 21 | print(" ", end="") 22 | print(city_ins.id, city_ins.name, sep=": ") 23 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/102-relationship_cities_states_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ prints the State object with the name passed as argument from the database 3 | """ 4 | import sys 5 | from relationship_state import Base, State 6 | from relationship_city import City 7 | from sqlalchemy import (create_engine) 8 | from sqlalchemy.orm import sessionmaker 9 | from sqlalchemy.orm import relationship 10 | 11 | 12 | if __name__ == "__main__": 13 | engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}' 14 | .format(sys.argv[1], sys.argv[2], sys.argv[3])) 15 | Base.metadata.create_all(engine) 16 | Session = sessionmaker(bind=engine) 17 | session = Session() 18 | for instance in session.query(State).order_by(State.id): 19 | for city_ins in instance.cities: 20 | print(city_ins.id, city_ins.name, sep=": ", end="") 21 | print(" -> " + instance.name) 22 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/11-model_state_insert.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ prints the State object with the name passed as argument from the database 3 | """ 4 | import sys 5 | from model_state import Base, State 6 | from sqlalchemy import (create_engine) 7 | from sqlalchemy.orm import sessionmaker 8 | 9 | 10 | if __name__ == "__main__": 11 | engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}' 12 | .format(sys.argv[1], sys.argv[2], sys.argv[3])) 13 | Base.metadata.create_all(engine) 14 | Session = sessionmaker(bind=engine) 15 | session = Session() 16 | new_state = State(name='Louisiana') 17 | session.add(new_state) 18 | new_instance = session.query(State).filter_by(name='Louisiana').first() 19 | print(new_instance.id) 20 | session.commit() 21 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/12-model_state_update_id_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ prints the State object with the name passed as argument from the database 3 | """ 4 | import sys 5 | from model_state import Base, State 6 | from sqlalchemy import (create_engine) 7 | from sqlalchemy.orm import sessionmaker 8 | 9 | 10 | if __name__ == "__main__": 11 | engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}' 12 | .format(sys.argv[1], sys.argv[2], sys.argv[3])) 13 | Base.metadata.create_all(engine) 14 | Session = sessionmaker(bind=engine) 15 | session = Session() 16 | new_instance = session.query(State).filter_by(id=2).first() 17 | new_instance.name = 'New Mexico' 18 | session.commit() 19 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/13-model_state_delete_a.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ prints the State object with the name passed as argument from the database 3 | """ 4 | import sys 5 | from model_state import Base, State 6 | from sqlalchemy import (create_engine) 7 | from sqlalchemy.orm import sessionmaker 8 | 9 | 10 | if __name__ == "__main__": 11 | engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}' 12 | .format(sys.argv[1], sys.argv[2], sys.argv[3])) 13 | Base.metadata.create_all(engine) 14 | Session = sessionmaker(bind=engine) 15 | session = Session() 16 | for instance in session.query(State).filter(State.name.like('%a%')): 17 | session.delete(instance) 18 | session.commit() 19 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/14-model_city_fetch_by_state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ prints the State object with the name passed as argument from the database 3 | """ 4 | import sys 5 | from model_state import Base, State 6 | from model_city import City 7 | from sqlalchemy import (create_engine) 8 | from sqlalchemy.orm import sessionmaker 9 | 10 | 11 | if __name__ == "__main__": 12 | engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}' 13 | .format(sys.argv[1], sys.argv[2], sys.argv[3])) 14 | Base.metadata.create_all(engine) 15 | Session = sessionmaker(bind=engine) 16 | session = Session() 17 | for instance in (session.query(State.name, City.id, City.name) 18 | .filter(State.id == City.state_id)): 19 | print(instance[0] + ": (" + str(instance[1]) + ") " + instance[2]) 20 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/2-my_filter_states.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ lists all states from the database hbtn_0e_0_usa """ 3 | import MySQLdb 4 | import sys 5 | 6 | 7 | if __name__ == "__main__": 8 | db = MySQLdb.connect(host="localhost", user=sys.argv[1], 9 | passwd=sys.argv[2], db=sys.argv[3], port=3306) 10 | cur = db.cursor() 11 | cur.execute("SELECT * FROM states WHERE name LIKE BINARY '{}'" 12 | .format(sys.argv[4])) 13 | rows = cur.fetchall() 14 | for row in rows: 15 | print(row) 16 | cur.close() 17 | db.close() 18 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/3-my_safe_filter_states.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ lists all states from the database hbtn_0e_0_usa """ 3 | import MySQLdb 4 | import sys 5 | 6 | 7 | if __name__ == "__main__": 8 | db = MySQLdb.connect(host="localhost", user=sys.argv[1], 9 | passwd=sys.argv[2], db=sys.argv[3], port=3306) 10 | cur = db.cursor() 11 | match = sys.argv[4] 12 | cur.execute("SELECT * FROM states WHERE name LIKE %s", (match, )) 13 | rows = cur.fetchall() 14 | for row in rows: 15 | print(row) 16 | cur.close() 17 | db.close() 18 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/4-cities_by_state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ lists all states from the database hbtn_0e_0_usa """ 3 | import MySQLdb 4 | import sys 5 | 6 | 7 | if __name__ == "__main__": 8 | db = MySQLdb.connect(host="localhost", user=sys.argv[1], 9 | passwd=sys.argv[2], db=sys.argv[3], port=3306) 10 | cur = db.cursor() 11 | cur.execute("""SELECT cities.id, cities.name, states.name FROM 12 | cities INNER JOIN states ON states.id=cities.state_id""") 13 | rows = cur.fetchall() 14 | for row in rows: 15 | print(row) 16 | cur.close() 17 | db.close() 18 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/5-filter_cities.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ lists all states from the database hbtn_0e_0_usa """ 3 | import MySQLdb 4 | import sys 5 | 6 | 7 | if __name__ == "__main__": 8 | db = MySQLdb.connect(host="localhost", user=sys.argv[1], 9 | passwd=sys.argv[2], db=sys.argv[3], port=3306) 10 | cur = db.cursor() 11 | cur.execute("""SELECT cities.name FROM 12 | cities INNER JOIN states ON states.id=cities.state_id 13 | WHERE states.name=%s""", (sys.argv[4],)) 14 | rows = cur.fetchall() 15 | tmp = list(row[0] for row in rows) 16 | print(*tmp, sep=", ") 17 | cur.close() 18 | db.close() 19 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/6-model_state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Start link class to table in database 3 | """ 4 | import sys 5 | from model_state import Base, State 6 | 7 | from sqlalchemy import (create_engine) 8 | 9 | if __name__ == "__main__": 10 | engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}'.format(sys.argv[1], sys.argv[2], sys.argv[3]), pool_pre_ping=True) 11 | Base.metadata.create_all(engine) 12 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/7-model_state_fetch_all.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Start link class to table in database 3 | """ 4 | import sys 5 | from model_state import Base, State 6 | from sqlalchemy import (create_engine) 7 | from sqlalchemy.orm import sessionmaker 8 | 9 | 10 | if __name__ == "__main__": 11 | engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}' 12 | .format(sys.argv[1], sys.argv[2], sys.argv[3])) 13 | Base.metadata.create_all(engine) 14 | Session = sessionmaker(bind=engine) 15 | session = Session() 16 | for instance in session.query(State).order_by(State.id): 17 | print(instance.id, instance.name, sep=": ") 18 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/8-model_state_fetch_first.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ prints the first State object from the database hbtn_0e_6_usa 3 | """ 4 | import sys 5 | from model_state import Base, State 6 | from sqlalchemy import (create_engine) 7 | from sqlalchemy.orm import sessionmaker 8 | 9 | 10 | if __name__ == "__main__": 11 | engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}' 12 | .format(sys.argv[1], sys.argv[2], sys.argv[3])) 13 | Base.metadata.create_all(engine) 14 | Session = sessionmaker(bind=engine) 15 | session = Session() 16 | instance = session.query(State).first() 17 | if instance is None: 18 | print("Nothing") 19 | else: 20 | print(instance.id, instance.name, sep=": ") 21 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/9-model_state_filter_a.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ prints the first State object from the database hbtn_0e_6_usa 3 | """ 4 | import sys 5 | from model_state import Base, State 6 | from sqlalchemy import (create_engine) 7 | from sqlalchemy.orm import sessionmaker 8 | 9 | 10 | if __name__ == "__main__": 11 | engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}' 12 | .format(sys.argv[1], sys.argv[2], sys.argv[3])) 13 | Base.metadata.create_all(engine) 14 | Session = sessionmaker(bind=engine) 15 | session = Session() 16 | for instance in session.query(State).filter(State.name.like('%a%')): 17 | print(instance.id, instance.name, sep=": ") 18 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/model_city.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Contains the class definition of a City 4 | """ 5 | from model_state import Base 6 | from sqlalchemy import Column, Integer, String, ForeignKey 7 | from sqlalchemy.ext.declarative import declarative_base 8 | 9 | 10 | class City(Base): 11 | """ 12 | Class that defines each city 13 | """ 14 | __tablename__ = 'cities' 15 | id = Column(Integer, unique=True, nullable=False, primary_key=True) 16 | name = Column(String(128), nullable=False) 17 | state_id = Column(Integer, ForeignKey("states.id"), nullable=False) 18 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/model_state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Contains State class and Base, an instance of declarative_base() 4 | """ 5 | from sqlalchemy import Column, Integer, String, MetaData 6 | from sqlalchemy.ext.declarative import declarative_base 7 | 8 | mymetadata = MetaData() 9 | Base = declarative_base(metadata=mymetadata) 10 | 11 | 12 | class State(Base): 13 | """ 14 | Class with id and name attributes of each state 15 | """ 16 | __tablename__ = 'states' 17 | id = Column(Integer, unique=True, nullable=False, primary_key=True) 18 | name = Column(String(128), nullable=False) 19 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/relationship_city.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Contains the class definition of a City 4 | """ 5 | from relationship_state import Base 6 | from sqlalchemy import Column, Integer, String, ForeignKey 7 | from sqlalchemy.ext.declarative import declarative_base 8 | 9 | 10 | class City(Base): 11 | """ 12 | Class that defines each city 13 | """ 14 | __tablename__ = 'cities' 15 | id = Column(Integer, unique=True, nullable=False, primary_key=True) 16 | name = Column(String(128), nullable=False) 17 | state_id = Column(Integer, ForeignKey("states.id"), nullable=False) 18 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/relationship_state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Contains State class and Base, an instance of declarative_base() 4 | """ 5 | from sqlalchemy import Column, Integer, String, MetaData 6 | from sqlalchemy.ext.declarative import declarative_base 7 | from sqlalchemy.orm import relationship 8 | 9 | mymetadata = MetaData() 10 | Base = declarative_base(metadata=mymetadata) 11 | 12 | 13 | class State(Base): 14 | """ 15 | Class with id and name attributes of each state 16 | """ 17 | __tablename__ = 'states' 18 | id = Column(Integer, unique=True, nullable=False, primary_key=True) 19 | name = Column(String(128), nullable=False) 20 | cities = relationship("City", backref="states") 21 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/tests/0-select_states.sql: -------------------------------------------------------------------------------- 1 | -- Create states table in hbtn_0e_0_usa with some data 2 | CREATE DATABASE IF NOT EXISTS hbtn_0e_0_usa; 3 | USE hbtn_0e_0_usa; 4 | 5 | CREATE TABLE IF NOT EXISTS states ( 6 | id INT NOT NULL AUTO_INCREMENT, 7 | name VARCHAR(256) NOT NULL, 8 | PRIMARY KEY (id) 9 | ); 10 | 11 | INSERT INTO states (name) VALUES ("California"), ("Arizona"), ("Texas"), ("New York"), ("Nevada"); 12 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/tests/100-relationship_states_cities.sql: -------------------------------------------------------------------------------- 1 | -- Create the database hbtn_0e_100_usa 2 | CREATE DATABASE IF NOT EXISTS hbtn_0e_100_usa; 3 | USE hbtn_0e_100_usa; 4 | SELECT * FROM states; 5 | SELECT * FROM cities; 6 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/tests/101-relationship_states_cities_list.sql: -------------------------------------------------------------------------------- 1 | -- Create states table in hbtn_0e_101_usa with some data 2 | CREATE DATABASE IF NOT EXISTS hbtn_0e_101_usa; 3 | USE hbtn_0e_101_usa; 4 | CREATE TABLE IF NOT EXISTS states ( 5 | id INT NOT NULL AUTO_INCREMENT, 6 | name VARCHAR(256) NOT NULL, 7 | PRIMARY KEY (id) 8 | ); 9 | 10 | INSERT INTO states (name) VALUES ("California"), ("Arizona"), ("Texas"), ("New York"), ("Nevada"); 11 | CREATE TABLE IF NOT EXISTS cities ( 12 | id INT NOT NULL AUTO_INCREMENT, 13 | state_id INT NOT NULL, 14 | name VARCHAR(256) NOT NULL, 15 | PRIMARY KEY (id), 16 | FOREIGN KEY(state_id) REFERENCES states(id) 17 | ); 18 | INSERT INTO cities (state_id, name) VALUES (1,"San Francisco"), (1, "San Jose"), (1, "Los Angeles"), (1, "Fremont"), (1, "Livermore"); 19 | INSERT INTO cities (state_id, name) VALUES (2, "Page"), (2, "Phoenix"); 20 | INSERT INTO cities (state_id, name) VALUES (3, "Dallas"), (3, "Houston"), (3, "Austin"); 21 | INSERT INTO cities (state_id, name) VALUES (4, "New York"); 22 | INSERT INTO cities (state_id, name) VALUES (5, "Las Vegas"), (5, "Reno"), (5, "Henderson"), (5, "Carson City"); 23 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/tests/14-model_city_fetch_by_state.sql: -------------------------------------------------------------------------------- 1 | -- Create database hbtn_0e_14_usa, tables states and cities + some data 2 | CREATE DATABASE IF NOT EXISTS hbtn_0e_14_usa; 3 | USE hbtn_0e_14_usa; 4 | CREATE TABLE IF NOT EXISTS states ( 5 | id INT NOT NULL AUTO_INCREMENT, 6 | name VARCHAR(256) NOT NULL, 7 | PRIMARY KEY (id) 8 | ); 9 | 10 | INSERT INTO states (name) VALUES ("California"), ("Arizona"), ("Texas"), ("New York"), ("Nevada"); 11 | CREATE TABLE IF NOT EXISTS cities ( 12 | id INT NOT NULL AUTO_INCREMENT, 13 | state_id INT NOT NULL, 14 | name VARCHAR(256) NOT NULL, 15 | PRIMARY KEY (id), 16 | FOREIGN KEY(state_id) REFERENCES states(id) 17 | ); 18 | 19 | INSERT INTO cities (state_id, name) VALUES (1, "San Francisco"), (1, "San Jose"), (1, "Los Angeles"), (1, "Fremont"), (1, "Livermore"); 20 | INSERT INTO cities (state_id, name) VALUES (2, "Page"), (2, "Phoenix"); 21 | INSERT INTO cities (state_id, name) VALUES (3, "Dallas"), (3, "Houston"), (3, "Austin"); 22 | INSERT INTO cities (state_id, name) VALUES (4, "New York"); 23 | INSERT INTO cities (state_id, name) VALUES (5, "Las Vegas"), (5, "Reno"), (5, "Henderson"), (5, "Carson City"); 24 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/tests/4-cities_by_state.sql: -------------------------------------------------------------------------------- 1 | -- Create states table in hbtn_0e_4_usa with some data 2 | 3 | CREATE DATABASE IF NOT EXISTS hbtn_0e_4_usa; 4 | USE hbtn_0e_4_usa; 5 | 6 | CREATE TABLE IF NOT EXISTS states ( 7 | id INT NOT NULL AUTO_INCREMENT, 8 | name VARCHAR(256) NOT NULL, 9 | PRIMARY KEY (id) 10 | ); 11 | 12 | INSERT INTO states (name) VALUES ("California"), ("Arizona"), ("Texas"), ("New York"), ("Nevada"); 13 | 14 | CREATE TABLE IF NOT EXISTS cities ( 15 | id INT NOT NULL AUTO_INCREMENT, 16 | state_id INT NOT NULL, 17 | name VARCHAR(256) NOT NULL, 18 | PRIMARY KEY (id), 19 | FOREIGN KEY(state_id) REFERENCES states(id) 20 | ); 21 | 22 | INSERT INTO cities (state_id, name) VALUES (1, "San Francisco"), (1, "San Jose"), (1, "Los Angeles"), (1, "Fremont"), (1, "Livermore"); 23 | INSERT INTO cities (state_id, name) VALUES (2, "Page"), (2, "Phoenix"); 24 | INSERT INTO cities (state_id, name) VALUES (3, "Dallas"), (3, "Houston"), (3, "Austin"); 25 | INSERT INTO cities (state_id, name) VALUES (4, "New York"); 26 | INSERT INTO cities (state_id, name) VALUES (5, "Las Vegas"), (5, "Reno"), (5, "Henderson"), (5, "Carson City"); 27 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/tests/6-model_state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Start link class to table in database 3 | """ 4 | 5 | import sys 6 | from model_state import Base, State 7 | from sqlalchemy import (create_engine) 8 | 9 | if __name__ == "__main__": 10 | engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}' 11 | .format(sys.argv[1], sys.argv[2], sys.argv[3]), 12 | pool_pre_ping=True) 13 | Base.metadata.create_all(engine) 14 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/tests/6-model_state.sql: -------------------------------------------------------------------------------- 1 | -- Create database hbtn_0e_6_usa 2 | CREATE DATABASE IF NOT EXISTS hbtn_0e_6_usa; 3 | USE hbtn_0e_6_usa; 4 | SHOW CREATE TABLE states; 5 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/tests/7-model_state_fetch_all.sql: -------------------------------------------------------------------------------- 1 | -- Insert states 2 | INSERT INTO states (name) VALUES ("California"), ("Arizona"), ("Texas"), ("New York"), ("Nevada"); 3 | -------------------------------------------------------------------------------- /0x10-python-network_0/0-body_size.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Get the byte size of the HTTP response header for a given URL. 3 | curl -s "$1" | wc -c 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/1-body.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # takes in a URL, sends a GET request to the URL, and displays the body of the response 3 | curl -sL "$1" 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/100-status_code.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # sends a request to a URL passed as an argument, and displays only the status code of the response. no pipe 3 | awk 'NR==1{printf "%s", $2}' test7 $(curl -sI "$1" -o test7) 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/101-post_json.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Sends a JSON POST request to a given URL with a given JSON file. 3 | curl -s -H "Content-Type: application/json" -d "$(cat "$2")" "$1" 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/102-catch_me.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Makes a request to 0.0.0.0:5000/catch_me that gets the message "You got me!". 3 | curl -sL -X PUT -H "Origin: HolbertonSchool" -d "user_id=98" 0.0.0.0:5000/catch_me 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/2-delete.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Send a DELETE request to a given URL and display the response body. 3 | curl -sX DELETE "$1" 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/3-methods.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # takes in a URL and displays all HTTP methods the server will accept. 3 | curl -Is "$1" | grep "Allow:" | cut -d ":" -f 2 | cut -c 2- | rev | cut -c 2- | rev 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/4-header.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Send a GET request to a given URL with a header variable. 3 | curl -sH "X-School-User-Id: 98" "${1}" 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/5-post_params.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Script that sends a POST request and displays the body response 3 | curl -s "$1" -X POST -d "email=test@gmail.com&subject=I will always be here for PLD" 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/6-peak.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Finds a peak in a list of unsorted integers""" 3 | 4 | 5 | def find_peak(list_of_integers): 6 | """Finds a peak in list_of_integers""" 7 | 8 | if list_of_integers is None or list_of_integers == []: 9 | return None 10 | lo = 0 11 | hi = len(list_of_integers) 12 | mid = ((hi - lo) // 2) + lo 13 | mid = int(mid) 14 | if hi == 1: 15 | return list_of_integers[0] 16 | if hi == 2: 17 | return max(list_of_integers) 18 | if list_of_integers[mid] >= list_of_integers[mid - 1] and\ 19 | list_of_integers[mid] >= list_of_integers[mid + 1]: 20 | return list_of_integers[mid] 21 | if mid > 0 and list_of_integers[mid] < list_of_integers[mid + 1]: 22 | return find_peak(list_of_integers[mid:]) 23 | if mid > 0 and list_of_integers[mid] < list_of_integers[mid - 1]: 24 | return find_peak(list_of_integers[:mid]) 25 | -------------------------------------------------------------------------------- /0x10-python-network_0/6-peak.txt: -------------------------------------------------------------------------------- 1 | O(log(n)) 2 | -------------------------------------------------------------------------------- /0x10-python-network_0/tests/6-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ Test function find_peak """ 3 | find_peak = __import__('6-peak').find_peak 4 | 5 | print(find_peak([1, 2, 4, 6, 3])) 6 | print(find_peak([4, 2, 1, 2, 3, 1])) 7 | print(find_peak([2, 2, 2])) 8 | print(find_peak([])) 9 | print(find_peak([-2, -4, 2, 1])) 10 | print(find_peak([4, 2, 1, 2, 3, 1])) 11 | -------------------------------------------------------------------------------- /0x11-python-network_1/0-hbtn_status.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """A script that 3 | - fetches https://alx-intranet.hbtn.io/status. 4 | - uses urlib package 5 | """ 6 | 7 | 8 | if __name__ == '__main__': 9 | import urllib.request 10 | 11 | with urllib.request.urlopen('https://alx-intranet.hbtn.io/status') as res: 12 | content = res.read() 13 | print("Body response:") 14 | print("\t- type: {}".format(type(content))) 15 | print("\t- content: {}".format(content)) 16 | print("\t- utf8 content: {}".format(content.decode('utf-8'))) 17 | -------------------------------------------------------------------------------- /0x11-python-network_1/1-hbtn_header.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """A script that: 3 | - takes in a URL, 4 | - sends a request to the URL and displays the value 5 | - of the X-Request-Id variable found in the header ofthe response. 6 | """ 7 | import sys 8 | import urllib.request 9 | 10 | if __name__ == "__main__": 11 | url = sys.argv[1] 12 | 13 | request = urllib.request.Request(url) 14 | with urllib.request.urlopen(request) as response: 15 | print(dict(response.headers).get("X-Request-Id")) 16 | -------------------------------------------------------------------------------- /0x11-python-network_1/10-my_github.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """A script that: 3 | - takes your GitHub credentials (username and password) 4 | - uses the GitHub API to display your id 5 | """ 6 | import sys 7 | import requests 8 | from requests.auth import HTTPBasicAuth 9 | 10 | 11 | if __name__ == "__main__": 12 | auth = HTTPBasicAuth(sys.argv[1], sys.argv[2]) 13 | r = requests.get("https://api.github.com/user", auth=auth) 14 | print(r.json().get("id")) 15 | -------------------------------------------------------------------------------- /0x11-python-network_1/100-github_commits.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """lists the 10 most recent commits on a given GitHub repository. 3 | """ 4 | import sys 5 | import requests 6 | 7 | 8 | if __name__ == "__main__": 9 | url = "https://api.github.com/repos/{}/{}/commits".format( 10 | sys.argv[2], sys.argv[1]) 11 | 12 | r = requests.get(url) 13 | commits = r.json() 14 | try: 15 | for i in range(10): 16 | print("{}: {}".format( 17 | commits[i].get("sha"), 18 | commits[i].get("commit").get("author").get("name"))) 19 | except IndexError: 20 | pass 21 | -------------------------------------------------------------------------------- /0x11-python-network_1/2-post_email.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """A script that: 3 | - takes in a URL 4 | - sends a POST request to the passed URL 5 | - takes email as a parameter 6 | - displays the body of the response 7 | """ 8 | import sys 9 | import urllib.parse 10 | import urllib.request 11 | 12 | 13 | if __name__ == "__main__": 14 | url = sys.argv[1] 15 | value = {"email": sys.argv[2]} 16 | data = urllib.parse.urlencode(value).encode("ascii") 17 | 18 | request = urllib.request.Request(url, data) 19 | with urllib.request.urlopen(request) as response: 20 | print(response.read().decode("utf-8")) 21 | -------------------------------------------------------------------------------- /0x11-python-network_1/3-error_code.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """A script that: 3 | - takes in a URL, 4 | - sends a request to the URL 5 | - displays the body of the response (decoded in utf-8). 6 | """ 7 | 8 | 9 | if __name__ == "__main__": 10 | import sys 11 | from urllib import request, error 12 | 13 | try: 14 | with request.urlopen(sys.argv[1]) as res: 15 | print(res.read().decode('UTF-8')) 16 | except error.HTTPError as er: 17 | print('Error code:', er.code) 18 | -------------------------------------------------------------------------------- /0x11-python-network_1/4-hbtn_status.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | requests model 4 | """ 5 | 6 | if __name__ == '__main__': 7 | import requests 8 | html = requests.get('https://alx-intranet.hbtn.io/status') 9 | print("Body response:") 10 | print("\t- type: {}".format(html.text.__class__)) 11 | print("\t- content: {}".format(html.text)) 12 | -------------------------------------------------------------------------------- /0x11-python-network_1/5-hbtn_header.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Displays the X-Request-Id header variable of a request to a given URL 3 | """ 4 | import sys 5 | import requests 6 | 7 | 8 | if __name__ == "__main__": 9 | url = sys.argv[1] 10 | 11 | r = requests.get(url) 12 | print(r.headers.get("X-Request-Id")) 13 | -------------------------------------------------------------------------------- /0x11-python-network_1/6-post_email.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """A script that: 3 | - takes in a URL and an email address 4 | - sends a POST request to the passed URL with the email as a parameter 5 | - displays the body of the response. 6 | """ 7 | import sys 8 | import requests 9 | 10 | 11 | if __name__ == "__main__": 12 | url = sys.argv[1] 13 | value = {"email": sys.argv[2]} 14 | 15 | r = requests.post(url, data=value) 16 | print(r.text) 17 | -------------------------------------------------------------------------------- /0x11-python-network_1/7-error_code.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """A script that 3 | - takes in a URL 4 | - sends a request to the URL 5 | - displays the body of the response. 6 | """ 7 | import sys 8 | import requests 9 | 10 | 11 | if __name__ == "__main__": 12 | url = sys.argv[1] 13 | 14 | r = requests.get(url) 15 | if r.status_code >= 400: 16 | print("Error code: {}".format(r.status_code)) 17 | else: 18 | print(r.text) 19 | -------------------------------------------------------------------------------- /0x11-python-network_1/8-json_api.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """A script tha: 3 | - takes in a letter 4 | - sends POST request to http://0.0.0.0:5000/search_user 5 | with the letter as a parameter. 6 | """ 7 | import sys 8 | import requests 9 | 10 | 11 | if __name__ == "__main__": 12 | letter = "" if len(sys.argv) == 1 else sys.argv[1] 13 | payload = {"q": letter} 14 | 15 | r = requests.post("http://0.0.0.0:5000/search_user", data=payload) 16 | try: 17 | response = r.json() 18 | if response == {}: 19 | print("No result") 20 | else: 21 | print("[{}] {}".format(response.get("id"), response.get("name"))) 22 | except ValueError: 23 | print("Not a valid JSON") 24 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/0-javascript_is_amazing.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const myVar = 'JavaScript is amazing'; 3 | console.log(myVar); 4 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/1-multi_languages.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | console.log('C is fun'); 3 | console.log('Python is cool'); 4 | console.log('JavaScript is amazing'); 5 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/10-factorial.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | function factorial (n) { 3 | return n === 0 || isNaN(n) ? 1 : n * factorial(n - 1); 4 | } 5 | 6 | console.log(factorial(Number(process.argv[2]))); 7 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/100-let_me_const.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | myVar = 333; 3 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/101-call_me_moby.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | exports.callMeMoby = function (x, theFunction) { 3 | for (let i = 0; i < x; i++) theFunction(); 4 | }; 5 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/102-add_me_maybe.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | exports.addMeMaybe = function (number, theFunction) { 3 | theFunction(++number); 4 | }; 5 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/103-object_fct.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const myObject = { 3 | type: 'object', 4 | value: 12 5 | }; 6 | console.log(myObject); 7 | myObject.incr = function () { 8 | this.value++; 9 | }; 10 | myObject.incr(); 11 | console.log(myObject); 12 | myObject.incr(); 13 | console.log(myObject); 14 | myObject.incr(); 15 | console.log(myObject); 16 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/11-second_biggest.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | if (process.argv.length <= 3) { 3 | console.log(0); 4 | } else { 5 | const args = process.argv.map(Number) 6 | .slice(2, process.argv.length) 7 | .sort((a, b) => a - b); 8 | console.log(args[args.length - 2]); 9 | } 10 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/12-object.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const myObject = { 3 | type: 'object', 4 | value: 12 5 | }; 6 | console.log(myObject); 7 | myObject.value = 89; 8 | console.log(myObject); 9 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/13-add.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | exports.add = (a, b) => a + b; 3 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/2-arguments.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const count = process.argv.length; 3 | console.log(count === 2 ? 'No argument' : count === 3 ? 'Argument found' : 'Arguments found'); 4 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/3-value_argument.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | console.log(typeof process.argv[2] === 'undefined' ? 'No argument' : process.argv[2]); 3 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/4-concat.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | console.log(`${process.argv[2]} is ${process.argv[3]}`); 3 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/5-to_integer.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const num = Math.floor(Number(process.argv[2])); 3 | console.log(isNaN(num) ? 'Not a number' : `My number: ${num}`); 4 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/6-multi_languages_loop.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | for (const line of ['C is fun', 'Python is cool', 'JavaScript is amazing']) { 3 | console.log(line); 4 | } 5 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/7-multi_c.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const x = Math.floor(Number(process.argv[2])); 3 | if (isNaN(x)) { 4 | console.log('Missing number of occurrences'); 5 | } else { 6 | for (let i = 0; i < x; i++) { 7 | console.log('C is fun'); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/8-square.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const size = Math.floor(Number(process.argv[2])); 3 | if (isNaN(size)) { 4 | console.log('Missing size'); 5 | } else { 6 | for (let r = 0; r < size; r++) { 7 | let row = ''; 8 | for (let c = 0; c < size; c++) row += 'X'; 9 | console.log(row); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/9-add.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | function add (a, b) { 3 | return a + b; 4 | } 5 | 6 | console.log(add(Number(process.argv[2]), Number(process.argv[3]))); 7 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/0-rectangle.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | module.exports = class Rectangle {}; 3 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/1-rectangle.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | module.exports = class Rectangle { 3 | constructor (w, h) { 4 | this.width = w; 5 | this.height = h; 6 | } 7 | }; 8 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/10-converter.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | exports.converter = function (base) { return num => num.toString(base); }; 3 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/100-data.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | exports.list = [1, 2, 3, 4, 5]; 3 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/100-map.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const list = require('./100-data.js').list; 3 | console.log(list); 4 | console.log(list.map((item, index) => item * index)); 5 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/101-data.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | exports.dict = { 3 | 89: 1, 4 | 90: 2, 5 | 91: 1, 6 | 92: 3, 7 | 93: 1, 8 | 94: 2 9 | }; 10 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/101-sorted.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const dict = require('./101-data').dict; 3 | 4 | const totalist = Object.entries(dict); 5 | const vals = Object.values(dict); 6 | const valsUniq = [...new Set(vals)]; 7 | const newDict = {}; 8 | for (const j in valsUniq) { 9 | const list = []; 10 | for (const k in totalist) { 11 | if (totalist[k][1] === valsUniq[j]) { 12 | list.unshift(totalist[k][0]); 13 | } 14 | } 15 | newDict[valsUniq[j]] = list; 16 | } 17 | console.log(newDict); 18 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/102-concat.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const fs = require('fs'); 3 | const a = fs.readFileSync(process.argv[2], 'utf8'); 4 | const b = fs.readFileSync(process.argv[3], 'utf8'); 5 | fs.writeFileSync(process.argv[4], a + b); 6 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/2-rectangle.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | module.exports = class Rectangle { 3 | constructor (w, h) { 4 | if (w > 0 && h > 0) { [this.width, this.height] = [w, h]; } 5 | } 6 | }; 7 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/3-rectangle.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | module.exports = class Rectangle { 3 | constructor (w, h) { 4 | if (w > 0 && h > 0) { [this.width, this.height] = [w, h]; } 5 | } 6 | 7 | print () { 8 | for (let i = 0; i < this.height; i++) console.log('X'.repeat(this.width)); 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/4-rectangle.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | module.exports = class Rectangle { 3 | constructor (w, h) { 4 | if (w > 0 && h > 0) { [this.width, this.height] = [w, h]; } 5 | } 6 | 7 | print () { 8 | for (let i = 0; i < this.height; i++) console.log('X'.repeat(this.width)); 9 | } 10 | 11 | rotate () { 12 | [this.width, this.height] = [this.height, this.width]; 13 | } 14 | 15 | double () { 16 | [this.width, this.height] = [this.width * 2, this.height * 2]; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/5-square.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | module.exports = class Square extends require('./4-rectangle.js') { 3 | constructor (size) { 4 | super(size, size); 5 | } 6 | }; 7 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/6-square.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | module.exports = class Square extends require('./5-square.js') { 3 | charPrint (c) { 4 | if (c === undefined) { 5 | this.print(); 6 | } else { 7 | for (let i = 0; i < this.height; i++) console.log(c.repeat(this.width)); 8 | } 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/7-occurrences.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | exports.nbOccurences = function (list, searchElement) { 3 | return list.reduce((count, current) => current === searchElement ? count + 1 : count, 0); 4 | }; 5 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/8-esrever.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | exports.esrever = function (list) { 3 | return list.reduceRight(function (array, current) { 4 | array.push(current); 5 | return array; 6 | }, []); 7 | }; 8 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/9-logme.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | let count = 0; 3 | exports.logMe = function (item) { console.log(`${count++}: ${item}`); }; 4 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/tests/0-main.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const Rectangle = require('../0-rectangle'); 3 | 4 | const r1 = new Rectangle(); 5 | console.log(r1); 6 | console.log(r1.constructor); 7 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/tests/1-main.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const Rectangle = require('../1-rectangle'); 3 | 4 | const r1 = new Rectangle(2, 3); 5 | console.log(r1); 6 | console.log(r1.width); 7 | console.log(r1.height); 8 | 9 | const r2 = new Rectangle(2, -3); 10 | console.log(r2); 11 | console.log(r2.width); 12 | console.log(r2.height); 13 | 14 | const r3 = new Rectangle(2); 15 | console.log(r3); 16 | console.log(r3.width); 17 | console.log(r3.height); 18 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/tests/10-main.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const converter = require('../10-converter').converter; 3 | 4 | let myConverter = converter(10); 5 | 6 | console.log(myConverter(2)); 7 | console.log(myConverter(12)); 8 | console.log(myConverter(89)); 9 | 10 | myConverter = converter(16); 11 | 12 | console.log(myConverter(2)); 13 | console.log(myConverter(12)); 14 | console.log(myConverter(89)); 15 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/tests/2-main.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const Rectangle = require('../2-rectangle'); 3 | 4 | const r1 = new Rectangle(2, 3); 5 | console.log(r1); 6 | console.log(r1.width); 7 | console.log(r1.height); 8 | 9 | const r2 = new Rectangle(2, -3); 10 | console.log(r2); 11 | console.log(r2.width); 12 | console.log(r2.height); 13 | 14 | const r3 = new Rectangle(2); 15 | console.log(r3); 16 | console.log(r3.width); 17 | console.log(r3.height); 18 | 19 | const r4 = new Rectangle(2, 0); 20 | console.log(r4); 21 | console.log(r4.width); 22 | console.log(r4.height); 23 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/tests/3-main.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const Rectangle = require('../3-rectangle'); 3 | 4 | const r1 = new Rectangle(2, 3); 5 | r1.print(); 6 | 7 | const r2 = new Rectangle(10, 5); 8 | r2.print(); 9 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/tests/4-main.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const Rectangle = require('../4-rectangle'); 3 | 4 | const r1 = new Rectangle(2, 3); 5 | console.log('Normal:'); 6 | r1.print(); 7 | 8 | console.log('Double:'); 9 | r1.double(); 10 | r1.print(); 11 | 12 | console.log('Rotate:'); 13 | r1.rotate(); 14 | r1.print(); 15 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/tests/5-main.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const Square = require('../5-square'); 3 | 4 | const s1 = new Square(4); 5 | s1.print(); 6 | s1.double(); 7 | s1.print(); 8 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/tests/6-main.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const Square = require('../6-square'); 3 | 4 | const s1 = new Square(4); 5 | s1.charPrint(); 6 | 7 | s1.charPrint('C'); 8 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/tests/7-main.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const nbOccurences = require('../7-occurrences').nbOccurences; 3 | 4 | console.log(nbOccurences([1, 2, 3, 4, 5, 6], 3)); 5 | console.log(nbOccurences([3, 2, 3, 4, 5, 3, 3], 3)); 6 | console.log(nbOccurences(['H', 12, 'c', 'H', 'Holberton', 8], 'H')); 7 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/tests/8-main.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const esrever = require('../8-esrever').esrever; 3 | 4 | console.log(esrever([1, 2, 3, 4, 5])); 5 | console.log(esrever(['School', 89, { id: 12 }, 'String'])); 6 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/tests/9-main.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const logMe = require('../9-logme').logMe; 3 | 4 | logMe('Hello'); 5 | logMe('Best'); 6 | logMe('School'); 7 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/0-readme.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | const fs = require('fs'); 4 | const file = process.argv[2]; 5 | 6 | fs.readFile(file, 'utf-8', function (err, data) { 7 | if (err) { 8 | console.log(err); 9 | } else { 10 | console.log(data); 11 | } 12 | }); 13 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/1-writeme.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | const fs = require('fs'); 4 | const file = process.argv[2]; 5 | const string = process.argv[3]; 6 | 7 | fs.writeFile(file, string, 'utf-8', function (err) { 8 | if (err) console.log(err); 9 | }); 10 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/100-starwars_characters.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | const req = require('request'); 4 | const id = process.argv[2]; 5 | const url = 'https://swapi-api.hbtn.io/api/films/'; 6 | req.get(url + id, function (error, res, body) { 7 | if (error) { 8 | console.log(error); 9 | } 10 | const data = JSON.parse(body); 11 | const dd = data.characters; 12 | for (const i of dd) { 13 | req.get(i, function (error, res, body1) { 14 | if (error) { 15 | console.log(error); 16 | } 17 | const data1 = JSON.parse(body1); 18 | console.log(data1.name); 19 | }); 20 | } 21 | }); 22 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/101-starwars_characters.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const request = require('request'); 3 | const url = 'https://swapi-api.hbtn.io/api/films/' + process.argv[2]; 4 | request(url, function (error, response, body) { 5 | if (!error) { 6 | const characters = JSON.parse(body).characters; 7 | printCharacters(characters, 0); 8 | } 9 | }); 10 | 11 | function printCharacters (characters, index) { 12 | request(characters[index], function (error, response, body) { 13 | if (!error) { 14 | console.log(JSON.parse(body).name); 15 | if (index + 1 < characters.length) { 16 | printCharacters(characters, index + 1); 17 | } 18 | } 19 | }); 20 | } 21 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/2-statuscode.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | const request = require('request'); 4 | const URL = process.argv[2]; 5 | 6 | request(URL, function (err, response) { 7 | if (err) { 8 | console.log(err); 9 | } else { 10 | console.log('code: ' + response.statusCode); 11 | } 12 | }); 13 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/3-starwars_title.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | const request = require('request'); 4 | const episodeNum = process.argv[2]; 5 | const API_URL = 'https://swapi-api.hbtn.io/api/films/'; 6 | 7 | request(API_URL + episodeNum, function (err, response, body) { 8 | if (err) { 9 | console.log(err); 10 | } else if (response.statusCode === 200) { 11 | const responseJSON = JSON.parse(body); 12 | console.log(responseJSON.title); 13 | } else { 14 | console.log('Error code: ' + response.statusCode); 15 | } 16 | }); 17 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/4-starwars_count.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | const request = require('request'); 4 | const url = process.argv[2]; 5 | 6 | request(url, function (err, response, body) { 7 | if (err) { 8 | console.log(err); 9 | } else if (response.statusCode === 200) { 10 | const films = JSON.parse(body).results; 11 | let count = 0; 12 | for (const filmIndex in films) { 13 | const filmChars = films[filmIndex].characters; 14 | for (const charIndex in filmChars) { 15 | if (filmChars[charIndex].includes('18')) { 16 | count++; 17 | } 18 | } 19 | } 20 | console.log(count); 21 | } else { 22 | console.log('An error occured. Status code: ' + response.statusCode); 23 | } 24 | }); 25 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/5-request_store.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const request = require('request'); 3 | const fs = require('fs'); 4 | 5 | request(process.argv[2], function (err, response, body) { 6 | if (err == null) { 7 | fs.writeFileSync(process.argv[3], body); 8 | } 9 | }); 10 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/6-completed_tasks.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | const request = require('request'); 4 | const url = process.argv[2]; 5 | 6 | request(url, function (err, response, body) { 7 | if (err) { 8 | console.log(err); 9 | } else if (response.statusCode === 200) { 10 | const completed = {}; 11 | const tasks = JSON.parse(body); 12 | for (const i in tasks) { 13 | const task = tasks[i]; 14 | if (task.completed === true) { 15 | if (completed[task.userId] === undefined) { 16 | completed[task.userId] = 1; 17 | } else { 18 | completed[task.userId]++; 19 | } 20 | } 21 | } 22 | console.log(completed); 23 | } else { 24 | console.log('An error occured. Status code: ' + response.statusCode); 25 | } 26 | }); 27 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/0-main.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Holberton School 5 | 6 | 7 |
8 | First HTML page 9 |
10 |
11 | Holberton School - 2017 12 |
13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/0-script.js: -------------------------------------------------------------------------------- 1 | const headerElem = document.querySelector('HEADER'); 2 | headerElem.style.color = '#FF0000'; 3 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/1-main.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Holberton School 5 | 6 | 7 | 8 |
9 | First HTML page 10 |
11 |
12 | Holberton School - 2017 13 |
14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/1-script.js: -------------------------------------------------------------------------------- 1 | $(function () { 2 | $('HEADER').css({ color: '#FF0000' }); 3 | }); 4 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/100-main.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Holberton School 5 | 6 | 7 | 8 |
9 | First HTML page 10 |
11 |
12 | Holberton School - 2017 13 |
14 | 15 | 16 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/100-script.js: -------------------------------------------------------------------------------- 1 | document.addEventListener('DOMContentLoaded', function () { 2 | const headerElem = document.querySelector('HEADER'); 3 | headerElem.style.color = '#FF0000'; 4 | }); 5 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/101-main.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Holberton School 5 | 6 | 7 | 8 | 9 |
10 | First HTML page 11 |
12 |
13 |
Add item
14 |
Remove item
15 |
Clear list
16 |
17 |
    18 |
  • Item
  • 19 |
20 |
21 | Holberton School - 2017 22 |
23 | 24 | 25 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/101-script.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function () { 2 | $('DIV#add_item').click(function () { 3 | $('UL.my_list').append('
  • Item
  • '); 4 | }); 5 | $('DIV#remove_item').click(function () { 6 | $('UL.my_list li:last-child').remove(); 7 | }); 8 | $('DIV#clear_list').click(function () { 9 | $('UL.my_list').empty('ul'); 10 | }); 11 | }); 12 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/102-main.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Holberton School 5 | 6 | 7 | 8 | 9 |
    10 | Say Hello 11 |
    12 |
    13 | 14 | 15 |
    16 |
    17 |
    18 |
    19 | Holberton School - 2017 20 |
    21 | 22 | 23 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/102-script.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function () { 2 | $('INPUT#btn_translate').click(function () { 3 | $('DIV#hello').empty(); 4 | const len = $('INPUT#language_code').val(); 5 | $.ajax({ 6 | type: 'GET', 7 | url: 'https://fourtonfish.com/hellosalut/?lang=' + len, 8 | success: function (data) { 9 | $('DIV#hello').append(data.hello); 10 | } 11 | }); 12 | }); 13 | }); 14 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/103-main.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Holberton School 5 | 6 | 7 | 8 | 9 |
    10 | Say Hello 11 |
    12 |
    13 | 14 | 15 |
    16 |
    17 |
    18 |
    19 | Holberton School - 2017 20 |
    21 | 22 | 23 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/103-script.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function () { 2 | function translate () { 3 | $('DIV#hello').empty(); 4 | const len = $('INPUT#language_code').val(); 5 | $.ajax({ 6 | type: 'GET', 7 | url: 'https://fourtonfish.com/hellosalut/?lang=' + len, 8 | success: function (data) { 9 | $('DIV#hello').append(data.hello); 10 | } 11 | }); 12 | } 13 | $('INPUT#btn_translate').click(function () { 14 | translate(); 15 | }); 16 | $('INPUT#language_code').keypress(function (e) { 17 | const key = e.which; 18 | if (key === 13) { 19 | translate(); 20 | } 21 | }); 22 | }); 23 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/2-main.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Holberton School 5 | 6 | 7 | 8 |
    9 | First HTML page 10 |
    11 |
    Red header
    12 |
    13 | Holberton School - 2017 14 |
    15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/2-script.js: -------------------------------------------------------------------------------- 1 | $(function () { 2 | $('DIV#red_header').click(function () { 3 | $('HEADER').css({ color: '#FF0000' }); 4 | }); 5 | }); 6 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/3-main.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Holberton School 5 | 6 | 11 | 12 | 13 |
    14 | First HTML page 15 |
    16 |
    Red header
    17 |
    18 | Holberton School - 2017 19 |
    20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/3-script.js: -------------------------------------------------------------------------------- 1 | $(function () { 2 | $('DIV#red_header').click(function () { 3 | $('HEADER').addClass('red'); 4 | }); 5 | }); 6 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/4-main.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Holberton School 5 | 6 | 14 | 15 | 16 |
    17 | First HTML page 18 |
    19 |
    Toggle header
    20 |
    21 | Holberton School - 2017 22 |
    23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/4-script.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function () { 2 | $('DIV#toggle_header').click(function () { 3 | $('HEADER').toggleClass('red'); 4 | $('HEADER').toggleClass('green'); 5 | }); 6 | }); 7 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/5-main.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Holberton School 5 | 6 | 7 | 8 |
    9 | First HTML page 10 |
    11 |
    12 |
    Add item
    13 |
    14 |
      15 |
    • Item
    • 16 |
    17 |
    18 | Holberton School - 2017 19 |
    20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/5-script.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function () { 2 | $('DIV#add_item').click(function () { 3 | $('UL.my_list').append('
  • Item
  • '); 4 | }); 5 | }); 6 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/6-main.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Holberton School 5 | 6 | 7 | 8 |
    9 | First HTML page 10 |
    11 |
    12 |
    Update the header
    13 |
    14 |
    15 | Holberton School - 2017 16 |
    17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/6-script.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function () { 2 | $('DIV#update_header').click(function () { 3 | $('HEADER').text('New Header!!!'); 4 | }); 5 | }); 6 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/7-main.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Holberton School 5 | 6 | 7 | 8 |
    9 | Star Wars character 10 |
    11 |
    12 |
    13 |
    14 |
    15 | Holberton School - 2017 16 |
    17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/7-script.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function () { 2 | $.ajax({ 3 | type: 'GET', 4 | url: 'https://swapi.co/api/people/5/?format=json', 5 | success: function (data) { 6 | $('DIV#character').text(data.name); 7 | } 8 | }); 9 | }); 10 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/8-main.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Holberton School 5 | 6 | 7 | 8 |
    9 | Star Wars movies 10 |
    11 |
    12 |
      13 |
    14 |
    15 |
    16 | Holberton School - 2017 17 |
    18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/8-script.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function () { 2 | $.ajax({ 3 | type: 'GET', 4 | url: 'https://swapi.co/api/films/?format=json', 5 | success: function (data) { 6 | $.each(data.results, function (i, film) { 7 | $('UL#list_movies').append('
  • ' + film.title + '
  • '); 8 | }); 9 | } 10 | }); 11 | }); 12 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/9-main.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Holberton School 5 | 6 | 7 | 8 | 9 |
    10 | Say Hello! 11 |
    12 |
    13 |
    14 |
    15 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/9-script.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function () { 2 | $.ajax({ 3 | type: 'GET', 4 | url: 'https://fourtonfish.com/hellosalut/?lang=fr', 5 | success: function (data) { 6 | $('DIV#hello').append(data.hello); 7 | } 8 | }); 9 | }); 10 | --------------------------------------------------------------------------------