├── 0x00-python-hello_world ├── 0-run ├── 1-run_inline ├── 10-check_cycle.c ├── 10-linked_lists.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 ├── 1-calculation.py ├── 100-my_calculator.py ├── 101-easy_print.py ├── 102-magic_calculation.py ├── 103-fast_alphabet.py ├── 2-args.py ├── 3-infinite_add.py ├── 4-hidden_discovery.py ├── 5-variable_load.py ├── README.md ├── add_0.py ├── calculator_1.py ├── hidden_4.pyc └── variable_load_5.py ├── 0x03-python-data_structures ├── .gitignore ├── 0-print_list_integer.py ├── 1-element_at.py ├── 10-divisible_by_2.py ├── 100-print_python_list_info.c ├── 100-test_lists.py ├── 11-delete_at.py ├── 12-switch.py ├── 13-is_palindrome.c ├── 2-replace_in_list.py ├── 3-print_reversed_list_integer.py ├── 4-new_in_list.py ├── 5-no_c.py ├── 6-print_matrix_integer.py ├── 7-add_tuple.py ├── 8-multiple_returns.py ├── 9-max_integer.py ├── README.md ├── libPyList.so ├── linked_lists.c ├── lists.h └── tests │ ├── 0-main.py │ ├── 0-print_list_integer.py │ ├── 1-element_at.py │ ├── 1-main.py │ ├── 10-divisible_by_2.py │ ├── 10-main.py │ ├── 11-delete_at.py │ ├── 11-main.py │ ├── 2-main.py │ ├── 2-replace_in_list.py │ ├── 3-main.py │ ├── 3-print_reversed_list_integer.py │ ├── 4-main.py │ ├── 4-new_in_list.py │ ├── 5-main.py │ ├── 5-no_c.py │ ├── 6-main.py │ ├── 6-print_matrix_integer.py │ ├── 7-add_tuple.py │ ├── 7-main.py │ ├── 8-main.py │ ├── 8-multiple_returns.py │ ├── 9-main.py │ └── 9-max_integer.py ├── 0x04-python-more_data_structures ├── 0-square_matrix_simple.py ├── 1-search_replace.py ├── 10-best_score.py ├── 100-weight_average.py ├── 101-square_matrix_map.py ├── 102-complex_delete.py ├── 103-python.c ├── 103-tests.py ├── 11-multiply_list_map.py ├── 12-roman_to_int.py ├── 2-uniq_add.py ├── 3-common_elements.py ├── 4-only_diff_elements.py ├── 5-number_keys.py ├── 6-print_sorted_dictionary.py ├── 7-update_dictionary.py ├── 8-simple_delete.py ├── 9-multiply_by_2.py ├── README.md ├── libPython.so └── tests │ ├── 0-main.py │ ├── 1-main.py │ ├── 10-main.py │ ├── 100-main.py │ ├── 101-main.py │ ├── 102-main.py │ ├── 11-main.py │ ├── 12-main.py │ ├── 2-main.py │ ├── 3-main.py │ ├── 4-main.py │ ├── 5-main.py │ ├── 6-main.py │ ├── 7-main.py │ ├── 8-main.py │ └── 9-main.py ├── 0x05-python-exceptions ├── 0-safe_print_list.py ├── 1-safe_print_integer.py ├── 100-safe_print_integer_err.py ├── 101-safe_function.py ├── 102-magic_calculation.py ├── 103-python.c ├── 103-tests.py ├── 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 ├── libPython.so └── tests │ ├── 0-main.py │ ├── 1-main.py │ ├── 100-main.py │ ├── 101-main.py │ ├── 2-main.py │ ├── 3-main.py │ ├── 4-main.py │ ├── 5-main.py │ └── 6-main.py ├── 0x06-python-classes ├── 0-square.py ├── 1-square.py ├── 100-singly_linked_list.py ├── 101-square.py ├── 102-square.py ├── 103-magic_class.py ├── 2-square.py ├── 3-square.py ├── 4-square.py ├── 5-square.py ├── 6-square.py ├── README.md └── tests │ ├── 0-main.py │ ├── 1-main.py │ ├── 100-main.py │ ├── 101-main.py │ ├── 102-main.py │ ├── 2-main.py │ ├── 3-main.py │ ├── 4-main.py │ ├── 5-main.py │ └── 6-main.py ├── 0x07-python-test_driven_development ├── 0-add_integer.py ├── 100-matrix_mul.py ├── 101-lazy_matrix_mul.py ├── 102-python.c ├── 2-matrix_divided.py ├── 3-say_my_name.py ├── 4-print_square.py ├── 5-text_indentation.py ├── 6-max_integer.py ├── README.md └── tests │ ├── 0-add_integer.txt │ ├── 0-main.py │ ├── 100-main.py │ ├── 100-matrix_mul.txt │ ├── 101-lazy_matrix_mul.txt │ ├── 101-main.py │ ├── 2-main.py │ ├── 2-matrix_divided.txt │ ├── 3-main.py │ ├── 3-say_my_name.txt │ ├── 4-main.py │ ├── 4-print_square.txt │ ├── 5-main.py │ ├── 5-text_indentation.txt │ └── 6-max_integer_test.py ├── 0x08-python-more_classes ├── 0-rectangle.py ├── 1-rectangle.py ├── 101-nqueens.py ├── 2-rectangle.py ├── 3-rectangle.py ├── 4-rectangle.py ├── 5-rectangle.py ├── 6-rectangle.py ├── 7-rectangle.py ├── 8-rectangle.py ├── 9-rectangle.py ├── README.md └── tests │ ├── 0-main.py │ ├── 1-main.py │ ├── 2-main.py │ ├── 3-main.py │ ├── 4-main.py │ ├── 5-main.py │ ├── 6-main.py │ ├── 7-main.py │ ├── 8-main.py │ └── 9-main.py ├── 0x09-python-everything_is_object ├── 0-answer.txt ├── 1-answer.txt ├── 10-answer.txt ├── 100-magic_string.py ├── 101-locked_class.py ├── 103-line1.txt ├── 103-line2.txt ├── 104-line1.txt ├── 104-line2.txt ├── 104-line3.txt ├── 104-line4.txt ├── 104-line5.txt ├── 105-line1.txt ├── 106-line1.txt ├── 106-line2.txt ├── 106-line3.txt ├── 106-line4.txt ├── 106-line5.txt ├── 11-answer.txt ├── 12-answer.txt ├── 13-answer.txt ├── 14-answer.txt ├── 15-answer.txt ├── 16-answer.txt ├── 17-answer.txt ├── 18-answer.txt ├── 19-copy_list.py ├── 2-answer.txt ├── 20-answer.txt ├── 21-answer.txt ├── 22-answer.txt ├── 23-answer.txt ├── 24-answer.txt ├── 25-answer.txt ├── 26-answer.txt ├── 27-answer.txt ├── 28-answer.txt ├── 3-answer.txt ├── 4-answer.txt ├── 5-answer.txt ├── 6-answer.txt ├── 7-answer.txt ├── 8-answer.txt ├── 9-answer.txt ├── README.md └── tests │ ├── 100-main.py │ ├── 101-main.py │ └── 19-main.py ├── 0x0A-python-inheritance ├── 0-lookup.py ├── 1-my_list.py ├── 10-square.py ├── 100-my_int.py ├── 101-add_attribute.py ├── 11-square.py ├── 2-is_same_class.py ├── 3-is_kind_of_class.py ├── 4-inherits_from.py ├── 5-base_geometry.py ├── 6-base_geometry.py ├── 7-base_geometry.py ├── 8-rectangle.py ├── 9-rectangle.py ├── README.md └── tests │ ├── 0-main.py │ ├── 1-main.py │ ├── 1-my_list.txt │ ├── 10-main.py │ ├── 100-main.py │ ├── 101-main.py │ ├── 11-main.py │ ├── 2-main.py │ ├── 3-main.py │ ├── 4-main.py │ ├── 5-main.py │ ├── 6-main.py │ ├── 7-base_geometry.txt │ ├── 7-main.py │ ├── 8-main.py │ └── 9-main.py ├── 0x0B-python-input_output ├── 0-read_file.py ├── 1-write_file.py ├── 10-student.py ├── 100-append_after.py ├── 101-stats.py ├── 11-student.py ├── 12-pascal_triangle.py ├── 2-append_write.py ├── 3-to_json_string.py ├── 4-from_json_string.py ├── 5-save_to_json_file.py ├── 6-load_from_json_file.py ├── 7-add_item.py ├── 8-class_to_json.py ├── 9-student.py ├── README.md └── tests │ ├── 0-main.py │ ├── 1-main.py │ ├── 10-main.py │ ├── 10-my_class.py │ ├── 100-main.py │ ├── 11-main.py │ ├── 12-main.py │ ├── 14-main.py │ ├── 2-main.py │ ├── 3-main.py │ ├── 4-main.py │ ├── 5-main.py │ └── 6-main.py ├── 0x0C-python-almost_a_circle ├── 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 └── temperatures.sql ├── 0x0E-SQL_more_queries ├── 0-privileges.sql ├── 1-create_user.sql ├── 10-genre_id_by_show.sql ├── 100-not_my_genres.sql ├── 101-not_a_comedy.sql ├── 102-rating_shows.sql ├── 103-rating_genres.sql ├── 11-genre_id_all_shows.sql ├── 12-no_genre.sql ├── 13-count_shows_by_genre.sql ├── 14-my_genres.sql ├── 15-comedy_only.sql ├── 16-shows_by_genre.sql ├── 2-create_read_user.sql ├── 3-force_name.sql ├── 4-never_empty.sql ├── 5-unique_id.sql ├── 6-states.sql ├── 7-cities.sql ├── 8-cities_of_california_subquery.sql ├── 9-cities_by_state_join.sql ├── README.md ├── 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 ├── 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 ├── 9-starwars.py └── README.md ├── 0x12-javascript-warm_up ├── 0-javascript_is_amazing.js ├── 1-multi_languages.js ├── 10-factorial.js ├── 100-let_me_const.js ├── 101-call_me_moby.js ├── 102-add_me_maybe.js ├── 103-object_fct.js ├── 11-second_biggest.js ├── 12-object.js ├── 13-add.js ├── 2-arguments.js ├── 3-value_argument.js ├── 4-concat.js ├── 5-to_integer.js ├── 6-multi_languages_loop.js ├── 7-multi_c.js ├── 8-square.js ├── 9-add.js ├── README.md └── tests │ ├── 100-main.js │ ├── 101-main.js │ ├── 102-main.js │ └── 13-main.js ├── 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 ├── 102-search_twitter.js ├── 2-statuscode.js ├── 3-starwars_title.js ├── 4-starwars_count.js ├── 5-request_store.js ├── 6-completed_tasks.js └── README.md ├── 0x15-javascript-web_jquery ├── 0-script.js ├── 1-script.js ├── 100-script.js ├── 101-script.js ├── 102-script.js ├── 103-script.js ├── 2-script.js ├── 3-script.js ├── 4-script.js ├── 5-script.js ├── 6-script.js ├── 7-script.js ├── 8-script.js ├── 9-script.js ├── README.md └── tests │ ├── 0-main.html │ ├── 1-main.html │ ├── 100-main.html │ ├── 101-main.html │ ├── 102-main.html │ ├── 103-main.html │ ├── 2-main.html │ ├── 3-main.html │ ├── 4-main.html │ ├── 5-main.html │ ├── 6-main.html │ ├── 7-main.html │ ├── 8-main.html │ └── 9-main.html └── 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 | /* 2 | * File: 10-check_cycle.c 3 | * Auth: Brennan D Baraban 4 | */ 5 | 6 | #include 7 | #include "lists.h" 8 | 9 | /** 10 | * check_cycle - Checks if a singly-linked list contains a cycle. 11 | * @list: A singly-linked list. 12 | * 13 | * Return: If there is no cycle - 0. 14 | * If there is a cycle - 1. 15 | */ 16 | int check_cycle(listint_t *list) 17 | { 18 | listint_t *turtle, *hare; 19 | 20 | if (list == NULL || list->next == NULL) 21 | return (0); 22 | 23 | turtle = list->next; 24 | hare = list->next->next; 25 | 26 | while (turtle && hare && hare->next) 27 | { 28 | if (turtle == hare) 29 | return (1); 30 | 31 | turtle = turtle->next; 32 | hare = hare->next->next; 33 | } 34 | 35 | return (0); 36 | } 37 | -------------------------------------------------------------------------------- /0x00-python-hello_world/100-write.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import sys 3 | sys.stderr.write("and that piece of art is useful - Dora Korpar, 2015-10-19\n") 4 | sys.exit(1) 5 | -------------------------------------------------------------------------------- /0x00-python-hello_world/101-compile: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | python3 -c "import py_compile; py_compile.compile('$PYFILE', '$PYFILE' + 'c')" 3 | -------------------------------------------------------------------------------- /0x00-python-hello_world/102-magic_calculation.py: -------------------------------------------------------------------------------- 1 | def magic_calculation(a, b): 2 | return (98 + a ** b) 3 | -------------------------------------------------------------------------------- /0x00-python-hello_world/2-print.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | print("\"Programming is like building a multilingual puzzle") 3 | -------------------------------------------------------------------------------- /0x00-python-hello_world/3-print_number.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | number = 98 3 | print("{:d} Battery street".format(number)) 4 | -------------------------------------------------------------------------------- /0x00-python-hello_world/4-print_float.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | number = 3.14159 3 | print("Float: {:.2f}".format(number)) 4 | -------------------------------------------------------------------------------- /0x00-python-hello_world/5-print_string.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | str = "Holberton School" 3 | print(str + str + str) 4 | print(str[:9]) 5 | -------------------------------------------------------------------------------- /0x00-python-hello_world/6-concat.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | str1 = "Holberton" 3 | str2 = "School" 4 | str1 += (" " + str2) 5 | print("Welcome to {}!".format(str1)) 6 | -------------------------------------------------------------------------------- /0x00-python-hello_world/7-edges.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | word = "Holberton" 3 | word_first_3 = word[:3] 4 | word_last_2 = word[-2:] 5 | middle_word = word[1:-1] 6 | print("First 3 letters: {}".format(word_first_3)) 7 | print("Last 2 letters: {}".format(word_last_2)) 8 | print("Middle word: {}".format(middle_word)) 9 | -------------------------------------------------------------------------------- /0x00-python-hello_world/8-concat_edges.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | str = "Python is an interpreted, interactive, object-oriented programming\ 3 | language that combines remarkable power with very clear syntax" 4 | str = str[39: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 | */ 13 | typedef struct listint_s 14 | { 15 | int n; 16 | struct listint_s *next; 17 | } listint_t; 18 | 19 | size_t print_listint(const listint_t *h); 20 | listint_t *add_nodeint(listint_t **head, const int n); 21 | void free_listint(listint_t *head); 22 | int check_cycle(listint_t *list); 23 | 24 | #endif /* LISTS_H */ 25 | -------------------------------------------------------------------------------- /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("{} is positive".format(number)) 6 | elif number == 0: 7 | print("{} is zero".format(number)) 8 | else: 9 | print("{} 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 | digit = abs(number) % 10 5 | if number < 0: 6 | digit = -digit 7 | print("Last digit of {} is {} and is ".format(number, digit), end="") 8 | if digit > 5: 9 | print("greater than 5") 10 | elif digit == 0: 11 | print("0") 12 | else: 13 | print("less than 6 and not 0") 14 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/10-add.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def add(a, b): 3 | return (a + b) 4 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/100-print_tebahpla.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | i = 0 3 | for c in range(ord('z'), ord('a') - 1, -1): 4 | print("{}".format(chr(c - i)), end="") 5 | i = 32 if i == 0 else 0 6 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/101-remove_char_at.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def remove_char_at(str, n): 3 | if n < 0: 4 | return (str) 5 | return (str[:n] + str[n+1:]) 6 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/102-magic_calculation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def magic_calculation(a, b, c): 3 | if a < b: 4 | return (c) 5 | if c > b: 6 | return (a + b) 7 | return (a*b - c) 8 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/11-pow.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def pow(a, b): 3 | return (a ** b) 4 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/12-fizzbuzz.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def fizzbuzz(): 3 | for number in range(1, 101): 4 | if number % 3 == 0 and number % 5 == 0: 5 | print("FizzBuzz ", end="") 6 | elif number % 3 == 0: 7 | print("Fizz ", end="") 8 | elif number % 5 == 0: 9 | print("Buzz ", end="") 10 | else: 11 | print("{} ".format(number), end="") 12 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/13-insert_number.c: -------------------------------------------------------------------------------- 1 | #include "lists.h" 2 | 3 | /** 4 | * insert_node - Inserts a number into a sorted singly-linked list. 5 | * @head: A pointer the head of the linked list. 6 | * @number: The number to insert. 7 | * 8 | * Return: If the function fails - NULL. 9 | * Otherwise - a pointer to the new node. 10 | */ 11 | listint_t *insert_node(listint_t **head, int number) 12 | { 13 | listint_t *node = *head, *new; 14 | 15 | new = malloc(sizeof(listint_t)); 16 | if (new == NULL) 17 | return (NULL); 18 | new->n = number; 19 | 20 | if (node == NULL || node->n >= number) 21 | { 22 | new->next = node; 23 | *head = new; 24 | return (new); 25 | } 26 | 27 | while (node && node->next && node->next->n < number) 28 | node = node->next; 29 | 30 | new->next = node->next; 31 | node->next = new; 32 | 33 | return (new); 34 | } 35 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/2-print_alphabet.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for letter in range(97, 123): 3 | print("{}".format(chr(letter)), end="") 4 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/3-print_alphabt.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for letter in range(97, 123): 3 | if chr(letter) != 'q' and chr(letter) != 'e': 4 | print("{}".format(chr(letter)), end="") 5 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/4-print_hexa.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for number in range(0, 99): 3 | print("{} = {}".format(number, hex(number))) 4 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/5-print_comb2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for number in range(0, 100): 3 | if number == 99: 4 | print("{}".format(number)) 5 | else: 6 | print("{:0>2}".format(number), end=", ") 7 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/6-print_comb3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for digit1 in range(0, 10): 3 | for digit2 in range(digit1 + 1, 10): 4 | if digit1 == 8 and digit2 == 9: 5 | print("{}{}".format(digit1, digit2)) 6 | else: 7 | print("{}{}".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 c in str: 4 | if ord(c) >= 97 and ord(c) <= 122: 5 | c = chr(ord(c) - 32) 6 | print("{}".format(c), end="") 7 | print("") 8 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/9-print_last_digit.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def print_last_digit(number): 3 | print(abs(number) % 10, end="") 4 | return (abs(number) % 10) 5 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/lists.h: -------------------------------------------------------------------------------- 1 | #ifndef LISTS_H 2 | #define LISTS_H 3 | 4 | #include 5 | 6 | /** 7 | * struct listint_s - singly linked list 8 | * @n: integer 9 | * @next: points to the next node 10 | * 11 | * Description: singly linked list node structure 12 | */ 13 | typedef struct listint_s 14 | { 15 | int n; 16 | struct listint_s *next; 17 | } listint_t; 18 | 19 | size_t print_listint(const listint_t *h); 20 | listint_t *add_nodeint_end(listint_t **head, const int n); 21 | void free_listint(listint_t *head); 22 | listint_t *insert_node(listint_t **head, int number); 23 | 24 | #endif /* LISTS_H */ 25 | -------------------------------------------------------------------------------- /0x02-python-import_modules/0-add.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | if __name__ == "__main__": 3 | from add_0 import add 4 | 5 | a = 1 6 | b = 2 7 | print("{} + {} = {}".format(a, b, add(a, b))) 8 | -------------------------------------------------------------------------------- /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 | 5 | a = 10 6 | b = 5 7 | 8 | print("{} + {} = {}".format(a, b, add(a, b))) 9 | print("{} - {} = {}".format(a, b, sub(a, b))) 10 | print("{} * {} = {}".format(a, b, mul(a, b))) 11 | print("{} / {} = {}".format(a, b, div(a, b))) 12 | -------------------------------------------------------------------------------- /0x02-python-import_modules/100-my_calculator.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | if __name__ == "__main__": 3 | from calculator_1 import add, sub, mul, div 4 | import sys 5 | 6 | if len(sys.argv) - 1 != 3: 7 | print("Usage: ./100-my_calculator.py ") 8 | sys.exit(1) 9 | 10 | ops = {"+": add, "-": sub, "*": mul, "/": div} 11 | if sys.argv[2] not in list(ops.keys()): 12 | print("Unknown operator. Available operators: +, -, * and /") 13 | sys.exit(1) 14 | 15 | a = int(sys.argv[1]) 16 | b = int(sys.argv[3]) 17 | print("{} {} {} = {}".format(a, sys.argv[2], b, ops[sys.argv[2]](a, b))) 18 | -------------------------------------------------------------------------------- /0x02-python-import_modules/101-easy_print.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | __import__("os").write(1, "#pythoniscool\n".encode("UTF-8")) 3 | -------------------------------------------------------------------------------- /0x02-python-import_modules/102-magic_calculation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def magic_calculation(a, b): 3 | from magic_calculation_102 import add, sub 4 | 5 | if a < b: 6 | c = add(a, b) 7 | for i in range(4, 6): 8 | c = add(c, i) 9 | return (c) 10 | 11 | else: 12 | return(sub(a, b)) 13 | -------------------------------------------------------------------------------- /0x02-python-import_modules/103-fast_alphabet.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import string 3 | print(string.ascii_uppercase) 4 | -------------------------------------------------------------------------------- /0x02-python-import_modules/2-args.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | if __name__ == "__main__": 3 | import sys 4 | 5 | count = len(sys.argv) - 1 6 | if count == 0: 7 | print("0 arguments.") 8 | elif count == 1: 9 | print("1 argument:") 10 | else: 11 | print("{} arguments:".format(count)) 12 | for i in range(count): 13 | print("{}: {}".format(i + 1, sys.argv[i + 1])) 14 | -------------------------------------------------------------------------------- /0x02-python-import_modules/3-infinite_add.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | if __name__ == "__main__": 3 | import sys 4 | 5 | total = 0 6 | for i in range(len(sys.argv) - 1): 7 | total += int(sys.argv[i + 1]) 8 | print("{}".format(total)) 9 | -------------------------------------------------------------------------------- /0x02-python-import_modules/4-hidden_discovery.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | if __name__ == "__main__": 3 | import hidden_4 4 | 5 | names = dir(hidden_4) 6 | for name in names: 7 | if name[:2] != "__": 8 | print(name) 9 | -------------------------------------------------------------------------------- /0x02-python-import_modules/5-variable_load.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | if __name__ == "__main__": 3 | from variable_load_5 import a 4 | 5 | print(a) 6 | -------------------------------------------------------------------------------- /0x02-python-import_modules/add_0.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def add(a, b): 3 | """My addition function 4 | 5 | Args: 6 | a: first integer 7 | b: second integer 8 | 9 | Returns: 10 | The return value. a + b 11 | """ 12 | return (a + b) 13 | -------------------------------------------------------------------------------- /0x02-python-import_modules/calculator_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def add(a, b): 3 | """My addition function 4 | 5 | Args: 6 | a: first integer 7 | b: second integer 8 | 9 | Returns: 10 | The return value. a + b 11 | """ 12 | return (a + b) 13 | 14 | 15 | def sub(a, b): 16 | """My subtraction function 17 | 18 | Args: 19 | a: first integer 20 | b: second integer 21 | 22 | Returns: 23 | The return value. a - b 24 | """ 25 | return (a - b) 26 | 27 | 28 | def mul(a, b): 29 | """My multiplication function 30 | 31 | Args: 32 | a: first integer 33 | b: second integer 34 | 35 | Returns: 36 | The return value. a * b 37 | """ 38 | return (a * b) 39 | 40 | 41 | def div(a, b): 42 | """My division function 43 | 44 | Args: 45 | a: first integer 46 | b: second integer 47 | 48 | Returns: 49 | The return value. a / b 50 | """ 51 | return int(a / b) 52 | -------------------------------------------------------------------------------- /0x02-python-import_modules/hidden_4.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/underscoDe/alx-higher_level_programming/65dba7607ebd18cefaffda5df24b47de586864d3/0x02-python-import_modules/hidden_4.pyc -------------------------------------------------------------------------------- /0x02-python-import_modules/variable_load_5.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | a = 98 3 | """Simple variable 4 | """ 5 | -------------------------------------------------------------------------------- /0x03-python-data_structures/.gitignore: -------------------------------------------------------------------------------- 1 | test.* 2 | __pycache__ 3 | -------------------------------------------------------------------------------- /0x03-python-data_structures/0-print_list_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def print_list_integer(my_list=[]): 3 | """ 4 | Print a list of integers 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | my_list : list optional 10 | The list of integers 11 | 12 | Return: 13 | None 14 | """ 15 | 16 | for element in my_list: 17 | print("{:d}".format(element)) 18 | -------------------------------------------------------------------------------- /0x03-python-data_structures/1-element_at.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def element_at(my_list, idx): 3 | """ 4 | Retrieves an element at a given index 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | my_list : list 10 | The list of integers 11 | idx : integer 12 | The given index 13 | 14 | Return: 15 | The element when found 16 | None if the index is negative 17 | None if the index is larger than the list length 18 | """ 19 | 20 | if idx < 0 or idx > (len(my_list) - 1): 21 | return None 22 | else: 23 | return my_list[idx] 24 | -------------------------------------------------------------------------------- /0x03-python-data_structures/10-divisible_by_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def divisible_by_2(my_list=[]): 3 | """ 4 | Finds all multiples of 2 in a list 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | my_list : list 10 | The list to check 11 | 12 | Return: 13 | A new list with True or False, depending 14 | on whether the integer at the same position 15 | in the original list is a multiple of 2 16 | """ 17 | 18 | multiples = [] 19 | for i in range(len(my_list)): 20 | if my_list[i] % 2 == 0: 21 | multiples.append(True) 22 | else: 23 | multiples.append(False) 24 | 25 | return (multiples) 26 | -------------------------------------------------------------------------------- /0x03-python-data_structures/100-print_python_list_info.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /** 5 | * print_python_list_info - Prints basic info about Python lists 6 | * @p: A PyObject list. 7 | * 8 | * Return: nothing 9 | */ 10 | void print_python_list_info(PyObject *p) 11 | { 12 | int list_size, allocated, i; 13 | PyObject *list_object; 14 | 15 | list_size = Py_SIZE(p); 16 | allocated = ((PyListObject *)p)->allocated; 17 | 18 | printf("[*] Size of the Python List = %d\n", list_size); 19 | printf("[*] Allocated = %d\n", allocated); 20 | 21 | for (i = 0; i < list_size; i++) 22 | { 23 | printf("Element %d: ", i); 24 | 25 | list_object = PyList_GetItem(p, i); 26 | printf("%s\n", Py_TYPE(list_object)->tp_name); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /0x03-python-data_structures/100-test_lists.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | 3 | lib = ctypes.CDLL('./libPyList.so') 4 | lib.print_python_list_info.argtypes = [ctypes.py_object] 5 | l = ['hello', 'World'] 6 | lib.print_python_list_info(l) 7 | del l[1] 8 | lib.print_python_list_info(l) 9 | l = l + [4, 5, 6.0, (9, 8), [9, 8, 1024], "My string"] 10 | lib.print_python_list_info(l) 11 | l = [] 12 | lib.print_python_list_info(l) 13 | l.append(0) 14 | lib.print_python_list_info(l) 15 | l.append(1) 16 | l.append(2) 17 | l.append(3) 18 | l.append(4) 19 | lib.print_python_list_info(l) 20 | l.pop() 21 | lib.print_python_list_info(l) -------------------------------------------------------------------------------- /0x03-python-data_structures/11-delete_at.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def delete_at(my_list=[], idx=0): 3 | """ 4 | Deletes the item at a specific position in a list 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | my_list : list 10 | The list to remove item from 11 | idx : integer 12 | The given position 13 | 14 | Return: 15 | The same list if idx is negative 16 | the list without the deleted item 17 | """ 18 | 19 | if idx >= 0 and idx < len(my_list): 20 | del my_list[idx] 21 | return (my_list) 22 | -------------------------------------------------------------------------------- /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 | """ 4 | Replaces an element of a list at a specific position 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | my_list : list 10 | The list of elements 11 | idx : integer 12 | The given position 13 | element : the new element 14 | 15 | Return: 16 | The original list if idx is negative or 17 | if idx out of range (> len(my_list)) 18 | """ 19 | 20 | if idx >= 0 and idx <= (len(my_list) - 1): 21 | my_list[idx] = element 22 | return my_list 23 | -------------------------------------------------------------------------------- /0x03-python-data_structures/3-print_reversed_list_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def print_reversed_list_integer(my_list=[]): 3 | """ 4 | Prints all integers of a list, in reverse order 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | my_list : list 10 | The list of elements 11 | idx : integer 12 | The given position 13 | element : the new element 14 | 15 | Return: 16 | The original list if idx is negative or 17 | if idx out of range (> len(my_list)) 18 | """ 19 | 20 | if isinstance(my_list, list): 21 | reversed_list = my_list 22 | reversed_list.reverse() 23 | 24 | for element in reversed_list: 25 | print("{:d}".format(element)) 26 | -------------------------------------------------------------------------------- /0x03-python-data_structures/4-new_in_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def new_in_list(my_list, idx, element): 3 | """ 4 | Replaces an element in a copy of a list at a specific position 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | my_list : list 10 | The list of elements 11 | idx : integer 12 | The given position 13 | element : the new element 14 | 15 | Return: 16 | The copy of the list if idx is negative or 17 | if idx out of range (> len(my_list)) 18 | """ 19 | 20 | list_copy = my_list.copy() 21 | 22 | if idx >= 0 and idx <= (len(my_list) - 1): 23 | list_copy[idx] = element 24 | return list_copy 25 | -------------------------------------------------------------------------------- /0x03-python-data_structures/5-no_c.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def no_c(my_string): 3 | """ 4 | Removes all characters c and C from a string 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | my_string : str 10 | The string to remove 'Cc' from 11 | 12 | Return: 13 | The new string 14 | """ 15 | 16 | return ("".join([c for c in my_string if c not in ['c', 'C']])) 17 | -------------------------------------------------------------------------------- /0x03-python-data_structures/6-print_matrix_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def print_matrix_integer(matrix=[[]]): 3 | """ 4 | Prints a matrix of integers 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | matrix : list (of lists) 10 | The list to print 11 | 12 | Return: 13 | None 14 | """ 15 | 16 | for i in range(len(matrix)): 17 | for j in range(len(matrix[i])): 18 | print("{:d}".format(matrix[i][j]), end="") 19 | if j != (len(matrix[i]) - 1): 20 | print(" ", end="") 21 | print("") 22 | -------------------------------------------------------------------------------- /0x03-python-data_structures/7-add_tuple.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def add_tuple(tuple_a=(), tuple_b=()): 3 | """ 4 | Adds 2 tuples 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | tuple_a : tuple 10 | The first tuple 11 | tuple_b : tuple 12 | The second tuple 13 | 14 | Return: 15 | A tuple with 2 integers 16 | """ 17 | 18 | if len(tuple_a) < 2: 19 | if len(tuple_a) == 0: 20 | tuple_a = 0, 0 21 | else: 22 | tuple_a = tuple_a[0], 0 23 | if len(tuple_b) < 2: 24 | if len(tuple_b) == 0: 25 | tuple_b = 0, 0 26 | else: 27 | tuple_b = tuple_b[0], 0 28 | 29 | return (tuple_a[0] + tuple_b[0], tuple_a[1] + tuple_b[1]) 30 | -------------------------------------------------------------------------------- /0x03-python-data_structures/8-multiple_returns.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def multiple_returns(sentence): 3 | """ 4 | Returns a tuple with the length of a string and its first character 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | sentence : str 10 | The string to treat 11 | 12 | Return: 13 | A tuple 14 | """ 15 | 16 | if len(sentence) == 0: 17 | return (0, None) 18 | else: 19 | return len(sentence), sentence[0] 20 | -------------------------------------------------------------------------------- /0x03-python-data_structures/9-max_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def max_integer(my_list=[]): 3 | """ 4 | Finds the biggest integer of a list 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | my_list : list 10 | The list to treat 11 | 12 | Return: 13 | An integer that is the biggest integer of the list 14 | """ 15 | 16 | if len(my_list) == 0: 17 | return (None) 18 | 19 | big = my_list[0] 20 | for i in range(len(my_list)): 21 | if my_list[i] > big: 22 | big = my_list[i] 23 | 24 | return (big) 25 | -------------------------------------------------------------------------------- /0x03-python-data_structures/libPyList.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/underscoDe/alx-higher_level_programming/65dba7607ebd18cefaffda5df24b47de586864d3/0x03-python-data_structures/libPyList.so -------------------------------------------------------------------------------- /0x03-python-data_structures/lists.h: -------------------------------------------------------------------------------- 1 | #ifndef LISTS_H 2 | #define LISTS_H 3 | 4 | #include 5 | #include 6 | 7 | /** 8 | * struct listint_s - singly linked list 9 | * @n: integer 10 | * @next: points to the next node 11 | * 12 | * Description: singly linked list node structure 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 | int is_palindrome(listint_t **head); 24 | 25 | #endif /* LISTS_H */ 26 | -------------------------------------------------------------------------------- /0x03-python-data_structures/tests/0-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | print_list_integer = __import__('0-print_list_integer').print_list_integer 3 | 4 | my_list = [1, 2, 3, 4, 5] 5 | print_list_integer(my_list) 6 | -------------------------------------------------------------------------------- /0x03-python-data_structures/tests/0-print_list_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def print_list_integer(my_list=[]): 3 | """ 4 | Print a list of integers 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | my_list : list optional 10 | The list of integers 11 | 12 | Return: 13 | None 14 | """ 15 | 16 | for element in my_list: 17 | print("{:d}".format(element)) 18 | -------------------------------------------------------------------------------- /0x03-python-data_structures/tests/1-element_at.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def element_at(my_list, idx): 3 | """ 4 | Retrieves an element at a given index 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | my_list : list 10 | The list of integers 11 | idx : integer 12 | The given index 13 | 14 | Return: 15 | The element when found 16 | None if the index is negative 17 | None if the index is larger than the list length 18 | """ 19 | 20 | if idx < 0 or idx > (len(my_list) - 1): 21 | return None 22 | else: 23 | return my_list[idx] 24 | -------------------------------------------------------------------------------- /0x03-python-data_structures/tests/1-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | element_at = __import__('1-element_at').element_at 3 | 4 | my_list = [1, 2, 3, 4, 5] 5 | idx = 3 6 | print("Element at index {:d} is {}".format(idx, element_at(my_list, idx))) 7 | -------------------------------------------------------------------------------- /0x03-python-data_structures/tests/10-divisible_by_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def divisible_by_2(my_list=[]): 3 | """ 4 | Finds all multiples of 2 in a list 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | my_list : list 10 | The list to check 11 | 12 | Return: 13 | A new list with True or False, depending 14 | on whether the integer at the same position 15 | in the original list is a multiple of 2 16 | """ 17 | 18 | multiples = [] 19 | for i in range(len(my_list)): 20 | if my_list[i] % 2 == 0: 21 | multiples.append(True) 22 | else: 23 | multiples.append(False) 24 | 25 | return (multiples) 26 | -------------------------------------------------------------------------------- /0x03-python-data_structures/tests/10-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | divisible_by_2 = __import__('10-divisible_by_2').divisible_by_2 3 | 4 | my_list = [0, 1, 2, 3, 4, 5, 6] 5 | list_result = divisible_by_2(my_list) 6 | 7 | i = 0 8 | while i < len(list_result): 9 | print("{:d} {:s} divisible by 2".format(my_list[i], "is" if list_result[i] else "is not")) 10 | i += 1 11 | -------------------------------------------------------------------------------- /0x03-python-data_structures/tests/11-delete_at.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def delete_at(my_list=[], idx=0): 3 | """ 4 | Deletes the item at a specific position in a list 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | my_list : list 10 | The list to remove item from 11 | idx : integer 12 | The given position 13 | 14 | Return: 15 | The same list if idx is negative 16 | the list without the deleted item 17 | """ 18 | 19 | if idx >= 0 and idx < len(my_list): 20 | del my_list[idx] 21 | return (my_list) 22 | -------------------------------------------------------------------------------- /0x03-python-data_structures/tests/11-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | delete_at = __import__('11-delete_at').delete_at 3 | 4 | my_list = [1, 2, 3, 4, 5] 5 | idx = 3 6 | new_list = delete_at(my_list, idx) 7 | print(new_list) 8 | print(my_list) 9 | -------------------------------------------------------------------------------- /0x03-python-data_structures/tests/2-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | replace_in_list = __import__('2-replace_in_list').replace_in_list 3 | 4 | my_list = [1, 2, 3, 4, 5] 5 | idx = 3 6 | new_element = 9 7 | new_list = replace_in_list(my_list, idx, new_element) 8 | 9 | print(new_list) 10 | print(my_list) 11 | -------------------------------------------------------------------------------- /0x03-python-data_structures/tests/2-replace_in_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def replace_in_list(my_list, idx, element): 3 | """ 4 | Replaces an element of a list at a specific position 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | my_list : list 10 | The list of elements 11 | idx : integer 12 | The given position 13 | element : the new element 14 | 15 | Return: 16 | The original list if idx is negative or 17 | if idx out of range (> len(my_list)) 18 | """ 19 | 20 | if idx >= 0 and idx <= (len(my_list) - 1): 21 | my_list[idx] = element 22 | return my_list 23 | -------------------------------------------------------------------------------- /0x03-python-data_structures/tests/3-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | print_reversed_list_integer = __import__('3-print_reversed_list_integer').print_reversed_list_integer 3 | 4 | my_list = [1, 2, 3, 4, 5] 5 | print_reversed_list_integer(my_list) 6 | -------------------------------------------------------------------------------- /0x03-python-data_structures/tests/3-print_reversed_list_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def print_reversed_list_integer(my_list=[]): 3 | """ 4 | Prints all integers of a list, in reverse order 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | my_list : list 10 | The list of elements 11 | idx : integer 12 | The given position 13 | element : the new element 14 | 15 | Return: 16 | The original list if idx is negative or 17 | if idx out of range (> len(my_list)) 18 | """ 19 | 20 | if isinstance(my_list, list): 21 | reversed_list = my_list 22 | reversed_list.reverse() 23 | 24 | for element in reversed_list: 25 | print("{:d}".format(element)) 26 | -------------------------------------------------------------------------------- /0x03-python-data_structures/tests/4-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | new_in_list = __import__('4-new_in_list').new_in_list 3 | 4 | my_list = [1, 2, 3, 4, 5] 5 | idx = 3 6 | new_element = 9 7 | new_list = new_in_list(my_list, idx, new_element) 8 | 9 | print(new_list) 10 | print(my_list) 11 | -------------------------------------------------------------------------------- /0x03-python-data_structures/tests/4-new_in_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def new_in_list(my_list, idx, element): 3 | """ 4 | Replaces an element in a copy of a list at a specific position 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | my_list : list 10 | The list of elements 11 | idx : integer 12 | The given position 13 | element : the new element 14 | 15 | Return: 16 | The copy of the list if idx is negative or 17 | if idx out of range (> len(my_list)) 18 | """ 19 | 20 | list_copy = my_list.copy() 21 | 22 | if idx >= 0 and idx <= (len(my_list) - 1): 23 | list_copy[idx] = element 24 | return list_copy 25 | -------------------------------------------------------------------------------- /0x03-python-data_structures/tests/5-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | no_c = __import__('5-no_c').no_c 3 | 4 | print(no_c("Best School")) 5 | print(no_c("Chicago")) 6 | print(no_c("C is fun!")) 7 | -------------------------------------------------------------------------------- /0x03-python-data_structures/tests/5-no_c.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def no_c(my_string): 3 | """ 4 | Removes all characters c and C from a string 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | my_string : str 10 | The string to remove 'Cc' from 11 | 12 | Return: 13 | The new string 14 | """ 15 | 16 | return ("".join([c for c in my_string if c not in ['c', 'C']])) 17 | -------------------------------------------------------------------------------- /0x03-python-data_structures/tests/6-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | print_matrix_integer = __import__('6-print_matrix_integer').print_matrix_integer 3 | 4 | matrix = [ 5 | [1, 2, 3], 6 | [4, 5, 6], 7 | [7, 8, 9] 8 | ] 9 | 10 | print_matrix_integer(matrix) 11 | print("--") 12 | print_matrix_integer() 13 | -------------------------------------------------------------------------------- /0x03-python-data_structures/tests/6-print_matrix_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def print_matrix_integer(matrix=[[]]): 3 | """ 4 | Prints a matrix of integers 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | matrix : list (of lists) 10 | The list to print 11 | 12 | Return: 13 | None 14 | """ 15 | 16 | for i in range(len(matrix)): 17 | for j in range(len(matrix[i])): 18 | print("{:d}".format(matrix[i][j]), end="") 19 | if j != (len(matrix[i]) - 1): 20 | print(" ", end="") 21 | print("") 22 | -------------------------------------------------------------------------------- /0x03-python-data_structures/tests/7-add_tuple.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def add_tuple(tuple_a=(), tuple_b=()): 3 | """ 4 | Adds 2 tuples 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | tuple_a : tuple 10 | The first tuple 11 | tuple_b : tuple 12 | The second tuple 13 | 14 | Return: 15 | A tuple with 2 integers 16 | """ 17 | 18 | if len(tuple_a) < 2: 19 | if len(tuple_a) == 0: 20 | tuple_a = 0, 0 21 | else: 22 | tuple_a = tuple_a[0], 0 23 | if len(tuple_b) < 2: 24 | if len(tuple_b) == 0: 25 | tuple_b = 0, 0 26 | else: 27 | tuple_b = tuple_b[0], 0 28 | 29 | return (tuple_a[0] + tuple_b[0], tuple_a[1] + tuple_b[1]) 30 | -------------------------------------------------------------------------------- /0x03-python-data_structures/tests/7-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | add_tuple = __import__('7-add_tuple').add_tuple 3 | 4 | tuple_a = (1, 89) 5 | tuple_b = (88, 11) 6 | new_tuple = add_tuple(tuple_a, tuple_b) 7 | print(new_tuple) 8 | 9 | print(add_tuple(tuple_a, (1, ))) 10 | print(add_tuple(tuple_a, ())) 11 | -------------------------------------------------------------------------------- /0x03-python-data_structures/tests/8-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | multiple_returns = __import__('8-multiple_returns').multiple_returns 3 | 4 | sentence = "At school, I learnt C!" 5 | length, first = multiple_returns(sentence) 6 | print("Length: {:d} - First character: {}".format(length, first)) 7 | -------------------------------------------------------------------------------- /0x03-python-data_structures/tests/8-multiple_returns.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def multiple_returns(sentence): 3 | """ 4 | Returns a tuple with the length of a string and its first character 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | sentence : str 10 | The string to treat 11 | 12 | Return: 13 | A tuple 14 | """ 15 | 16 | if len(sentence) == 0: 17 | return (0, None) 18 | else: 19 | return len(sentence), sentence[0] 20 | -------------------------------------------------------------------------------- /0x03-python-data_structures/tests/9-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | max_integer = __import__('9-max_integer').max_integer 3 | 4 | my_list = [1, 90, 2, 13, 34, 5, -13, 3] 5 | max_value = max_integer(my_list) 6 | print("Max: {}".format(max_value)) 7 | -------------------------------------------------------------------------------- /0x03-python-data_structures/tests/9-max_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def max_integer(my_list=[]): 3 | """ 4 | Finds the biggest integer of a list 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | my_list : list 10 | The list to treat 11 | 12 | Return: 13 | An integer that is the biggest integer of the list 14 | """ 15 | 16 | if len(my_list) == 0: 17 | return (None) 18 | 19 | big = my_list[0] 20 | for i in range(len(my_list)): 21 | if my_list[i] > big: 22 | big = my_list[i] 23 | 24 | return (big) 25 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/0-square_matrix_simple.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def square_matrix_simple(matrix=[]): 3 | """ 4 | Computes the square value of all integers of a matrix 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | matrix : list (of lists) 10 | The list of elements 11 | 12 | Return: 13 | a new matrix: 14 | Same size as matrix 15 | Each value should be the square of the value of the input 16 | """ 17 | 18 | return ([list(map(lambda x: x * x, row)) for row in matrix]) 19 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/1-search_replace.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def search_replace(my_list, search, replace): 3 | """ 4 | Replaces all occurrences of an element by another in a new list 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | my_list : list 10 | Initial list of elements 11 | search : integer 12 | The element to replace in the list 13 | replace : integer 14 | The new element 15 | 16 | Return: 17 | a new list with the new elements 18 | """ 19 | 20 | new_list = my_list[:] 21 | for i in range(len(new_list)): 22 | if new_list[i] == search: 23 | new_list[i] = replace 24 | return (new_list) 25 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/10-best_score.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def best_score(a_dictionary): 3 | """ 4 | Returns a key with the biggest integer value 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | a_dictionary : dictionary 10 | the given dictionary 11 | 12 | Return: 13 | If no score found, return None 14 | Key with biggest integer value otherwise 15 | """ 16 | 17 | if not isinstance(a_dictionary, dict) or len(a_dictionary) == 0: 18 | return None 19 | 20 | ret = list(a_dictionary.keys())[0] 21 | big = a_dictionary[ret] 22 | for k, v in a_dictionary.items(): 23 | if v > big: 24 | big = v 25 | ret = k 26 | return (ret) 27 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/100-weight_average.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def weight_average(my_list=[]): 3 | """ 4 | Returns the weighted average of all integers tuple (, ) 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | my_list : list 10 | list of tuples 11 | 12 | Return: 13 | the average 14 | """ 15 | 16 | if not isinstance(my_list, list) or len(my_list) == 0: 17 | return (0) 18 | 19 | avg = 0 20 | size = 0 21 | for tup in my_list: 22 | avg += (tup[0] * tup[1]) 23 | size += tup[1] 24 | return (avg / size) 25 | -------------------------------------------------------------------------------- /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 | """ 4 | Deletes keys with a specific value in a dictionary 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | a_dictionary : dictionary 10 | the given dictionary to delete value from 11 | 12 | Return: 13 | the new dictionary 14 | """ 15 | 16 | while value in a_dictionary.values(): 17 | for k, v in a_dictionary.items(): 18 | if v == value: 19 | del a_dictionary[k] 20 | break 21 | 22 | return (a_dictionary) 23 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/103-tests.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | 3 | lib = ctypes.CDLL('./libPython.so') 4 | lib.print_python_list.argtypes = [ctypes.py_object] 5 | lib.print_python_bytes.argtypes = [ctypes.py_object] 6 | s = b"Hello" 7 | lib.print_python_bytes(s); 8 | b = b'\xff\xf8\x00\x00\x00\x00\x00\x00'; 9 | lib.print_python_bytes(b); 10 | b = b'What does the \'b\' character do in front of a string literal?'; 11 | lib.print_python_bytes(b); 12 | l = [b'Hello', b'World'] 13 | lib.print_python_list(l) 14 | del l[1] 15 | lib.print_python_list(l) 16 | l = l + [4, 5, 6.0, (9, 8), [9, 8, 1024], b"Holberton", "Betty"] 17 | lib.print_python_list(l) 18 | l = [] 19 | lib.print_python_list(l) 20 | l.append(0) 21 | lib.print_python_list(l) 22 | l.append(1) 23 | l.append(2) 24 | l.append(3) 25 | l.append(4) 26 | lib.print_python_list(l) 27 | l.pop() 28 | lib.print_python_list(l) 29 | l = ["Holberton"] 30 | lib.print_python_list(l) 31 | lib.print_python_bytes(l); -------------------------------------------------------------------------------- /0x04-python-more_data_structures/11-multiply_list_map.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def multiply_list_map(my_list=[], number=0): 3 | return list(map(lambda x: x*number, my_list)) 4 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/2-uniq_add.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def uniq_add(my_list=[]): 3 | """ 4 | Adds all unique integers in a list (only once for each integer) 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | my_list : list 10 | List of elements 11 | 12 | Return: 13 | the result of the addition 14 | """ 15 | 16 | result = 0 17 | for x in set(my_list): 18 | result += x 19 | return (result) 20 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/3-common_elements.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def common_elements(set_1, set_2): 3 | """ 4 | Returns a set of common elements in two sets 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | set_1 : set 10 | first set of elements 11 | set_2 : set 12 | second set of elements 13 | 14 | Return: 15 | the result of the operation (&) 16 | """ 17 | 18 | return (set_1 & set_2) 19 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/4-only_diff_elements.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def only_diff_elements(set_1, set_2): 3 | """ 4 | Returns a set of all elements present in only one set 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | set_1 : set 10 | first set of elements 11 | set_2 : set 12 | second set of elements 13 | 14 | Return: 15 | the result of the operation (&) 16 | """ 17 | 18 | return (set_1 ^ set_2) 19 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/5-number_keys.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def number_keys(a_dictionary): 3 | """ 4 | Returns the number of keys in a dictionary 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | a_dictionary : dictionary 10 | the given dictionary 11 | 12 | Return: 13 | the number of keys 14 | """ 15 | 16 | return (len(a_dictionary)) 17 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/6-print_sorted_dictionary.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def print_sorted_dictionary(a_dictionary): 3 | """ 4 | Prints a dictionary by ordered keys 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | a_dictionary : dictionary 10 | the given dictionary 11 | 12 | Return: 13 | Nothing 14 | """ 15 | 16 | [print("{}: {}".format(k, a_dictionary[k])) for k in sorted(a_dictionary)] 17 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/7-update_dictionary.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def update_dictionary(a_dictionary, key, value): 3 | """ 4 | Replaces or adds key/value in a dictionary 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | a_dictionary : dictionary 10 | the given dictionary 11 | key : string 12 | argument will be always a string 13 | value : any type 14 | argument will be any type 15 | 16 | Return: 17 | the dictionary with the new inserted value 18 | """ 19 | 20 | a_dictionary[key] = value 21 | return (a_dictionary) 22 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/8-simple_delete.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def simple_delete(a_dictionary, key=""): 3 | """ 4 | Deletes a key in a dictionary 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | a_dictionary : dictionary 10 | the given dictionary 11 | key : string 12 | argument will be always a string 13 | 14 | Return: 15 | the new dictionary 16 | """ 17 | 18 | if key in a_dictionary: 19 | del a_dictionary[key] 20 | return (a_dictionary) 21 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/9-multiply_by_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def multiply_by_2(a_dictionary): 3 | """ 4 | Returns a new dictionary with all values multiplied by 2 5 | ... 6 | 7 | Parameters 8 | ---------- 9 | a_dictionary : dictionary 10 | the given dictionary 11 | 12 | Return: 13 | a new dictionary 14 | """ 15 | 16 | return ({k: a_dictionary[k] * 2 for k in a_dictionary}) 17 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/libPython.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/underscoDe/alx-higher_level_programming/65dba7607ebd18cefaffda5df24b47de586864d3/0x04-python-more_data_structures/libPython.so -------------------------------------------------------------------------------- /0x04-python-more_data_structures/tests/0-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | square_matrix_simple = __import__('0-square_matrix_simple').square_matrix_simple 3 | 4 | matrix = [ 5 | [1, 2, 3], 6 | [4, 5, 6], 7 | [7, 8, 9] 8 | ] 9 | 10 | new_matrix = square_matrix_simple(matrix) 11 | print(new_matrix) 12 | print(matrix) 13 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/tests/1-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | search_replace = __import__('1-search_replace').search_replace 3 | 4 | my_list = [1, 2, 3, 4, 5, 4, 2, 1, 1, 4, 89] 5 | new_list = search_replace(my_list, 2, 89) 6 | 7 | print(new_list) 8 | print(my_list) 9 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/tests/10-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | best_score = __import__('10-best_score').best_score 3 | 4 | a_dictionary = {'John': 12, 'Bob': 14, 'Mike': 14, 'Molly': 16, 'Adam': 10} 5 | best_key = best_score(a_dictionary) 6 | print("Best score: {}".format(best_key)) 7 | 8 | best_key = best_score(None) 9 | print("Best score: {}".format(best_key)) 10 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/tests/100-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | weight_average = __import__('100-weight_average').weight_average 3 | 4 | my_list = [(1, 2), (2, 1), (3, 10), (4, 2)] 5 | # = ((1 * 2) + (2 * 1) + (3 * 10) + (4 * 2)) / (2 + 1 + 10 + 2) 6 | result = weight_average(my_list) 7 | print("Average: {:0.2f}".format(result)) 8 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/tests/101-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | square_matrix_map = \ 3 | __import__('101-square_matrix_map').square_matrix_map 4 | 5 | matrix = [ 6 | [1, 2, 3], 7 | [4, 5, 6], 8 | [7, 8, 9] 9 | ] 10 | 11 | new_matrix = square_matrix_map(matrix) 12 | print(new_matrix) 13 | print(matrix) 14 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/tests/102-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | complex_delete = __import__('102-complex_delete').complex_delete 3 | print_sorted_dictionary = \ 4 | __import__('6-print_sorted_dictionary').print_sorted_dictionary 5 | 6 | a_dictionary = {'lang': "C", 'track': "Low", 'pref': "C", 'ids': [1, 2, 3]} 7 | new_dict = complex_delete(a_dictionary, 'C') 8 | print_sorted_dictionary(a_dictionary) 9 | print("--") 10 | print_sorted_dictionary(new_dict) 11 | 12 | print("--") 13 | print("--") 14 | new_dict = complex_delete(a_dictionary, 'c_is_fun') 15 | print_sorted_dictionary(a_dictionary) 16 | print("--") 17 | print_sorted_dictionary(new_dict) 18 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/tests/11-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | multiply_list_map = __import__('11-multiply_list_map').multiply_list_map 3 | 4 | my_list = [1, 2, 3, 4, 6] 5 | new_list = multiply_list_map(my_list, 4) 6 | print(new_list) 7 | print(my_list) 8 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/tests/12-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ Roman to Integer test file 3 | """ 4 | roman_to_int = __import__('12-roman_to_int').roman_to_int 5 | 6 | roman_number = "X" 7 | print("{} = {}".format(roman_number, roman_to_int(roman_number))) 8 | 9 | roman_number = "VII" 10 | print("{} = {}".format(roman_number, roman_to_int(roman_number))) 11 | 12 | roman_number = "IX" 13 | print("{} = {}".format(roman_number, roman_to_int(roman_number))) 14 | 15 | roman_number = "LXXXVII" 16 | print("{} = {}".format(roman_number, roman_to_int(roman_number))) 17 | 18 | roman_number = "DCCVII" 19 | print("{} = {}".format(roman_number, roman_to_int(roman_number))) 20 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/tests/2-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | uniq_add = __import__('2-uniq_add').uniq_add 3 | 4 | my_list = [1, 2, 3, 1, 4, 2, 5] 5 | result = uniq_add(my_list) 6 | print("Result: {:d}".format(result)) 7 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/tests/3-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | common_elements = __import__('3-common_elements').common_elements 3 | 4 | set_1 = { "Python", "C", "Javascript" } 5 | set_2 = { "Bash", "C", "Ruby", "Perl" } 6 | c_set = common_elements(set_1, set_2) 7 | print(sorted(list(c_set))) 8 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/tests/4-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | only_diff_elements = __import__('4-only_diff_elements').only_diff_elements 3 | 4 | set_1 = { "Python", "C", "Javascript" } 5 | set_2 = { "Bash", "C", "Ruby", "Perl" } 6 | od_set = only_diff_elements(set_1, set_2) 7 | print(sorted(list(od_set))) 8 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/tests/5-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | number_keys = __import__('5-number_keys').number_keys 3 | 4 | a_dictionary = { 'language': "C", 'number': 13, 'track': "Low level" } 5 | nb_keys = number_keys(a_dictionary) 6 | print("Number of keys: {:d}".format(nb_keys)) 7 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/tests/6-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | print_sorted_dictionary = __import__('6-print_sorted_dictionary').print_sorted_dictionary 3 | 4 | a_dictionary = { 'language': "C", 'Number': 89, 'track': "Low level", 'ids': [1, 2, 3] } 5 | print_sorted_dictionary(a_dictionary) 6 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/tests/7-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | update_dictionary = __import__('7-update_dictionary').update_dictionary 3 | print_sorted_dictionary = __import__('6-print_sorted_dictionary').print_sorted_dictionary 4 | 5 | a_dictionary = { 'language': "C", 'number': 89, 'track': "Low level" } 6 | new_dict = update_dictionary(a_dictionary, 'language', "Python") 7 | print_sorted_dictionary(new_dict) 8 | print("--") 9 | print_sorted_dictionary(a_dictionary) 10 | 11 | print("--") 12 | print("--") 13 | 14 | new_dict = update_dictionary(a_dictionary, 'city', "San Francisco") 15 | print_sorted_dictionary(new_dict) 16 | print("--") 17 | print_sorted_dictionary(a_dictionary) 18 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/tests/8-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | simple_delete = __import__('8-simple_delete').simple_delete 3 | print_sorted_dictionary = \ 4 | __import__('6-print_sorted_dictionary').print_sorted_dictionary 5 | 6 | a_dictionary = { 'language': "C", 'Number': 89, 'track': "Low", 'ids': [1, 2, 3] } 7 | new_dict = simple_delete(a_dictionary, 'track') 8 | print_sorted_dictionary(a_dictionary) 9 | print("--") 10 | print_sorted_dictionary(new_dict) 11 | 12 | print("--") 13 | print("--") 14 | new_dict = simple_delete(a_dictionary, 'c_is_fun') 15 | print_sorted_dictionary(a_dictionary) 16 | print("--") 17 | print_sorted_dictionary(new_dict) 18 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/tests/9-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | multiply_by_2 = __import__('9-multiply_by_2').multiply_by_2 3 | print_sorted_dictionary = \ 4 | __import__('6-print_sorted_dictionary').print_sorted_dictionary 5 | 6 | a_dictionary = {'John': 12, 'Alex': 8, 'Bob': 14, 'Mike': 14, 'Molly': 16} 7 | new_dict = multiply_by_2(a_dictionary) 8 | print_sorted_dictionary(a_dictionary) 9 | print("--") 10 | print_sorted_dictionary(new_dict) 11 | -------------------------------------------------------------------------------- /0x05-python-exceptions/0-safe_print_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def safe_print_list(my_list=[], x=0): 3 | ret = 0 4 | for i in range(x): 5 | try: 6 | print("{}".format(my_list[i]), end="") 7 | ret += 1 8 | except IndexError: 9 | break 10 | print("") 11 | return (ret) 12 | -------------------------------------------------------------------------------- /0x05-python-exceptions/1-safe_print_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def safe_print_integer(value): 3 | try: 4 | print("{:d}".format(value)) 5 | return (True) 6 | except (TypeError, ValueError): 7 | return (False) 8 | -------------------------------------------------------------------------------- /0x05-python-exceptions/100-safe_print_integer_err.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import sys 3 | 4 | 5 | def safe_print_integer_err(value): 6 | try: 7 | print("{:d}".format(value)) 8 | return (True) 9 | except (TypeError, ValueError): 10 | print("Exception: {}".format(sys.exc_info()[1]), file=sys.stderr) 11 | return (False) 12 | -------------------------------------------------------------------------------- /0x05-python-exceptions/101-safe_function.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import sys 3 | 4 | 5 | def safe_function(fct, *args): 6 | try: 7 | result = fct(*args) 8 | return (result) 9 | except: 10 | print("Exception: {}".format(sys.exc_info()[1]), file=sys.stderr) 11 | return (None) 12 | -------------------------------------------------------------------------------- /0x05-python-exceptions/102-magic_calculation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def magic_calculation(a, b): 3 | result = 0 4 | for i in range(1, 3): 5 | try: 6 | if i > a: 7 | raise Exception('Too far') 8 | else: 9 | result += a ** b / i 10 | except: 11 | result = b + a 12 | break 13 | return (result) 14 | -------------------------------------------------------------------------------- /0x05-python-exceptions/2-safe_print_list_integers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def safe_print_list_integers(my_list=[], x=0): 3 | ret = 0 4 | for i in range(0, x): 5 | try: 6 | print("{:d}".format(my_list[i]), end="") 7 | ret += 1 8 | except (ValueError, TypeError): 9 | continue 10 | print("") 11 | return (ret) 12 | -------------------------------------------------------------------------------- /0x05-python-exceptions/3-safe_print_division.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def safe_print_division(a, b): 3 | """Returns the division of a by b.""" 4 | try: 5 | div = a / b 6 | except (TypeError, ZeroDivisionError): 7 | div = None 8 | finally: 9 | print("Inside result: {}".format(div)) 10 | return (div) 11 | -------------------------------------------------------------------------------- /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(0, list_length): 5 | try: 6 | div = my_list_1[i] / my_list_2[i] 7 | except TypeError: 8 | print("wrong type") 9 | div = 0 10 | except ZeroDivisionError: 11 | print("division by 0") 12 | div = 0 13 | except IndexError: 14 | print("out of range") 15 | div = 0 16 | finally: 17 | new_list.append(div) 18 | return (new_list) 19 | -------------------------------------------------------------------------------- /0x05-python-exceptions/5-raise_exception.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def raise_exception(): 3 | raise TypeError 4 | -------------------------------------------------------------------------------- /0x05-python-exceptions/6-raise_exception_msg.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def raise_exception_msg(message=""): 3 | raise NameError(message) 4 | -------------------------------------------------------------------------------- /0x05-python-exceptions/libPython.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/underscoDe/alx-higher_level_programming/65dba7607ebd18cefaffda5df24b47de586864d3/0x05-python-exceptions/libPython.so -------------------------------------------------------------------------------- /0x05-python-exceptions/tests/0-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | safe_print_list = __import__('0-safe_print_list').safe_print_list 3 | 4 | my_list = [1, 2, 3, 4, 5] 5 | 6 | nb_print = safe_print_list(my_list, 2) 7 | print("nb_print: {:d}".format(nb_print)) 8 | nb_print = safe_print_list(my_list, len(my_list)) 9 | print("nb_print: {:d}".format(nb_print)) 10 | nb_print = safe_print_list(my_list, len(my_list) + 2) 11 | print("nb_print: {:d}".format(nb_print)) 12 | -------------------------------------------------------------------------------- /0x05-python-exceptions/tests/1-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | safe_print_integer = __import__('1-safe_print_integer').safe_print_integer 3 | 4 | value = 89 5 | has_been_print = safe_print_integer(value) 6 | if not has_been_print: 7 | print("{} is not an integer".format(value)) 8 | 9 | value = -89 10 | has_been_print = safe_print_integer(value) 11 | if not has_been_print: 12 | print("{} is not an integer".format(value)) 13 | 14 | value = "Holberton" 15 | has_been_print = safe_print_integer(value) 16 | if not has_been_print: 17 | print("{} is not an integer".format(value)) 18 | -------------------------------------------------------------------------------- /0x05-python-exceptions/tests/100-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | safe_print_integer_err = \ 3 | __import__('100-safe_print_integer_err').safe_print_integer_err 4 | 5 | value = 89 6 | has_been_print = safe_print_integer_err(value) 7 | if not has_been_print: 8 | print("{} is not an integer".format(value)) 9 | 10 | value = -89 11 | has_been_print = safe_print_integer_err(value) 12 | if not has_been_print: 13 | print("{} is not an integer".format(value)) 14 | 15 | value = "Holberton" 16 | has_been_print = safe_print_integer_err(value) 17 | if not has_been_print: 18 | print("{} is not an integer".format(value)) 19 | -------------------------------------------------------------------------------- /0x05-python-exceptions/tests/101-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | safe_function = __import__('101-safe_function').safe_function 3 | 4 | 5 | def my_div(a, b): 6 | return a / b 7 | 8 | result = safe_function(my_div, 10, 2) 9 | print("result of my_div: {}".format(result)) 10 | 11 | result = safe_function(my_div, 10, 0) 12 | print("result of my_div: {}".format(result)) 13 | 14 | 15 | def print_list(my_list, len): 16 | i = 0 17 | while i < len: 18 | print(my_list[i]) 19 | i += 1 20 | return len 21 | 22 | result = safe_function(print_list, [1, 2, 3, 4], 10) 23 | print("result of print_list: {}".format(result)) 24 | -------------------------------------------------------------------------------- /0x05-python-exceptions/tests/2-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | safe_print_list_integers = \ 3 | __import__('2-safe_print_list_integers').safe_print_list_integers 4 | 5 | my_list = [1, 2, 3, 4, 5] 6 | 7 | nb_print = safe_print_list_integers(my_list, 2) 8 | print("nb_print: {:d}".format(nb_print)) 9 | 10 | my_list = [1, 2, 3, "Holberton", 4, 5, [1, 2, 3]] 11 | nb_print = safe_print_list_integers(my_list, len(my_list)) 12 | print("nb_print: {:d}".format(nb_print)) 13 | 14 | nb_print = safe_print_list_integers(my_list, len(my_list) + 2) 15 | print("nb_print: {:d}".format(nb_print)) 16 | -------------------------------------------------------------------------------- /0x05-python-exceptions/tests/3-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | safe_print_division = __import__('3-safe_print_division').safe_print_division 3 | 4 | a = 12 5 | b = 2 6 | result = safe_print_division(a, b) 7 | print("{:d} / {:d} = {}".format(a, b, result)) 8 | 9 | a = 12 10 | b = 0 11 | result = safe_print_division(a, b) 12 | print("{:d} / {:d} = {}".format(a, b, result)) 13 | -------------------------------------------------------------------------------- /0x05-python-exceptions/tests/4-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | list_division = __import__('4-list_division').list_division 3 | 4 | my_l_1 = [10, 8, 4] 5 | my_l_2 = [2, 4, 4] 6 | result = list_division(my_l_1, my_l_2, max(len(my_l_1), len(my_l_2))) 7 | print(result) 8 | 9 | print("--") 10 | 11 | my_l_1 = [10, 8, 4, 4] 12 | my_l_2 = [2, 0, "H", 2, 7] 13 | result = list_division(my_l_1, my_l_2, max(len(my_l_1), len(my_l_2))) 14 | print(result) 15 | -------------------------------------------------------------------------------- /0x05-python-exceptions/tests/5-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | raise_exception = __import__('5-raise_exception').raise_exception 3 | 4 | try: 5 | raise_exception() 6 | except TypeError as te: 7 | print("Exception raised") 8 | -------------------------------------------------------------------------------- /0x05-python-exceptions/tests/6-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | raise_exception_msg = __import__('6-raise_exception_msg').raise_exception_msg 3 | 4 | try: 5 | raise_exception_msg("C is fun") 6 | except NameError as ne: 7 | print(ne) 8 | -------------------------------------------------------------------------------- /0x06-python-classes/0-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a class Square.""" 3 | 4 | 5 | class Square: 6 | """Represents a square. No body.""" 7 | pass 8 | -------------------------------------------------------------------------------- /0x06-python-classes/1-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a class Square.""" 3 | 4 | 5 | class Square: 6 | """Represents a square.""" 7 | 8 | def __init__(self, size): 9 | """Initializes a new Square. 10 | 11 | Args: 12 | size (int): The size of the new square. 13 | """ 14 | self.__size = size 15 | -------------------------------------------------------------------------------- /0x06-python-classes/103-magic_class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Define a MagicClass matching exactly a bytecode provided by Holberton.""" 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 | """Defines a class Square.""" 3 | 4 | 5 | class Square: 6 | """Represents a square.""" 7 | 8 | def __init__(self, size=0): 9 | """Initialize a new Square. 10 | 11 | Args: 12 | size (int): The size of the new square. 13 | """ 14 | if not isinstance(size, int): 15 | raise TypeError("size must be an integer") 16 | elif size < 0: 17 | raise ValueError("size must be >= 0") 18 | self.__size = size 19 | -------------------------------------------------------------------------------- /0x06-python-classes/3-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Define a class Square.""" 3 | 4 | 5 | class Square: 6 | """Represent a square.""" 7 | 8 | def __init__(self, size=0): 9 | """Initialize a new square. 10 | 11 | Args: 12 | size (int): The size of the new square. 13 | """ 14 | if not isinstance(size, int): 15 | raise TypeError("size must be an integer") 16 | elif size < 0: 17 | raise ValueError("size must be >= 0") 18 | self.__size = size 19 | 20 | def area(self): 21 | """Return the current area of the square.""" 22 | return (self.__size ** 2) 23 | -------------------------------------------------------------------------------- /0x06-python-classes/4-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a class Square.""" 3 | 4 | 5 | class Square: 6 | """Represents a square.""" 7 | 8 | def __init__(self, size=0): 9 | """Initializes a new square. 10 | 11 | Args: 12 | size (int): The size of the new square. 13 | """ 14 | self.__size = size 15 | 16 | @property 17 | def size(self): 18 | """Get/set the current size of the square.""" 19 | return (self.__size) 20 | 21 | @size.setter 22 | def size(self, value): 23 | if not isinstance(value, int): 24 | raise TypeError("size must be an integer") 25 | elif value < 0: 26 | raise ValueError("size must be >= 0") 27 | self.__size = value 28 | 29 | def area(self): 30 | """Return the current area of the square.""" 31 | return (self.__size ** 2) 32 | -------------------------------------------------------------------------------- /0x06-python-classes/tests/0-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Square = __import__('0-square').Square 3 | 4 | my_square = Square() 5 | print(type(my_square)) 6 | print(my_square.__dict__) 7 | -------------------------------------------------------------------------------- /0x06-python-classes/tests/1-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Square = __import__('1-square').Square 3 | 4 | my_square = Square(3) 5 | print(type(my_square)) 6 | print(my_square.__dict__) 7 | 8 | try: 9 | print(my_square.size) 10 | except Exception as e: 11 | print(e) 12 | 13 | try: 14 | print(my_square.__size) 15 | except Exception as e: 16 | print(e) 17 | -------------------------------------------------------------------------------- /0x06-python-classes/tests/100-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | SinglyLinkedList = __import__('100-singly_linked_list').SinglyLinkedList 3 | 4 | sll = SinglyLinkedList() 5 | sll.sorted_insert(2) 6 | sll.sorted_insert(5) 7 | sll.sorted_insert(3) 8 | sll.sorted_insert(10) 9 | sll.sorted_insert(1) 10 | sll.sorted_insert(-4) 11 | sll.sorted_insert(-3) 12 | sll.sorted_insert(4) 13 | sll.sorted_insert(5) 14 | sll.sorted_insert(12) 15 | sll.sorted_insert(3) 16 | print(sll) 17 | -------------------------------------------------------------------------------- /0x06-python-classes/tests/101-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Square = __import__('101-square').Square 3 | 4 | my_square = Square(5, (0, 0)) 5 | print(my_square) 6 | 7 | print("--") 8 | 9 | my_square = Square(5, (4, 1)) 10 | print(my_square) 11 | -------------------------------------------------------------------------------- /0x06-python-classes/tests/102-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Square = __import__('102-square').Square 3 | 4 | s_5 = Square(5) 5 | s_6 = Square(6) 6 | 7 | if s_5 < s_6: 8 | print("Square 5 < Square 6") 9 | if s_5 <= s_6: 10 | print("Square 5 <= Square 6") 11 | if s_5 == s_6: 12 | print("Square 5 == Square 6") 13 | if s_5 != s_6: 14 | print("Square 5 != Square 6") 15 | if s_5 > s_6: 16 | print("Square 5 > Square 6") 17 | if s_5 >= s_6: 18 | print("Square 5 >= Square 6") 19 | -------------------------------------------------------------------------------- /0x06-python-classes/tests/2-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Square = __import__('2-square').Square 3 | 4 | my_square_1 = Square(3) 5 | print(type(my_square_1)) 6 | print(my_square_1.__dict__) 7 | 8 | my_square_2 = Square() 9 | print(type(my_square_2)) 10 | print(my_square_2.__dict__) 11 | 12 | try: 13 | print(my_square_1.size) 14 | except Exception as e: 15 | print(e) 16 | 17 | try: 18 | print(my_square_1.__size) 19 | except Exception as e: 20 | print(e) 21 | 22 | try: 23 | my_square_3 = Square("3") 24 | print(type(my_square_3)) 25 | print(my_square_3.__dict__) 26 | except Exception as e: 27 | print(e) 28 | 29 | try: 30 | my_square_4 = Square(-89) 31 | print(type(my_square_4)) 32 | print(my_square_4.__dict__) 33 | except Exception as e: 34 | print(e) 35 | -------------------------------------------------------------------------------- /0x06-python-classes/tests/3-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Square = __import__('3-square').Square 3 | 4 | my_square_1 = Square(3) 5 | print("Area: {}".format(my_square_1.area())) 6 | 7 | try: 8 | print(my_square_1.size) 9 | except Exception as e: 10 | print(e) 11 | 12 | try: 13 | print(my_square_1.__size) 14 | except Exception as e: 15 | print(e) 16 | 17 | my_square_2 = Square(5) 18 | print("Area: {}".format(my_square_2.area())) 19 | -------------------------------------------------------------------------------- /0x06-python-classes/tests/4-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Square = __import__('4-square').Square 3 | 4 | my_square = Square(89) 5 | print("Area: {} for size: {}".format(my_square.area(), my_square.size)) 6 | 7 | my_square.size = 3 8 | print("Area: {} for size: {}".format(my_square.area(), my_square.size)) 9 | 10 | try: 11 | my_square.size = "5 feet" 12 | print("Area: {} for size: {}".format(my_square.area(), my_square.size)) 13 | except Exception as e: 14 | print(e) 15 | -------------------------------------------------------------------------------- /0x06-python-classes/tests/5-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Square = __import__('5-square').Square 3 | 4 | my_square = Square(3) 5 | my_square.my_print() 6 | 7 | print("--") 8 | 9 | my_square.size = 10 10 | my_square.my_print() 11 | 12 | print("--") 13 | 14 | my_square.size = 0 15 | my_square.my_print() 16 | 17 | print("--") 18 | -------------------------------------------------------------------------------- /0x06-python-classes/tests/6-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Square = __import__('6-square').Square 3 | 4 | my_square_1 = Square(3) 5 | my_square_1.my_print() 6 | 7 | print("--") 8 | 9 | my_square_2 = Square(3, (1, 1)) 10 | my_square_2.my_print() 11 | 12 | print("--") 13 | 14 | my_square_3 = Square(3, (3, 0)) 15 | my_square_3.my_print() 16 | 17 | print("--") 18 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/0-add_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines an integer addition function.""" 3 | 4 | 5 | def add_integer(a, b=98): 6 | """Return the integer addition of a and b. 7 | 8 | Float arguments are typecasted to ints before addition is performed. 9 | 10 | Raises: 11 | TypeError: If either of a or b is a non-integer and non-float. 12 | """ 13 | if ((not isinstance(a, int) and not isinstance(a, float))): 14 | raise TypeError("a must be an integer") 15 | if ((not isinstance(b, int) and not isinstance(b, float))): 16 | raise TypeError("b must be an integer") 17 | return (int(a) + int(b)) 18 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/101-lazy_matrix_mul.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a matrix multiplication function using NumPy.""" 3 | import numpy as np 4 | 5 | 6 | def lazy_matrix_mul(m_a, m_b): 7 | """Return the multiplication of two matrices. 8 | 9 | Args: 10 | m_a (list of lists of ints/floats): The first matrix. 11 | m_b (list of lists of ints/floats): The second matrix. 12 | """ 13 | 14 | return (np.matmul(m_a, m_b)) 15 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/102-python.c: -------------------------------------------------------------------------------- 1 | #include "Python.h" 2 | 3 | /** 4 | * print_python_string - Prints information about Python strings. 5 | * @p: A PyObject string object. 6 | */ 7 | void print_python_string(PyObject *p) 8 | { 9 | long int length; 10 | 11 | fflush(stdout); 12 | 13 | printf("[.] string object info\n"); 14 | if (strcmp(p->ob_type->tp_name, "str") != 0) 15 | { 16 | printf(" [ERROR] Invalid String Object\n"); 17 | return; 18 | } 19 | 20 | length = ((PyASCIIObject *)(p))->length; 21 | 22 | if (PyUnicode_IS_COMPACT_ASCII(p)) 23 | printf(" type: compact ascii\n"); 24 | else 25 | printf(" type: compact unicode object\n"); 26 | printf(" length: %ld\n", length); 27 | printf(" value: %ls\n", PyUnicode_AsWideCharString(p, &length)); 28 | } 29 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/3-say_my_name.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a name-printing function.""" 3 | 4 | 5 | def say_my_name(first_name, last_name=""): 6 | """Print a name. 7 | 8 | Args: 9 | first_name (str): The first name to print. 10 | last_name (str): The last name to print. 11 | Raises: 12 | TypeError: If either of first_name or last_name are not strings. 13 | """ 14 | if not isinstance(first_name, str): 15 | raise TypeError("first_name must be a string") 16 | if not isinstance(last_name, str): 17 | raise TypeError("last_name must be a string") 18 | print("My name is {} {}".format(first_name, last_name)) 19 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/4-print_square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a square-printing function.""" 3 | 4 | 5 | def print_square(size): 6 | """Print a square with the # character. 7 | 8 | Args: 9 | size (int): The height/width of the square. 10 | Raises: 11 | TypeError: If size is not an integer. 12 | ValueError: If size is < 0 13 | """ 14 | if not isinstance(size, int): 15 | raise TypeError("size must be an integer") 16 | if size < 0: 17 | raise ValueError("size must be >= 0") 18 | 19 | for i in range(size): 20 | [print("#", end="") for j in range(size)] 21 | print("") 22 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/5-text_indentation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a text-indentation function.""" 3 | 4 | 5 | def text_indentation(text): 6 | """Print text with two new lines after each '.', '?', and ':'. 7 | 8 | Args: 9 | text (string): The text to print. 10 | Raises: 11 | TypeError: If text is not a string. 12 | """ 13 | if not isinstance(text, str): 14 | raise TypeError("text must be a string") 15 | 16 | c = 0 17 | while c < len(text) and text[c] == ' ': 18 | c += 1 19 | 20 | while c < len(text): 21 | print(text[c], end="") 22 | if text[c] == "\n" or text[c] in ".?:": 23 | if text[c] in ".?:": 24 | print("\n") 25 | c += 1 26 | while c < len(text) and text[c] == ' ': 27 | c += 1 28 | continue 29 | c += 1 30 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/6-max_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Module to find the max integer in a list 3 | """ 4 | 5 | 6 | def max_integer(list=[]): 7 | """Function to find and return the max integer in a list of integers 8 | If the list is empty, the function returns None 9 | """ 10 | if len(list) == 0: 11 | return None 12 | result = list[0] 13 | i = 1 14 | while i < len(list): 15 | if list[i] > result: 16 | result = list[i] 17 | i += 1 18 | return result 19 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/0-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | add_integer = __import__('0-add_integer').add_integer 3 | 4 | print(add_integer(1, 2)) 5 | print(add_integer(100, -2)) 6 | print(add_integer(2)) 7 | print(add_integer(100.3, -2)) 8 | try: 9 | print(add_integer(4, "School")) 10 | except Exception as e: 11 | print(e) 12 | try: 13 | print(add_integer(None)) 14 | except Exception as e: 15 | print(e) 16 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/100-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | matrix_mul = __import__('100-matrix_mul').matrix_mul 3 | 4 | print(matrix_mul([[1, 2], [3, 4]], [[1, 2], [3, 4]])) 5 | print(matrix_mul([[1, 2]], [[3, 4], [5, 6]])) 6 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/101-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | lazy_matrix_mul = __import__('101-lazy_matrix_mul').lazy_matrix_mul 3 | 4 | print(lazy_matrix_mul([[1, 2], [3, 4]], [[1, 2], [3, 4]])) 5 | print(lazy_matrix_mul([[1, 2]], [[3, 4], [5, 6]])) 6 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/2-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | matrix_divided = __import__('2-matrix_divided').matrix_divided 3 | 4 | matrix = [ 5 | [1, 2, 3], 6 | [4, 5, 6] 7 | ] 8 | print(matrix_divided(matrix, 3)) 9 | print(matrix) 10 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/3-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | say_my_name = __import__('3-say_my_name').say_my_name 3 | 4 | say_my_name("John", "Smith") 5 | say_my_name("Walter", "White") 6 | say_my_name("Bob") 7 | try: 8 | say_my_name(12, "White") 9 | except Exception as e: 10 | print(e) 11 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/4-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | print_square = __import__('4-print_square').print_square 3 | 4 | print_square(4) 5 | print("") 6 | print_square(10) 7 | print("") 8 | print_square(0) 9 | print("") 10 | print_square(1) 11 | print("") 12 | try: 13 | print_square(-1) 14 | except Exception as e: 15 | print(e) 16 | print("") 17 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/5-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | text_indentation = __import__('5-text_indentation').text_indentation 3 | 4 | text_indentation("""Lorem ipsum dolor sit amet, consectetur adipiscing elit. \ 5 | Quonam modo? Utrum igitur tibi litteram videor an totas paginas commovere? \ 6 | Non autem hoc: igitur ne illud quidem. Fortasse id optimum, sed ubi illud: \ 7 | Plus semper voluptatis? Teneo, inquit, finem illi videri nihil dolere. \ 8 | Transfer idem ad modestiam vel temperantiam, quae est moderatio cupiditatum \ 9 | rationi oboediens. Si id dicis, vicimus. Inde sermone vario sex illa a Dipylo \ 10 | stadia confecimus. Sin aliud quid voles, postea. Quae animi affectio suum \ 11 | cuique tribuens atque hanc, quam dico. Utinam quidem dicerent alium alio \ 12 | beatiorem! Iam ruinas videres""") 13 | -------------------------------------------------------------------------------- /0x08-python-more_classes/0-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a Rectangle class.""" 3 | 4 | 5 | class Rectangle: 6 | """Represent a rectangle.""" 7 | pass 8 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/0-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('0-rectangle').Rectangle 3 | 4 | my_rectangle = Rectangle() 5 | print(type(my_rectangle)) 6 | print(my_rectangle.__dict__) 7 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/1-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('1-rectangle').Rectangle 3 | 4 | my_rectangle = Rectangle(2, 4) 5 | print(my_rectangle.__dict__) 6 | 7 | my_rectangle.width = 10 8 | my_rectangle.height = 3 9 | print(my_rectangle.__dict__) 10 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/2-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('2-rectangle').Rectangle 3 | 4 | my_rectangle = Rectangle(2, 4) 5 | print("Area: {} - Perimeter: {}".format(my_rectangle.area(), my_rectangle.perimeter())) 6 | 7 | print("--") 8 | 9 | my_rectangle.width = 10 10 | my_rectangle.height = 3 11 | print("Area: {} - Perimeter: {}".format(my_rectangle.area(), my_rectangle.perimeter())) 12 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/3-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('3-rectangle').Rectangle 3 | 4 | my_rectangle = Rectangle(2, 4) 5 | print("Area: {} - Perimeter: {}".format(my_rectangle.area(), my_rectangle.perimeter())) 6 | 7 | print(str(my_rectangle)) 8 | print(repr(my_rectangle)) 9 | 10 | print("--") 11 | 12 | my_rectangle.width = 10 13 | my_rectangle.height = 3 14 | print(my_rectangle) 15 | print(repr(my_rectangle)) 16 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/4-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('4-rectangle').Rectangle 3 | 4 | my_rectangle = Rectangle(2, 4) 5 | print(str(my_rectangle)) 6 | print("--") 7 | print(my_rectangle) 8 | print("--") 9 | print(repr(my_rectangle)) 10 | print("--") 11 | print(hex(id(my_rectangle))) 12 | print("--") 13 | 14 | # create new instance based on representation 15 | new_rectangle = eval(repr(my_rectangle)) 16 | print(str(new_rectangle)) 17 | print("--") 18 | print(new_rectangle) 19 | print("--") 20 | print(repr(new_rectangle)) 21 | print("--") 22 | print(hex(id(new_rectangle))) 23 | print("--") 24 | 25 | print(new_rectangle is my_rectangle) 26 | print(type(new_rectangle) is type(my_rectangle)) 27 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/5-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('5-rectangle').Rectangle 3 | 4 | my_rectangle = Rectangle(2, 4) 5 | print("Area: {} - Perimeter: {}".format(my_rectangle.area(), my_rectangle.perimeter())) 6 | 7 | del my_rectangle 8 | 9 | try: 10 | print(my_rectangle) 11 | except Exception as e: 12 | print("[{}] {}".format(e.__class__.__name__, e)) 13 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/6-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('6-rectangle').Rectangle 3 | 4 | my_rectangle_1 = Rectangle(2, 4) 5 | my_rectangle_2 = Rectangle(2, 4) 6 | print("{:d} instances of Rectangle".format(Rectangle.number_of_instances)) 7 | del my_rectangle_1 8 | print("{:d} instances of Rectangle".format(Rectangle.number_of_instances)) 9 | del my_rectangle_2 10 | print("{:d} instances of Rectangle".format(Rectangle.number_of_instances)) 11 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/7-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('7-rectangle').Rectangle 3 | 4 | my_rectangle_1 = Rectangle(8, 4) 5 | print(my_rectangle_1) 6 | print("--") 7 | my_rectangle_1.print_symbol = "&" 8 | print(my_rectangle_1) 9 | print("--") 10 | 11 | my_rectangle_2 = Rectangle(2, 1) 12 | print(my_rectangle_2) 13 | print("--") 14 | Rectangle.print_symbol = "C" 15 | print(my_rectangle_2) 16 | print("--") 17 | 18 | my_rectangle_3 = Rectangle(7, 3) 19 | print(my_rectangle_3) 20 | 21 | print("--") 22 | 23 | my_rectangle_3.print_symbol = ["C", "is", "fun!"] 24 | print(my_rectangle_3) 25 | 26 | print("--") 27 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/8-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('8-rectangle').Rectangle 3 | 4 | my_rectangle_1 = Rectangle(8, 4) 5 | my_rectangle_2 = Rectangle(2, 3) 6 | 7 | if my_rectangle_1 is Rectangle.bigger_or_equal(my_rectangle_1, my_rectangle_2): 8 | print("my_rectangle_1 is bigger or equal to my_rectangle_2") 9 | else: 10 | print("my_rectangle_2 is bigger than my_rectangle_1") 11 | 12 | 13 | my_rectangle_2.width = 10 14 | my_rectangle_2.height = 5 15 | if my_rectangle_1 is Rectangle.bigger_or_equal(my_rectangle_1, my_rectangle_2): 16 | print("my_rectangle_1 is bigger or equal to my_rectangle_2") 17 | else: 18 | print("my_rectangle_2 is bigger than my_rectangle_1") 19 | -------------------------------------------------------------------------------- /0x08-python-more_classes/tests/9-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('9-rectangle').Rectangle 3 | 4 | my_square = Rectangle.square(5) 5 | print("Area: {} - Perimeter: {}".format(my_square.area(), my_square.perimeter())) 6 | print(my_square) 7 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/0-answer.txt: -------------------------------------------------------------------------------- 1 | type 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/1-answer.txt: -------------------------------------------------------------------------------- 1 | id 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/10-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/100-magic_string.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def magic_string(): 3 | magic_string.n = getattr(magic_string, 'n', 0) + 1 4 | return ("BestSchool, " * (magic_string.n - 1) + "BestSchool") 5 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/101-locked_class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a locked class.""" 3 | 4 | 5 | class LockedClass: 6 | """ 7 | Prevent the user from instantiating new LockedClass attributes 8 | for anything but attributes called 'first_name'. 9 | """ 10 | 11 | __slots__ = ["first_name"] 12 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/103-line1.txt: -------------------------------------------------------------------------------- 1 | 0 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/103-line2.txt: -------------------------------------------------------------------------------- 1 | 0 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/104-line1.txt: -------------------------------------------------------------------------------- 1 | 1 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/104-line2.txt: -------------------------------------------------------------------------------- 1 | 1 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/104-line3.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/104-line4.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/104-line5.txt: -------------------------------------------------------------------------------- 1 | 1 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/105-line1.txt: -------------------------------------------------------------------------------- 1 | 262 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/106-line1.txt: -------------------------------------------------------------------------------- 1 | 1 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/106-line2.txt: -------------------------------------------------------------------------------- 1 | 0 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/106-line3.txt: -------------------------------------------------------------------------------- 1 | No 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/106-line4.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/106-line5.txt: -------------------------------------------------------------------------------- 1 | 1 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/11-answer.txt: -------------------------------------------------------------------------------- 1 | False 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/12-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/13-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/14-answer.txt: -------------------------------------------------------------------------------- 1 | [1, 2, 3, 4] 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/15-answer.txt: -------------------------------------------------------------------------------- 1 | [1, 2, 3] 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/16-answer.txt: -------------------------------------------------------------------------------- 1 | 1 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/17-answer.txt: -------------------------------------------------------------------------------- 1 | [1, 2, 3, 4] 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/18-answer.txt: -------------------------------------------------------------------------------- 1 | [1, 2, 3] 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/19-copy_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def copy_list(l): 3 | return l.copy() 4 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/2-answer.txt: -------------------------------------------------------------------------------- 1 | No 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/20-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/21-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/22-answer.txt: -------------------------------------------------------------------------------- 1 | No 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/23-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/24-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/25-answer.txt: -------------------------------------------------------------------------------- 1 | False 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/26-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/27-answer.txt: -------------------------------------------------------------------------------- 1 | No 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/28-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/3-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/4-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/5-answer.txt: -------------------------------------------------------------------------------- 1 | No 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/6-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/7-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/8-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/9-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/tests/100-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | magic_string = __import__('100-magic_string').magic_string 3 | 4 | for i in range(10): 5 | print(magic_string()) 6 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/tests/101-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | LockedClass = __import__('101-locked_class').LockedClass 3 | 4 | lc = LockedClass() 5 | lc.first_name = "John" 6 | try: 7 | lc.last_name = "Snow" 8 | except Exception as e: 9 | print("[{}] {}".format(e.__class__.__name__, e)) 10 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/tests/19-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | copy_list = __import__('19-copy_list').copy_list 3 | 4 | my_list = [1, 2, 3] 5 | print(my_list) 6 | 7 | new_list = copy_list(my_list) 8 | 9 | print(my_list) 10 | print(new_list) 11 | 12 | print(new_list == my_list) 13 | print(new_list is my_list) 14 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/0-lookup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines an object attribute lookup function.""" 3 | 4 | 5 | def lookup(obj): 6 | """Return a list of an object's available attributes.""" 7 | return (dir(obj)) 8 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/1-my_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines an inherited list class MyList.""" 3 | 4 | 5 | class MyList(list): 6 | """Implements sorted printing for the built-in list class.""" 7 | 8 | def print_sorted(self): 9 | """Print a list in sorted ascending order.""" 10 | print(sorted(self)) 11 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/10-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a Rectangle subclass Square.""" 3 | Rectangle = __import__('9-rectangle').Rectangle 4 | 5 | 6 | class Square(Rectangle): 7 | """Represent a square.""" 8 | 9 | def __init__(self, size): 10 | """Initialize a new square. 11 | 12 | Args: 13 | size (int): The size of the new square. 14 | """ 15 | self.integer_validator("size", size) 16 | super().__init__(size, size) 17 | self.__size = size 18 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/100-my_int.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a class MyInt that inherits from int.""" 3 | 4 | 5 | class MyInt(int): 6 | """Invert int operators == and !=.""" 7 | 8 | def __eq__(self, value): 9 | """Override == opeartor with != behavior.""" 10 | return self.real != value 11 | 12 | def __ne__(self, value): 13 | """Override != operator with == behavior.""" 14 | return self.real == value 15 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/101-add_attribute.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a function that adds attributes to objects.""" 3 | 4 | 5 | def add_attribute(obj, att, value): 6 | """Add a new attribute to an object if possible. 7 | 8 | Args: 9 | obj (any): The object to add an attribute to. 10 | att (str): The name of the attribute to add to obj. 11 | value (any): The value of att. 12 | Raises: 13 | TypeError: If the attribute cannot be added. 14 | """ 15 | if not hasattr(obj, "__dict__"): 16 | raise TypeError("can't add new attribute") 17 | setattr(obj, att, value) 18 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/11-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a Rectangle subclass Square.""" 3 | Rectangle = __import__('9-rectangle').Rectangle 4 | 5 | 6 | class Square(Rectangle): 7 | """Represent a square.""" 8 | 9 | def __init__(self, size): 10 | """Initialize a new square. 11 | 12 | Args: 13 | size (int): The size of the new square. 14 | """ 15 | self.integer_validator("size", size) 16 | super().__init__(size, size) 17 | self.__size = size 18 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/2-is_same_class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a class-checking function.""" 3 | 4 | 5 | def is_same_class(obj, a_class): 6 | """Check if an object is exactly an instance of a given class. 7 | 8 | Args: 9 | obj (any): The object to check. 10 | a_class (type): The class to match the type of obj to. 11 | Returns: 12 | If obj is exactly an instance of a_class - True. 13 | Otherwise - False. 14 | """ 15 | if type(obj) == a_class: 16 | return True 17 | return False 18 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/3-is_kind_of_class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a class and inherited class-checking function.""" 3 | 4 | 5 | def is_kind_of_class(obj, a_class): 6 | """Check if an object is an instance or inherited instance of a class. 7 | 8 | Args: 9 | obj (any): The object to check. 10 | a_class (type): The class to match the type of obj to. 11 | Returns: 12 | If obj is an instance or inherited instance of a_class - True. 13 | Otherwise - False. 14 | """ 15 | if isinstance(obj, a_class): 16 | return True 17 | return False 18 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/4-inherits_from.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines an inherited class-checking function.""" 3 | 4 | 5 | def inherits_from(obj, a_class): 6 | """Checks if an object is an inherited instance of a class. 7 | 8 | Args: 9 | obj (any): The object to check. 10 | a_class (type): The class to match the type of obj to. 11 | Returns: 12 | If obj is an inherited instance of a_class - True. 13 | Otherwise - False. 14 | """ 15 | if issubclass(type(obj), a_class) and type(obj) != a_class: 16 | return True 17 | return False 18 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/5-base_geometry.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines an empty class BaseGeometry.""" 3 | 4 | 5 | class BaseGeometry: 6 | """Represent base geometry.""" 7 | pass 8 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/6-base_geometry.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a base geometry class BaseGeometry.""" 3 | 4 | 5 | class BaseGeometry: 6 | """Represent base geometry.""" 7 | 8 | def area(self): 9 | """Not implemented.""" 10 | raise Exception("area() is not implemented yet") 11 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/7-base_geometry.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a base geometry class BaseGeometry.""" 3 | 4 | 5 | class BaseGeometry: 6 | """Reprsent base geometry.""" 7 | 8 | def area(self): 9 | """Not yet implemented.""" 10 | raise Exception("area() is not implemented yet") 11 | 12 | def integer_validator(self, name, value): 13 | """Validate a parameter as an integer. 14 | 15 | Args: 16 | name (str): The name of the parameter. 17 | value (int): The parameter to validate. 18 | Raises: 19 | TypeError: If value is not an integer. 20 | ValueError: If value is <= 0. 21 | """ 22 | if type(value) != int: 23 | raise TypeError("{} must be an integer".format(name)) 24 | if value <= 0: 25 | raise ValueError("{} must be greater than 0".format(name)) 26 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/8-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a class Rectangle that inherits from BaseGeometry.""" 3 | BaseGeometry = __import__('7-base_geometry').BaseGeometry 4 | 5 | 6 | class Rectangle(BaseGeometry): 7 | """Represent a rectangle using BaseGeometry.""" 8 | 9 | def __init__(self, width, height): 10 | """Intialize a new Rectangle. 11 | 12 | Args: 13 | width (int): The width of the new Rectangle. 14 | height (int): The height of the new Rectangle. 15 | """ 16 | self.integer_validator("width", width) 17 | self.__width = width 18 | self.integer_validator("height", height) 19 | self.__height = height 20 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/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(13) 5 | 6 | print(s) 7 | print(s.area()) 8 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/100-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | MyInt = __import__('100-my_int').MyInt 3 | 4 | my_i = MyInt(3) 5 | print(my_i) 6 | print(my_i == 3) 7 | print(my_i != 3) 8 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/101-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | add_attribute = __import__('101-add_attribute').add_attribute 3 | 4 | class MyClass(): 5 | pass 6 | 7 | mc = MyClass() 8 | add_attribute(mc, "name", "John") 9 | print(mc.name) 10 | 11 | try: 12 | a = "My String" 13 | add_attribute(a, "name", "Bob") 14 | print(a.name) 15 | except Exception as e: 16 | print("[{}] {}".format(e.__class__.__name__, e)) 17 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/11-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Square = __import__('11-square').Square 3 | 4 | s = Square(13) 5 | 6 | print(s) 7 | print(s.area()) 8 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/2-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | is_same_class = __import__('2-is_same_class').is_same_class 3 | 4 | a = 1 5 | if is_same_class(a, int): 6 | print("{} is an instance of the class {}".format(a, int.__name__)) 7 | if is_same_class(a, float): 8 | print("{} is an instance of the class {}".format(a, float.__name__)) 9 | if is_same_class(a, object): 10 | print("{} is an instance of the class {}".format(a, object.__name__)) 11 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/3-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | is_kind_of_class = __import__('3-is_kind_of_class').is_kind_of_class 3 | 4 | a = 1 5 | if is_kind_of_class(a, int): 6 | print("{} comes from {}".format(a, int.__name__)) 7 | if is_kind_of_class(a, float): 8 | print("{} comes from {}".format(a, float.__name__)) 9 | if is_kind_of_class(a, object): 10 | print("{} comes from {}".format(a, object.__name__)) 11 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/4-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | inherits_from = __import__('4-inherits_from').inherits_from 3 | 4 | a = True 5 | if inherits_from(a, int): 6 | print("{} inherited from class {}".format(a, int.__name__)) 7 | if inherits_from(a, bool): 8 | print("{} inherited from class {}".format(a, bool.__name__)) 9 | if inherits_from(a, object): 10 | print("{} inherited from class {}".format(a, object.__name__)) 11 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/5-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | BaseGeometry = __import__('5-base_geometry').BaseGeometry 3 | 4 | bg = BaseGeometry() 5 | 6 | print(bg) 7 | print(dir(bg)) 8 | print(dir(BaseGeometry)) 9 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/6-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | BaseGeometry = __import__('6-base_geometry').BaseGeometry 3 | 4 | bg = BaseGeometry() 5 | 6 | try: 7 | print(bg.area()) 8 | except Exception as e: 9 | print("[{}] {}".format(e.__class__.__name__, e)) 10 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/7-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | BaseGeometry = __import__('7-base_geometry').BaseGeometry 3 | 4 | bg = BaseGeometry() 5 | 6 | bg.integer_validator("my_int", 12) 7 | bg.integer_validator("width", 89) 8 | 9 | try: 10 | bg.integer_validator("name", "John") 11 | except Exception as e: 12 | print("[{}] {}".format(e.__class__.__name__, e)) 13 | 14 | try: 15 | bg.integer_validator("age", 0) 16 | except Exception as e: 17 | print("[{}] {}".format(e.__class__.__name__, e)) 18 | 19 | try: 20 | bg.integer_validator("distance", -4) 21 | except Exception as e: 22 | print("[{}] {}".format(e.__class__.__name__, e)) 23 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/8-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('8-rectangle').Rectangle 3 | 4 | r = Rectangle(3, 5) 5 | 6 | print(r) 7 | print(dir(r)) 8 | 9 | try: 10 | print("Rectangle: {} - {}".format(r.width, r.height)) 11 | except Exception as e: 12 | print("[{}] {}".format(e.__class__.__name__, e)) 13 | 14 | try: 15 | r2 = Rectangle(4, True) 16 | except Exception as e: 17 | print("[{}] {}".format(e.__class__.__name__, e)) 18 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/9-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('9-rectangle').Rectangle 3 | 4 | r = Rectangle(3, 5) 5 | 6 | print(r) 7 | print(r.area()) 8 | -------------------------------------------------------------------------------- /0x0B-python-input_output/0-read_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a text file-reading function.""" 3 | 4 | 5 | def read_file(filename=""): 6 | """Print the contents of a UTF8 text file to stdout.""" 7 | with open(filename, encoding="utf-8") as f: 8 | print(f.read(), end="") 9 | -------------------------------------------------------------------------------- /0x0B-python-input_output/1-write_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a file-writing function.""" 3 | 4 | 5 | def write_file(filename="", text=""): 6 | """Write a string to a UTF8 text file. 7 | 8 | Args: 9 | filename (str): The name of the file to write. 10 | text (str): The text to write to the file. 11 | Returns: 12 | The number of characters written. 13 | """ 14 | with open(filename, "w", encoding="utf-8") as f: 15 | return f.write(text) 16 | -------------------------------------------------------------------------------- /0x0B-python-input_output/100-append_after.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a text file insertion function.""" 3 | 4 | 5 | def append_after(filename="", search_string="", new_string=""): 6 | """Insert text after each line containing a given string in a file. 7 | 8 | Args: 9 | filename (str): The name of the file. 10 | search_string (str): The string to search for within the file. 11 | new_string (str): The string to insert. 12 | """ 13 | text = "" 14 | with open(filename) as r: 15 | for line in r: 16 | text += line 17 | if search_string in line: 18 | text += new_string 19 | with open(filename, "w") as w: 20 | w.write(text) 21 | -------------------------------------------------------------------------------- /0x0B-python-input_output/12-pascal_triangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a Pascal's Triangle function.""" 3 | 4 | 5 | def pascal_triangle(n): 6 | """Represent Pascal's Triangle of size n. 7 | 8 | Returns a list of lists of integers representing the triangle. 9 | """ 10 | if n <= 0: 11 | return [] 12 | 13 | triangles = [[1]] 14 | while len(triangles) != n: 15 | tri = triangles[-1] 16 | tmp = [1] 17 | for i in range(len(tri) - 1): 18 | tmp.append(tri[i] + tri[i + 1]) 19 | tmp.append(1) 20 | triangles.append(tmp) 21 | return triangles 22 | -------------------------------------------------------------------------------- /0x0B-python-input_output/2-append_write.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a file-appending function.""" 3 | 4 | 5 | def append_write(filename="", text=""): 6 | """Appends a string to the end of a UTF8 text file. 7 | 8 | Args: 9 | filename (str): The name of the file to append to. 10 | text (str): The string to append to the file. 11 | Returns: 12 | The number of characters appended. 13 | """ 14 | with open(filename, "a", encoding="utf-8") as f: 15 | return f.write(text) 16 | -------------------------------------------------------------------------------- /0x0B-python-input_output/3-to_json_string.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a string-to-JSON function.""" 3 | import json 4 | 5 | 6 | def to_json_string(my_obj): 7 | """Return the JSON representation of a string object.""" 8 | return json.dumps(my_obj) 9 | -------------------------------------------------------------------------------- /0x0B-python-input_output/4-from_json_string.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a JSON-to-object function.""" 3 | 4 | 5 | import json 6 | 7 | 8 | def from_json_string(my_str): 9 | """Return the Python object representation of a JSON string.""" 10 | return json.loads(my_str) 11 | -------------------------------------------------------------------------------- /0x0B-python-input_output/5-save_to_json_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a JSON file-writing function.""" 3 | import json 4 | 5 | 6 | def save_to_json_file(my_obj, filename): 7 | """Write an object to a text file using JSON representation.""" 8 | with open(filename, "w") as f: 9 | json.dump(my_obj, f) 10 | -------------------------------------------------------------------------------- /0x0B-python-input_output/6-load_from_json_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a JSON file-reading function.""" 3 | import json 4 | 5 | 6 | def load_from_json_file(filename): 7 | """Create a Python object from a JSON file.""" 8 | with open(filename) as f: 9 | return json.load(f) 10 | -------------------------------------------------------------------------------- /0x0B-python-input_output/7-add_item.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Add all arguments to a Python list and save them to a file.""" 3 | 4 | 5 | import sys 6 | 7 | if __name__ == "__main__": 8 | save_to_json_file = __import__('5-save_to_json_file').save_to_json_file 9 | load_from_json_file = \ 10 | __import__('6-load_from_json_file').load_from_json_file 11 | 12 | try: 13 | items = load_from_json_file("add_item.json") 14 | except FileNotFoundError: 15 | items = [] 16 | items.extend(sys.argv[1:]) 17 | save_to_json_file(items, "add_item.json") 18 | -------------------------------------------------------------------------------- /0x0B-python-input_output/8-class_to_json.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a Python class-to-JSON function.""" 3 | 4 | 5 | def class_to_json(obj): 6 | """Return the dictionary representation of a simple data structure.""" 7 | return obj.__dict__ 8 | -------------------------------------------------------------------------------- /0x0B-python-input_output/9-student.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a class Student.""" 3 | 4 | 5 | class Student: 6 | """Represent a student.""" 7 | 8 | def __init__(self, first_name, last_name, age): 9 | """Initialize a new Student. 10 | 11 | Args: 12 | first_name (str): The first name of the student. 13 | last_name (str): The last name of the student. 14 | age (int): The age of the student. 15 | """ 16 | self.first_name = first_name 17 | self.last_name = last_name 18 | self.age = age 19 | 20 | def to_json(self): 21 | """Get a dictionary representation of the Student.""" 22 | return self.__dict__ 23 | -------------------------------------------------------------------------------- /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 | number_of_lines = __import__('1-number_of_lines').number_of_lines 3 | 4 | filename = "my_file_0.txt" 5 | nb_lines = number_of_lines(filename) 6 | print("{} has {:d} lines".format(filename, nb_lines)) 7 | -------------------------------------------------------------------------------- /0x0B-python-input_output/tests/10-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/10-my_class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ My class module 3 | """ 4 | 5 | class MyClass: 6 | """ My class 7 | """ 8 | 9 | def __init__(self, name): 10 | self.name = name 11 | self.number = 0 12 | 13 | 14 | def __str__(self): 15 | return "[MyClass] {} - {:d}".format(self.name, self.number) 16 | -------------------------------------------------------------------------------- /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/11-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 | -------------------------------------------------------------------------------- /0x0B-python-input_output/tests/12-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/14-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 | read_lines = __import__('2-read_lines').read_lines 3 | 4 | print("1 line:") 5 | read_lines("my_file_0.txt", 1) 6 | print("--") 7 | print("3 lines:") 8 | read_lines("my_file_0.txt", 3) 9 | print("--") 10 | print("Full content:") 11 | read_lines("my_file_0.txt") 12 | -------------------------------------------------------------------------------- /0x0B-python-input_output/tests/3-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", "Holberton School is so cool!\n") 5 | print(nb_characters) 6 | -------------------------------------------------------------------------------- /0x0B-python-input_output/tests/4-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", "Holberton School is so cool!\n") 5 | print(nb_characters_added) 6 | -------------------------------------------------------------------------------- /0x0B-python-input_output/tests/5-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/6-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 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/models/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/underscoDe/alx-higher_level_programming/65dba7607ebd18cefaffda5df24b47de586864d3/0x0C-python-almost_a_circle/models/__init__.py -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/tests/test_models/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/underscoDe/alx-higher_level_programming/65dba7607ebd18cefaffda5df24b47de586864d3/0x0C-python-almost_a_circle/tests/test_models/__init__.py -------------------------------------------------------------------------------- /0x0D-SQL_introduction/0-list_databases.sql: -------------------------------------------------------------------------------- 1 | -- Lists all databases of your MySQL server 2 | SHOW DATABASES; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/1-create_database_if_missing.sql: -------------------------------------------------------------------------------- 1 | -- creates the database hbtn_0c_0 in your 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 your MySQL server. 2 | DROP DATABASE IF EXISTS `hbtn_0c_0`; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/3-list_tables.sql: -------------------------------------------------------------------------------- 1 | -- lists all the tables of a database in your MySQL server. 2 | SHOW TABLES; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/4-first_table.sql: -------------------------------------------------------------------------------- 1 | -- creates a table called first_table in the current database in your MySQL server. 2 | CREATE TABLE IF NOT EXISTS `first_table` (`id` INT, `name` VARCHAR(256)); 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/5-full_table.sql: -------------------------------------------------------------------------------- 1 | -- prints the full description of the table first_table 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 | FLUSH PRIVILEGES; 9 | -------------------------------------------------------------------------------- /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 IF NOT EXISTS hbtn_0d_2; 4 | CREATE USER IF NOT EXISTS 'user_0d_2'@'localhost' 5 | IDENTIFIED BY 'user_0d_2_pwd'; 6 | GRANT SELECT 7 | ON hbtn_0d_2.* 8 | TO 'user_0d_2'@'localhost'; 9 | FLUSH PRIVILEGES; 10 | -------------------------------------------------------------------------------- /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 | Usage: ./0-select_states.py 4 | 5 | 6 | """ 7 | 8 | import sys 9 | import MySQLdb 10 | 11 | if __name__ == "__main__": 12 | db = MySQLdb.connect(user=sys.argv[1], passwd=sys.argv[2], db=sys.argv[3]) 13 | c = db.cursor() 14 | c.execute("SELECT * FROM `states`") 15 | [print(state) for state in c.fetchall()] 16 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/1-filter_states.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Lists all states with a name starting with\ 3 | N from the database hbtn_0e_0_usa. 4 | Usage: ./1-filter_states.py \ 5 | \ 6 | 7 | """ 8 | 9 | import sys 10 | import MySQLdb 11 | 12 | if __name__ == "__main__": 13 | db = MySQLdb.connect( 14 | user=sys.argv[1], passwd=sys.argv[2], db=sys.argv[3] 15 | ) 16 | c = db.cursor() 17 | c.execute("SELECT * FROM `states` ORDER BY `id`") 18 | [print(state) for state in c.fetchall() if state[1][0] == "N"] 19 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/102-relationship_cities_states_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Lists all City objects from the database hbtn_0e_101_usa. 3 | Usage: ./102-relationship_cities_states_list.py / 4 | / 5 | 6 | """ 7 | 8 | import sys 9 | from sqlalchemy import create_engine 10 | from sqlalchemy.orm import sessionmaker 11 | from relationship_state import State 12 | from relationship_city import City 13 | 14 | if __name__ == "__main__": 15 | engine = create_engine("mysql+mysqldb://{}:{}@localhost/{}" 16 | .format(sys.argv[1], sys.argv[2], sys.argv[3]), 17 | pool_pre_ping=True) 18 | Session = sessionmaker(bind=engine) 19 | session = Session() 20 | 21 | for city in session.query(City).order_by(City.id): 22 | print("{}: {} -> {}".format(city.id, city.name, city.state.name)) 23 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/11-model_state_insert.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Adds the State object "Louisiana" to the database hbtn_0e_6_usa. 3 | Usage: ./11-model_state_insert.py / 4 | / 5 | 6 | """ 7 | 8 | import sys 9 | from sqlalchemy import create_engine 10 | from sqlalchemy.orm import sessionmaker 11 | from model_state import State 12 | 13 | if __name__ == "__main__": 14 | engine = create_engine("mysql+mysqldb://{}:{}@localhost/{}" 15 | .format(sys.argv[1], sys.argv[2], sys.argv[3]), 16 | pool_pre_ping=True) 17 | Session = sessionmaker(bind=engine) 18 | session = Session() 19 | 20 | louisiana = State(name="Louisiana") 21 | session.add(louisiana) 22 | session.commit() 23 | print(louisiana.id) 24 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/12-model_state_update_id_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Changes the name of the State object with id = 2 to 3 | New Mexico in the database hbtn_0e_6_usa. 4 | Usage: ./12-model_state_update_id_2.py / 5 | / 6 | 7 | """ 8 | 9 | import sys 10 | from sqlalchemy import create_engine 11 | from sqlalchemy.orm import sessionmaker 12 | from model_state import State 13 | 14 | if __name__ == "__main__": 15 | engine = create_engine("mysql+mysqldb://{}:{}@localhost/{}" 16 | .format(sys.argv[1], sys.argv[2], sys.argv[3]), 17 | pool_pre_ping=True) 18 | Session = sessionmaker(bind=engine) 19 | session = Session() 20 | 21 | state = session.query(State).filter_by(id=2).first() 22 | state.name = "New Mexico" 23 | session.commit() 24 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/13-model_state_delete_a.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Deletes all State objects with a name containing 3 | the letter a from the database hbtn_0e_6_usa. 4 | Usage: ./13-model_state_delete_a.py / 5 | / 6 | 7 | """ 8 | 9 | 10 | import sys 11 | from sqlalchemy import create_engine 12 | from sqlalchemy.orm import sessionmaker 13 | from model_state import State 14 | 15 | if __name__ == "__main__": 16 | engine = create_engine("mysql+mysqldb://{}:{}@localhost/{}".format( 17 | sys.argv[1], sys.argv[2], sys.argv[3]), pool_pre_ping=True) 18 | session_maker = sessionmaker(bind=engine) 19 | session = session_maker() 20 | 21 | states = session.query(State).filter(State.name.like('%a%')).all() 22 | for state in states: 23 | session.delete(state) 24 | 25 | session.commit() 26 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/2-my_filter_states.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Displays all values in the states table of the database hbtn_0e_0_usa 3 | whose name matches that supplied as argument. 4 | Usage: ./2-my_filter_states.py \ 5 | \ 6 | \ 7 | 8 | """ 9 | 10 | import sys 11 | import MySQLdb 12 | 13 | if __name__ == "__main__": 14 | db = MySQLdb.connect(user=sys.argv[1], passwd=sys.argv[2], db=sys.argv[3]) 15 | c = db.cursor() 16 | c.execute("SELECT * \ 17 | FROM `states` \ 18 | WHERE BINARY `name` = '{}'".format(sys.argv[4])) 19 | [print(state) for state in c.fetchall()] 20 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/3-my_safe_filter_states.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Displays all values in the states table of the database hbtn_0e_0_usa 3 | whose name matches that supplied as argument. 4 | Safe from SQL injections. 5 | Usage: ./3-my_safe_filter_states.py \ 6 | \ 7 | \ 8 | 9 | """ 10 | 11 | import sys 12 | import MySQLdb 13 | 14 | if __name__ == "__main__": 15 | db = MySQLdb.connect(user=sys.argv[1], passwd=sys.argv[2], db=sys.argv[3]) 16 | c = db.cursor() 17 | c.execute("SELECT * FROM `states`") 18 | [print(state) for state in c.fetchall() if state[1] == sys.argv[4]] 19 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/4-cities_by_state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Lists all cities of the database hbtn_0e_4_usa, ordered by city id. 3 | Usage: ./4-cities_by_state.py \ 4 | \ 5 | 6 | """ 7 | 8 | import sys 9 | import MySQLdb 10 | 11 | if __name__ == "__main__": 12 | db = MySQLdb.connect(user=sys.argv[1], passwd=sys.argv[2], db=sys.argv[3]) 13 | c = db.cursor() 14 | c.execute("SELECT `c`.`id`, `c`.`name`, `s`.`name` \ 15 | FROM `cities` as `c` \ 16 | INNER JOIN `states` as `s` \ 17 | ON `c`.`state_id` = `s`.`id` \ 18 | ORDER BY `c`.`id`") 19 | [print(city) for city in c.fetchall()] 20 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/5-filter_cities.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Displays all cities of a given state from the 3 | states table of the database hbtn_0e_4_usa. 4 | Safe from SQL injections. 5 | Usage: ./5-filter_cities.py \ 6 | \ 7 | \ 8 | 9 | """ 10 | 11 | import sys 12 | import MySQLdb 13 | 14 | if __name__ == "__main__": 15 | db = MySQLdb.connect(user=sys.argv[1], passwd=sys.argv[2], db=sys.argv[3]) 16 | c = db.cursor() 17 | c.execute("SELECT * FROM `cities` as `c` \ 18 | INNER JOIN `states` as `s` \ 19 | ON `c`.`state_id` = `s`.`id` \ 20 | ORDER BY `c`.`id`") 21 | print(", ".join([ct[2] for ct in c.fetchall() if ct[4] == sys.argv[4]])) 22 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/7-model_state_fetch_all.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Lists all State objects from the database hbtn_0e_6_usa. 3 | Usage: ./7-model_state_fetch_all.py / 4 | / 5 | 6 | """ 7 | 8 | import sys 9 | from sqlalchemy import create_engine 10 | from sqlalchemy.orm import sessionmaker 11 | from model_state import State 12 | 13 | if __name__ == "__main__": 14 | engine = create_engine("mysql+mysqldb://{}:{}@localhost/{}" 15 | .format(sys.argv[1], sys.argv[2], sys.argv[3]), 16 | pool_pre_ping=True) 17 | Session = sessionmaker(bind=engine) 18 | session = Session() 19 | 20 | for state in session.query(State).order_by(State.id): 21 | print("{}: {}".format(state.id, state.name)) 22 | -------------------------------------------------------------------------------- /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 | Usage: ./8-model_state_fetch_first.py / 4 | / 5 | 6 | """ 7 | 8 | import sys 9 | from sqlalchemy import create_engine 10 | from sqlalchemy.orm import sessionmaker 11 | from model_state import State 12 | 13 | if __name__ == "__main__": 14 | engine = create_engine("mysql+mysqldb://{}:{}@localhost/{}" 15 | .format(sys.argv[1], sys.argv[2], sys.argv[3]), 16 | pool_pre_ping=True) 17 | Session = sessionmaker(bind=engine) 18 | session = Session() 19 | 20 | state = session.query(State).order_by(State.id).first() 21 | if state is None: 22 | print("Nothing") 23 | else: 24 | print("{}: {}".format(state.id, state.name)) 25 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/9-model_state_filter_a.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Lists all State objects that contain the letter a 3 | from the database hbtn_0e_6_usa. 4 | Usage: ./9-model_state_filter_a.py / 5 | / 6 | 7 | """ 8 | 9 | import sys 10 | from sqlalchemy import create_engine 11 | from sqlalchemy.orm import sessionmaker 12 | from model_state import State 13 | 14 | if __name__ == "__main__": 15 | engine = create_engine("mysql+mysqldb://{}:{}@localhost/{}" 16 | .format(sys.argv[1], sys.argv[2], sys.argv[3]), 17 | pool_pre_ping=True) 18 | Session = sessionmaker(bind=engine) 19 | session = Session() 20 | 21 | for state in session.query(State).order_by(State.id): 22 | if "a" in state.name: 23 | print("{}: {}".format(state.id, state.name)) 24 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/model_city.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a City model. 3 | Inherits from SQLAlchemy Base and links to the MySQL table cities. 4 | """ 5 | 6 | from sqlalchemy import Column, ForeignKey, Integer, String 7 | from sqlalchemy.ext.declarative import declarative_base 8 | 9 | Base = declarative_base() 10 | 11 | 12 | class City(Base): 13 | """Represents a city for a MySQL database. 14 | 15 | Attributes: 16 | id (str): The city's id. 17 | name (sqlalchemy.Integer): The city's name. 18 | state_id (sqlalchemy.String): The city's state id. 19 | """ 20 | __tablename__ = "cities" 21 | id = Column(Integer, primary_key=True) 22 | name = Column(String(128), nullable=False) 23 | state_id = Column(Integer, ForeignKey("states.id"), nullable=False) 24 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/model_state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a State model. 3 | Inherits from SQLAlchemy Base and links to the MySQL table states. 4 | """ 5 | 6 | from sqlalchemy import Column, Integer, String 7 | from sqlalchemy.ext.declarative import declarative_base 8 | 9 | Base = declarative_base() 10 | 11 | 12 | class State(Base): 13 | """Represents a state for a MySQL database. 14 | 15 | __tablename__ (str): The name of the MySQL table to store States. 16 | id (sqlalchemy.Integer): The state's id. 17 | name (sqlalchemy.String): The state's name. 18 | """ 19 | __tablename__ = "states" 20 | id = Column(Integer, primary_key=True) 21 | name = Column(String(128), nullable=False) 22 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/relationship_city.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a City model. 3 | Inherits from SQLAlchemy Base and links to the MySQL table cities. 4 | """ 5 | 6 | from sqlalchemy import Column, ForeignKey, Integer, String 7 | from sqlalchemy.ext.declarative import declarative_base 8 | 9 | Base = declarative_base() 10 | 11 | 12 | class City(Base): 13 | """Represents a city for a MySQL database. 14 | 15 | Attributes: 16 | id (sqlalchemy.Column): The city's id. 17 | name (sqlalchemy.Column): The city's name. 18 | state_id (sqlalchemy.Column): The city's state id. 19 | """ 20 | __tablename__ = "cities" 21 | id = Column(Integer, primary_key=True) 22 | name = Column(String(128), nullable=False) 23 | state_id = Column(Integer, ForeignKey("states.id"), nullable=False) 24 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/relationship_state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a State model. 3 | Inherits from SQLAlchemy Base and links to the MySQL table states. 4 | """ 5 | 6 | from sqlalchemy import Column, Integer, String 7 | from sqlalchemy.orm import relationship 8 | from sqlalchemy.ext.declarative import declarative_base 9 | from relationship_city import Base, City 10 | 11 | 12 | class State(Base): 13 | """Represents a state for a MySQL database. 14 | 15 | Attributes: 16 | __tablename__ (str): The name of the MySQL table to store States. 17 | id (sqlalchemy.Integer): The state's id. 18 | name (sqlalchemy.String): The state's name. 19 | cities (sqlalchemy.orm.relationship): The State-City relationship. 20 | """ 21 | __tablename__ = "states" 22 | id = Column(Integer, primary_key=True) 23 | name = Column(String(128), nullable=False) 24 | 25 | cities = relationship("City", backref="state", cascade="all, delete") 26 | -------------------------------------------------------------------------------- /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/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 | # sends a request an URL, and displays the size of the body of the response 3 | curl -s "$1" | wc -c 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/1-body.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # sends a GET request to an 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, and displays only the status code of the response. 3 | curl -s -o /dev/null -w "%{http_code}" "$1" 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/101-post_json.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # sends a JSON POST request to a URL, and displays the body of the response. 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 -s -X PUT -d "user_id=98" -H "Origin: You got me!" -L 0.0.0.0:5000/catch_me 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/2-delete.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # sends a DELETE request to an URL and displays the body of the response 3 | curl -sX DELETE "$1" 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/3-methods.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # displays all HTTP methods the server will accept. 3 | curl -sI "$1" | grep "Allow" | cut -d " " -f 2- 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/4-header.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # sends a GET request to the URL, and displays the body of the response 3 | curl -sH "X-School-User-Id: 98" "$1" 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/5-post_params.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # sends a POST request to the passed URL, and displays the body of the response 3 | curl -s -X POST -d "email=test@gmail.com&subject=I will always be here for PLD" "$1" 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/6-peak.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines a peak-finding algorithm.""" 3 | 4 | 5 | def find_peak(list_of_integers): 6 | """Return a peak in a list of unsorted integers.""" 7 | if list_of_integers == []: 8 | return None 9 | 10 | size = len(list_of_integers) 11 | if size == 1: 12 | return list_of_integers[0] 13 | elif size == 2: 14 | return max(list_of_integers) 15 | 16 | mid = int(size / 2) 17 | peak = list_of_integers[mid] 18 | if peak > list_of_integers[mid - 1] and peak > list_of_integers[mid + 1]: 19 | return peak 20 | elif peak < list_of_integers[mid - 1]: 21 | return find_peak(list_of_integers[:mid]) 22 | else: 23 | return find_peak(list_of_integers[mid + 1:]) 24 | -------------------------------------------------------------------------------- /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 | """Fetches https://alx-intranet.hbtn.io/status.""" 3 | import urllib.request 4 | 5 | 6 | if __name__ == "__main__": 7 | request = urllib.request.Request("https://alx-intranet.hbtn.io/status") 8 | with urllib.request.urlopen(request) as response: 9 | body = response.read() 10 | print("Body response:") 11 | print("\t- type: {}".format(type(body))) 12 | print("\t- content: {}".format(body)) 13 | print("\t- utf8 content: {}".format(body.decode("utf-8"))) 14 | -------------------------------------------------------------------------------- /0x11-python-network_1/1-hbtn_header.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Displays the X-Request-Id header variable of a request to a given URL. 3 | 4 | Usage: ./1-hbtn_header.py 5 | """ 6 | import sys 7 | import urllib.request 8 | 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 | """Uses the GitHub API to display a GitHub ID based on given credentials. 3 | 4 | Usage: ./10-my_github.py 5 | - Uses Basic Authentication to access the ID. 6 | """ 7 | import sys 8 | import requests 9 | from requests.auth import HTTPBasicAuth 10 | 11 | 12 | if __name__ == "__main__": 13 | auth = HTTPBasicAuth(sys.argv[1], sys.argv[2]) 14 | r = requests.get("https://api.github.com/user", auth=auth) 15 | print(r.json().get("id")) 16 | -------------------------------------------------------------------------------- /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 | Usage: ./100-github_commits.py 5 | """ 6 | import sys 7 | import requests 8 | 9 | 10 | if __name__ == "__main__": 11 | url = "https://api.github.com/repos/{}/{}/commits".format( 12 | sys.argv[2], sys.argv[1]) 13 | 14 | r = requests.get(url) 15 | commits = r.json() 16 | try: 17 | for i in range(10): 18 | print("{}: {}".format( 19 | commits[i].get("sha"), 20 | commits[i].get("commit").get("author").get("name"))) 21 | except IndexError: 22 | pass 23 | -------------------------------------------------------------------------------- /0x11-python-network_1/2-post_email.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Sends a POST request to a given URL with a given email. 3 | 4 | Usage: ./2-post_email.py 5 | - Displays the body of the response. 6 | """ 7 | import sys 8 | import urllib.parse 9 | import urllib.request 10 | 11 | 12 | if __name__ == "__main__": 13 | url = sys.argv[1] 14 | value = {"email": sys.argv[2]} 15 | data = urllib.parse.urlencode(value).encode("ascii") 16 | 17 | request = urllib.request.Request(url, data) 18 | with urllib.request.urlopen(request) as response: 19 | print(response.read().decode("utf-8")) 20 | -------------------------------------------------------------------------------- /0x11-python-network_1/3-error_code.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Sends a request to a given URL and displays the response body. 3 | 4 | Usage: ./3-error_code.py 5 | - Handles HTTP errors. 6 | """ 7 | import sys 8 | import urllib.error 9 | import urllib.request 10 | 11 | 12 | if __name__ == "__main__": 13 | url = sys.argv[1] 14 | 15 | request = urllib.request.Request(url) 16 | try: 17 | with urllib.request.urlopen(request) as response: 18 | print(response.read().decode("ascii")) 19 | except urllib.error.HTTPError as e: 20 | print("Error code: {}".format(e.code)) 21 | -------------------------------------------------------------------------------- /0x11-python-network_1/4-hbtn_status.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Fetches https://alx-intranet.hbtn.io/status.""" 3 | import requests 4 | 5 | 6 | if __name__ == "__main__": 7 | r = requests.get("https://alx-intranet.hbtn.io/status") 8 | print("Body response:") 9 | print("\t- type: {}".format(type(r.text))) 10 | print("\t- content: {}".format(r.text)) 11 | -------------------------------------------------------------------------------- /0x11-python-network_1/5-hbtn_header.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Displays the X-Request-Id header variable of a request to a given URL. 3 | 4 | Usage: ./5-hbtn_header.py 5 | """ 6 | import sys 7 | import requests 8 | 9 | 10 | if __name__ == "__main__": 11 | url = sys.argv[1] 12 | 13 | r = requests.get(url) 14 | print(r.headers.get("X-Request-Id")) 15 | -------------------------------------------------------------------------------- /0x11-python-network_1/6-post_email.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Sends a POST request to a given URL with a given email. 3 | 4 | Usage: ./6-post_email.py 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 | """Sends a request to a given URL and displays the response body. 3 | 4 | Usage: ./7-error_code.py 5 | - Handles HTTP errors. 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 | """Sends a POST request to http://0.0.0.0:5000/search_user with a given letter. 3 | 4 | Usage: ./8-json_api.py 5 | - The letter is sent as the value of the variable `q`. 6 | - If no letter is provided, sends `q=""`. 7 | """ 8 | import sys 9 | import requests 10 | 11 | 12 | if __name__ == "__main__": 13 | letter = "" if len(sys.argv) == 1 else sys.argv[1] 14 | payload = {"q": letter} 15 | 16 | r = requests.post("http://0.0.0.0:5000/search_user", data=payload) 17 | try: 18 | response = r.json() 19 | if response == {}: 20 | print("No result") 21 | else: 22 | print("[{}] {}".format(response.get("id"), response.get("name"))) 23 | except ValueError: 24 | print("Not a valid JSON") 25 | -------------------------------------------------------------------------------- /0x11-python-network_1/9-starwars.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Sends a search request for a given string to the Star Wars API. 3 | 4 | Usage: ./9-starwars.py 5 | - The search request is sent to the Star Wars API search people endpoint. 6 | """ 7 | import sys 8 | import requests 9 | 10 | 11 | if __name__ == "__main__": 12 | url = "https://swapi.co/api/people" 13 | params = {"search": sys.argv[1]} 14 | results = requests.get(url, params=params).json() 15 | 16 | print("Number of results: {}".format(results.get("count"))) 17 | [print(r.get("name")) for r in results.get("results")] 18 | -------------------------------------------------------------------------------- /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\nPython is cool\nJavaScript is amazing'); 3 | -------------------------------------------------------------------------------- /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 | 8 | myObject.incr = function () { 9 | this.value++; 10 | }; 11 | 12 | myObject.incr(); 13 | console.log(myObject); 14 | myObject.incr(); 15 | console.log(myObject); 16 | myObject.incr(); 17 | console.log(myObject); 18 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/11-second_biggest.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | if (process.argv.length <= 3) { 3 | console.log(0); 4 | } else { 5 | const args = process.argv.map(Number) 6 | .slice(2, process.argv.length) 7 | .sort((a, b) => a - b); 8 | console.log(args[args.length - 2]); 9 | } 10 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/12-object.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const myObject = { 3 | type: 'object', 4 | value: 12 5 | }; 6 | console.log(myObject); 7 | myObject.value = 89; 8 | console.log(myObject); 9 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/13-add.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | exports.add = (a, b) => a + b; 3 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/2-arguments.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const count = process.argv.length; 3 | console.log(count === 2 ? 'No argument' : count === 3 ? 'Argument found' : 'Arguments found'); 4 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/3-value_argument.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | console.log(typeof process.argv[2] === 'undefined' ? 'No argument' : process.argv[2]); 3 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/4-concat.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | console.log(`${process.argv[2]} is ${process.argv[3]}`); 3 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/5-to_integer.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const num = Math.floor(Number(process.argv[2])); 3 | console.log(isNaN(num) ? 'Not a number' : `My number: ${num}`); 4 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/6-multi_languages_loop.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | for (const line of ['C is fun', 'Python is cool', 'JavaScript is amazing']) { 3 | console.log(line); 4 | } 5 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/7-multi_c.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const x = Math.floor(Number(process.argv[2])); 3 | if (isNaN(x)) { 4 | console.log('Missing number of occurrences'); 5 | } else { 6 | for (let i = 0; i < x; i++) { 7 | console.log('C is fun'); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/8-square.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const size = Math.floor(Number(process.argv[2])); 3 | if (isNaN(size)) { 4 | console.log('Missing size'); 5 | } else { 6 | for (let r = 0; r < size; r++) { 7 | let row = ''; 8 | for (let c = 0; c < size; c++) row += 'X'; 9 | console.log(row); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/9-add.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | function add (a, b) { 3 | return a + b; 4 | } 5 | 6 | console.log(add(Number(process.argv[2]), Number(process.argv[3]))); 7 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/tests/100-main.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | myVar = 89; 3 | require('../100-let_me_const') 4 | console.log(myVar); 5 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/tests/101-main.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const callMeMoby = require('../101-call_me_moby').callMeMoby; 3 | callMeMoby(3, function () { 4 | console.log('C is fun'); 5 | }); 6 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/tests/102-main.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const addMeMaybe = require('../102-add_me_maybe').addMeMaybe; 3 | addMeMaybe(4, function (nb) { 4 | console.log('New value: ' + nb); 5 | }); 6 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/tests/13-main.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const add = require('../13-add').add; 3 | console.log(add(3, 5)); 4 | -------------------------------------------------------------------------------- /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.js').dict; 3 | const newDict = {}; 4 | for (const key in dict) { 5 | if (newDict[dict[key]] === undefined) { 6 | newDict[dict[key]] = [key]; 7 | } else { 8 | newDict[dict[key]].push(key); 9 | } 10 | } 11 | console.log(newDict); 12 | -------------------------------------------------------------------------------- /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(['Holberton', 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('Holberton'); 6 | logMe('School'); 7 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/0-readme.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const fs = require('fs'); 3 | fs.readFile(process.argv[2], 'utf8', function (error, content) { 4 | console.log(error || content); 5 | }); 6 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/1-writeme.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const fs = require('fs'); 3 | fs.writeFile(process.argv[2], process.argv[3], error => { 4 | if (error) console.log(error); 5 | }); 6 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/100-starwars_characters.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 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 | characters.forEach((character) => { 8 | request(character, function (error, response, body) { 9 | if (!error) { 10 | console.log(JSON.parse(body).name); 11 | } 12 | }); 13 | }); 14 | } 15 | }); 16 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/101-starwars_characters.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const request = require('request'); 3 | const url = 'https://swapi-api.hbtn.io/api/films/' + process.argv[2]; 4 | request(url, function (error, response, body) { 5 | if (!error) { 6 | const characters = JSON.parse(body).characters; 7 | printCharacters(characters, 0); 8 | } 9 | }); 10 | 11 | function printCharacters (characters, index) { 12 | request(characters[index], function (error, response, body) { 13 | if (!error) { 14 | console.log(JSON.parse(body).name); 15 | if (index + 1 < characters.length) { 16 | printCharacters(characters, index + 1); 17 | } 18 | } 19 | }); 20 | } 21 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/2-statuscode.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const request = require('request'); 3 | request.get(process.argv[2]).on('response', function (response) { 4 | console.log(`code: ${response.statusCode}`); 5 | }); 6 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/3-starwars_title.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const request = require('request'); 3 | const url = 'https://swapi-api.hbtn.io/api/films/' + process.argv[2]; 4 | request(url, function (error, response, body) { 5 | console.log(error || JSON.parse(body).title); 6 | }); 7 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/4-starwars_count.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const request = require('request'); 3 | request(process.argv[2], function (error, response, body) { 4 | if (!error) { 5 | const results = JSON.parse(body).results; 6 | console.log(results.reduce((count, movie) => { 7 | return movie.characters.find((character) => character.endsWith('/18/')) 8 | ? count + 1 9 | : count; 10 | }, 0)); 11 | } 12 | }); 13 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/5-request_store.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const fs = require('fs'); 3 | const request = require('request'); 4 | request(process.argv[2]).pipe(fs.createWriteStream(process.argv[3])); 5 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/6-completed_tasks.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const request = require('request'); 3 | request(process.argv[2], function (error, response, body) { 4 | if (!error) { 5 | const todos = JSON.parse(body); 6 | let completed = {}; 7 | todos.forEach((todo) => { 8 | if (todo.completed && completed[todo.userId] === undefined) { 9 | completed[todo.userId] = 1; 10 | } else if (todo.completed) { 11 | completed[todo.userId] += 1; 12 | } 13 | }); 14 | console.log(completed); 15 | } 16 | }); 17 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/0-script.js: -------------------------------------------------------------------------------- 1 | document.querySelector('HEADER').style.color = '#FF0000'; 2 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/1-script.js: -------------------------------------------------------------------------------- 1 | $('HEADER').css('color', '#FF0000'); 2 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/100-script.js: -------------------------------------------------------------------------------- 1 | document.addEventListener('DOMContentLoaded', function () { 2 | document.querySelector('HEADER').style.color = '#FF0000'; 3 | }); 4 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/101-script.js: -------------------------------------------------------------------------------- 1 | $('document').ready(function () { 2 | $('DIV#add_item').click(function () { 3 | $('UL.my_list').append('
  • Item
  • '); 4 | }); 5 | $('DIV#remove_item').click(function () { 6 | $('UL.my_list li:last').remove(); 7 | }); 8 | $('DIV#clear_list').click(function () { 9 | $('UL.my_list').empty(); 10 | }); 11 | }); 12 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/102-script.js: -------------------------------------------------------------------------------- 1 | $('document').ready(function () { 2 | const url = 'https://www.fourtonfish.com/hellosalut/?'; 3 | $('INPUT#btn_translate').click(function () { 4 | $.get(url + $.param({ lang: $('INPUT#language_code').val() }), function (data) { 5 | $('DIV#hello').html(data.hello); 6 | }); 7 | }); 8 | }); 9 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/103-script.js: -------------------------------------------------------------------------------- 1 | $('document').ready(function () { 2 | $('INPUT#btn_translate').click(translate); 3 | $('INPUT#language_code').focus(function () { 4 | $(this).keydown(function (e) { 5 | if (e.keyCode === 13) { 6 | translate(); 7 | } 8 | }); 9 | }); 10 | }); 11 | 12 | function translate () { 13 | const url = 'https://www.fourtonfish.com/hellosalut/?'; 14 | $.get(url + $.param({ lang: $('INPUT#language_code').val() }), function (data) { 15 | $('DIV#hello').html(data.hello); 16 | }); 17 | } 18 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/2-script.js: -------------------------------------------------------------------------------- 1 | $('DIV#red_header').click(function () { 2 | $('HEADER').css('color', '#FF0000'); 3 | }); 4 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/3-script.js: -------------------------------------------------------------------------------- 1 | $('DIV#red_header').click(function () { 2 | $('HEADER').addClass('red'); 3 | }); 4 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/4-script.js: -------------------------------------------------------------------------------- 1 | $('DIV#toggle_header').click(function () { 2 | $('HEADER').toggleClass('green red'); 3 | }); 4 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/5-script.js: -------------------------------------------------------------------------------- 1 | $('DIV#add_item').click(function () { 2 | $('UL.my_list').append('
  • Item
  • '); 3 | }); 4 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/6-script.js: -------------------------------------------------------------------------------- 1 | $('DIV#update_header').click(function () { 2 | $('HEADER').text('New Header!!!'); 3 | }); 4 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/7-script.js: -------------------------------------------------------------------------------- 1 | $.get('https://swapi-api.hbtn.io/api/people/5/?format=json', function (data) { 2 | $('DIV#character').text(data.name); 3 | }); 4 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/8-script.js: -------------------------------------------------------------------------------- 1 | $.get('https://swapi-api.hbtn.io/api/films/?format=json', function (data) { 2 | $('UL#list_movies').append(...data.results.map(movie => `
  • ${movie.title}
  • `)); 3 | }); 4 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/9-script.js: -------------------------------------------------------------------------------- 1 | $('document').ready(function () { 2 | $.get('https://fourtonfish.com/hellosalut/?lang=fr', function (data) { 3 | $('DIV#hello').text(data.hello); 4 | }); 5 | }); 6 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/tests/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/tests/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/tests/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/tests/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/tests/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/tests/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/tests/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/tests/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/tests/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/tests/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/tests/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/tests/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/tests/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/tests/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 | --------------------------------------------------------------------------------