├── .gitignore ├── 0x00-python-hello_world ├── 0-run ├── 1-run_inline ├── 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 └── main.py ├── 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 ├── 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 ├── 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 └── trythis.py ├── 0x03-python-data_structures ├── 0-print_list_integer.py ├── 1-element_at.py ├── 10-divisible_by_2.py ├── 11-delete_at.py ├── 12-switch.py ├── 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 ├── 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 ├── 11-mutiply_list_map.py ├── 2-uniq_add.py ├── 3-common_elements.py ├── 4-only_diff_elements.py ├── 5-number_keys.py ├── 6-print_sorted_dictionary.py ├── 7-update_dictionary.py ├── 8-simple_delete.py ├── 9-multiply_by_2.py └── README.md ├── 0x05-python-exceptions ├── 0-safe_print_list.py ├── 1-safe_print_integer.py ├── 100-safe_print_integer_err.py ├── 101-safe_function.py ├── 102-magic_calculation.py ├── 2-safe_print_list_integers.py ├── 3-safe_print_division.py ├── 4-list_division.py ├── 5-raise_exception.py ├── 6-raise_exception_msg.py └── README.md ├── 0x06-python-test_driven_development ├── 0-add_integer.py ├── 1-mul.py ├── 2-matrix_divided.py ├── 3-say_my_name.py ├── 4-print_square.py ├── README.md └── tests │ ├── 0-add_integer.txt │ ├── 1-mul.txt │ ├── 2-matrix_divided.txt │ ├── 3-say_my_name.txt │ └── 4-print_square.txt ├── 0x07-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 │ ├── 102-square.txt │ └── 4-square.txt ├── 0x08-python-more_classes ├── 0-rectangle.py ├── 1-rectangle.py ├── 2-rectangle.py ├── 3-rectangle.py ├── 4-rectangle.py ├── 5-rectangle.py ├── 6-rectangle.py ├── 7-rectangle.py ├── 8-rectangle.py ├── 9-rectangle.py └── README.md ├── 0x09-python-everything_is_object ├── 0-answer.txt ├── 1-answer.txt ├── 10-answer.txt ├── 100-magic_string.py ├── 103-line1.txt ├── 103-line2.txt ├── 104-line1.txt ├── 104-line2.txt ├── 104-line3.txt ├── 104-line4.txt ├── 104-line5.txt ├── 11-answer.txt ├── 12-answer.txt ├── 13-answer.txt ├── 14-answer.txt ├── 15-answer.txt ├── 16-answer.txt ├── 17-answer.txt ├── 18-answer.txt ├── 19-copy_list.py ├── 2-answer.txt ├── 20-answer.txt ├── 21-answer.txt ├── 22-answer.txt ├── 23-answer.txt ├── 24-answer.txt ├── 25-answer.txt ├── 26-answer.txt ├── 27-answer.txt ├── 28-answer.txt ├── 3-answer.txt ├── 4-answer.txt ├── 5-answer.txt ├── 6-answer.txt ├── 7-answer.txt ├── 8-answer.txt ├── 9-answer.txt └── README.md ├── 0x0A-python-inheritance ├── 0-lookup.py ├── 1-my_list.py ├── 10-square.py ├── 100-my_int.py ├── 101-add_attribute.py ├── 11-square.py ├── 2-is_same_class.py ├── 3-is_kind_of_class.py ├── 4-inherits_from.py ├── 5-base_geometry.py ├── 6-base_geometry.py ├── 7-base_geometry.py ├── 8-rectangle.py ├── 9-rectangle.py ├── README.md └── tests │ ├── 1-my_list.txt │ └── 7-base_geometry.txt ├── 0x0B-python-input_output ├── 0-read_file.py ├── 1-number_of_lines.py ├── 2-read_lines.py ├── 3-write_file.py ├── 4-append_write.py ├── 5-to_json_string.py ├── 6-from_json_string.py ├── 7-save_to_json_file.py ├── 8-load_from_json_file.py ├── 9-add_item.py └── README.md ├── 0x0C-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 ├── 0x0D-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 ├── 0x0E-python-object_relational_mapping ├── 0-select_states.py ├── 0-select_states.sql ├── 1-filter_states.py ├── 10-model_state_my_get.py ├── 11-model_state_insert.py ├── 12-model_state_update_id_2.py ├── 13-model_state_delete_a.py ├── 14-model_city_fetch_by_state.py ├── 14-model_city_fetch_by_state.sql ├── 2-my_filter_states.py ├── 3-my_safe_filter_states.py ├── 4-cities_by_state.py ├── 4-cities_by_state.sql ├── 5-filter_cities.py ├── 6-model_state.py ├── 6-model_state.sql ├── 7-model_state_fetch_all.py ├── 7-model_state_fetch_all.sql ├── 8-model_state_fetch_first.py ├── 9-model_state_filter_a.py ├── README.md ├── model_city.py └── model_state.py ├── 0x0F-python-network_0 ├── 0-url_hostname ├── 1-url_protocol ├── 10-url_query_string ├── 100-status_code.sh ├── 11-url_query_string ├── 12-url_query_string ├── 13-http_verb ├── 14-http_verb ├── 15-http_verb ├── 16-http_status_code ├── 17-http_status_code ├── 18-http_status_code ├── 19-http_status_code ├── 2-url_port ├── 20-http_header ├── 21-http_header ├── 22-http_header ├── 23-http_header ├── 24-http_header ├── 25-http_header ├── 26-http_header ├── 27-http_header ├── 28-http_header ├── 29-curl_http_method ├── 3-url_port ├── 30-curl_301 ├── 31-curl_header ├── 32-curl_body_parameters ├── 33-curl_cookie ├── 34-curl_no_progress ├── 35-curl_request_body ├── 36-body_size.sh ├── 37-body.sh ├── 38-delete.sh ├── 39-methods.sh ├── 4-url_port ├── 40-header.sh ├── 41-post_params.sh ├── 5-url_subdomain ├── 6-url_subdomain ├── 7-url_path ├── 8-url_path ├── 9-url_path └── README.md ├── 0x10-python-network_1 ├── 0-hbtn_status.py ├── 1-hbtn_header.py ├── 10-my_github.py ├── 101-starwars.py ├── 102-starwars.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 ├── 0x11-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 ├── 0x12-javascript-web_scraping ├── 0-rectangle.js ├── 1-rectangle.js ├── 10-starwars_title.js ├── 100-data.js ├── 100-map.js ├── 101-data.js ├── 101-sorted.js ├── 102-concat.js ├── 11-starwars_count.js ├── 12-request_store.js ├── 13-completed_tasks.js ├── 2-rectangle.js ├── 3-rectangle.js ├── 4-rectangle.js ├── 5-square.js ├── 6-square.js ├── 7-readme.js ├── 8-writeme.js ├── 9-statuscode.js └── README.md └── 0x13-javascript-web_jquery ├── 0-tag_count.txt ├── 1-tag_count.txt ├── 10-selector.txt ├── 100-script.js ├── 101-script.js ├── 102-script.js ├── 103-script.js ├── 11-selector.txt ├── 12-selector.txt ├── 13-selector.txt ├── 14-script.js ├── 15-script.js ├── 16-script.js ├── 17-script.js ├── 18-script.js ├── 19-script.js ├── 2-tag_count.txt ├── 20-script.js ├── 21-script.js ├── 22-script.js ├── 23-script.js ├── 3-selector.txt ├── 4-selector.txt ├── 5-selector.txt ├── 6-selector.txt ├── 7-selector.txt ├── 8-selector.txt ├── 9-selector.txt └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | __pycache__ 3 | *main* 4 | io*.txt -------------------------------------------------------------------------------- /0x00-python-hello_world/0-run: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | python $PYFILE 3 | -------------------------------------------------------------------------------- /0x00-python-hello_world/1-run_inline: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | python3 -c "$PYCODE" 3 | -------------------------------------------------------------------------------- /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 | exit(1) 5 | -------------------------------------------------------------------------------- /0x00-python-hello_world/101-compile: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | python3 -m py_compile $PYFILE; mv ./__pycache__/*.pyc "${PYFILE}c" 3 | -------------------------------------------------------------------------------- /0x00-python-hello_world/102-magic_calculation.py: -------------------------------------------------------------------------------- 1 | def magic_calculation(a, b): 2 | return ( 3 | 98 + (a ** b)) 4 | -------------------------------------------------------------------------------- /0x00-python-hello_world/2-print.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | print("\"Programming is like building a multilingual puzzle") 3 | -------------------------------------------------------------------------------- /0x00-python-hello_world/3-print_number.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | number = 98 3 | print("{: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("{}{}{}\n{}".format(str, str, str, str[0:9])) 4 | -------------------------------------------------------------------------------- /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[0: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("{}".format(str)) 6 | -------------------------------------------------------------------------------- /0x00-python-hello_world/9-easter_egg.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import this 3 | -------------------------------------------------------------------------------- /0x00-python-hello_world/README.md: -------------------------------------------------------------------------------- 1 | # 0x00. Python - Hello, World -------------------------------------------------------------------------------- /0x00-python-hello_world/main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | print("Holberton School") 3 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/0-positive_or_negative.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import random 3 | number = random.randint(-10, 10) 4 | if number < 0: 5 | print("{:d} is negative".format(number)) 6 | elif number > 0: 7 | print("{:d} is positive".format(number)) 8 | else: 9 | print("0 is zero") 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 | ldigit = number % 10 if number > 0 else int(repr(number)[-1]) * -1 5 | if (ldigit > 5): 6 | print("Last digit of {:d} is {:d} and is greater than 5" 7 | .format(number, ldigit)) 8 | elif (ldigit == 0): 9 | print("Last digit of {:d} is {:d} and is 0" 10 | .format(number, ldigit)) 11 | else: 12 | print("Last digit of {:d} is {:d} and is less than 6 and not 0" 13 | .format(number, ldigit)) 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 | for i in 'zYxWvUtSrQpOnMlKjIhGfEdCbA': 3 | print("{}".format(i), end="") 4 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/101-remove_char_at.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def remove_char_at(str, n): 3 | if (n >= 0): 4 | return str[:n] + str[n+1:] 5 | return str 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 i in range(1, 101): 4 | if (i % 15 == 0): 5 | print("FizzBuzz ", end="") 6 | elif (i % 3 == 0): 7 | print("Fizz ", end="") 8 | elif (i % 5 == 0): 9 | print("Buzz ", end="") 10 | else: 11 | print("{:d} ".format(i), end="") 12 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/2-print_alphabet.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for i in 'abcdefghijklmnopqrstuvwxyz': 3 | print("{}".format(i), end="") 4 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/3-print_alphabt.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for i in 'abcdefghijklmnopqrstuvwxyz': 3 | if (i != "q" and i != "e"): 4 | print("{}".format(i), end="") 5 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/4-print_hexa.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for i in range(0, 99): 3 | print("{:d} = {}".format(i, hex(i))) 4 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/5-print_comb2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | print(", ".join("{0:0>2}".format(i) for i in range(100))) 3 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/6-print_comb3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for i in range(10): 3 | for j in range(i + 1, 10): 4 | print("{}".format(str(i) + str(j)), end="") 5 | if int(str(i) + str(j)) < 89: 6 | print(", ", end="") 7 | print("") 8 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/7-islower.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def islower(c): 3 | if ord(c) > 96 and ord(c) < 123: 4 | return True 5 | return False 6 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/8-uppercase.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def uppercase(str): 3 | tmp = list(str) 4 | for i in range(len(tmp)): 5 | if (ord(tmp[i]) > 96 and ord(tmp[i]) < 123): 6 | tmp[i] = chr(ord(tmp[i]) - 32) 7 | print("{}".format(("").join(tmp))) 8 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/9-print_last_digit.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def print_last_digit(number): 3 | tmp = int(repr(number)[-1]) 4 | print("{}".format(tmp), end="") 5 | return tmp 6 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/README.md: -------------------------------------------------------------------------------- 1 | # 0x01. Python - if/else, loops, functions 2 | 3 | This directory contains exercises/projects for learning about Python if/else statements, loops, and building functions. 4 | 5 | | File | Description | 6 | | ---- |:-----------:| 7 | | 0-positive_or_negative.py | Given a random number, print to stdout is the singles digit is positive, zero, or negative. | 8 | | 1-last_digit.py | Given a random number between -10,000 to 10,000, print to stdout if the singles digit is greater than 5, equal to 0, or less than 6 and not 0. | 9 | | 2-print_alphabet.py | Print to stdout the alphabet with no newline. Restricted to using only one `print` function, one loop, and cannot import any modules. | 10 | | 3-print_alphabt.py | Print to stdout the alphabet with no newline except for letters "q" and "e". Same restrictions apply to exercise 2. | 11 | | 4-print_hexa.py | Print all numbers from 0 to 98 in decimal and hexadecimal. Restricted to using only one `print` with string format statement, one loop, and cannot import any modules. | 12 | | 5-print_comb2.py | Print to stdout numbers 0 to 99. Numbers must be comma and space separated, should print in ascending order with 2 digits, and the last number should be followed by a newline. Restricted to using no more than 2 `print` functions with string format, one loop, and cannot import any modules. | 13 | | 6-print_comb3.py | Print to stdout all possible different combinations of two digits from 0 to 99. 01 and 10 are considered as the same combination of digits 0 and 1. Must print in ascending order, and tens digit must be lower than singles digit. Numbers must be comma and space separated. Restricted to no more than 3 `print` functions with string format, 2 loops, and cannot import any modules. | 14 | | 7-islower.py | Write a function that checks if a character is lowercased. Return a boolean value. Assume input will always be a single character. Default to printing "upper" for invalid characters. Cannot import any modules, and cannot use `.upper()` and `.isupper()`. | 15 | | 8-uppercase.py | Print to stdout a string in uppercase followed by a newline. Restricted to no more than 2 `print` functions with string format, one loop, cannot import any modules, and cannot use `.upper()` and `.isupper()`. | 16 | | 9-print_last_digit.py | Write a function that prints the last digit of a number. Cannot import any modules. | 17 | | 10-add.py | Write a function that adds two integers and returns the result. Cannot import any modules. | 18 | | 11-pow.py | Write a function that computes `a` to the power of `b` and return the value. Cannot import any modules. | 19 | | 12-fizzbuzz.py | Write a function that prints the numbers from 1 to 100 separated by spaces. For each multiple of 3, print "Fizz". For each multiple of 5, print "Buzz". For each multiple of both 3 and 5, print "FizzBuzz". Cannot import any modules. | 20 | | 100-print_tebahpla.py | Write a program that prints the alphabet, in reverse order, alternating lowercase and uppercase starting with lowercase "z", not followed by a newline. Restricted to only one `print` function with string format, one loop, and cannot import any modules. | 21 | | 101-remove_char_at.py | Write a function that creates a copy of the string, removing the character at position `n`. Cannot import any modules. | 22 | | 102-magic_calculation.py | Write the Python function `def magic_calculation(a, b, c):` that does exactly the same as the Python bytecode given. See below for more info. | 23 | 24 | 25 | ## Other 26 | 27 | For exercise 102, we are given a Python bytecode. We are tasked with writing a function that disassembles exactly into the bytecode we are provided. The bytecode we were given was: 28 | 29 | ``` 30 | 3 0 LOAD_FAST 0 (a) 31 | 3 LOAD_FAST 1 (b) 32 | 6 COMPARE_OP 0 (<) 33 | 9 POP_JUMP_IF_FALSE 16 34 | 35 | 4 12 LOAD_FAST 2 (c) 36 | 15 RETURN_VALUE 37 | 38 | 5 >> 16 LOAD_FAST 2 (c) 39 | 19 LOAD_FAST 1 (b) 40 | 22 COMPARE_OP 4 (>) 41 | 25 POP_JUMP_IF_FALSE 36 42 | 43 | 6 28 LOAD_FAST 0 (a) 44 | 31 LOAD_FAST 1 (b) 45 | 34 BINARY_ADD 46 | 35 RETURN_VALUE 47 | 48 | 7 >> 36 LOAD_FAST 0 (a) 49 | 39 LOAD_FAST 1 (b) 50 | 42 BINARY_MULTIPLY 51 | 43 LOAD_FAST 2 (c) 52 | 46 BINARY_SUBTRACT 53 | 47 RETURN_VALUE 54 | ``` -------------------------------------------------------------------------------- /0x02-python-import_modules/0-add.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | if __name__ == "__main__": 3 | from add_0 import add 4 | a = 1 5 | b = 2 6 | print("{:d} + {:d} = {:d}".format(a, b, add(a, b))) 7 | -------------------------------------------------------------------------------- /0x02-python-import_modules/1-calculation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | if __name__ == "__main__": 3 | from calculator_1 import add, sub, mul, div 4 | a = 10 5 | b = 5 6 | print("{:d} + {:d} = {:d}".format(a, b, add(a, b))) 7 | print("{:d} - {:d} = {:d}".format(a, b, sub(a, b))) 8 | print("{:d} * {:d} = {:d}".format(a, b, mul(a, b))) 9 | print("{:d} / {:d} = {:d}".format(a, b, div(a, b))) 10 | -------------------------------------------------------------------------------- /0x02-python-import_modules/100-my_calculator.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | if __name__ == "__main__": 3 | from sys import argv 4 | from calculator_1 import add, sub, mul, div 5 | count = len(argv) 6 | 7 | if count != 4: 8 | print("Usage: {} ".format(argv[0])) 9 | exit(1) 10 | 11 | num1 = int(argv[1]) 12 | num2 = int(argv[3]) 13 | op = argv[2] 14 | 15 | def not_found(): 16 | print("Unknown operator. Available operators: +, -, * and /") 17 | exit(1) 18 | 19 | def my_add(): 20 | total = add(num1, num2) 21 | print("{:d} + {:d} = {:d}".format(num1, num2, total)) 22 | return total 23 | 24 | def my_sub(): 25 | total = sub(num1, num2) 26 | print("{:d} - {:d} = {:d}".format(num1, num2, total)) 27 | return total 28 | 29 | def my_mul(): 30 | total = mul(num1, num2) 31 | print("{:d} * {:d} = {:d}".format(num1, num2, total)) 32 | return total 33 | 34 | def my_div(): 35 | total = div(num1, num2) 36 | print("{:d} / {:d} = {:d}".format(num1, num2, total)) 37 | return total 38 | 39 | options = { 40 | "+": my_add, 41 | "-": my_sub, 42 | "*": my_mul, 43 | "/": my_div 44 | } 45 | options.get(op, not_found)() 46 | -------------------------------------------------------------------------------- /0x02-python-import_modules/101-easy_print.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import trythis 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 | else: 11 | return sub(a, b) 12 | -------------------------------------------------------------------------------- /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 | total = len(sys.argv) 5 | if total <= 1: 6 | print("0 argument.") 7 | else: 8 | if total == 2: 9 | print("{:d} argument:".format(total - 1)) 10 | else: 11 | print("{:d} arguments:".format(total - 1)) 12 | for i in range(1, total): 13 | print("{:d}: {}".format(i, sys.argv[i])) 14 | -------------------------------------------------------------------------------- /0x02-python-import_modules/3-infinite_add.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | if __name__ == "__main__": 3 | from sys import argv 4 | num_args = len(argv) 5 | total = 0 6 | for i in range(1, num_args): 7 | total += int(argv[i]) 8 | print("{:d}".format(total)) 9 | -------------------------------------------------------------------------------- /0x02-python-import_modules/4-hidden_discovery.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | if __name__ == "__main__": 3 | import hidden_4 4 | all_dir = dir(hidden_4) 5 | avoid = "__" 6 | for i in range(0, len(all_dir)): 7 | if avoid not in all_dir[i]: 8 | print(all_dir[i]) 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 | print(a) 5 | -------------------------------------------------------------------------------- /0x02-python-import_modules/README.md: -------------------------------------------------------------------------------- 1 | # 0x02. Python - import & modules 2 | -------------------------------------------------------------------------------- /0x02-python-import_modules/trythis.py: -------------------------------------------------------------------------------- 1 | print("#pythoniscool") 2 | -------------------------------------------------------------------------------- /0x03-python-data_structures/0-print_list_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def print_list_integer(my_list=[]): 3 | for n in my_list: 4 | print("{:d}".format(n)) 5 | -------------------------------------------------------------------------------- /0x03-python-data_structures/1-element_at.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def element_at(my_list, idx): 3 | return my_list[idx] if (0 <= idx < len(my_list)) else None 4 | -------------------------------------------------------------------------------- /0x03-python-data_structures/10-divisible_by_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def divisible_by_2(my_list=[]): 3 | if my_list is None: 4 | return 5 | new_list = [] 6 | for n in my_list: 7 | if n % 2 == 0: 8 | new_list.append(True) 9 | else: 10 | new_list.append(False) 11 | return new_list 12 | -------------------------------------------------------------------------------- /0x03-python-data_structures/11-delete_at.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def delete_at(my_list=[], idx=0): 3 | if not my_list: 4 | return my_list 5 | if 0 <= idx < len(my_list): 6 | del my_list[idx] 7 | return my_list 8 | -------------------------------------------------------------------------------- /0x03-python-data_structures/12-switch.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | a = 89 3 | b = 10 4 | a, b = b, a 5 | print("a={:d} - b={:d}".format(a, b)) 6 | -------------------------------------------------------------------------------- /0x03-python-data_structures/2-replace_in_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def replace_in_list(my_list, idx, element): 3 | if (0 <= idx < len(my_list)): 4 | my_list[idx] = element 5 | return my_list 6 | -------------------------------------------------------------------------------- /0x03-python-data_structures/3-print_reversed_list_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def print_reversed_list_integer(my_list=[]): 3 | if my_list is None: 4 | return 5 | for i in reversed(my_list): 6 | print("{:d}".format(i)) 7 | -------------------------------------------------------------------------------- /0x03-python-data_structures/4-new_in_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def new_in_list(my_list, idx, element): 3 | if my_list is None: 4 | return 5 | new_list = my_list[:] 6 | if 0 <= idx < len(new_list): 7 | new_list[idx] = element 8 | return new_list 9 | -------------------------------------------------------------------------------- /0x03-python-data_structures/5-no_c.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def no_c(my_string): 3 | return my_string.translate({ord(c): None for c in "cC"}) 4 | -------------------------------------------------------------------------------- /0x03-python-data_structures/6-print_matrix_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def print_matrix_integer(matrix=[[]]): 3 | for sublist in matrix: 4 | for i in range(len(sublist)): 5 | print("{:d}".format(sublist[i]), end="") 6 | if i is not len(sublist) - 1: 7 | print(" ", end="") 8 | print("") 9 | -------------------------------------------------------------------------------- /0x03-python-data_structures/7-add_tuple.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def add_tuple(tuple_a=(), tuple_b=()): 3 | a = list(tuple_a) + [0]*2 4 | b = list(tuple_b) + [0]*2 5 | c = [x + y for x, y in zip(a, b)] 6 | return tuple(c[0:2]) 7 | -------------------------------------------------------------------------------- /0x03-python-data_structures/8-multiple_returns.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def multiple_returns(sentence): 3 | if len(sentence) > 0: 4 | return tuple([len(sentence), sentence[0]]) 5 | else: 6 | return tuple([0, None]) 7 | -------------------------------------------------------------------------------- /0x03-python-data_structures/9-max_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def max_integer(my_list=[]): 3 | if my_list is None or len(my_list) is 0: 4 | return None 5 | max = my_list[0] 6 | for i in range(len(my_list)): 7 | if max < my_list[i]: 8 | max = my_list[i] 9 | return max 10 | -------------------------------------------------------------------------------- /0x03-python-data_structures/README.md: -------------------------------------------------------------------------------- 1 | # 0x03. Python - Data Structuers: Lists, Tuples -------------------------------------------------------------------------------- /0x04-python-more_data_structures/0-square_matrix_simple.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def square_matrix_simple(matrix=[]): 3 | return [list(map(lambda n: n**2, sublist)) for sublist in matrix] 4 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/1-search_replace.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def search_replace(my_list, search, replace): 3 | return [replace if search == n else n for n in my_list] 4 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/10-best_score.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def best_score(my_dict): 3 | return max(my_dict, key=my_dict.get) if my_dict else None 4 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/100-weight_average.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def weight_average(my_list=[]): 3 | if len(my_list) is 0: 4 | return 0 5 | a = list(map(list, zip(*my_list))) 6 | b = [x * y for x, y in zip(a[0], a[1])] 7 | return sum(b) / sum(a[1]) 8 | -------------------------------------------------------------------------------- /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 row: list(map(lambda n: n**2, row)), matrix)) 4 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/102-complex_delete.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def complex_delete(my_dict, value): 3 | copy = my_dict.copy() 4 | for k, v in copy.items(): 5 | if value in v: 6 | del my_dict[k] 7 | return my_dict 8 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/11-mutiply_list_map.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def mutiply_list_map(my_list=[], number=0): 3 | return list(map(lambda n: n * number, my_list)) 4 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/2-uniq_add.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def uniq_add(my_list=[]): 3 | return sum(set(my_list)) 4 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/3-common_elements.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def common_elements(set_1, set_2): 3 | return set_1 & set_2 4 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/4-only_diff_elements.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def only_diff_elements(set_1, set_2): 3 | return set_1 ^ set_2 4 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/5-number_keys.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def number_keys(my_dict): 3 | return len(my_dict.keys()) 4 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/6-print_sorted_dictionary.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def print_sorted_dictionary(my_dict): 3 | for k in sorted(my_dict.keys()): 4 | print("{}: {}".format(k, my_dict[k])) 5 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/7-update_dictionary.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def update_dictionary(my_dict, key, value): 3 | my_dict[key] = value 4 | return my_dict 5 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/8-simple_delete.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def simple_delete(my_dict, key=""): 3 | my_dict.pop(key, None) 4 | return my_dict 5 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/9-multiply_by_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def multiply_by_2(my_dict): 3 | new_dict = {} 4 | for k, v in my_dict.items(): 5 | new_dict[k] = v * 2 6 | return new_dict 7 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/README.md: -------------------------------------------------------------------------------- 1 | # 0x04. Python - More data structures: Set, Dictionary -------------------------------------------------------------------------------- /0x05-python-exceptions/0-safe_print_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def safe_print_list(my_list=[], x=0): 3 | try: 4 | for i in range(x): 5 | print("{}".format(my_list[i]), end="") 6 | except IndexError: 7 | return i 8 | else: 9 | return x 10 | finally: 11 | print("") 12 | -------------------------------------------------------------------------------- /0x05-python-exceptions/1-safe_print_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def safe_print_integer(value): 3 | try: 4 | print("{:d}".format(value)) 5 | except: 6 | return False 7 | else: 8 | return True 9 | -------------------------------------------------------------------------------- /0x05-python-exceptions/100-safe_print_integer_err.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import sys 3 | 4 | 5 | def safe_print_integer_err(value): 6 | try: 7 | print("{:d}".format(value)) 8 | except (ValueError, TypeError) as err: 9 | print("Exception: {}".format(err), file=sys.stderr) 10 | return False 11 | else: 12 | return True 13 | -------------------------------------------------------------------------------- /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 | r = fct(*args) 8 | except Exception as err: 9 | r = None 10 | print("Exception: {}".format(err), file=sys.stderr) 11 | finally: 12 | return r 13 | -------------------------------------------------------------------------------- /0x05-python-exceptions/102-magic_calculation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def magic_calculation(a, b): 3 | result = 0 4 | for i in range(1, 3): 5 | try: 6 | if i > a: 7 | raise Exception("Too far") 8 | result += (a ** b) / i 9 | except: 10 | result = b + a 11 | break 12 | return result 13 | -------------------------------------------------------------------------------- /0x05-python-exceptions/2-safe_print_list_integers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def safe_print_list_integers(my_list=[], x=0): 3 | try: 4 | count = 0 5 | for i in range(x): 6 | if isinstance(my_list[i], int): 7 | count += 1 8 | print("{:d}".format(my_list[i]), end="") 9 | except TypeError as err: 10 | print(err) 11 | else: 12 | print("") 13 | return count 14 | -------------------------------------------------------------------------------- /0x05-python-exceptions/3-safe_print_division.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def safe_print_division(a, b): 3 | try: 4 | x = a / b 5 | except ZeroDivisionError: 6 | x = None 7 | finally: 8 | print("Inside result: {}".format(x)) 9 | return x 10 | -------------------------------------------------------------------------------- /0x05-python-exceptions/4-list_division.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def list_division(my_list_1, my_list_2, list_length): 3 | store = [] 4 | switch = 0 5 | for i in range(list_length): 6 | try: 7 | x = my_list_1[i] / my_list_2[i] 8 | except ZeroDivisionError: 9 | print("division by 0") 10 | switch = 1 11 | except TypeError: 12 | print("wrong type") 13 | switch = 1 14 | except IndexError: 15 | print("out of range") 16 | switch = 1 17 | finally: 18 | if switch: 19 | switch = 0 20 | store.append(0) 21 | else: 22 | store.append(x) 23 | return store 24 | -------------------------------------------------------------------------------- /0x05-python-exceptions/5-raise_exception.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def raise_exception(): 3 | raise TypeError 4 | -------------------------------------------------------------------------------- /0x05-python-exceptions/6-raise_exception_msg.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def raise_exception_msg(message=""): 3 | raise NameError(message) 4 | -------------------------------------------------------------------------------- /0x05-python-exceptions/README.md: -------------------------------------------------------------------------------- 1 | # 0x05. Python - Exceptions -------------------------------------------------------------------------------- /0x06-python-test_driven_development/0-add_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This is the "Add Integer" module. 4 | 5 | This module supplies one function, add_integer(), 6 | which adds together 2 int or float types and returns an int. 7 | """ 8 | 9 | 10 | def add_integer(a, b): 11 | """Return the sum of two integers or floats as an integer. 12 | Otherwise raise a TypeError for given incorrect argument type. 13 | """ 14 | h = list(map(lambda x: isinstance(x, (int, float)), [a, b])) 15 | 16 | if all(h): 17 | return int(a) + int(b) 18 | 19 | for x, y in list(zip(h, ['a', 'b'])): 20 | if not x: 21 | raise TypeError("{} must be an integer".format(y)) 22 | -------------------------------------------------------------------------------- /0x06-python-test_driven_development/1-mul.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This is the "Multiplication" module. 4 | 5 | The Multiplication module supplies a simple function \ 6 | to multiply 2 Python variables. 7 | """ 8 | 9 | 10 | def mul(a, b): 11 | """Return the multiplication of 2 arguments 12 | """ 13 | return a * b 14 | -------------------------------------------------------------------------------- /0x06-python-test_driven_development/2-matrix_divided.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This is the "Matrix Divided" module. 4 | 5 | The Matrix Divided module takes in a list of lists matrix and divisor. 6 | All valid elements are divided by the divisor and returned as new matrix. 7 | """ 8 | 9 | 10 | def matrix_divided(matrix, div): 11 | """Return a new matrix with all values divided by `div`. 12 | Matrix must be a list of lists. 13 | Each sub-list must contain only integers or floats. 14 | Empty sub-lists are not allowed. 15 | Divisor must be greater than 0 and must be an int or float. 16 | """ 17 | if not isinstance(matrix, list): 18 | raise TypeError("matrix must be a matrix (list of lists)" 19 | " of integers/floats") 20 | if len(matrix) is 0: 21 | raise TypeError("matrix must be a matrix (list of lists)" 22 | " of integers/floats") 23 | if not all(len(l) > 0 for l in matrix): 24 | raise TypeError("matrix must be a matrix (list of lists)" 25 | " of integers/floats") 26 | 27 | if not all(len(l) == len(matrix[0]) for l in matrix): 28 | raise TypeError("Each row of the matrix must have the same size") 29 | 30 | for l in matrix: 31 | if not isinstance(l, list): 32 | raise TypeError("matrix must be a matrix (list of lists)" 33 | " of integers/floats") 34 | if not all(isinstance(x, (int, float)) for x in l): 35 | raise TypeError("matrix must be a matrix (list of lists)" 36 | " of integers/floats") 37 | 38 | if div is 0: 39 | raise ZeroDivisionError("division by zero") 40 | if isinstance(div, bool): 41 | raise TypeError("div must be a number") 42 | if not isinstance(div, (int, float)): 43 | raise TypeError("div must be a number") 44 | 45 | new_matrix = [] 46 | for l in matrix: 47 | new_matrix.append(list(map(lambda n: round(n / div, 2), l))) 48 | 49 | return new_matrix 50 | -------------------------------------------------------------------------------- /0x06-python-test_driven_development/3-say_my_name.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This is the "Say My Name" module. 4 | 5 | The Say My Name module takes one required parameter and one optional. 6 | It prints "My name is (first) (last)" where (first) and (last) are the args. 7 | """ 8 | 9 | 10 | def say_my_name(first_name, last_name=""): 11 | """Print My name is (first) (last) if given, else print error. 12 | """ 13 | if not isinstance(first_name, str): 14 | raise TypeError("first_name must be a string") 15 | if not isinstance(last_name, str): 16 | raise TypeError("last_name must be a string") 17 | print("My name is {} {}".format(first_name, last_name)) 18 | -------------------------------------------------------------------------------- /0x06-python-test_driven_development/4-print_square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This is the "Print Square" module. 4 | 5 | The Print Square module prints a square using "#". 6 | The argument supplied should determine the width/height of square. 7 | """ 8 | 9 | 10 | def print_square(size): 11 | """Print a perfect square given a valid int or float argument. 12 | """ 13 | if not isinstance(size, (int, float)) or isinstance(size, bool): 14 | raise TypeError("size must be an integer") 15 | if isinstance(size, float) and size < 0: 16 | raise TypeError("size must be an integer") 17 | if size < 0: 18 | raise ValueError("size must be >= 0") 19 | 20 | for i in range(int(size)): 21 | print("#" * int(size)) 22 | -------------------------------------------------------------------------------- /0x06-python-test_driven_development/README.md: -------------------------------------------------------------------------------- 1 | # 0x06. Python - Test-driven development -------------------------------------------------------------------------------- /0x06-python-test_driven_development/tests/0-add_integer.txt: -------------------------------------------------------------------------------- 1 | The ``Add Integer`` module 2 | ============================ 3 | 4 | Using ``add_integer`` 5 | --------------------- 6 | 7 | This is an example text file in reStructuredText format. First 8 | ``add_integer`` from the ``Add Integer`` module: 9 | 10 | >>> add_integer = __import__("0-add_integer").add_integer 11 | 12 | Now use it: 13 | 14 | >>> add_integer("School", 1) 15 | Traceback (most recent call last): 16 | ... 17 | TypeError: a must be an integer 18 | 19 | >>> add_integer(1, "School") 20 | Traceback (most recent call last): 21 | ... 22 | TypeError: b must be an integer 23 | 24 | >>> add_integer(float("inf"), 1) 25 | Traceback (most recent call last): 26 | ... 27 | OverflowError: cannot convert float infinity to integer 28 | 29 | >>> add_integer(1, float("inf")) 30 | Traceback (most recent call last): 31 | ... 32 | OverflowError: cannot convert float infinity to integer 33 | 34 | >>> add_integer(-float("inf"), 1) 35 | Traceback (most recent call last): 36 | ... 37 | OverflowError: cannot convert float infinity to integer 38 | 39 | >>> add_integer(1, -float("inf")) 40 | Traceback (most recent call last): 41 | ... 42 | OverflowError: cannot convert float infinity to integer 43 | 44 | >>> add_integer([1, 2, 3], 0) 45 | Traceback (most recent call last): 46 | ... 47 | TypeError: a must be an integer 48 | 49 | >>> add_integer(0, [1, 2, 3]) 50 | Traceback (most recent call last): 51 | ... 52 | TypeError: b must be an integer 53 | 54 | >>> add_integer({1: "yo"}, 0) 55 | Traceback (most recent call last): 56 | ... 57 | TypeError: a must be an integer 58 | 59 | >>> add_integer(0, {1: "yo"}) 60 | Traceback (most recent call last): 61 | ... 62 | TypeError: b must be an integer 63 | 64 | >>> add_integer(2, 96) 65 | 98 66 | 67 | >>> add_integer(-2, -96) 68 | -98 69 | 70 | >>> add_integer(100, -2) 71 | 98 72 | 73 | >>> add_integer(-2, 100) 74 | 98 75 | 76 | >>> add_integer("Hello", "Holberton") 77 | Traceback (most recent call last): 78 | ... 79 | TypeError: a must be an integer 80 | 81 | >>> add_integer(100.1, -2.9) 82 | 98 83 | 84 | >>> add_integer(True, 2) 85 | 3 86 | 87 | >>> add_integer(2, False) 88 | 2 89 | 90 | >>> add_integer(None, 1) 91 | Traceback (most recent call last): 92 | ... 93 | TypeError: a must be an integer 94 | 95 | >>> add_integer(1, None) 96 | Traceback (most recent call last): 97 | ... 98 | TypeError: b must be an integer 99 | 100 | >>> add_integer(None, None) 101 | Traceback (most recent call last): 102 | ... 103 | TypeError: a must be an integer 104 | 105 | >>> add_integer(10.9, 2) 106 | 12 107 | 108 | >>> add_integer(2, 10.9) 109 | 12 110 | 111 | >>> add_integer(-2.9, 10) 112 | 8 113 | 114 | >>> add_integer(2.9, -10) 115 | -8 116 | 117 | >>> add_integer({1, 2, 3}, 2) 118 | Traceback (most recent call last): 119 | ... 120 | TypeError: a must be an integer 121 | 122 | >>> add_integer(2, {1, 2, 3}) 123 | Traceback (most recent call last): 124 | ... 125 | TypeError: b must be an integer 126 | 127 | >>> add_integer((1, 2, 3), 2) 128 | Traceback (most recent call last): 129 | ... 130 | TypeError: a must be an integer 131 | 132 | >>> add_integer(2, (1, 2, 3)) 133 | Traceback (most recent call last): 134 | ... 135 | TypeError: b must be an integer 136 | 137 | >>> add_integer("17", 2) 138 | Traceback (most recent call last): 139 | ... 140 | TypeError: a must be an integer 141 | 142 | >>> add_integer(2, "17") 143 | Traceback (most recent call last): 144 | ... 145 | TypeError: b must be an integer 146 | 147 | >>> add_integer([1], [2, 3]) 148 | Traceback (most recent call last): 149 | ... 150 | TypeError: a must be an integer 151 | 152 | >>> add_integer(lambda x: x, 2.5) 153 | Traceback (most recent call last): 154 | ... 155 | TypeError: a must be an integer 156 | 157 | >>> add_integer(2.5, lambda x: x) 158 | Traceback (most recent call last): 159 | ... 160 | TypeError: b must be an integer 161 | 162 | >>> add_integer() 163 | Traceback (most recent call last): 164 | ... 165 | TypeError: add_integer() missing 2 required positional arguments: 'a' and 'b' 166 | 167 | >>> add_integer(1) 168 | Traceback (most recent call last): 169 | ... 170 | TypeError: add_integer() missing 1 required positional argument: 'b' 171 | -------------------------------------------------------------------------------- /0x06-python-test_driven_development/tests/1-mul.txt: -------------------------------------------------------------------------------- 1 | The ``1-mul`` module 2 | ==================== 3 | 4 | Using ``mul`` 5 | ------------- 6 | 7 | This is an text file in reStructuredText format. 8 | First import ``mul`` from the ``1-mul`` module: 9 | 10 | >>> mul = __import__("1-mul").mul 11 | 12 | Now use it: 13 | 14 | >>> mul(-1, 2) 15 | -2 16 | 17 | >>> mul(1, -2) 18 | -2 19 | 20 | >>> mul(2, False) 21 | 0 22 | 23 | >>> mul(True, 2) 24 | 2 25 | 26 | >>> mul(True, False) 27 | 0 28 | 29 | >>> mul(True, True) 30 | 1 31 | 32 | >>> mul(False, True) 33 | 0 34 | 35 | >>> mul(False, False) 36 | 0 37 | 38 | >>> mul(1, 2) 39 | 2 40 | 41 | >>> mul(2, 1) 42 | 2 43 | 44 | >>> mul(-1.01, 0) 45 | -0.0 46 | 47 | >>> mul(("tup", 2), 2) 48 | ('tup', 2, 'tup', 2) 49 | 50 | >>> mul(["list", 2], 2) 51 | ['list', 2, 'list', 2] 52 | 53 | >>> mul("a string", 3) 54 | 'a stringa stringa string' 55 | 56 | >>> mul(5.000, 2.0) 57 | 10.0 58 | 59 | >>> mul("""hello""", 2) 60 | 'hellohello' 61 | 62 | >>> mul(2, """hello""") 63 | 'hellohello' 64 | 65 | >>> mul(1e10000, 1e10000) 66 | inf 67 | 68 | >>> mul(float("inf"), float("inf")) 69 | inf 70 | 71 | >>> mul(1E+100, -3E+102) 72 | -2.9999999999999997e+202 73 | 74 | >>> mul({"a": 1, "b": [1, 2, 3]}, 2) 75 | Traceback (most recent call last): 76 | ... 77 | TypeError: unsupported operand type(s) for *: 'dict' and 'int' 78 | 79 | >>> mul("a string", 2.1) 80 | Traceback (most recent call last): 81 | ... 82 | TypeError: can't multiply sequence by non-int of type 'float' 83 | 84 | >>> mul("coffee", "good") 85 | Traceback (most recent call last): 86 | ... 87 | TypeError: can't multiply sequence by non-int of type 'str' 88 | 89 | >>> mul((2, 3), None) 90 | Traceback (most recent call last): 91 | ... 92 | TypeError: can't multiply sequence by non-int of type 'NoneType' 93 | 94 | >>> mul([2, 3], None) 95 | Traceback (most recent call last): 96 | ... 97 | TypeError: can't multiply sequence by non-int of type 'NoneType' 98 | 99 | >>> mul({1, 2, 3}, 3) 100 | Traceback (most recent call last): 101 | ... 102 | TypeError: unsupported operand type(s) for *: 'set' and 'int' 103 | 104 | >>> mul(2.0, None) 105 | Traceback (most recent call last): 106 | ... 107 | TypeError: unsupported operand type(s) for *: 'float' and 'NoneType' 108 | 109 | >>> mul(2, None) 110 | Traceback (most recent call last): 111 | ... 112 | TypeError: unsupported operand type(s) for *: 'int' and 'NoneType' 113 | 114 | >>> mul(None, None) 115 | Traceback (most recent call last): 116 | ... 117 | TypeError: unsupported operand type(s) for *: 'NoneType' and 'NoneType' 118 | 119 | >>> mul(1) 120 | Traceback (most recent call last): 121 | ... 122 | TypeError: mul() missing 1 required positional argument: 'b' 123 | 124 | >>> mul(1, 2, 3) 125 | Traceback (most recent call last): 126 | ... 127 | TypeError: mul() takes 2 positional arguments but 3 were given 128 | 129 | >>> mul() 130 | Traceback (most recent call last): 131 | ... 132 | TypeError: mul() missing 2 required positional arguments: 'a' and 'b' 133 | 134 | ========== 135 | 136 | >>> mul([1], [2]) 137 | Traceback (most recent call last): 138 | ... 139 | TypeError: can't multiply sequence by non-int of type 'list' 140 | 141 | >>> mul({}, {}) 142 | Traceback (most recent call last): 143 | ... 144 | TypeError: unsupported operand type(s) for *: 'dict' and 'dict' 145 | 146 | >>> mul(2, [4]) 147 | [4, 4] 148 | 149 | >>> mul(5, [3]) 150 | [3, 3, 3, 3, 3] 151 | 152 | >>> mul(3, {}) 153 | Traceback (most recent call last): 154 | ... 155 | TypeError: unsupported operand type(s) for *: 'int' and 'dict' 156 | 157 | >>> mul(3, lambda x: x) 158 | Traceback (most recent call last): 159 | ... 160 | TypeError: unsupported operand type(s) for *: 'int' and 'function' 161 | -------------------------------------------------------------------------------- /0x06-python-test_driven_development/tests/2-matrix_divided.txt: -------------------------------------------------------------------------------- 1 | The ``Matrix Divided`` module 2 | ============================= 3 | 4 | Using ``matrix_divided`` 5 | ------------------------ 6 | 7 | This is a text file in reStructuredText format. 8 | First ``matrix_divided`` from the ``Matrix Divided`` module: 9 | 10 | >>> matrix_divided = __import__("2-matrix_divided").matrix_divided 11 | 12 | Now use it: 13 | 14 | >>> m = [[1.1, 2.2, 3.3]] 15 | >>> matrix_divided(m, 2) 16 | [[0.55, 1.1, 1.65]] 17 | 18 | >>> m = [[1, 3, 5], [2, 4, 6], [7, 8, 9]] 19 | >>> matrix_divided(m, 6) 20 | [[0.17, 0.5, 0.83], [0.33, 0.67, 1.0], [1.17, 1.33, 1.5]] 21 | 22 | >>> matrix_divided(m, 8) 23 | [[0.12, 0.38, 0.62], [0.25, 0.5, 0.75], [0.88, 1.0, 1.12]] 24 | 25 | >>> m = [[1, 2, 3], [4, 5, 6]] 26 | >>> new = matrix_divided(m, 3) 27 | >>> new 28 | [[0.33, 0.67, 1.0], [1.33, 1.67, 2.0]] 29 | 30 | >>> new == m 31 | False 32 | 33 | >>> m = [[1]] 34 | >>> matrix_divided(m, 2) 35 | [[0.5]] 36 | 37 | >>> m = [[1, 2, 3], [4, 5, 6]] 38 | >>> matrix_divided(m, float("inf")) 39 | [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] 40 | 41 | >>> matrix_divided([], 2) 42 | Traceback (most recent call last): 43 | ... 44 | TypeError: matrix must be a matrix (list of lists) of integers/floats 45 | 46 | >>> matrix_divided([[]], 2) 47 | Traceback (most recent call last): 48 | ... 49 | TypeError: matrix must be a matrix (list of lists) of integers/floats 50 | 51 | >>> matrix_divided([[], []], 2) 52 | Traceback (most recent call last): 53 | ... 54 | TypeError: matrix must be a matrix (list of lists) of integers/floats 55 | 56 | >>> m = [[1, 2, 3], [4, 5, "a"]] 57 | >>> matrix_divided(m, 3) 58 | Traceback (most recent call last): 59 | ... 60 | TypeError: matrix must be a matrix (list of lists) of integers/floats 61 | 62 | >>> m = [[1, 2], [3, 4, 5]] 63 | >>> matrix_divided(m, 3) 64 | Traceback (most recent call last): 65 | ... 66 | TypeError: Each row of the matrix must have the same size 67 | 68 | >>> m = [[1, 2, 3], [4, 5, 6]] 69 | >>> matrix_divided(m) 70 | Traceback (most recent call last): 71 | ... 72 | TypeError: matrix_divided() missing 1 required positional argument: 'div' 73 | 74 | >>> matrix_divided([[1, 2, 3], [4, 5, 6]], 2, 3) 75 | Traceback (most recent call last): 76 | ... 77 | TypeError: matrix_divided() takes 2 positional arguments but 3 were given 78 | 79 | >>> matrix_divided(1, 2, 3) 80 | Traceback (most recent call last): 81 | ... 82 | TypeError: matrix_divided() takes 2 positional arguments but 3 were given 83 | 84 | >>> m = [[1, 2], [3, 4]] 85 | >>> matrix_divided(m, 0) 86 | Traceback (most recent call last): 87 | ... 88 | ZeroDivisionError: division by zero 89 | 90 | >>> matrix_divided([[1, 2], [3, 4]], "a") 91 | Traceback (most recent call last): 92 | ... 93 | TypeError: div must be a number 94 | 95 | >>> matrix_divided([[1, 2], [3, 4]], [1]) 96 | Traceback (most recent call last): 97 | ... 98 | TypeError: div must be a number 99 | 100 | >>> matrix_divided(0, [[1, 2], [3, 4]]) 101 | Traceback (most recent call last): 102 | ... 103 | TypeError: matrix must be a matrix (list of lists) of integers/floats 104 | 105 | >>> matrix_divided(("tup", 2), 1) 106 | Traceback (most recent call last): 107 | ... 108 | TypeError: matrix must be a matrix (list of lists) of integers/floats 109 | 110 | >>> matrix_divided([(1, 2), (3, 4)], 2) 111 | Traceback (most recent call last): 112 | ... 113 | TypeError: matrix must be a matrix (list of lists) of integers/floats 114 | 115 | >>> matrix_divided([[1]], None) 116 | Traceback (most recent call last): 117 | ... 118 | TypeError: div must be a number 119 | 120 | >>> matrix_divided([[1, 2, 3], [4, 5, 6]], True) 121 | Traceback (most recent call last): 122 | ... 123 | TypeError: div must be a number 124 | 125 | >>> matrix_divided([[1, 2, 3], [4, 5, 6]], False) 126 | Traceback (most recent call last): 127 | ... 128 | TypeError: div must be a number 129 | 130 | >>> m = [[1, 2, 3], [4, 5, ("tup", 2)]] 131 | >>> matrix_divided(m, 2) 132 | Traceback (most recent call last): 133 | ... 134 | TypeError: matrix must be a matrix (list of lists) of integers/floats 135 | 136 | >>> m = [[1, 2, 3], [4, 5, [1, 2, 3]]] 137 | >>> matrix_divided(m, 2) 138 | Traceback (most recent call last): 139 | ... 140 | TypeError: matrix must be a matrix (list of lists) of integers/floats 141 | 142 | >>> m = [[1, 2, 3], [4, 5, {1: "hi"}]] 143 | >>> matrix_divided(m, 2) 144 | Traceback (most recent call last): 145 | ... 146 | TypeError: matrix must be a matrix (list of lists) of integers/floats 147 | 148 | >>> m = [['a', 'b'], ['c', 'd']] 149 | >>> matrix_divided(m, 4) 150 | Traceback (most recent call last): 151 | ... 152 | TypeError: matrix must be a matrix (list of lists) of integers/floats 153 | 154 | >>> m = [['a', 'b'], ['c', 'd', 'e']] 155 | >>> matrix_divided(m, 4) 156 | Traceback (most recent call last): 157 | ... 158 | TypeError: Each row of the matrix must have the same size 159 | 160 | >>> m = [[1, [2, 3]], [2, [3, 4]]] 161 | >>> matrix_divided(m, 3) 162 | Traceback (most recent call last): 163 | ... 164 | TypeError: matrix must be a matrix (list of lists) of integers/floats 165 | -------------------------------------------------------------------------------- /0x06-python-test_driven_development/tests/3-say_my_name.txt: -------------------------------------------------------------------------------- 1 | The ``Say My Name`` module 2 | ========================== 3 | 4 | Using ``say_my_name`` 5 | --------------------- 6 | 7 | This is a text file in reStructuredText format. 8 | First import ``say_my_name`` from the ``Say My Name`` module: 9 | 10 | >>> smn = __import__("3-say_my_name").say_my_name 11 | 12 | Now use it: 13 | 14 | >>> smn("John", "Smith") 15 | My name is John Smith 16 | 17 | >>> smn("Bob") 18 | My name is Bob 19 | 20 | >>> smn("Bob", 12) 21 | Traceback (most recent call last): 22 | ... 23 | TypeError: last_name must be a string 24 | 25 | >>> smn("") 26 | My name is 27 | 28 | >>> smn(1) 29 | Traceback (most recent call last): 30 | ... 31 | TypeError: first_name must be a string 32 | 33 | >>> smn(1, "Ross") 34 | Traceback (most recent call last): 35 | ... 36 | TypeError: first_name must be a string 37 | 38 | >>> smn() 39 | Traceback (most recent call last): 40 | ... 41 | TypeError: say_my_name() missing 1 required positional argument: 'first_name' 42 | 43 | >>> smn("Ace", "of Spades") 44 | My name is Ace of Spades 45 | 46 | >>> smn(["Holberton", "School"], 10) 47 | Traceback (most recent call last): 48 | ... 49 | TypeError: first_name must be a string 50 | 51 | >>> smn("None", None) 52 | Traceback (most recent call last): 53 | ... 54 | TypeError: last_name must be a string 55 | 56 | >>> smn("League", "of", "Legends") 57 | Traceback (most recent call last): 58 | ... 59 | TypeError: say_my_name() takes from 1 to 2 positional arguments but 3 were given 60 | -------------------------------------------------------------------------------- /0x06-python-test_driven_development/tests/4-print_square.txt: -------------------------------------------------------------------------------- 1 | The ``Print Square`` module 2 | =========================== 3 | 4 | Using ``print_square`` 5 | ---------------------- 6 | 7 | This is a text file in reStructuredText format. 8 | First import ``print_square`` from the ``Print Square`` module: 9 | 10 | >>> print_square = __import__("4-print_square").print_square 11 | 12 | Now use it: 13 | 14 | >>> print_square(4) 15 | #### 16 | #### 17 | #### 18 | #### 19 | 20 | >>> print_square(10) 21 | ########## 22 | ########## 23 | ########## 24 | ########## 25 | ########## 26 | ########## 27 | ########## 28 | ########## 29 | ########## 30 | ########## 31 | 32 | >>> print_square(0) 33 | 34 | >>> print_square(-1) 35 | Traceback (most recent call last): 36 | ... 37 | ValueError: size must be >= 0 38 | 39 | >>> print_square(5.5) 40 | ##### 41 | ##### 42 | ##### 43 | ##### 44 | ##### 45 | 46 | >>> print_square(-2.3) 47 | Traceback (most recent call last): 48 | ... 49 | TypeError: size must be an integer 50 | 51 | >>> print_square([1, 2]) 52 | Traceback (most recent call last): 53 | ... 54 | TypeError: size must be an integer 55 | 56 | >>> print_square({1}) 57 | Traceback (most recent call last): 58 | ... 59 | TypeError: size must be an integer 60 | 61 | >>> print_square("4") 62 | Traceback (most recent call last): 63 | ... 64 | TypeError: size must be an integer 65 | 66 | >>> print_square(True) 67 | Traceback (most recent call last): 68 | ... 69 | TypeError: size must be an integer 70 | 71 | >>> print_square(False) 72 | Traceback (most recent call last): 73 | ... 74 | TypeError: size must be an integer 75 | 76 | >>> print_square((1, 2)) 77 | Traceback (most recent call last): 78 | ... 79 | TypeError: size must be an integer 80 | 81 | >>> print_square({1}) 82 | Traceback (most recent call last): 83 | ... 84 | TypeError: size must be an integer 85 | -------------------------------------------------------------------------------- /0x07-python-classes/0-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This is the "Square" module. 4 | 5 | This module provides a simple Square class. 6 | """ 7 | 8 | 9 | class Square: 10 | """A simple Square class""" 11 | pass 12 | -------------------------------------------------------------------------------- /0x07-python-classes/1-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This is the "Square" module. 4 | 5 | This module provides a simple Square class with initialize size. 6 | """ 7 | 8 | 9 | class Square: 10 | """A class that defines a Square by size""" 11 | def __init__(self, size): 12 | self.__size = size 13 | -------------------------------------------------------------------------------- /0x07-python-classes/100-singly_linked_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This is the "Single Linked List" module. 4 | 5 | Class Node takes in integer values as data within each node, 6 | and a next attribute which points to the next node or to None. 7 | 8 | Class SinglyLinkedList initializes a default head of None. 9 | Method sorted_insert handles all nodes created and adds them to 10 | the linked list sorted by the int value stored within. 11 | """ 12 | 13 | 14 | class Node: 15 | """A class that creates a single Node in a Linked List. 16 | """ 17 | def __init__(self, data, next_node=None): 18 | self.data = data 19 | self.next_node = next_node 20 | 21 | @property 22 | def data(self): 23 | return self.__data 24 | 25 | @data.setter 26 | def data(self, value): 27 | if type(value) != int: 28 | raise TypeError("data must be an integer") 29 | self.__data = value 30 | 31 | @property 32 | def next_node(self): 33 | return self.__next_node 34 | 35 | @next_node.setter 36 | def next_node(self, value): 37 | if not (value is None or type(value) is Node): 38 | raise TypeError("next must be a Node object") 39 | self.__next_node = value 40 | 41 | 42 | class SinglyLinkedList: 43 | """A class that creates a Singly Linked List. 44 | """ 45 | def __init__(self): 46 | self.__head = None 47 | 48 | def __repr__(self): 49 | temp = self.__head 50 | total = "" 51 | while temp: 52 | total += "{:d}".format(temp.data) 53 | temp = temp.next_node 54 | if temp: 55 | total += "\n" 56 | return total 57 | 58 | def sorted_insert(self, value): 59 | if self.__head is None: 60 | self.__head = Node(value) 61 | else: 62 | curr = self.__head 63 | prev = None 64 | while curr and value > curr.data: 65 | prev = curr 66 | curr = curr.next_node 67 | if curr is None: 68 | prev.next_node = Node(value) 69 | elif curr is self.__head and prev is None: 70 | self.__head = Node(value, curr) 71 | else: 72 | newNode = Node(value, curr) 73 | prev.next_node = newNode 74 | -------------------------------------------------------------------------------- /0x07-python-classes/101-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This is the "Square" module. 4 | 5 | This module provides a simple Square class with initialize size. 6 | Defaults size to 0. Raise error on invalid size inputs. 7 | Attribute position which takes a default (0, 0) tuple. 8 | Methods Getter and Setter properties for size and position. 9 | Method area returns size of area of the square. 10 | Method my_print prints the square using "#", moved over left and top using 11 | position tuple. 12 | Method __repr__ should return the string to print out the square. 13 | """ 14 | 15 | 16 | class Square: 17 | """A class that defines a square by size, which defaults 0. 18 | Also defines position using a tuple, which defaults (0, 0). 19 | Square can also get area, and print square using '#'. 20 | When printing, using position, offset on top and left. 21 | """ 22 | def __init__(self, size=0, position=(0, 0)): 23 | self.size = size 24 | self.position = position 25 | 26 | @property 27 | def size(self): 28 | return self.__size 29 | 30 | @size.setter 31 | def size(self, size): 32 | if type(size) != int: 33 | raise TypeError("size must be an integer") 34 | if size < 0: 35 | raise ValueError("size must be >= 0") 36 | self.__size = size 37 | 38 | @property 39 | def position(self): 40 | return self.__position 41 | 42 | @position.setter 43 | def position(self, value): 44 | if type(value) != tuple or len(value) != 2 or \ 45 | not all([type(i) == int for i in value]): 46 | raise TypeError("position must be a tuple of 2 positive integers") 47 | self.__position = value 48 | 49 | def __repr__(self): 50 | return (self.get_str()) 51 | 52 | def area(self): 53 | return self.__size * self.__size 54 | 55 | def get_str(self): 56 | total = "" 57 | if self.__size is 0: 58 | total += "\n" 59 | return total 60 | for i in range(self.__position[1]): 61 | total += "\n" 62 | for i in range(self.__size): 63 | total += (" " * self.__position[0]) 64 | total += ("#" * self.__size) 65 | if i is not (self.__size - 1): 66 | total += "\n" 67 | return total 68 | 69 | def my_print(self): 70 | print(self.get_str()) 71 | -------------------------------------------------------------------------------- /0x07-python-classes/102-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This is the "Square" module. 4 | 5 | This module provides a simple Square class with initialize size. 6 | Defaults size to 0. Raise error on invalid size inputs. 7 | Methods Getter and Setter properties for size. 8 | Method area returns size of area of the square. 9 | Methods __lt__, __le__, __eq__, __ne__, __gt__, __ge__ allow 10 | comparisons between Square objects and their sizes. 11 | """ 12 | 13 | 14 | class Square: 15 | """A class that defines a square by size and can compute area""" 16 | def __init__(self, size=0): 17 | self.size = size 18 | 19 | @property 20 | def size(self): 21 | return self.__size 22 | 23 | @size.setter 24 | def size(self, size): 25 | if type(size) != int: 26 | raise TypeError("size must be an integer") 27 | if size < 0: 28 | raise ValueError("size must be >= 0") 29 | self.__size = size 30 | 31 | def area(self): 32 | return self.__size * self.__size 33 | 34 | def __lt__(self, other): 35 | return self.__size < other.size 36 | 37 | def __le__(self, other): 38 | return self.__size <= other.size 39 | 40 | def __eq__(self, other): 41 | return self.__size == other.size 42 | 43 | def __ne__(self, other): 44 | return self.__size != other.size 45 | 46 | def __gt__(self, other): 47 | return self.__size > other.size 48 | 49 | def __ge__(self, other): 50 | return self.__size >= other.size 51 | -------------------------------------------------------------------------------- /0x07-python-classes/103-magic_class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import dis 3 | import math 4 | 5 | 6 | class MagicClass: 7 | def __init__(self, radius=0): 8 | self.__radius = 0 9 | 10 | if type(radius) is not int and type(radius) is not float: 11 | raise TypeError("radius must be a number") 12 | self.__radius = radius 13 | 14 | @property 15 | def radius(self): 16 | return self.__radius 17 | 18 | def area(self): 19 | return self.__radius ** 2 * math.pi 20 | 21 | def circumference(self): 22 | return 2 * math.pi * self.__radius 23 | -------------------------------------------------------------------------------- /0x07-python-classes/2-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This is the "Square" module. 4 | 5 | This module provides a simple Square class with initialize size. 6 | Size defaults to 0. Raise errors on invalid inputs. 7 | """ 8 | 9 | 10 | class Square: 11 | """A class that defines a square by size""" 12 | def __init__(self, size=0): 13 | if type(size) != int: 14 | raise TypeError("size must be an integer") 15 | if size < 0: 16 | raise ValueError("size must be >= 0") 17 | self.__size = size 18 | -------------------------------------------------------------------------------- /0x07-python-classes/3-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This is the "Square" module. 4 | 5 | This module provides a simple Square class with initialize size. 6 | Defaults size to 0. Raise error on invalid size inputs. 7 | Method area returns size of area of the square. 8 | """ 9 | 10 | 11 | class Square: 12 | """A class that defines a square by size and can compute area""" 13 | def __init__(self, size=0): 14 | if type(size) != int: 15 | raise TypeError("size must be an integer") 16 | if size < 0: 17 | raise ValueError("size must be >= 0") 18 | self.__size = size 19 | 20 | def area(self): 21 | return self.__size * self.__size 22 | -------------------------------------------------------------------------------- /0x07-python-classes/4-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This is the "Square" module. 4 | 5 | This module provides a simple Square class with initialize size. 6 | Defaults size to 0. Raise error on invalid size inputs. 7 | Methods Getter and Setter properties for size. 8 | Method area returns size of area of the square. 9 | """ 10 | 11 | 12 | class Square: 13 | """A class that defines a square by size and can compute area""" 14 | def __init__(self, size=0): 15 | self.size = size 16 | 17 | @property 18 | def size(self): 19 | return self.__size 20 | 21 | @size.setter 22 | def size(self, size): 23 | if type(size) != int: 24 | raise TypeError("size must be an integer") 25 | if size < 0: 26 | raise ValueError("size must be >= 0") 27 | self.__size = size 28 | 29 | def area(self): 30 | return self.__size * self.__size 31 | -------------------------------------------------------------------------------- /0x07-python-classes/5-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This is the "Square" module. 4 | 5 | This module provides a simple Square class with initialize size. 6 | Defaults size to 0. Raise error on invalid size inputs. 7 | Methods Getter and Setter properties for size. 8 | Method area returns size of area of the square. 9 | Method my_print prints the square using "#". 10 | """ 11 | 12 | 13 | class Square: 14 | """A class that defines a square by size, which defaults 0. 15 | Square can also get area, and print square using '#'. 16 | """ 17 | def __init__(self, size=0): 18 | self.size = size 19 | 20 | @property 21 | def size(self): 22 | return self.__size 23 | 24 | @size.setter 25 | def size(self, size): 26 | if type(size) != int: 27 | raise TypeError("size must be an integer") 28 | if size < 0: 29 | raise ValueError("size must be >= 0") 30 | self.__size = size 31 | 32 | def area(self): 33 | return self.__size * self.__size 34 | 35 | def my_print(self): 36 | if self.__size is 0: 37 | print("") 38 | for i in range(self.__size): 39 | print("#" * self.__size) 40 | -------------------------------------------------------------------------------- /0x07-python-classes/6-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This is the "Square" module. 4 | 5 | This module provides a simple Square class with initialize size. 6 | Defaults size to 0. Raise error on invalid size inputs. 7 | Attribute position which takes a default (0, 0) tuple. 8 | Methods Getter and Setter properties for size and position. 9 | Method area returns size of area of the square. 10 | Method my_print prints the square using "#", moved over left and top using 11 | position tuple. 12 | """ 13 | 14 | 15 | class Square: 16 | """A class that defines a square by size, which defaults 0. 17 | Also defines position using a tuple, which defaults (0, 0). 18 | Square can also get area, and print square using '#'. 19 | When printing, using position, offset on top and left. 20 | """ 21 | def __init__(self, size=0, position=(0, 0)): 22 | self.size = size 23 | self.position = position 24 | 25 | @property 26 | def size(self): 27 | return self.__size 28 | 29 | @size.setter 30 | def size(self, size): 31 | if type(size) != int: 32 | raise TypeError("size must be an integer") 33 | if size < 0: 34 | raise ValueError("size must be >= 0") 35 | self.__size = size 36 | 37 | @property 38 | def position(self): 39 | return self.__position 40 | 41 | @position.setter 42 | def position(self, value): 43 | if type(value) != tuple or len(value) != 2 or \ 44 | not all([type(i) == int for i in value]) or \ 45 | not all([i >= 0 for i in value]): 46 | raise TypeError("position must be a tuple of 2 positive integers") 47 | self.__position = value 48 | 49 | def area(self): 50 | return self.__size * self.__size 51 | 52 | def my_print(self): 53 | if self.__size is 0: 54 | print("") 55 | return 56 | for i in range(self.__position[1]): 57 | print("") 58 | for i in range(self.__size): 59 | print(" " * self.__position[0], end="") 60 | print("#" * self.__size) 61 | -------------------------------------------------------------------------------- /0x07-python-classes/README.md: -------------------------------------------------------------------------------- 1 | # 0x07. Python - Classes and Objects -------------------------------------------------------------------------------- /0x07-python-classes/tests/102-square.txt: -------------------------------------------------------------------------------- 1 | The ``102-square`` module 2 | ==================== 3 | 4 | Using ``Square`` class 5 | ---------------------- 6 | 7 | This is a text file in reStructuredText format. 8 | First import ``Square`` from the ``102-square`` module: 9 | 10 | >>> Square = __import__("102-square").Square 11 | 12 | Now use it: 13 | 14 | >>> s1 = Square(10) 15 | >>> s1.__class__ 16 | 17 | 18 | >>> s1.size 19 | 10 20 | 21 | >>> s1.size = "a" 22 | Traceback (most recent call last): 23 | ... 24 | TypeError: size must be an integer 25 | 26 | >>> s1.size = 12 27 | >>> s1.size 28 | 12 29 | 30 | >>> s1.area() 31 | 144 32 | 33 | >>> s1.area(1) 34 | Traceback (most recent call last): 35 | ... 36 | TypeError: area() takes 1 positional argument but 2 were given 37 | 38 | >>> s1.__dict__ 39 | {'_Square__size': 12} 40 | 41 | >>> s1.size = -10 42 | Traceback (most recent call last): 43 | ... 44 | ValueError: size must be >= 0 45 | 46 | >>> s1.size 47 | 12 48 | 49 | >>> s2 = Square(5) 50 | >>> s2.__class__ 51 | 52 | 53 | >>> print(s1 < s2) 54 | False 55 | 56 | >>> s1.size = 5 57 | >>> print(s1 <= s2) 58 | True 59 | 60 | >>> print(s1 == s2) 61 | True 62 | 63 | >>> s1.size = 6 64 | >>> print(s1 == s2) 65 | False 66 | 67 | >>> print(s1 != s2) 68 | True 69 | 70 | >>> s1.size = 5 71 | >>> print(s1 != s2) 72 | False 73 | 74 | >>> print(s1 > s2) 75 | False 76 | 77 | >>> s2.size = 10 78 | >>> print(s1 > s2) 79 | False 80 | 81 | >>> s1.size = 10 82 | >>> print(s1 >= s2) 83 | True 84 | 85 | >>> s2.size = 11 86 | >>> print(s1 >= s2) 87 | False 88 | -------------------------------------------------------------------------------- /0x07-python-classes/tests/4-square.txt: -------------------------------------------------------------------------------- 1 | The ``4-square`` module 2 | ==================== 3 | 4 | Using ``Square`` class 5 | ---------------------- 6 | 7 | This is a text file in reStructuredText format. 8 | First import ``Square`` from the ``4-square`` module: 9 | 10 | >>> Square = __import__("4-square").Square 11 | 12 | Now use it: 13 | 14 | >>> s1 = Square(10) 15 | >>> s1.__class__ 16 | 17 | 18 | >>> s1.size 19 | 10 20 | 21 | >>> s1.size = "a" 22 | Traceback (most recent call last): 23 | ... 24 | TypeError: size must be an integer 25 | 26 | >>> s1.size = 12 27 | >>> s1.size 28 | 12 29 | 30 | >>> s1.area() 31 | 144 32 | 33 | >>> s1.area(1) 34 | Traceback (most recent call last): 35 | ... 36 | TypeError: area() takes 1 positional argument but 2 were given 37 | 38 | >>> s1.__dict__ 39 | {'_Square__size': 12} 40 | 41 | >>> s1.size = -10 42 | Traceback (most recent call last): 43 | ... 44 | ValueError: size must be >= 0 45 | 46 | >>> s1.size 47 | 12 48 | 49 | >>> def test_init_bad(tests): 50 | ... for test in tests: 51 | ... try: 52 | ... x = Square(test) 53 | ... except Exception as e: 54 | ... print("{}: {}".format(type(e).__name__, e)) 55 | ... 56 | 57 | >>> test_init_bad(["hello", [1, 2], {}, ("a", 1), 23.456, set(), test_init_bad]) 58 | TypeError: size must be an integer 59 | TypeError: size must be an integer 60 | TypeError: size must be an integer 61 | TypeError: size must be an integer 62 | TypeError: size must be an integer 63 | TypeError: size must be an integer 64 | TypeError: size must be an integer 65 | 66 | >>> s2 = Square() 67 | >>> print(type(s2)) 68 | 69 | 70 | >>> print(s2.size) 71 | 0 72 | 73 | >>> s2 = Square(3) 74 | >>> print(s2._Square__size) 75 | 3 76 | 77 | >>> x = Square() 78 | >>> def test_init_bad2(tests): 79 | ... for test in tests: 80 | ... try: 81 | ... x.size = test 82 | ... except Exception as e: 83 | ... print("{}: {}".format(type(e).__name__, e)) 84 | 85 | >>> test_init_bad2(["hello", [1, 2], {}, ("a", 1), 23.456, set(), test_init_bad2]) 86 | TypeError: size must be an integer 87 | TypeError: size must be an integer 88 | TypeError: size must be an integer 89 | TypeError: size must be an integer 90 | TypeError: size must be an integer 91 | TypeError: size must be an integer 92 | TypeError: size must be an integer 93 | -------------------------------------------------------------------------------- /0x08-python-more_classes/0-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This is the "Rectangle" module. 4 | 5 | This module provides a simple Rectangle class. 6 | """ 7 | 8 | 9 | class Rectangle: 10 | """A simple Rectangle class""" 11 | pass 12 | -------------------------------------------------------------------------------- /0x08-python-more_classes/1-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This is the "Rectangle" module. 4 | 5 | This module provides a simple Rectangle class with attribute width and height. 6 | Default values of both attributes are 0. 7 | """ 8 | 9 | 10 | class Rectangle: 11 | """A Rectangle class with attributes width and height""" 12 | def __init__(self, width=0, height=0): 13 | self.width = width 14 | self.height = height 15 | 16 | @property 17 | def width(self): 18 | return self.__width 19 | 20 | @width.setter 21 | def width(self, value): 22 | if type(value) is not int: 23 | raise TypeError('width must be an integer') 24 | if value < 0: 25 | raise ValueError('width must be >= 0') 26 | self.__width = value 27 | 28 | @property 29 | def height(self): 30 | return self.__height 31 | 32 | @height.setter 33 | def height(self, value): 34 | if type(value) is not int: 35 | raise TypeError('height must be an integer') 36 | if value < 0: 37 | raise ValueError('height must be >= 0') 38 | self.__height = value 39 | -------------------------------------------------------------------------------- /0x08-python-more_classes/2-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This is the "Rectangle" module. 4 | 5 | This module provides a simple Rectangle class. 6 | """ 7 | 8 | 9 | class Rectangle: 10 | """A Rectangle class with attributes width and height, and 11 | methods area and perimiter. 12 | """ 13 | def __init__(self, width=0, height=0): 14 | self.width = width 15 | self.height = height 16 | 17 | @property 18 | def width(self): 19 | return self.__width 20 | 21 | @width.setter 22 | def width(self, value): 23 | if type(value) is not int: 24 | raise TypeError("width must be an integer") 25 | if value < 0: 26 | raise ValueError("width must be >= 0") 27 | self.__width = value 28 | 29 | @property 30 | def height(self): 31 | return self.__height 32 | 33 | @height.setter 34 | def height(self, value): 35 | if type(value) is not int: 36 | raise TypeError("height must be an integer") 37 | if value < 0: 38 | raise ValueError("height must be >= 0") 39 | self.__height = value 40 | 41 | def area(self): 42 | return self.__width * self.__height 43 | 44 | def perimeter(self): 45 | if self.__width is 0 or self.__height is 0: 46 | return 0 47 | return (2 * self.__width) + (2 * self.__height) 48 | -------------------------------------------------------------------------------- /0x08-python-more_classes/3-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This is the "Rectangle" module. 4 | 5 | This module provides a simple Rectangle class. 6 | """ 7 | 8 | 9 | class Rectangle: 10 | """A Rectangle class with attributes width and height, and 11 | methods area, perimeter, print, and str. 12 | """ 13 | def __init__(self, width=0, height=0): 14 | self.width = width 15 | self.height = height 16 | 17 | @property 18 | def width(self): 19 | return self.__width 20 | 21 | @width.setter 22 | def width(self, value): 23 | if type(value) is not int: 24 | raise TypeError("width must be an integer") 25 | if value < 0: 26 | raise ValueError("width must be >= 0") 27 | self.__width = value 28 | 29 | @property 30 | def height(self): 31 | return self.__height 32 | 33 | @height.setter 34 | def height(self, value): 35 | if type(value) is not int: 36 | raise TypeError("height must be an integer") 37 | if value < 0: 38 | raise ValueError("height must be >= 0") 39 | self.__height = value 40 | 41 | def __str__(self): 42 | total = "" 43 | if self.__height == 0 or self.width == 0: 44 | return total 45 | for i in range(self.__height): 46 | total += ("#" * self.__width) 47 | if i is not self.__height - 1: 48 | total += "\n" 49 | return total 50 | 51 | def area(self): 52 | return self.__width * self.__height 53 | 54 | def perimeter(self): 55 | if self.__width is 0 or self.__height is 0: 56 | return 0 57 | return (2 * self.__width) + (2 * self.__height) 58 | -------------------------------------------------------------------------------- /0x08-python-more_classes/4-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This is the "Rectangle" module. 4 | 5 | This module provides a Rectangle class. 6 | """ 7 | 8 | 9 | class Rectangle: 10 | """A Rectangle class with attributes width and height, and 11 | methods area, perimeter, print, str, and repr. 12 | """ 13 | def __init__(self, width=0, height=0): 14 | self.width = width 15 | self.height = height 16 | 17 | @property 18 | def width(self): 19 | return self.__width 20 | 21 | @width.setter 22 | def width(self, value): 23 | if type(value) is not int: 24 | raise TypeError("width must be an integer") 25 | if value < 0: 26 | raise ValueError("width must be >= 0") 27 | self.__width = value 28 | 29 | @property 30 | def height(self): 31 | return self.__height 32 | 33 | @height.setter 34 | def height(self, value): 35 | if type(value) is not int: 36 | raise TypeError("height must be an integer") 37 | if value < 0: 38 | raise ValueError("height must be >= 0") 39 | self.__height = value 40 | 41 | def __repr__(self): 42 | return "Rectangle({:d}, {:d})".format(self.__width, self.__height) 43 | 44 | def __str__(self): 45 | total = "" 46 | for i in range(self.__height): 47 | total += ("#" * self.__width) 48 | if i is not self.__height - 1: 49 | total += "\n" 50 | return total 51 | 52 | def area(self): 53 | return self.__width * self.__height 54 | 55 | def perimeter(self): 56 | if self.__width is 0 or self.__height is 0: 57 | return 0 58 | return (2 * self.__width) + (2 * self.__height) 59 | -------------------------------------------------------------------------------- /0x08-python-more_classes/5-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This is the "Rectangle" module. 4 | 5 | This module provides a Rectangle class. 6 | """ 7 | 8 | 9 | class Rectangle: 10 | """A Rectangle class with attributes width and height, and 11 | methods area, perimeter, print, str, repr, and del. 12 | """ 13 | def __init__(self, width=0, height=0): 14 | self.width = width 15 | self.height = height 16 | 17 | @property 18 | def width(self): 19 | return self.__width 20 | 21 | @width.setter 22 | def width(self, value): 23 | if type(value) is not int: 24 | raise TypeError("width must be an integer") 25 | if value < 0: 26 | raise ValueError("width must be >= 0") 27 | self.__width = value 28 | 29 | @property 30 | def height(self): 31 | return self.__height 32 | 33 | @height.setter 34 | def height(self, value): 35 | if type(value) is not int: 36 | raise TypeError("height must be an integer") 37 | if value < 0: 38 | raise ValueError("height must be >= 0") 39 | self.__height = value 40 | 41 | def __repr__(self): 42 | return "Rectangle({:d}, {:d})".format(self.__width, self.__height) 43 | 44 | def __str__(self): 45 | total = "" 46 | for i in range(self.__height): 47 | total += ("#" * self.__width) 48 | if i is not self.__height - 1: 49 | total += "\n" 50 | return total 51 | 52 | def __del__(self): 53 | print("Bye rectangle...") 54 | 55 | def area(self): 56 | return self.__width * self.__height 57 | 58 | def perimeter(self): 59 | if self.__width is 0 or self.__height is 0: 60 | return 0 61 | return (2 * self.__width) + (2 * self.__height) 62 | -------------------------------------------------------------------------------- /0x08-python-more_classes/6-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This is the "Rectangle" module. 4 | 5 | This module provides a Rectangle class. 6 | """ 7 | 8 | 9 | class Rectangle: 10 | """A Rectangle class with attributes width and height, 11 | methods area, perimeter, print, str, repr, and del, and 12 | class attribute number_of_instances that keeps track of # of instances. 13 | """ 14 | 15 | number_of_instances = 0 16 | 17 | def __init__(self, width=0, height=0): 18 | self.width = width 19 | self.height = height 20 | Rectangle.number_of_instances += 1 21 | 22 | @property 23 | def width(self): 24 | return self.__width 25 | 26 | @width.setter 27 | def width(self, value): 28 | if type(value) is not int: 29 | raise TypeError("width must be an integer") 30 | if value < 0: 31 | raise ValueError("width must be >= 0") 32 | self.__width = value 33 | 34 | @property 35 | def height(self): 36 | return self.__height 37 | 38 | @height.setter 39 | def height(self, value): 40 | if type(value) is not int: 41 | raise TypeError("height must be an integer") 42 | if value < 0: 43 | raise ValueError("height must be >= 0") 44 | self.__height = value 45 | 46 | def __repr__(self): 47 | return "Rectangle({:d}, {:d})".format(self.__width, self.__height) 48 | 49 | def __str__(self): 50 | total = "" 51 | for i in range(self.__height): 52 | total += ("#" * self.__width) 53 | if i is not self.__height - 1: 54 | total += "\n" 55 | return total 56 | 57 | def __del__(self): 58 | print("Bye rectangle...") 59 | Rectangle.number_of_instances -= 1 60 | 61 | def area(self): 62 | return self.__width * self.__height 63 | 64 | def perimeter(self): 65 | if self.__width is 0 or self.__height is 0: 66 | return 0 67 | return (2 * self.__width) + (2 * self.__height) 68 | -------------------------------------------------------------------------------- /0x08-python-more_classes/7-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This is the "Rectangle" module. 4 | 5 | This module provides a Rectangle class. 6 | """ 7 | 8 | 9 | class Rectangle: 10 | """A Rectangle class with attributes width and height, 11 | methods area, perimeter, print, str, repr, and del, and 12 | class attribute number_of_instances that keeps track of # of instances, 13 | and class attribute print_symbol which is used as symbol for printing. 14 | """ 15 | 16 | number_of_instances = 0 17 | print_symbol = "#" 18 | 19 | def __init__(self, width=0, height=0): 20 | self.width = width 21 | self.height = height 22 | Rectangle.number_of_instances += 1 23 | 24 | @property 25 | def width(self): 26 | return self.__width 27 | 28 | @width.setter 29 | def width(self, value): 30 | if type(value) is not int: 31 | raise TypeError("width must be an integer") 32 | if value < 0: 33 | raise ValueError("width must be >= 0") 34 | self.__width = value 35 | 36 | @property 37 | def height(self): 38 | return self.__height 39 | 40 | @height.setter 41 | def height(self, value): 42 | if type(value) is not int: 43 | raise TypeError("height must be an integer") 44 | if value < 0: 45 | raise ValueError("height must be >= 0") 46 | self.__height = value 47 | 48 | def __repr__(self): 49 | return "Rectangle({:d}, {:d})".format(self.__width, self.__height) 50 | 51 | def __str__(self): 52 | total = "" 53 | for i in range(self.__height): 54 | for j in range(self.__width): 55 | try: 56 | total += str(self.print_symbol) 57 | except Exception: 58 | total += type(self).print_symbol 59 | if i is not self.__height - 1: 60 | total += "\n" 61 | return total 62 | 63 | def __del__(self): 64 | print("Bye rectangle...") 65 | Rectangle.number_of_instances -= 1 66 | 67 | def area(self): 68 | return self.__width * self.__height 69 | 70 | def perimeter(self): 71 | if self.__width is 0 or self.__height is 0: 72 | return 0 73 | return (2 * self.__width) + (2 * self.__height) 74 | -------------------------------------------------------------------------------- /0x08-python-more_classes/8-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This is the "Rectangle" module. 4 | 5 | This module provides a Rectangle class. 6 | """ 7 | 8 | 9 | class Rectangle: 10 | """A Rectangle class with attributes width and height, 11 | methods area, perimeter, print, str, repr, and del, and 12 | class attribute number_of_instances that keeps track of # of instances, 13 | class attribute print_symbol which is used as symbol for printing, 14 | and static method bigger_or_equal that returns biggest rectangle. 15 | """ 16 | 17 | number_of_instances = 0 18 | print_symbol = "#" 19 | 20 | def __init__(self, width=0, height=0): 21 | self.width = width 22 | self.height = height 23 | Rectangle.number_of_instances += 1 24 | 25 | @property 26 | def width(self): 27 | return self.__width 28 | 29 | @width.setter 30 | def width(self, value): 31 | if type(value) is not int: 32 | raise TypeError("width must be an integer") 33 | if value < 0: 34 | raise ValueError("width must be >= 0") 35 | self.__width = value 36 | 37 | @property 38 | def height(self): 39 | return self.__height 40 | 41 | @height.setter 42 | def height(self, value): 43 | if type(value) is not int: 44 | raise TypeError("height must be an integer") 45 | if value < 0: 46 | raise ValueError("height must be >= 0") 47 | self.__height = value 48 | 49 | @staticmethod 50 | def bigger_or_equal(rect_1, rect_2): 51 | if not isinstance(rect_1, Rectangle): 52 | raise TypeError("rect_1 must be an instance of Rectangle") 53 | if not isinstance(rect_2, Rectangle): 54 | raise TypeError("rect_2 must be an instance of Rectangle") 55 | if rect_1.area() >= rect_2.area(): 56 | return rect_1 57 | else: 58 | return rect_2 59 | 60 | def __repr__(self): 61 | return "Rectangle({:d}, {:d})".format(self.__width, self.__height) 62 | 63 | def __str__(self): 64 | total = "" 65 | for i in range(self.__height): 66 | for j in range(self.__width): 67 | try: 68 | total += str(self.print_symbol) 69 | except Exception: 70 | total += type(self).print_symbol 71 | if i is not self.__height - 1: 72 | total += "\n" 73 | return total 74 | 75 | def __del__(self): 76 | print("Bye rectangle...") 77 | Rectangle.number_of_instances -= 1 78 | 79 | def area(self): 80 | return self.__width * self.__height 81 | 82 | def perimeter(self): 83 | if self.__width is 0 or self.__height is 0: 84 | return 0 85 | return (2 * self.__width) + (2 * self.__height) 86 | -------------------------------------------------------------------------------- /0x08-python-more_classes/9-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This is the "Rectangle" module. 4 | 5 | This module provides a Rectangle class. 6 | """ 7 | 8 | 9 | class Rectangle: 10 | """A Rectangle class with attributes width and height, 11 | methods area, perimeter, print, str, repr, and del, and 12 | class attribute number_of_instances that keeps track of # of instances, 13 | class attribute print_symbol which is used as symbol for printing, 14 | static method bigger_or_equal that returns biggest rectangle, 15 | and class method square that returns a new Rectangle. 16 | """ 17 | number_of_instances = 0 18 | print_symbol = "#" 19 | 20 | def __init__(self, width=0, height=0): 21 | self.width = width 22 | self.height = height 23 | Rectangle.number_of_instances += 1 24 | 25 | @property 26 | def width(self): 27 | return self.__width 28 | 29 | @width.setter 30 | def width(self, value): 31 | if type(value) is not int: 32 | raise TypeError("width must be an integer") 33 | if value < 0: 34 | raise ValueError("width must be >= 0") 35 | self.__width = value 36 | 37 | @property 38 | def height(self): 39 | return self.__height 40 | 41 | @height.setter 42 | def height(self, value): 43 | if type(value) is not int: 44 | raise TypeError("height must be an integer") 45 | if value < 0: 46 | raise ValueError("height must be >= 0") 47 | self.__height = value 48 | 49 | @staticmethod 50 | def bigger_or_equal(rect_1, rect_2): 51 | if not isinstance(rect_1, Rectangle): 52 | raise TypeError("rect_1 must be an instance of Rectangle") 53 | if not isinstance(rect_2, Rectangle): 54 | raise TypeError("rect_2 must be an instance of Rectangle") 55 | if rect_1.area() >= rect_2.area(): 56 | return rect_1 57 | else: 58 | return rect_2 59 | 60 | @classmethod 61 | def square(cls, size=0): 62 | return Rectangle(size, size) 63 | 64 | def __repr__(self): 65 | return "Rectangle({:d}, {:d})".format(self.__width, self.__height) 66 | 67 | def __str__(self): 68 | total = "" 69 | for i in range(self.__height): 70 | for j in range(self.__width): 71 | try: 72 | total += str(self.print_symbol) 73 | except Exception: 74 | total += type(self).print_symbol 75 | if i is not self.__height - 1: 76 | total += "\n" 77 | return total 78 | 79 | def __del__(self): 80 | print("Bye rectangle...") 81 | Rectangle.number_of_instances -= 1 82 | 83 | def area(self): 84 | return self.__width * self.__height 85 | 86 | def perimeter(self): 87 | if self.__width is 0 or self.__height is 0: 88 | return 0 89 | return (2 * self.__width) + (2 * self.__height) 90 | -------------------------------------------------------------------------------- /0x08-python-more_classes/README.md: -------------------------------------------------------------------------------- 1 | # 0x08. Python - More Classes and Objects -------------------------------------------------------------------------------- /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.counter = getattr(magic_string, 'counter', 0) + 1 4 | return ", ".join(["Holberton" for i in range(magic_string.counter)]) 5 | -------------------------------------------------------------------------------- /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 | 0 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/104-line3.txt: -------------------------------------------------------------------------------- 1 | No 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/11-answer.txt: -------------------------------------------------------------------------------- 1 | False 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/12-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/13-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/14-answer.txt: -------------------------------------------------------------------------------- 1 | [1, 2, 3, 4] 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/15-answer.txt: -------------------------------------------------------------------------------- 1 | [1, 2, 3] 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/16-answer.txt: -------------------------------------------------------------------------------- 1 | 1 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/17-answer.txt: -------------------------------------------------------------------------------- 1 | [1, 2, 3, 4] 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/18-answer.txt: -------------------------------------------------------------------------------- 1 | [1, 2, 3] 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/19-copy_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def copy_list(l): 3 | return l[:] 4 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/2-answer.txt: -------------------------------------------------------------------------------- 1 | No 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/20-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/21-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/22-answer.txt: -------------------------------------------------------------------------------- 1 | No 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/23-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/24-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/25-answer.txt: -------------------------------------------------------------------------------- 1 | False 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/26-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/27-answer.txt: -------------------------------------------------------------------------------- 1 | No 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/28-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/3-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/4-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/5-answer.txt: -------------------------------------------------------------------------------- 1 | No 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/6-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/7-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/8-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/9-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/README.md: -------------------------------------------------------------------------------- 1 | # 0x09. Python - Everything is object -------------------------------------------------------------------------------- /0x0A-python-inheritance/0-lookup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def lookup(obj): 3 | return dir(obj) 4 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/1-my_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | class MyList(list): 3 | def print_sorted(self): 4 | print(sorted(self)) 5 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/10-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('9-rectangle').Rectangle 3 | 4 | 5 | class Square(Rectangle): 6 | def __init__(self, size): 7 | super().__init__(size, size) 8 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/100-my_int.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | class MyInt(int): 3 | def __eq__(self, other): 4 | return self - other != 0 5 | 6 | def __ne__(self, other): 7 | return self - other == 0 8 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/101-add_attribute.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def add_attribute(obj, a, v): 3 | res = getattr(obj, "__doc__", None) 4 | if res is None: 5 | setattr(obj, a, v) 6 | else: 7 | raise TypeError("can't add new attribute") 8 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/11-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | Rectangle = __import__('9-rectangle').Rectangle 3 | 4 | 5 | class Square(Rectangle): 6 | def __init__(self, size): 7 | super().__init__(size, size) 8 | self.__size = size 9 | 10 | def __str__(self): 11 | return "[Square] {:d}/{:d}".format(self.__size, self.__size) 12 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/2-is_same_class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def is_same_class(obj, a_class): 3 | return type(obj) == a_class 4 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/3-is_kind_of_class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def is_kind_of_class(obj, a_class): 3 | return isinstance(obj, a_class) 4 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/4-inherits_from.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def inherits_from(obj, a_class): 3 | if (type(obj) != a_class): 4 | return issubclass(type(obj), a_class) 5 | return False 6 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/5-base_geometry.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | class BaseGeometry: 3 | pass 4 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/6-base_geometry.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | class BaseGeometry: 3 | def area(self): 4 | raise Exception("area() is not implemented") 5 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/7-base_geometry.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | class BaseGeometry: 3 | def area(self): 4 | raise Exception("area() is not implemented") 5 | 6 | def integer_validator(self, name, value): 7 | if type(value) is not int: 8 | raise TypeError("{} must be an integer".format(name)) 9 | if value <= 0: 10 | raise ValueError("{} must be greater than 0".format(name)) 11 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/8-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | BaseGeometry = __import__("7-base_geometry").BaseGeometry 3 | 4 | 5 | class Rectangle(BaseGeometry): 6 | def __init__(self, width, height): 7 | self.integer_validator("width", width) 8 | self.integer_validator("height", height) 9 | self.__width = width 10 | self.__height = height 11 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/9-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | BaseGeometry = __import__('7-base_geometry').BaseGeometry 3 | 4 | 5 | class Rectangle(BaseGeometry): 6 | def __init__(self, width, height): 7 | self.integer_validator("width", width) 8 | self.integer_validator("height", height) 9 | self.__width = width 10 | self.__height = height 11 | 12 | def area(self): 13 | return self.__width * self.__height 14 | 15 | def __str__(self): 16 | return "[Rectangle] {:d}/{:d}".format(self.__width, self.__height) 17 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/README.md: -------------------------------------------------------------------------------- 1 | # 0x0A. Python - Inheritance -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/1-my_list.txt: -------------------------------------------------------------------------------- 1 | The ``Print Sorted List`` module 2 | ================================ 3 | 4 | Using ``MyList`` 5 | ---------------- 6 | 7 | This is an example text file in reStructuredText format. 8 | First import ``MyList`` from the ``1-my_list`` module: 9 | 10 | >>> MyList = __import__("1-my_list").MyList 11 | 12 | Now use it: 13 | 14 | >>> a = MyList() 15 | >>> a 16 | [] 17 | 18 | >>> a.append(1) 19 | >>> a 20 | [1] 21 | 22 | >>> a.append(5) 23 | >>> a.append(3) 24 | >>> a 25 | [1, 5, 3] 26 | 27 | >>> a.print_sorted() 28 | [1, 3, 5] 29 | 30 | >>> a.append("b") 31 | >>> a 32 | [1, 5, 3, 'b'] 33 | 34 | >>> a.print_sorted() 35 | Traceback (most recent call last): 36 | ... 37 | TypeError: unorderable types: str() < int() 38 | 39 | >>> b = MyList() 40 | >>> b.append(5) 41 | >>> b.append(-2) 42 | >>> b.append(0) 43 | >>> b.append(3) 44 | >>> b 45 | [5, -2, 0, 3] 46 | 47 | >>> b.print_sorted() 48 | [-2, 0, 3, 5] 49 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/7-base_geometry.txt: -------------------------------------------------------------------------------- 1 | The ``Base Geometry`` module 2 | ============================ 3 | 4 | Using ``BaseGeometry`` 5 | ---------------------- 6 | 7 | This is an example text file in reStructuredText format. 8 | First import ``BaseGeometry`` from the ``7-base_geometry`` module: 9 | 10 | >>> BaseGeometry = __import__("7-base_geometry").BaseGeometry 11 | 12 | Now use it: 13 | 14 | >>> bg = BaseGeometry() 15 | >>> type(bg) 16 | 17 | 18 | 19 | This class should define 2 functions 20 | 21 | ``area`` 22 | >>> 'area' in dir(BaseGeometry) 23 | True 24 | 25 | ``integer_validator`` 26 | >>> 'integer_validator' in dir(BaseGeometry) 27 | True 28 | 29 | Should test publicity of methods ? 30 | 31 | And no instance attributes or methods 32 | >>> dir(bg) == dir(BaseGeometry) 33 | True 34 | 35 | Test ``area`` 36 | ------------- 37 | It is not implemented 38 | >>> bg.area() 39 | Traceback (most recent call last): 40 | Exception: area() is not implemented 41 | 42 | Test ``integer_validator`` 43 | -------------------------- 44 | Integer takes in 2 arguments 45 | 46 | >>> bg.integer_validator() 47 | Traceback (most recent call last): 48 | TypeError: integer_validator() missing 2 required positional arguments: 'name' and 'value' 49 | 50 | >>> bg.integer_validator(1) 51 | Traceback (most recent call last): 52 | TypeError: integer_validator() missing 1 required positional argument: 'value' 53 | 54 | >>> bg.integer_validator(1, 2, 3) 55 | Traceback (most recent call last): 56 | TypeError: integer_validator() takes 3 positional arguments but 4 were given 57 | 58 | 59 | Test for type 60 | >>> def test_i(tests=[]): 61 | ... for test in tests: 62 | ... try: 63 | ... bg.integer_validator("name", test) 64 | ... except Exception as e: 65 | ... print("[{}] {} for type {}".format(e.__class__.__name__, e, type(test))) 66 | 67 | >>> tests = [True, 1.24, -76.87, set(), [1, 2], "a string", {"a":1}, ("11", 3), test_i, bg, BaseGeometry, None] 68 | >>> test_i(tests) 69 | [TypeError] name must be an integer for type 70 | [TypeError] name must be an integer for type 71 | [TypeError] name must be an integer for type 72 | [TypeError] name must be an integer for type 73 | [TypeError] name must be an integer for type 74 | [TypeError] name must be an integer for type 75 | [TypeError] name must be an integer for type 76 | [TypeError] name must be an integer for type 77 | [TypeError] name must be an integer for type 78 | [TypeError] name must be an integer for type 79 | [TypeError] name must be an integer for type 80 | [TypeError] name must be an integer for type 81 | 82 | Test for sign 83 | >>> bg.integer_validator("name", -23) 84 | Traceback (most recent call last): 85 | ValueError: name must be greater than 0 86 | 87 | >>> bg.integer_validator("name", 0) 88 | Traceback (most recent call last): 89 | ValueError: name must be greater than 0 90 | 91 | When it works it does not return anything 92 | >>> bg.integer_validator("name", 3) 93 | -------------------------------------------------------------------------------- /0x0B-python-input_output/0-read_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def read_file(filename=""): 3 | with open(filename, encoding="utf-8") as fd: 4 | for line in fd: 5 | print(line, end="") 6 | -------------------------------------------------------------------------------- /0x0B-python-input_output/1-number_of_lines.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def number_of_lines(filename=""): 3 | count = 0 4 | with open(filename, encoding="utf-8") as fd: 5 | for line in fd: 6 | count += 1 7 | return count 8 | -------------------------------------------------------------------------------- /0x0B-python-input_output/2-read_lines.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def read_lines(filename="", nb_lines=0): 3 | with open(filename, encoding="utf-8") as fd: 4 | if (nb_lines == 0): 5 | print(fd.read(), end="") 6 | else: 7 | for line in fd: 8 | if (nb_lines > 0): 9 | print(line, end="") 10 | nb_lines -= 1 11 | -------------------------------------------------------------------------------- /0x0B-python-input_output/3-write_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def write_file(filename="", text=""): 3 | with open(filename, mode="w", encoding="utf-8") as fd: 4 | fd.write(text) 5 | return len(text) 6 | -------------------------------------------------------------------------------- /0x0B-python-input_output/4-append_write.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def append_write(filename="", text=""): 3 | with open(filename, mode="a", encoding="utf-8") as fd: 4 | fd.write(text) 5 | return len(text) 6 | -------------------------------------------------------------------------------- /0x0B-python-input_output/5-to_json_string.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import json 3 | 4 | 5 | def to_json_string(my_obj): 6 | return json.dumps(my_obj) 7 | -------------------------------------------------------------------------------- /0x0B-python-input_output/6-from_json_string.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import json 3 | 4 | 5 | def from_json_string(my_str): 6 | return json.loads(my_str) 7 | -------------------------------------------------------------------------------- /0x0B-python-input_output/7-save_to_json_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import json 3 | 4 | 5 | def save_to_json_file(my_obj, filename): 6 | with open(filename, mode="w", encoding="utf-8") as fd: 7 | fd.write(json.dumps(my_obj)) 8 | -------------------------------------------------------------------------------- /0x0B-python-input_output/8-load_from_json_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import json 3 | 4 | 5 | def load_from_json_file(filename): 6 | with open(filename, encoding="utf-8") as fd: 7 | return json.load(fd) 8 | -------------------------------------------------------------------------------- /0x0B-python-input_output/9-add_item.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import json 3 | import sys 4 | import os.path 5 | 6 | save_to_json_file = __import__('7-save_to_json_file').save_to_json_file 7 | load_from_json_file = __import__('8-load_from_json_file').load_from_json_file 8 | 9 | filename = "add_item.json" 10 | if os.path.isfile(filename): 11 | obj = load_from_json_file(filename) 12 | else: 13 | obj = [] 14 | obj.extend(sys.argv[1:]) 15 | save_to_json_file(obj, filename) 16 | -------------------------------------------------------------------------------- /0x0B-python-input_output/README.md: -------------------------------------------------------------------------------- 1 | # 0x0B. Python - Input/Output -------------------------------------------------------------------------------- /0x0C-SQL_introduction/0-list_databases.sql: -------------------------------------------------------------------------------- 1 | -- Write a script that lists all databases of my MySQL server 2 | SHOW DATABASES; 3 | 4 | -------------------------------------------------------------------------------- /0x0C-SQL_introduction/1-create_database_if_missing.sql: -------------------------------------------------------------------------------- 1 | -- Write a script that creates the database 'hbtn_0c_0' in MySQL server 2 | -- If database already exists, the script should not fail 3 | -- Not allowed to use SELECT or SHOW 4 | CREATE DATABASE IF NOT EXISTS hbtn_0c_0; 5 | -------------------------------------------------------------------------------- /0x0C-SQL_introduction/10-top_score.sql: -------------------------------------------------------------------------------- 1 | -- List all records in 'second_table' of db 'hbtn_0c_0' 2 | -- Results should display both score and name 3 | -- Records should be ordered by score (top first) 4 | -- db name will be passed as arg to mysql cmd 5 | SELECT score, name FROM second_table 6 | ORDER BY score DESC; 7 | -------------------------------------------------------------------------------- /0x0C-SQL_introduction/100-move_to_utf8.sql: -------------------------------------------------------------------------------- 1 | -- Convert 'hbtn_0c_0' to utf8mb4, collate utf8mb4_unicode_ci 2 | -- Convert db 'hbtn_0c_0' 3 | ALTER DATABASE hbtn_0c_0 4 | CHARACTER SET = utf8mb4 5 | COLLATE = utf8mb4_unicode_ci; 6 | 7 | -- Convert table 'first_table' 8 | USE hbtn_0c_0; 9 | ALTER TABLE first_table 10 | CONVERT TO CHARACTER SET utf8mb4 11 | COLLATE utf8mb4_unicode_ci; 12 | 13 | -- Convert field 'name' in 'first_table' 14 | USE hbtn_0c_0; 15 | ALTER TABLE first_table 16 | CHANGE name name VARCHAR(256) 17 | CHARACTER SET utf8mb4 18 | COLLATE utf8mb4_unicode_ci; 19 | -------------------------------------------------------------------------------- /0x0C-SQL_introduction/101-avg_temperatures.sql: -------------------------------------------------------------------------------- 1 | -- From imported db weather info, display average temp by city 2 | -- ordered by temperature descending 3 | SELECT city, AVG(value) AS avg_temp 4 | FROM temperatures 5 | GROUP BY city 6 | ORDER BY avg_temp DESC; 7 | -------------------------------------------------------------------------------- /0x0C-SQL_introduction/102-top_city.sql: -------------------------------------------------------------------------------- 1 | -- Using temperature data set from ex.18 2 | -- Display top 3 cities by temperature during July and August 3 | -- ordered by temperature descending 4 | SELECT city, AVG(value) AS avg_temp 5 | FROM temperatures 6 | WHERE month = 7 OR month = 8 7 | GROUP BY city 8 | ORDER BY avg_temp DESC 9 | LIMIT 3; 10 | -------------------------------------------------------------------------------- /0x0C-SQL_introduction/103-max_state.sql: -------------------------------------------------------------------------------- 1 | -- Using the same data from ex.18 2 | -- Display the max temperature of each state 3 | SELECT state, MAX(value) AS max_temp 4 | FROM temperatures 5 | GROUP BY state 6 | LIMIT 3; 7 | -------------------------------------------------------------------------------- /0x0C-SQL_introduction/11-best_score.sql: -------------------------------------------------------------------------------- 1 | -- List all records with score >= 10 in 'second_table' of db 'hbtn_0c_0' 2 | -- Results should display both score and name 3 | -- Records should be ordered by score (top first) 4 | -- db name will be passed as arg to mysql cmd 5 | SELECT score, name FROM second_table 6 | WHERE score >= 10 7 | ORDER BY score DESC; 8 | -------------------------------------------------------------------------------- /0x0C-SQL_introduction/12-no_cheating.sql: -------------------------------------------------------------------------------- 1 | -- Update score of Bob to 10 from 'second_table' of db 'hbtn_0c_0' 2 | -- Not allowed to use Bob's id value, only name field 3 | -- db name will be passed as arg to mysql cmd 4 | UPDATE second_table 5 | SET score = 10 6 | WHERE name = "Bob"; 7 | -------------------------------------------------------------------------------- /0x0C-SQL_introduction/13-change_class.sql: -------------------------------------------------------------------------------- 1 | -- Remove all records with score <= 5 in 'second_table' of 'hbtn_0c_0' 2 | -- db name will be passed as arg to mysql cmd 3 | DELETE FROM second_table 4 | WHERE score <= 5; 5 | -------------------------------------------------------------------------------- /0x0C-SQL_introduction/14-average.sql: -------------------------------------------------------------------------------- 1 | -- Computer score average of all records in 'second_table' of 'hbtn_0c_0' 2 | -- Result column name should be 'average' 3 | -- db name will be passed as arg of mysql cmd 4 | SELECT AVG(score) AS average FROM second_table; 5 | -------------------------------------------------------------------------------- /0x0C-SQL_introduction/15-groups.sql: -------------------------------------------------------------------------------- 1 | -- List number of records with same score in 'second_table' 2 | -- of db 'hbtn_0c_0' 3 | -- Result should display the score and 4 | -- number of records for this score with label 'number' 5 | -- List should be sorted by number of records descending 6 | -- db name will be passed as arg to mysql cmd 7 | SELECT score, COUNT(1) AS number FROM second_table 8 | GROUP BY score 9 | ORDER BY number DESC; 10 | -------------------------------------------------------------------------------- /0x0C-SQL_introduction/16-no_link.sql: -------------------------------------------------------------------------------- 1 | -- List all records of 'second_table' of db 'hbtn_0c_0' 2 | -- Don't list rows without a 'name' value 3 | -- Results should display score and name 4 | -- Records should be listed descending score 5 | -- db name will be passed as arg to mysql cmd 6 | -- Not allowed to use JOIN or UNION 7 | SELECT score, name 8 | FROM second_table 9 | HAVING name IS NOT NULL 10 | ORDER BY score DESC; 11 | -------------------------------------------------------------------------------- /0x0C-SQL_introduction/2-remove_database.sql: -------------------------------------------------------------------------------- 1 | -- Delete the database 'hbtn_0c_0' 2 | -- If 'hbtn_0c_0' doesn't exist, script should not fail 3 | -- Not allowed to use SELECT or SHOW 4 | DROP DATABASE IF EXISTS hbtn_0c_0; 5 | -------------------------------------------------------------------------------- /0x0C-SQL_introduction/3-list_tables.sql: -------------------------------------------------------------------------------- 1 | -- List all tables of a database in your MySQL database 2 | -- DB name will be passed as argument of mysql command 3 | SHOW tables; 4 | -------------------------------------------------------------------------------- /0x0C-SQL_introduction/4-first_table.sql: -------------------------------------------------------------------------------- 1 | -- Create a table called 'first_table' in db 'hbtn_0c_0' 2 | -- 'first_table' should have (id INT) and (name VARCHAR(256)) 3 | -- db name will be passed as argument of mysql cmd 4 | -- If table 'first_table' already exists, should not fail. 5 | -- Not allowed to use SELECT or SHOW 6 | CREATE TABLE IF NOT EXISTS first_table (id INT, 7 | name VARCHAR(256)); 8 | -------------------------------------------------------------------------------- /0x0C-SQL_introduction/5-full_table.sql: -------------------------------------------------------------------------------- 1 | -- Print the full description of 'first_table' from db 'hbtn_0c_0' 2 | -- db name will be passed as an arg to mysql cmd 3 | -- Not allowed to use DESCRIBE or EXPLAIN 4 | SHOW CREATE TABLE first_table; 5 | -------------------------------------------------------------------------------- /0x0C-SQL_introduction/6-list_values.sql: -------------------------------------------------------------------------------- 1 | -- List all rows of 'first_table' from db 'hbtn_0c_0' 2 | -- db name will be passed as arg to mysql cmd 3 | SELECT * FROM first_table; 4 | -------------------------------------------------------------------------------- /0x0C-SQL_introduction/7-insert_value.sql: -------------------------------------------------------------------------------- 1 | -- Insert a new row in 'first_table' from db 'hbtn_0c_0' 2 | -- id == 89 3 | -- name == Holberton School 4 | -- db name will be passed as arg to mysql cmd 5 | INSERT INTO `first_table` (`id`, `name`) VALUES (89, "Holberton School"); 6 | -------------------------------------------------------------------------------- /0x0C-SQL_introduction/8-count_89.sql: -------------------------------------------------------------------------------- 1 | -- Display number of records with id == 89 in 'first_table' 2 | -- of db 'hbtn_0c_0' 3 | -- db name will be passed as arg to mysql cmd 4 | SELECT COUNT(*) FROM first_table 5 | WHERE id = 89; 6 | -------------------------------------------------------------------------------- /0x0C-SQL_introduction/9-full_creation.sql: -------------------------------------------------------------------------------- 1 | -- Create table 'second_table' in db 'hbtn_0c_0' 2 | -- Add descriptions (id INT), (name VARCHAR(256)), (score INT) 3 | -- db name will be passed as arg to mysql cmd 4 | -- Not allowed to use SELECT or SHOW 5 | CREATE TABLE IF NOT EXISTS second_table (id INT, name VARCHAR(256), score INT); 6 | 7 | -- Script should create 4 records 8 | INSERT INTO `second_table` (`id`, `name`, `score`) VALUES (1, "John", 10); 9 | INSERT INTO `second_table` (`id`, `name`, `score`) VALUES (2, "Alex", 3); 10 | INSERT INTO `second_table` (`id`, `name`, `score`) VALUES (3, "Bob", 14); 11 | INSERT INTO `second_table` (`id`, `name`, `score`) VALUES (4, "George", 8); 12 | -------------------------------------------------------------------------------- /0x0C-SQL_introduction/README.md: -------------------------------------------------------------------------------- 1 | # 0x0C. SQL - Introduction -------------------------------------------------------------------------------- /0x0D-SQL_more_queries/0-privileges.sql: -------------------------------------------------------------------------------- 1 | -- List all privileges for 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 | -------------------------------------------------------------------------------- /0x0D-SQL_more_queries/1-create_user.sql: -------------------------------------------------------------------------------- 1 | -- Create user 'user_0d_1' with all privileges 2 | -- Password for user set as 'user_0d_1_pwd' 3 | -- If user already exists, script should not fail 4 | CREATE USER IF NOT EXISTS 'user_0d_1'@'localhost' 5 | IDENTIFIED BY 'user_0d_1_pwd'; 6 | GRANT ALL PRIVILEGES ON *.* 7 | TO 'user_0d_1'@'localhost'; 8 | FLUSH PRIVILEGES; 9 | -------------------------------------------------------------------------------- /0x0D-SQL_more_queries/10-genre_id_by_show.sql: -------------------------------------------------------------------------------- 1 | -- List all shows in 'hbtn_0d_tvshows' that have at least one genre linked 2 | -- Each record should display 3 | -- tv_shows.title, tv_show_genres.genre_id 4 | -- Results must be in ascending order by tv_shows.title and tv_show_genres.genre_id 5 | -- You can only use one SELECT statement 6 | SELECT tv_shows.title, tv_show_genres.genre_id 7 | FROM tv_show_genres 8 | JOIN tv_shows ON tv_show_genres.show_id = tv_shows.id 9 | ORDER BY tv_shows.title, tv_show_genres.genre_id; 10 | -------------------------------------------------------------------------------- /0x0D-SQL_more_queries/100-not_my_genres.sql: -------------------------------------------------------------------------------- 1 | -- Use 'hbtn_0d_tvshows' to list all genres not linked to show 'Dexter' 2 | -- 'tv_shows' table contains only one record where title = Dexter 3 | -- Each record should display tv_genres.name 4 | -- Results must be sorted ascending order by genre name 5 | -- You can use max of two SELECT statements 6 | SELECT g.name 7 | FROM tv_genres g 8 | WHERE g.name NOT IN ( 9 | SELECT g.name 10 | FROM tv_genres g 11 | INNER JOIN tv_show_genres m ON g.id = m.genre_id 12 | INNER JOIN tv_shows s ON m.show_id = s.id 13 | WHERE s.title = 'Dexter' 14 | ) 15 | ORDER BY g.name ASC; 16 | -------------------------------------------------------------------------------- /0x0D-SQL_more_queries/101-not_a_comedy.sql: -------------------------------------------------------------------------------- 1 | -- List all shows without genre 'Comedy' in 'hbtn_0d_tvshows' 2 | -- 'tv_genres' table contains only one record where name = Comedy 3 | -- Each record should display tv_shows.title 4 | -- You can use max of 2 SELECT statements 5 | SELECT s.title 6 | FROM tv_shows s 7 | WHERE s.title NOT IN ( 8 | SELECT s.title 9 | FROM tv_shows s 10 | INNER JOIN tv_show_genres m ON s.id = m.show_id 11 | INNER JOIN tv_genres g ON m.genre_id = g.id 12 | WHERE g.name = 'Comedy' 13 | ) 14 | ORDER BY s.title ASC; 15 | -------------------------------------------------------------------------------- /0x0D-SQL_more_queries/102-rating_shows.sql: -------------------------------------------------------------------------------- 1 | -- List all shows from 'hbtn_0d_tvshows_rate' by their rating 2 | -- Each record should display tv_shows.title, rating sum 3 | -- Results must be sorted in ascending order by the rating 4 | -- You can use only one SELECT statement 5 | SELECT tv_shows.title, SUM(tv_show_ratings.rate) AS rating 6 | FROM tv_shows 7 | INNER JOIN tv_show_ratings ON tv_shows.id = tv_show_ratings.show_id 8 | GROUP BY tv_show_ratings.show_id 9 | ORDER BY rating DESC; 10 | -------------------------------------------------------------------------------- /0x0D-SQL_more_queries/103-rating_genres.sql: -------------------------------------------------------------------------------- 1 | -- List all genres in 'hbtn_0d_tvshows_rate' by their rating 2 | -- Each record should display tv_genres.name and rating sum 3 | -- You can use only one SELECT statement 4 | SELECT tv_genres.name, SUM(tv_show_ratings.rate) AS rating 5 | FROM tv_genres 6 | INNER JOIN tv_show_genres ON tv_genres.id = tv_show_genres.genre_id 7 | INNER JOIN tv_show_ratings ON tv_show_genres.show_id = tv_show_ratings.show_id 8 | GROUP BY tv_show_genres.genre_id 9 | ORDER BY rating DESC; 10 | -------------------------------------------------------------------------------- /0x0D-SQL_more_queries/11-genre_id_all_shows.sql: -------------------------------------------------------------------------------- 1 | -- List all shows in db 'hbtn_0d_tvshows' 2 | -- Each record show display tv_shows.title, tv_show_genres.genre_id 3 | -- If show doesn't have genre, display NULL 4 | -- You can use only one SELECT statement 5 | SELECT tv_shows.title, tv_show_genres.genre_id 6 | FROM tv_show_genres 7 | RIGHT JOIN tv_shows ON tv_show_genres.show_id = tv_shows.id 8 | ORDER BY tv_shows.title, tv_show_genres.genre_id; 9 | -------------------------------------------------------------------------------- /0x0D-SQL_more_queries/12-no_genre.sql: -------------------------------------------------------------------------------- 1 | -- List all shows contained in 'hbtn_0d_tvshows' without a genre linked 2 | -- Each record should display tv_shows.title, tv_show_genres.genre_id 3 | -- Results must be sorted ascending order by tv_shows.title and tv_show_genres.genre_id 4 | -- You can use only one SELECT statement 5 | SELECT tv_shows.title, tv_show_genres.genre_id 6 | FROM tv_shows 7 | LEFT JOIN tv_show_genres ON tv_show_genres.show_id = tv_shows.id 8 | WHERE tv_show_genres.show_id IS NULL 9 | ORDER BY tv_shows.title ASC, tv_show_genres.genre_id ASC; 10 | -------------------------------------------------------------------------------- /0x0D-SQL_more_queries/13-count_shows_by_genre.sql: -------------------------------------------------------------------------------- 1 | -- List all genres from 'hbtn_0d_tvshows' and display number of shows linked to each 2 | -- Each record should display tv_genres.name, number of shows 3 | -- Don't display a genre that doesn't have any shows linked 4 | -- Results must be sorted descending order by number of shows linked 5 | -- Can only use one SELECT statement 6 | SELECT tv_genres.name AS genre, COUNT(*) AS number_shows 7 | FROM tv_genres 8 | INNER JOIN tv_show_genres ON tv_genres.id = tv_show_genres.genre_id 9 | GROUP BY tv_show_genres.genre_id 10 | ORDER BY number_shows DESC; 11 | -------------------------------------------------------------------------------- /0x0D-SQL_more_queries/14-my_genres.sql: -------------------------------------------------------------------------------- 1 | -- Use 'hbtn_0d_tvshows' to list all genres of show 'Dexter' 2 | -- 'tv_shows' table contains only one record where title = Dexter 3 | -- Each record should display tv_genres.name 4 | -- Results must be sorted in ascending order by genre name 5 | -- You can only use one SELECT statement 6 | SELECT tv_genres.name 7 | FROM tv_genres 8 | INNER JOIN tv_show_genres m ON tv_genres.id = m.genre_id 9 | INNER JOIN tv_shows s ON m.show_id = s.id 10 | WHERE s.title = 'Dexter' 11 | ORDER BY tv_genres.name ASC; 12 | -------------------------------------------------------------------------------- /0x0D-SQL_more_queries/15-comedy_only.sql: -------------------------------------------------------------------------------- 1 | -- List all Comedy shows in 'hbtn_0d_tvshows' 2 | -- 'tv_genres' table contains only one record where name = Comedy 3 | -- Results must be sorted in ascending order by the show title 4 | -- You can only use one SELECT statement 5 | SELECT tv_shows.title 6 | FROM tv_shows 7 | INNER JOIN tv_show_genres m ON tv_shows.id = m.show_id 8 | INNER JOIN tv_genres g ON m.genre_id = g.id 9 | WHERE g.name = 'Comedy' 10 | ORDER BY tv_shows.title ASC; 11 | -------------------------------------------------------------------------------- /0x0D-SQL_more_queries/16-shows_by_genre.sql: -------------------------------------------------------------------------------- 1 | -- List all shows and genres linked to show from 'hbtn_0d_tvshows' 2 | -- If show doesn't have a genre, display NULL in genre column 3 | -- Each record should display tv_shows.title, tv_genres.name 4 | -- Results must be sorted in ascending order by show title 5 | -- You can only use one SELECT statement 6 | SELECT s.title, g.name 7 | FROM tv_shows s 8 | LEFT JOIN tv_show_genres m ON s.id = m.show_id 9 | LEFT JOIN tv_genres g ON m.genre_id = g.id 10 | ORDER BY s.title ASC; 11 | -------------------------------------------------------------------------------- /0x0D-SQL_more_queries/2-create_read_user.sql: -------------------------------------------------------------------------------- 1 | -- Create database 'hbtn_0d_2' 2 | -- If database already exists, script should not fail 3 | CREATE DATABASE IF NOT EXISTS hbtn_0d_2; 4 | 5 | -- Create user 'user_0d_2' 6 | -- User password should be set to 'user_0d_2_pwd' 7 | -- If user already exists, script should not fail 8 | CREATE USER IF NOT EXISTS 'user_0d_2'@'localhost' IDENTIFIED BY 'user_0d_2_pwd'; 9 | 10 | -- User 'user_0d_2' should have only SELECT privilege in db 'hbtn_0d_2' 11 | GRANT SELECT ON hbtn_0d_2.* TO 'user_0d_2'@'localhost'; 12 | FLUSH PRIVILEGES; 13 | -------------------------------------------------------------------------------- /0x0D-SQL_more_queries/3-force_name.sql: -------------------------------------------------------------------------------- 1 | -- Create table 'force_name' 2 | -- id INT, name VARCHAR(256) can't be null 3 | -- If table already exists, script should not fail 4 | CREATE TABLE IF NOT EXISTS force_name (id INT, name VARCHAR(256) NOT NULL); 5 | -------------------------------------------------------------------------------- /0x0D-SQL_more_queries/4-never_empty.sql: -------------------------------------------------------------------------------- 1 | -- Create table 'id_not_null' 2 | -- id INT default value 1, name VARCHAR(256) 3 | -- If table already exists, script should not fail 4 | CREATE TABLE IF NOT EXISTS id_not_null (id INT DEFAULT 1, name VARCHAR(256)); 5 | -------------------------------------------------------------------------------- /0x0D-SQL_more_queries/5-unique_id.sql: -------------------------------------------------------------------------------- 1 | -- Create table 'unique_id' 2 | -- id INT default 1 unique, name VARCHAR(256) 3 | -- If table already exists, script should not fail 4 | CREATE TABLE IF NOT EXISTS unique_id 5 | ( 6 | id INT DEFAULT 1 UNIQUE, 7 | name VARCHAR(256) 8 | ); 9 | -------------------------------------------------------------------------------- /0x0D-SQL_more_queries/6-states.sql: -------------------------------------------------------------------------------- 1 | -- Create db 'hbtn_0d_usa' 2 | -- If db already exists, script should not fail 3 | CREATE DATABASE IF NOT EXISTS hbtn_0d_usa; 4 | 5 | -- Create table 'states' in db 'hbtn_0d_usa' 6 | -- id INT unique auto-generated not null and primary key 7 | -- name VARCHAR(256) not null 8 | -- If table already exists, script should not fail 9 | CREATE TABLE IF NOT EXISTS hbtn_0d_usa.states 10 | ( 11 | id INT UNIQUE AUTO_INCREMENT NOT NULL, 12 | name VARCHAR(256) NOT NULL, 13 | PRIMARY KEY (id) 14 | ); 15 | -------------------------------------------------------------------------------- /0x0D-SQL_more_queries/7-cities.sql: -------------------------------------------------------------------------------- 1 | -- Create db 'hbtn_0d_usa' 2 | -- If db already exists, script should not fail 3 | CREATE DATABASE IF NOT EXISTS hbtn_0d_usa; 4 | 5 | -- Create table 'cities' in db 'hbtn_0d_usa' 6 | -- id INT unique, auto generated, not null, primary key 7 | -- state_id INT not null, foreign key that references id of 'states' table 8 | -- name VARCHAR(256) not null 9 | -- If table already exists, script should not fail 10 | CREATE TABLE IF NOT EXISTS hbtn_0d_usa.cities 11 | ( 12 | id INT UNIQUE AUTO_INCREMENT NOT NULL, 13 | state_id INT NOT NULL, 14 | name VARCHAR(256) NOT NULL, 15 | PRIMARY KEY (id), 16 | FOREIGN KEY (state_id) 17 | REFERENCES hbtn_0d_usa.states(id) 18 | ); 19 | -------------------------------------------------------------------------------- /0x0D-SQL_more_queries/8-cities_of_california_subquery.sql: -------------------------------------------------------------------------------- 1 | -- List all cities of CA that can be found in db 'hbtn_0d_usa' 2 | -- 'states' table contains only one record where 'name = California' 3 | -- but 'id' cant be different 4 | -- Results must be sorted in ascending order by 'cities.id' 5 | -- Not allowed to use JOIN keyword 6 | SELECT id, name 7 | FROM cities 8 | WHERE state_id = ( 9 | SELECT id 10 | FROM states 11 | WHERE name = 'California' 12 | ); 13 | -------------------------------------------------------------------------------- /0x0D-SQL_more_queries/9-cities_by_state_join.sql: -------------------------------------------------------------------------------- 1 | -- List all cities in db 'hbtn_0d_usa' 2 | -- Each record should display cities.id, cities.name, and states.name 3 | -- Can only use SELECT statement once 4 | SELECT cities.id, cities.name, states.name 5 | FROM states 6 | INNER JOIN cities 7 | ON states.id = cities.state_id; 8 | -------------------------------------------------------------------------------- /0x0D-SQL_more_queries/README.md: -------------------------------------------------------------------------------- 1 | # 0x0D. SQL - more queries -------------------------------------------------------------------------------- /0x0E-python-object_relational_mapping/0-select_states.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # List all states from a given db sorted in ascending order by id 3 | # Username, password, and database names are given as user args 4 | import sys 5 | import MySQLdb 6 | 7 | if __name__ == "__main__": 8 | db = MySQLdb.connect(user=sys.argv[1], 9 | passwd=sys.argv[2], 10 | db=sys.argv[3], 11 | host='localhost', 12 | port=3306) 13 | cur = db.cursor() 14 | cur.execute("SELECT id, name FROM states ORDER BY id ASC") 15 | allStates = cur.fetchall() 16 | 17 | for state in allStates: 18 | print(state) 19 | 20 | cur.close() 21 | db.close() 22 | -------------------------------------------------------------------------------- /0x0E-python-object_relational_mapping/0-select_states.sql: -------------------------------------------------------------------------------- 1 | -- Create states table in hbtn_0e_0_usa with some data 2 | CREATE DATABASE IF NOT EXISTS hbtn_0e_0_usa; 3 | USE hbtn_0e_0_usa; 4 | CREATE TABLE IF NOT EXISTS states ( 5 | id INT NOT NULL AUTO_INCREMENT, 6 | name VARCHAR(256) NOT NULL, 7 | PRIMARY KEY (id) 8 | ); 9 | INSERT INTO states (name) VALUES ("California"), ("Arizona"), ("Texas"), ("New York"), ("Nevada"); 10 | -------------------------------------------------------------------------------- /0x0E-python-object_relational_mapping/1-filter_states.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # List all states with a name starting with uppercase N 3 | # Username, password, and database names are given as user args 4 | import sys 5 | import MySQLdb 6 | 7 | if __name__ == "__main__": 8 | db = MySQLdb.connect(user=sys.argv[1], 9 | passwd=sys.argv[2], 10 | db=sys.argv[3], 11 | host='localhost', 12 | port=3306) 13 | cur = db.cursor() 14 | cmd = """SELECT id, name 15 | FROM states 16 | WHERE name LIKE 'N%' 17 | ORDER BY id ASC;""" 18 | cur.execute(cmd) 19 | nStates = cur.fetchall() 20 | 21 | for state in nStates: 22 | if (state[1][0] == 'N'): 23 | print(state) 24 | 25 | cur.close() 26 | db.close() 27 | -------------------------------------------------------------------------------- /0x0E-python-object_relational_mapping/10-model_state_my_get.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Print State obj with 'name' passed as arg from db 'hbtn_0e_6_usa' 3 | # Script should take 4 args: username, pw, db name, and state name 4 | # Must use SQLAlchemy 5 | import sys 6 | from sqlalchemy.orm import sessionmaker 7 | from sqlalchemy import create_engine 8 | from model_state import Base, State 9 | 10 | if __name__ == "__main__": 11 | engine = create_engine("mysql+mysqldb://{}:{}@localhost:3306/{}" 12 | .format(sys.argv[1], sys.argv[2], sys.argv[3])) 13 | Session = sessionmaker(bind=engine) 14 | session = Session() 15 | 16 | res = session.query(State.id).filter(State.name == sys.argv[4]) 17 | 18 | if (res.first() is None): 19 | print("Not found") 20 | else: 21 | print(res[0][0]) 22 | -------------------------------------------------------------------------------- /0x0E-python-object_relational_mapping/11-model_state_insert.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Add the State object "Louisiana" to db 'hbtn_0e_6_usa' 3 | # Print the new 'states.id' after creation 4 | # Script should take 3 args: username, pw, and db name 5 | # Must use SQLAlchemy 6 | import sys 7 | from sqlalchemy.orm import sessionmaker 8 | from sqlalchemy import create_engine 9 | from model_state import Base, State 10 | 11 | if __name__ == "__main__": 12 | engine = create_engine("mysql+mysqldb://{}:{}@localhost:3306/{}" 13 | .format(sys.argv[1], sys.argv[2], sys.argv[3])) 14 | Session = sessionmaker(bind=engine) 15 | session = Session() 16 | 17 | l = State(name='Louisiana') 18 | session.add(l) 19 | session.commit() 20 | 21 | print(l.id) 22 | -------------------------------------------------------------------------------- /0x0E-python-object_relational_mapping/12-model_state_update_id_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Change name of State obj from db 'hbtn_0e_6_usa' 3 | # Change name of State where "id = 2" to "New Mexico" 4 | # Script should take 3 args: username, pw, and db name 5 | # Must use SQLAlchemy 6 | import sys 7 | from sqlalchemy.orm import sessionmaker 8 | from sqlalchemy import create_engine 9 | from model_state import Base, State 10 | 11 | if __name__ == "__main__": 12 | engine = create_engine("mysql+mysqldb://{}:{}@localhost:3306/{}" 13 | .format(sys.argv[1], sys.argv[2], sys.argv[3])) 14 | Session = sessionmaker(bind=engine) 15 | session = Session() 16 | 17 | res = session.query(State).filter(State.id == 2) 18 | res.update({"name": ("New Mexico")}) 19 | 20 | session.commit() 21 | -------------------------------------------------------------------------------- /0x0E-python-object_relational_mapping/13-model_state_delete_a.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Delete all State objects with name containing letter "a" 3 | # from db 'hbtn_0e_6_usa' 4 | # Script should take 3 args: username, pw, and db name 5 | # Must use SQLAlchemy 6 | import sys 7 | from sqlalchemy.orm import sessionmaker 8 | from sqlalchemy import create_engine 9 | from model_state import Base, State 10 | 11 | if __name__ == "__main__": 12 | engine = create_engine("mysql+mysqldb://{}:{}@localhost:3306/{}" 13 | .format(sys.argv[1], sys.argv[2], sys.argv[3])) 14 | Session = sessionmaker(bind=engine) 15 | session = Session() 16 | 17 | for instance in session.query(State).filter(State.name.like('%a%')): 18 | session.delete(instance) 19 | 20 | session.commit() 21 | -------------------------------------------------------------------------------- /0x0E-python-object_relational_mapping/14-model_city_fetch_by_state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Print all City objs from db 'hbtn_0e_14_usa' 3 | # Sort in ascending order by cities.id 4 | # Display results as ": () " 5 | # Script should take 3 args: username, pw, and db name 6 | # Must use SQLAlchemy 7 | import sys 8 | from sqlalchemy.orm import sessionmaker 9 | from sqlalchemy import create_engine 10 | from model_state import Base, State 11 | from model_city import City 12 | 13 | if __name__ == "__main__": 14 | engine = create_engine("mysql+mysqldb://{}:{}@localhost:3306/{}" 15 | .format(sys.argv[1], sys.argv[2], sys.argv[3])) 16 | Session = sessionmaker(bind=engine) 17 | session = Session() 18 | 19 | for i in session.query(State, City).filter(State.id == City.state_id): 20 | print("{}: ({:d}) {}".format(i.State.name, i.City.id, i.City.name)) 21 | -------------------------------------------------------------------------------- /0x0E-python-object_relational_mapping/14-model_city_fetch_by_state.sql: -------------------------------------------------------------------------------- 1 | -- Create database hbtn_0e_14_usa, tables states and cities + some data 2 | CREATE DATABASE IF NOT EXISTS hbtn_0e_14_usa; 3 | USE hbtn_0e_14_usa; 4 | 5 | CREATE TABLE IF NOT EXISTS states ( 6 | id INT NOT NULL AUTO_INCREMENT, 7 | name VARCHAR(256) NOT NULL, 8 | PRIMARY KEY (id) 9 | ); 10 | INSERT INTO states (name) VALUES ("California"), ("Arizona"), ("Texas"), ("New York"), ("Nevada"); 11 | 12 | CREATE TABLE IF NOT EXISTS cities ( 13 | id INT NOT NULL AUTO_INCREMENT, 14 | state_id INT NOT NULL, 15 | name VARCHAR(256) NOT NULL, 16 | PRIMARY KEY (id), 17 | FOREIGN KEY(state_id) REFERENCES states(id) 18 | ); 19 | INSERT INTO cities (state_id, name) VALUES (1, "San Francisco"), (1, "San Jose"), (1, "Los Angeles"), (1, "Fremont"), (1, "Livermore"); 20 | INSERT INTO cities (state_id, name) VALUES (2, "Page"), (2, "Phoenix"); 21 | INSERT INTO cities (state_id, name) VALUES (3, "Dallas"), (3, "Huston"), (3, "Austin"); 22 | INSERT INTO cities (state_id, name) VALUES (4, "New York"); 23 | INSERT INTO cities (state_id, name) VALUES (5, "Las Vegas"), (5, "Reno"), (5, "Henderson"), (5, "Carson City"); 24 | -------------------------------------------------------------------------------- /0x0E-python-object_relational_mapping/2-my_filter_states.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # List all states where 'name' matches the argument 3 | # Username, password, database name, and state name given as user args 4 | import sys 5 | import MySQLdb 6 | 7 | if __name__ == "__main__": 8 | db = MySQLdb.connect(user=sys.argv[1], 9 | passwd=sys.argv[2], 10 | db=sys.argv[3], 11 | host='localhost', 12 | port=3306) 13 | cur = db.cursor() 14 | cmd = """SELECT id, name 15 | FROM states 16 | WHERE name='{}' 17 | ORDER BY id ASC""".format(sys.argv[4]) 18 | cur.execute(cmd) 19 | nStates = cur.fetchall() 20 | 21 | for state in nStates: 22 | if (state[1] == sys.argv[4]): 23 | print(state) 24 | 25 | cur.close() 26 | db.close() 27 | -------------------------------------------------------------------------------- /0x0E-python-object_relational_mapping/3-my_safe_filter_states.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # List all states where 'name' matches the argument 3 | # But this time, one safe from MySQL injection. 4 | # Username, password, database name, and state name given as user args 5 | import sys 6 | import MySQLdb 7 | 8 | if __name__ == "__main__": 9 | db = MySQLdb.connect(user=sys.argv[1], 10 | passwd=sys.argv[2], 11 | db=sys.argv[3], 12 | host='localhost', 13 | port=3306) 14 | cur = db.cursor() 15 | cmd = """SELECT id, name 16 | FROM states 17 | WHERE name=%s 18 | ORDER BY id ASC""" 19 | cur.execute(cmd, (sys.argv[4],)) 20 | nStates = cur.fetchall() 21 | 22 | for state in nStates: 23 | print(state) 24 | 25 | cur.close() 26 | db.close() 27 | -------------------------------------------------------------------------------- /0x0E-python-object_relational_mapping/4-cities_by_state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # List all cities from the db 3 | # Username, password, and database name given as user args 4 | # Can only use execute() once 5 | # Sort ascending order by cities.id 6 | import sys 7 | import MySQLdb 8 | 9 | if __name__ == "__main__": 10 | db = MySQLdb.connect(user=sys.argv[1], 11 | passwd=sys.argv[2], 12 | db=sys.argv[3], 13 | host='localhost', 14 | port=3306) 15 | cur = db.cursor() 16 | cmd = """SELECT cities.id, cities.name, states.name 17 | FROM states 18 | INNER JOIN cities ON states.id = cities.state_id 19 | ORDER BY cities.id ASC""" 20 | cur.execute(cmd) 21 | allCities = cur.fetchall() 22 | 23 | for city in allCities: 24 | print(city) 25 | 26 | cur.close() 27 | db.close() 28 | -------------------------------------------------------------------------------- /0x0E-python-object_relational_mapping/4-cities_by_state.sql: -------------------------------------------------------------------------------- 1 | -- Create states table in hbtn_0e_4_usa with some data 2 | CREATE DATABASE IF NOT EXISTS hbtn_0e_4_usa; 3 | USE hbtn_0e_4_usa; 4 | CREATE TABLE IF NOT EXISTS states ( 5 | id INT NOT NULL AUTO_INCREMENT, 6 | name VARCHAR(256) NOT NULL, 7 | PRIMARY KEY (id) 8 | ); 9 | INSERT INTO states (name) VALUES ("California"), ("Arizona"), ("Texas"), ("New York"), ("Nevada"); 10 | 11 | CREATE TABLE IF NOT EXISTS cities ( 12 | id INT NOT NULL AUTO_INCREMENT, 13 | state_id INT NOT NULL, 14 | name VARCHAR(256) NOT NULL, 15 | PRIMARY KEY (id), 16 | FOREIGN KEY(state_id) REFERENCES states(id) 17 | ); 18 | INSERT INTO cities (state_id, name) VALUES (1, "San Francisco"), (1, "San Jose"), (1, "Los Angeles"), (1, "Fremont"), (1, "Livermore"); 19 | INSERT INTO cities (state_id, name) VALUES (2, "Page"), (2, "Phoenix"); 20 | INSERT INTO cities (state_id, name) VALUES (3, "Dallas"), (3, "Huston"), (3, "Austin"); 21 | INSERT INTO cities (state_id, name) VALUES (4, "New York"); 22 | INSERT INTO cities (state_id, name) VALUES (5, "Las Vegas"), (5, "Reno"), (5, "Henderson"), (5, "Carson City"); 23 | -------------------------------------------------------------------------------- /0x0E-python-object_relational_mapping/5-filter_cities.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # List all cities from the db by given state 3 | # Username, password, database name, and state name given as user args 4 | # Can only use execute() once 5 | # Sort ascending order by cities.id 6 | import sys 7 | import MySQLdb 8 | 9 | if __name__ == "__main__": 10 | db = MySQLdb.connect(user=sys.argv[1], 11 | passwd=sys.argv[2], 12 | db=sys.argv[3], 13 | host='localhost', 14 | port=3306) 15 | cur = db.cursor() 16 | cmd = """SELECT cities.name 17 | FROM states 18 | INNER JOIN cities ON states.id = cities.state_id 19 | WHERE states.name=%s 20 | ORDER BY cities.id ASC""" 21 | cur.execute(cmd, (sys.argv[4],)) 22 | allCities = cur.fetchall() 23 | 24 | print(", ".join([city[0] for city in allCities])) 25 | 26 | cur.close() 27 | db.close() 28 | -------------------------------------------------------------------------------- /0x0E-python-object_relational_mapping/6-model_state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Start link class to table in database 3 | """ 4 | import sys 5 | from model_state import Base, State 6 | 7 | from sqlalchemy import (create_engine) 8 | 9 | if __name__ == "__main__": 10 | engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}'.format(sys.argv[1], sys.argv[2], sys.argv[3])) 11 | Base.metadata.create_all(engine) 12 | -------------------------------------------------------------------------------- /0x0E-python-object_relational_mapping/6-model_state.sql: -------------------------------------------------------------------------------- 1 | -- Create database hbtn_0e_6_usa 2 | CREATE DATABASE IF NOT EXISTS hbtn_0e_6_usa; 3 | USE hbtn_0e_6_usa; 4 | SHOW CREATE TABLE states; 5 | -------------------------------------------------------------------------------- /0x0E-python-object_relational_mapping/7-model_state_fetch_all.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # List all State objects from db 'hbtn_0e_6_usa' 3 | # Script should take 3 args: username, pw, and db name 4 | # Must use SQLAlchemy 5 | import sys 6 | from sqlalchemy.orm import sessionmaker 7 | from sqlalchemy import create_engine 8 | from model_state import Base, State 9 | 10 | if __name__ == "__main__": 11 | engine = create_engine("mysql+mysqldb://{}:{}@localhost:3306/{}" 12 | .format(sys.argv[1], sys.argv[2], sys.argv[3])) 13 | Session = sessionmaker(bind=engine) 14 | session = Session() 15 | 16 | for instance in session.query(State): 17 | print("{:d}: {}".format(instance.id, instance.name)) 18 | -------------------------------------------------------------------------------- /0x0E-python-object_relational_mapping/7-model_state_fetch_all.sql: -------------------------------------------------------------------------------- 1 | -- Insert states 2 | INSERT INTO states (name) VALUES ("California"), ("Arizona"), ("Texas"), ("New York"), ("Nevada"); 3 | -------------------------------------------------------------------------------- /0x0E-python-object_relational_mapping/8-model_state_fetch_first.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Print the first 'State' object from db 'hbtn_0e_6_usa' 3 | # Script should take 3 args: username, pw, and db name 4 | # Must use SQLAlchemy 5 | import sys 6 | from sqlalchemy.orm import sessionmaker 7 | from sqlalchemy import create_engine 8 | from model_state import Base, State 9 | 10 | if __name__ == "__main__": 11 | engine = create_engine("mysql+mysqldb://{}:{}@localhost:3306/{}" 12 | .format(sys.argv[1], sys.argv[2], sys.argv[3])) 13 | Session = sessionmaker(bind=engine) 14 | session = Session() 15 | 16 | res = session.query(State.id, State.name).first() 17 | if (res is None): 18 | print("Nothing") 19 | else: 20 | print("{:d}: {}".format(res[0], res[1])) 21 | -------------------------------------------------------------------------------- /0x0E-python-object_relational_mapping/9-model_state_filter_a.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # List all State objects that contain letter 'a' from db 'hbtn_0e_6_usa' 3 | # Script should take 3 args: username, pw, and db name 4 | # Must use SQLAlchemy 5 | import sys 6 | from sqlalchemy.orm import sessionmaker 7 | from sqlalchemy import create_engine 8 | from model_state import Base, State 9 | 10 | if __name__ == "__main__": 11 | engine = create_engine("mysql+mysqldb://{}:{}@localhost:3306/{}" 12 | .format(sys.argv[1], sys.argv[2], sys.argv[3])) 13 | Session = sessionmaker(bind=engine) 14 | session = Session() 15 | 16 | for instance in session.query(State).filter(State.name.like('%a%')): 17 | print("{:d}: {}".format(instance.id, instance.name)) 18 | -------------------------------------------------------------------------------- /0x0E-python-object_relational_mapping/README.md: -------------------------------------------------------------------------------- 1 | # 0x0E. Python - Object-relational mapping -------------------------------------------------------------------------------- /0x0E-python-object_relational_mapping/model_city.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Write a file that contains class defns of a City and an instance 3 | # Base = delcarative_base() 4 | # City class: 5 | # inherits from Base class, links to MySQL table 'cities', 6 | # has columns id, name, and state_id 7 | # Must use SQLAlchemy 8 | from sqlalchemy import Column, Integer, String, ForeignKey 9 | from sqlalchemy.ext.declarative import declarative_base 10 | from model_state import State 11 | 12 | Base = declarative_base() 13 | 14 | 15 | class City(Base): 16 | __tablename__ = 'cities' 17 | id = Column(Integer, primary_key=True, 18 | nullable=False, autoincrement=True) 19 | name = Column(String(128), nullable=False) 20 | state_id = Column(Integer, ForeignKey('states.id'), nullable=False) 21 | -------------------------------------------------------------------------------- /0x0E-python-object_relational_mapping/model_state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Write a file that contains class defns of a State and an instance 3 | # Base = delcarative_base() 4 | # State class: 5 | # inherits from Base class, links to MySQL table 'states', 6 | # has columns id and name 7 | # Must use SQLAlchemy 8 | from sqlalchemy import Column, Integer, String 9 | from sqlalchemy.ext.declarative import declarative_base 10 | 11 | Base = declarative_base() 12 | 13 | 14 | class State(Base): 15 | __tablename__ = 'states' 16 | id = Column(Integer, primary_key=True, 17 | nullable=False, autoincrement=True) 18 | name = Column(String(128), nullable=False) 19 | -------------------------------------------------------------------------------- /0x0F-python-network_0/0-url_hostname: -------------------------------------------------------------------------------- 1 | www.holbertonschool.com 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/1-url_protocol: -------------------------------------------------------------------------------- 1 | HTTP 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/10-url_query_string: -------------------------------------------------------------------------------- 1 | batch 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/100-status_code.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Send a request to a URL and display only status code of response with restrictions 3 | curl -s -o /dev/null -w "%{http_code}" "$1" 4 | -------------------------------------------------------------------------------- /0x0F-python-network_0/11-url_query_string: -------------------------------------------------------------------------------- 1 | 2 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/12-url_query_string: -------------------------------------------------------------------------------- 1 | 3 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/13-http_verb: -------------------------------------------------------------------------------- 1 | GET 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/14-http_verb: -------------------------------------------------------------------------------- 1 | POST 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/15-http_verb: -------------------------------------------------------------------------------- 1 | PUT 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/16-http_status_code: -------------------------------------------------------------------------------- 1 | 404 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/17-http_status_code: -------------------------------------------------------------------------------- 1 | 301 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/18-http_status_code: -------------------------------------------------------------------------------- 1 | 400 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/19-http_status_code: -------------------------------------------------------------------------------- 1 | 5 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/2-url_port: -------------------------------------------------------------------------------- 1 | 8080 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/20-http_header: -------------------------------------------------------------------------------- 1 | User-Agent 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/21-http_header: -------------------------------------------------------------------------------- 1 | Content-Length 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/22-http_header: -------------------------------------------------------------------------------- 1 | Cookie 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/23-http_header: -------------------------------------------------------------------------------- 1 | Set-Cookie 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/24-http_header: -------------------------------------------------------------------------------- 1 | Content-Length 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/25-http_header: -------------------------------------------------------------------------------- 1 | Status 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/26-http_header: -------------------------------------------------------------------------------- 1 | Content-Type 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/27-http_header: -------------------------------------------------------------------------------- 1 | Location 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/28-http_header: -------------------------------------------------------------------------------- 1 | Allow 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/29-curl_http_method: -------------------------------------------------------------------------------- 1 | -X 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/3-url_port: -------------------------------------------------------------------------------- 1 | 80 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/30-curl_301: -------------------------------------------------------------------------------- 1 | -L 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/31-curl_header: -------------------------------------------------------------------------------- 1 | -H 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/32-curl_body_parameters: -------------------------------------------------------------------------------- 1 | -d 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/33-curl_cookie: -------------------------------------------------------------------------------- 1 | --cookie 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/34-curl_no_progress: -------------------------------------------------------------------------------- 1 | -s 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/35-curl_request_body: -------------------------------------------------------------------------------- 1 | -o 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/36-body_size.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Script to take a URL, send request to URL, and display size of body response 3 | curl -sI "$1" | grep Content-Length | cut -d " " -f2 4 | -------------------------------------------------------------------------------- /0x0F-python-network_0/37-body.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Take in a URL, send GET request to URL, and display body of response 3 | curl -sfL "$1" 4 | -------------------------------------------------------------------------------- /0x0F-python-network_0/38-delete.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Send DELETE request to URL passed to script and display response body 3 | curl -sX "DELETE" "$1" 4 | -------------------------------------------------------------------------------- /0x0F-python-network_0/39-methods.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Takes in URL and displays all HTTP methods the server will accept 3 | curl -sI "$1" | grep "Allow" | cut -d " " -f2- 4 | -------------------------------------------------------------------------------- /0x0F-python-network_0/4-url_port: -------------------------------------------------------------------------------- 1 | 548 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/40-header.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Takes in URL, sends GET request setting a header variable, display body 3 | curl -sX "GET" -H "X-HolbertonSchool-User-Id: 98" "$1" 4 | -------------------------------------------------------------------------------- /0x0F-python-network_0/41-post_params.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Take in URL, send POST request setting some params, display body 3 | curl -sX POST -d "email=hr@holbertonschool.com&subject=I will always be there for PLD" "$1" 4 | -------------------------------------------------------------------------------- /0x0F-python-network_0/5-url_subdomain: -------------------------------------------------------------------------------- 1 | api 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/6-url_subdomain: -------------------------------------------------------------------------------- 1 | api-dev 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/7-url_path: -------------------------------------------------------------------------------- 1 | /index.html 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/8-url_path: -------------------------------------------------------------------------------- 1 | /assets/scripts/main.js 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/9-url_path: -------------------------------------------------------------------------------- 1 | /v1/auth/new 2 | -------------------------------------------------------------------------------- /0x0F-python-network_0/README.md: -------------------------------------------------------------------------------- 1 | # 0x0F. Python - Network 0 2 | -------------------------------------------------------------------------------- /0x10-python-network_1/0-hbtn_status.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Fetch from given URL using `urllib` package 3 | import urllib.request 4 | 5 | if __name__ == "__main__": 6 | with urllib.request.urlopen('https://intranet.hbtn.io/status') as res: 7 | content = res.read() 8 | print("Body response:") 9 | print("\t- type: {}".format(type(content))) 10 | print("\t- content: {}".format(content)) 11 | print("\t- utf8 content: {}".format(content.decode('utf-8'))) 12 | -------------------------------------------------------------------------------- /0x10-python-network_1/1-hbtn_header.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Take in a URL, send request to URL and display value of `X-Request-Id` 3 | import sys 4 | import urllib.request 5 | 6 | if __name__ == "__main__": 7 | with urllib.request.urlopen(sys.argv[1]) as res: 8 | print(res.info()['X-Request-Id']) 9 | -------------------------------------------------------------------------------- /0x10-python-network_1/10-my_github.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Use requests package to make a get request to the github api. 4 | First argument is username, second argument is password. 5 | """ 6 | import sys 7 | import requests 8 | 9 | if __name__ == "__main__": 10 | url = "https://api.github.com/user" 11 | r = requests.get(url, auth=(sys.argv[1], sys.argv[2])).json() 12 | try: 13 | print(r['id']) 14 | except: 15 | print("None") 16 | -------------------------------------------------------------------------------- /0x10-python-network_1/101-starwars.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Use requests package to make a get request to the swapi api. 4 | Use string argument as search value of request. Body response must 5 | be JSON and formatted to a Python dictionary. 6 | Display all character names, considering pagination on endpoint. 7 | """ 8 | import sys 9 | import requests 10 | 11 | if __name__ == "__main__": 12 | url = "https://swapi.co/api/people/?search={}".format(sys.argv[1]) 13 | r = requests.get(url).json() 14 | print("Number of result: {}".format(r['count'])) 15 | for c in r['results']: 16 | print(c['name']) 17 | while (r['next']): 18 | r = requests.get(r['next']).json() 19 | for c in r['results']: 20 | print(c['name']) 21 | -------------------------------------------------------------------------------- /0x10-python-network_1/102-starwars.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Use requests package to make a get request to the swapi api. 4 | Use string argument as search value of request. Body response must 5 | be JSON and formatted to a Python dictionary. 6 | Must display all results character name, and all films for character. 7 | """ 8 | import sys 9 | import requests 10 | 11 | if __name__ == "__main__": 12 | url = "https://swapi.co/api/people/?search={}".format(sys.argv[1]) 13 | r = requests.get(url).json() 14 | print("Number of result: {}".format(r['count'])) 15 | for c in r['results']: 16 | print(c['name']) 17 | for film in c['films']: 18 | print("\t{}".format(requests.get(film).json()['title'])) 19 | while (r['next']): 20 | r = requests.get(r['next']).json() 21 | for c in r['results']: 22 | print(c['name']) 23 | for film in c['films']: 24 | print("\t{}".format(requests.get(film).json()['title'])) 25 | -------------------------------------------------------------------------------- /0x10-python-network_1/2-post_email.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Take in a URL and email, send POST request, and display body of response 4 | decoded in utf-8 5 | """ 6 | import sys 7 | import urllib.request 8 | import urllib.parse 9 | 10 | if __name__ == "__main__": 11 | values = {'email': sys.argv[2]} 12 | data = urllib.parse.urlencode(values) 13 | data = data.encode('utf-8') 14 | req = urllib.request.Request(sys.argv[1], data) 15 | with urllib.request.urlopen(req) as res: 16 | print(res.read().decode('utf-8')) 17 | -------------------------------------------------------------------------------- /0x10-python-network_1/3-error_code.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Take in a URL, send a request to URL, and dispaly body of response decoded in 4 | utf-8. Manage urllib's error exceptions. 5 | """ 6 | import sys 7 | import urllib.request 8 | import urllib.error 9 | 10 | if __name__ == "__main__": 11 | req = urllib.request.Request(sys.argv[1]) 12 | try: 13 | with urllib.request.urlopen(req) as res: 14 | print(res.read().decode('utf-8')) 15 | except urllib.error.URLError as e: 16 | print("Error code: {}".format(e.code)) 17 | -------------------------------------------------------------------------------- /0x10-python-network_1/4-hbtn_status.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Use requests package to make a get request to given URL 3 | import requests 4 | 5 | if __name__ == "__main__": 6 | url = "https://intranet.hbtn.io/status" 7 | r = requests.get(url) 8 | print("Body response:") 9 | print("\t- type: {}".format(type(r.text))) 10 | print("\t- content: {}".format(r.text)) 11 | -------------------------------------------------------------------------------- /0x10-python-network_1/5-hbtn_header.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Use requests package to make a get request to given URL and display 4 | the value of `X-Request-Id` in response header. 5 | """ 6 | import sys 7 | import requests 8 | 9 | if __name__ == "__main__": 10 | url = sys.argv[1] 11 | r = requests.get(url) 12 | print(r.headers['x-request-id']) 13 | -------------------------------------------------------------------------------- /0x10-python-network_1/6-post_email.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Use requests package to make a post request sending email param 4 | and display body of response. 5 | """ 6 | import sys 7 | import requests 8 | 9 | if __name__ == "__main__": 10 | url = sys.argv[1] 11 | payload = {'email': sys.argv[2]} 12 | r = requests.post(url, data=payload) 13 | print(r.text) 14 | -------------------------------------------------------------------------------- /0x10-python-network_1/7-error_code.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Use requests package to make a get request to given URL and display 4 | the body of response, or error code if error. 5 | """ 6 | import sys 7 | import requests 8 | 9 | if __name__ == "__main__": 10 | url = sys.argv[1] 11 | r = requests.get(url) 12 | try: 13 | r.raise_for_status() 14 | print(r.text) 15 | except Exception as e: 16 | print("Error code: {}".format(r.status_code)) 17 | -------------------------------------------------------------------------------- /0x10-python-network_1/8-json_api.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Use requests package to make a post request to given URL with argument 4 | set in variable `q`, defaulting to empty string. If response body is properly 5 | JSON formatted and not empty, display `id` and `name` as given format. 6 | Otherwise display error message. 7 | """ 8 | import sys 9 | import requests 10 | 11 | if __name__ == "__main__": 12 | if len(sys.argv) > 1: 13 | arg = sys.argv[1] 14 | else: 15 | arg = "" 16 | payload = {'q': arg} 17 | url = "http://0.0.0.0:5000/search_user" 18 | r = requests.post(url, data=payload) 19 | try: 20 | r.raise_for_status() 21 | json = r.json() 22 | if len(json) == 0: 23 | print("No result") 24 | else: 25 | print("[{:d}] {}".format(json['id'], json['name'])) 26 | except Exception: 27 | print("Not a valid JSON") 28 | -------------------------------------------------------------------------------- /0x10-python-network_1/9-starwars.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Use requests package to make a get request to the swapi api. 4 | Use string argument as search value of request. Body response must 5 | be JSON and formatted to a Python dictionary. 6 | """ 7 | import sys 8 | import requests 9 | 10 | if __name__ == "__main__": 11 | url = "https://swapi.co/api/people/?search={}".format(sys.argv[1]) 12 | r = requests.get(url).json() 13 | print("Number of result: {}".format(r['count'])) 14 | for c in r['results']: 15 | print(c['name']) 16 | -------------------------------------------------------------------------------- /0x10-python-network_1/README.md: -------------------------------------------------------------------------------- 1 | # 0x10. Python - Network 1 -------------------------------------------------------------------------------- /0x11-javascript-warm_up/0-javascript_is_amazing.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const myVar = 'Javascript is amazing'; 3 | console.log(myVar); 4 | -------------------------------------------------------------------------------- /0x11-javascript-warm_up/1-multi_languages.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | console.log('C is fun'); 3 | console.log('Python is cool'); 4 | console.log('Javascript is amazing'); 5 | -------------------------------------------------------------------------------- /0x11-javascript-warm_up/10-factorial.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | function factorial (n) { 3 | if (isNaN(n) || n === 0) { 4 | return 1; 5 | } else { 6 | return n * factorial(n - 1); 7 | } 8 | } 9 | 10 | console.log(factorial(parseInt(process.argv[2]))); 11 | -------------------------------------------------------------------------------- /0x11-javascript-warm_up/100-let_me_const.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | myVar = 333; 3 | -------------------------------------------------------------------------------- /0x11-javascript-warm_up/101-call_me_moby.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | module.exports = { 3 | callMeMoby: function (n, f) { 4 | for (let i = 0; i < n; i++) { 5 | f(); 6 | } 7 | } 8 | }; 9 | -------------------------------------------------------------------------------- /0x11-javascript-warm_up/102-add_me_maybe.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | module.exports = { 3 | addMeMaybe: function (n, f) { 4 | return f(n + 1); 5 | } 6 | }; 7 | -------------------------------------------------------------------------------- /0x11-javascript-warm_up/103-object_fct.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | let myObject = { 3 | type: 'object', 4 | value: 12 5 | }; 6 | console.log(myObject); 7 | 8 | myObject.incr = function () { 9 | return 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 | -------------------------------------------------------------------------------- /0x11-javascript-warm_up/11-second_biggest.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | let args = process.argv.slice(2).map((x) => { 3 | return parseInt(x); 4 | }); 5 | 6 | if (args.length <= 1) { 7 | console.log(0); 8 | } else { 9 | console.log(args.sort((a, b) => { 10 | return b - a; 11 | })[1]); 12 | } 13 | -------------------------------------------------------------------------------- /0x11-javascript-warm_up/12-object.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | let myObject = { 3 | type: 'object', 4 | value: 12 5 | }; 6 | console.log(myObject); 7 | myObject.value = 89; 8 | console.log(myObject); 9 | -------------------------------------------------------------------------------- /0x11-javascript-warm_up/13-add.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | module.exports = { 3 | add: function (a, b) { 4 | return a + b; 5 | } 6 | }; 7 | -------------------------------------------------------------------------------- /0x11-javascript-warm_up/2-arguments.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const numArgs = process.argv.length - 2; 3 | if (numArgs === 0) { 4 | console.log('No argument'); 5 | } else if (numArgs === 1) { 6 | console.log('Argument found'); 7 | } else { 8 | console.log('Arguments found'); 9 | } 10 | -------------------------------------------------------------------------------- /0x11-javascript-warm_up/3-value_argument.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const firstArg = process.argv[2]; 3 | if (firstArg === undefined) { 4 | console.log('No argument'); 5 | } else { 6 | console.log(firstArg); 7 | } 8 | -------------------------------------------------------------------------------- /0x11-javascript-warm_up/4-concat.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const args = process.argv; 3 | console.log(args[2] + ' is ' + args[3]); 4 | -------------------------------------------------------------------------------- /0x11-javascript-warm_up/5-to_integer.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const convertArg = parseInt(process.argv[2]); 3 | if (isNaN(convertArg)) { 4 | console.log('Not a number'); 5 | } else { 6 | console.log('My number: ' + convertArg); 7 | } 8 | -------------------------------------------------------------------------------- /0x11-javascript-warm_up/6-multi_languages_loop.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const strings = ['C is fun', 'Python is cool', 'Javascript is amazing']; 3 | for (let i = 0; i < strings.length; i++) { 4 | console.log(strings[i]); 5 | } 6 | -------------------------------------------------------------------------------- /0x11-javascript-warm_up/7-multi_c.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const times = parseInt(process.argv[2]); 3 | if (isNaN(times)) { 4 | console.log('Missing number of occurrences'); 5 | } else { 6 | for (let i = 0; i < times; i++) { 7 | console.log('C is fun'); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /0x11-javascript-warm_up/8-square.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const size = parseInt(process.argv[2]); 3 | if (isNaN(size)) { 4 | console.log('Missing size'); 5 | } else { 6 | for (let i = 0; i < size; i++) { 7 | console.log('X'.repeat(size)); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /0x11-javascript-warm_up/9-add.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const first = parseInt(process.argv[2]); 3 | const second = parseInt(process.argv[3]); 4 | function add (a, b) { 5 | if (isNaN(a) || isNaN(b)) { 6 | return NaN; 7 | } 8 | return a + b; 9 | } 10 | console.log(add(first, second)); 11 | -------------------------------------------------------------------------------- /0x11-javascript-warm_up/README.md: -------------------------------------------------------------------------------- 1 | # 0x11. Javascript - Warm up 2 | -------------------------------------------------------------------------------- /0x12-javascript-web_scraping/0-rectangle.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | module.exports = { 3 | Rectangle: function () {} 4 | }; 5 | -------------------------------------------------------------------------------- /0x12-javascript-web_scraping/1-rectangle.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | module.exports = { 3 | Rectangle: function (w, h) { 4 | this.width = w; 5 | this.height = h; 6 | } 7 | }; 8 | -------------------------------------------------------------------------------- /0x12-javascript-web_scraping/10-starwars_title.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const request = require('request'); 3 | 4 | const episodeId = process.argv[2]; 5 | 6 | if (parseInt(episodeId) < 8) { 7 | const url = 'http://swapi.co/api/films/' + episodeId; 8 | 9 | request(url, (err, res, body) => { 10 | if (err) { 11 | return console.log(err); 12 | } 13 | console.log(JSON.parse(body).title); 14 | }); 15 | } 16 | -------------------------------------------------------------------------------- /0x12-javascript-web_scraping/100-data.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | exports.list = [1, 2, 3, 4, 5]; 3 | -------------------------------------------------------------------------------- /0x12-javascript-web_scraping/100-map.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | let list = require('./100-data').list; 3 | 4 | console.log(list); 5 | 6 | list = list.map((n, i) => { 7 | return n * i; 8 | }); 9 | 10 | console.log(list); 11 | -------------------------------------------------------------------------------- /0x12-javascript-web_scraping/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 | -------------------------------------------------------------------------------- /0x12-javascript-web_scraping/101-sorted.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | let dict = require('./101-data').dict; 3 | 4 | let storage = {}; 5 | 6 | for (let item in dict) { 7 | if (!storage[dict[item]]) { 8 | storage[dict[item]] = []; 9 | } 10 | storage[dict[item]].push(item); 11 | } 12 | 13 | console.log(storage); 14 | -------------------------------------------------------------------------------- /0x12-javascript-web_scraping/102-concat.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const fs = require('fs'); 3 | 4 | let fileA = process.argv[2]; 5 | let fileB = process.argv[3]; 6 | let fileC = process.argv[4]; 7 | 8 | try { 9 | [fileA, fileB].forEach((f) => { 10 | fs.readFileSync(f).toString().trim().split('\n').forEach((line) => { 11 | fs.appendFileSync(fileC, line.toString() + '\n'); 12 | }); 13 | }); 14 | } catch (err) { 15 | console.log(err); 16 | } 17 | -------------------------------------------------------------------------------- /0x12-javascript-web_scraping/11-starwars_count.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const request = require('request'); 3 | 4 | const url = process.argv[2]; 5 | 6 | request(url, (err, res, body) => { 7 | if (err) { 8 | return console.log(err); 9 | } 10 | 11 | let count = 0; 12 | let parsedBody = JSON.parse(body).results; 13 | 14 | for (let i = 0; i < parsedBody.length; i++) { 15 | let a = parsedBody[i].characters.find((c) => { 16 | return c.match(/18/); 17 | }); 18 | if (a !== undefined) { 19 | count++; 20 | } 21 | } 22 | 23 | console.log(count); 24 | }); 25 | -------------------------------------------------------------------------------- /0x12-javascript-web_scraping/12-request_store.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const fs = require('fs'); 3 | const request = require('request'); 4 | 5 | const url = process.argv[2] || ''; 6 | const filePath = process.argv[3]; 7 | 8 | request(url, (err, res, body) => { 9 | if (err) { 10 | return console.log(err); 11 | } 12 | 13 | fs.writeFile(filePath, body, 'utf8', (err) => { 14 | if (err) { 15 | return console.log(err); 16 | } 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /0x12-javascript-web_scraping/13-completed_tasks.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const request = require('request'); 3 | 4 | const url = process.argv[2] || ''; 5 | let storage = {}; 6 | 7 | request(url, (err, res, body) => { 8 | if (err) { 9 | return console.log(err); 10 | } 11 | 12 | let parsedBody = JSON.parse(body); 13 | 14 | for (let i = 0; i < parsedBody.length; i++) { 15 | let tmp = parsedBody[i].userId; 16 | if (parsedBody[i].completed) { 17 | storage[tmp] = (storage[tmp] || 0) + 1; 18 | } 19 | } 20 | 21 | console.log(storage); 22 | }); 23 | -------------------------------------------------------------------------------- /0x12-javascript-web_scraping/2-rectangle.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | module.exports = { 3 | Rectangle: function (w, h) { 4 | if (w > 0 && h > 0) { 5 | this.width = w; 6 | this.height = h; 7 | } 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /0x12-javascript-web_scraping/3-rectangle.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | module.exports = { 3 | Rectangle: function (w, h) { 4 | if (w > 0 && h > 0) { 5 | this.width = w; 6 | this.height = h; 7 | } 8 | this.print = function () { 9 | for (let i = 0; i < this.height; i++) { 10 | console.log(('X').repeat(this.width)); 11 | } 12 | }; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /0x12-javascript-web_scraping/4-rectangle.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | module.exports = { 3 | Rectangle: function (w, h) { 4 | if (w > 0 && h > 0) { 5 | this.width = w; 6 | this.height = h; 7 | } 8 | this.print = function () { 9 | for (let i = 0; i < this.height; i++) { 10 | console.log(('X').repeat(this.width)); 11 | } 12 | }; 13 | this.rotate = function () { 14 | [this.width, this.height] = [this.height, this.width]; 15 | }; 16 | this.double = function () { 17 | this.width *= 2; 18 | this.height *= 2; 19 | }; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /0x12-javascript-web_scraping/5-square.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const Rectangle = require('./4-rectangle.js').Rectangle; 3 | 4 | function Square (size) { 5 | Rectangle.call(this, size, size); 6 | } 7 | 8 | module.exports = { Square, Rectangle }; 9 | -------------------------------------------------------------------------------- /0x12-javascript-web_scraping/6-square.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const Square = require('./5-square.js').Square; 3 | 4 | Square.prototype.charPrint = function (c) { 5 | if (c === undefined) { 6 | c = 'X'; 7 | } 8 | for (let i = 0; i < this.height; i++) { 9 | console.log((c).repeat(this.width)); 10 | } 11 | }; 12 | 13 | module.exports = {Square}; 14 | -------------------------------------------------------------------------------- /0x12-javascript-web_scraping/7-readme.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const fs = require('fs'); 3 | 4 | fs.readFile(process.argv[2], 'utf8', (err, data) => { 5 | if (err) { 6 | return console.log(err); 7 | } 8 | process.stdout.write(data); 9 | }); 10 | -------------------------------------------------------------------------------- /0x12-javascript-web_scraping/8-writeme.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const fs = require('fs'); 3 | 4 | const file = process.argv[2] || ''; 5 | const data = process.argv[3] || ''; 6 | 7 | fs.writeFile(file, data, 'utf8', (err) => { 8 | if (err) { 9 | return console.log(err); 10 | } 11 | }); 12 | -------------------------------------------------------------------------------- /0x12-javascript-web_scraping/9-statuscode.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const request = require('request'); 3 | 4 | const url = process.argv[2] || ''; 5 | 6 | request(url, (err, res, body) => { 7 | if (err) { 8 | return console.log(err); 9 | } 10 | console.log('code: ' + res.statusCode); 11 | }); 12 | -------------------------------------------------------------------------------- /0x12-javascript-web_scraping/README.md: -------------------------------------------------------------------------------- 1 | # 0x12. Javascript - Web scraping -------------------------------------------------------------------------------- /0x13-javascript-web_jquery/0-tag_count.txt: -------------------------------------------------------------------------------- 1 | 6 2 | -------------------------------------------------------------------------------- /0x13-javascript-web_jquery/1-tag_count.txt: -------------------------------------------------------------------------------- 1 | 12 2 | -------------------------------------------------------------------------------- /0x13-javascript-web_jquery/10-selector.txt: -------------------------------------------------------------------------------- 1 | No 2 | -------------------------------------------------------------------------------- /0x13-javascript-web_jquery/100-script.js: -------------------------------------------------------------------------------- 1 | document.addEventListener('DOMContentLoaded', function () { 2 | document.querySelector('header').style.color = 'FF0000'; 3 | }); 4 | -------------------------------------------------------------------------------- /0x13-javascript-web_jquery/101-script.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function () { 2 | $('div#add_item').on('click', function () { 3 | $('ul.my_list').append('
  • Item
  • '); 4 | }); 5 | 6 | $('div#remove_item').on('click', function () { 7 | $('ul.my_list li:last-child').remove(); 8 | }); 9 | 10 | $('div#clear_list').on('click', function () { 11 | $('ul.my_list').empty(); 12 | }); 13 | }); 14 | -------------------------------------------------------------------------------- /0x13-javascript-web_jquery/102-script.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function () { 2 | $('#btn_search').on('click', function () { 3 | let cityName = $('#city_search').val(); 4 | $('#city_search').val(''); 5 | 6 | let url = 'https://query.yahooapis.com/v1/public/yql?q=select%20wind%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22' + cityName + '%22)&format=json'; 7 | 8 | $.get(url, (data) => { 9 | $('DIV#sf_wind_speed').text(data.query.results.channel.wind.speed); 10 | }); 11 | }); 12 | }); 13 | -------------------------------------------------------------------------------- /0x13-javascript-web_jquery/103-script.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function () { 2 | $('INPUT#city_search').keypress(function (e) { 3 | if (e.which === 13) { 4 | $('#btn_search').click(); 5 | } 6 | }); 7 | 8 | $('#btn_search').on('click', function () { 9 | let cityName = $('#city_search').val(); 10 | $('#city_search').val(''); 11 | 12 | let url = 'https://query.yahooapis.com/v1/public/yql?q=select%20wind%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22' + cityName + '%22)&format=json'; 13 | 14 | $.get(url, (data) => { 15 | $('DIV#wind_speed').text(data.query.results.channel.wind.speed); 16 | }); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /0x13-javascript-web_jquery/11-selector.txt: -------------------------------------------------------------------------------- 1 | No 2 | -------------------------------------------------------------------------------- /0x13-javascript-web_jquery/12-selector.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x13-javascript-web_jquery/13-selector.txt: -------------------------------------------------------------------------------- 1 | No 2 | -------------------------------------------------------------------------------- /0x13-javascript-web_jquery/14-script.js: -------------------------------------------------------------------------------- 1 | let header = document.querySelector('header'); 2 | header.style.color = '#FF0000'; 3 | -------------------------------------------------------------------------------- /0x13-javascript-web_jquery/15-script.js: -------------------------------------------------------------------------------- 1 | $('header').css('color', '#FF0000'); 2 | -------------------------------------------------------------------------------- /0x13-javascript-web_jquery/16-script.js: -------------------------------------------------------------------------------- 1 | $('div#red_header').on('click', function () { 2 | $('header').css('color', '#FF0000'); 3 | }); 4 | -------------------------------------------------------------------------------- /0x13-javascript-web_jquery/17-script.js: -------------------------------------------------------------------------------- 1 | $('div#red_header').on('click', function () { 2 | $('header').addClass('red'); 3 | }); 4 | -------------------------------------------------------------------------------- /0x13-javascript-web_jquery/18-script.js: -------------------------------------------------------------------------------- 1 | $('div#toggle_header').on('click', function () { 2 | $('header').toggleClass(function () { 3 | return $(this).hasClass('red') ? 'green' : 'red'; 4 | }); 5 | }); 6 | -------------------------------------------------------------------------------- /0x13-javascript-web_jquery/19-script.js: -------------------------------------------------------------------------------- 1 | $('div#add_item').on('click', function () { 2 | $('ul.my_list').append('
  • Item
  • '); 3 | }); 4 | -------------------------------------------------------------------------------- /0x13-javascript-web_jquery/2-tag_count.txt: -------------------------------------------------------------------------------- 1 | 15 2 | -------------------------------------------------------------------------------- /0x13-javascript-web_jquery/20-script.js: -------------------------------------------------------------------------------- 1 | $('div#update_header').on('click', function () { 2 | $('header').text('New Header!!!'); 3 | }); 4 | -------------------------------------------------------------------------------- /0x13-javascript-web_jquery/21-script.js: -------------------------------------------------------------------------------- 1 | $.get('https://swapi.co/api/people/5/?format=json', (data) => { 2 | $('DIV#character').text(data.name); 3 | }); 4 | -------------------------------------------------------------------------------- /0x13-javascript-web_jquery/22-script.js: -------------------------------------------------------------------------------- 1 | $.get('http://swapi.co/api/films?format=json', (data) => { 2 | for (let i = 0; i < data.results.length; i++) { 3 | $('ul#list_movies').append('
  • ' + data.results[i].title + '
  • '); 4 | } 5 | }); 6 | -------------------------------------------------------------------------------- /0x13-javascript-web_jquery/23-script.js: -------------------------------------------------------------------------------- 1 | const url = 'https://query.yahooapis.com/v1/public/yql?q=select%20wind%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22San%20Francisco%2C%20CA%22)&format=json'; 2 | 3 | $.get(url, (data) => { 4 | $('DIV#sf_wind_speed').text(data.query.results.channel.wind.speed); 5 | }); 6 | -------------------------------------------------------------------------------- /0x13-javascript-web_jquery/3-selector.txt: -------------------------------------------------------------------------------- 1 | No 2 | -------------------------------------------------------------------------------- /0x13-javascript-web_jquery/4-selector.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x13-javascript-web_jquery/5-selector.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x13-javascript-web_jquery/6-selector.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x13-javascript-web_jquery/7-selector.txt: -------------------------------------------------------------------------------- 1 | No 2 | -------------------------------------------------------------------------------- /0x13-javascript-web_jquery/8-selector.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x13-javascript-web_jquery/9-selector.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x13-javascript-web_jquery/README.md: -------------------------------------------------------------------------------- 1 | # 0x13. Javascript - Web JQuery 2 | --------------------------------------------------------------------------------