├── 0x06-python-classes
├── 102-square.py
├── README.md
├── 0-square.py
├── 1-square.py
├── 2-square.py
├── 3-square.py
├── 4-square.py
├── 5-square.py
├── 6-square.py
├── 100-singly_linked_list.py
└── 101-square.py
├── 0x07-python-test_driven_development
├── 102-python.c
├── 100-matrix_mul.py
├── 101-lazy_matrix_mul.py
├── tests
│ ├── 100-matrix_mul.txt
│ ├── 101-lazy_matrix_mul.txt
│ ├── 4-print_square.txt
│ ├── 0-add_integer.txt
│ ├── 5-text_indentation.txt
│ ├── 3-say_my_name.txt
│ ├── 6-max_integer_test.py
│ └── 2-matrix_divided.txt
├── README.md
├── __pycache__
│ ├── 0-add_integer.cpython-39.pyc
│ └── 2-matrix_divided.cpython-39.pyc
├── 0-add_integer.py
├── 3-say_my_name.py
├── 5-text_indentation.py
├── 4-print_square.py
└── 2-matrix_divided.py
├── 0x0B-python-input_output
├── tests
│ └── 7-add_item.py
├── README.md
├── 8-class_to_json.py
├── 3-to_json_string.py
├── 0-read_file.py
├── 6-load_from_json_file.py
├── 4-from_json_string.py
├── 5-save_to_json_file.py
├── 7-add_item.py
├── 9-student.py
├── 12-pascal_triangle.py
├── 2-append_write.py
├── 1-write_file.py
├── 100-append_after.py
├── 10-student.py
├── 11-student.py
└── 101-stats.py
├── 0x0C-python-almost_a_circle
├── models
│ ├── __init__.py
│ ├── README.md
│ ├── base.py
│ ├── square.py
│ └── rectangle.py
├── README.md
└── tests
│ ├── README.md
│ ├── test_base.py
│ ├── 0-test_base.txt
│ └── 0-main.py
├── 0x09-python-everything_is_object
├── 1-answer.txt
├── 103-line1.txt
├── 103-line2.txt
├── 104-line1.txt
├── 104-line2.txt
├── 104-line5.txt
├── 106-line1.txt
├── 106-line2.txt
├── 106-line3.txt
├── 106-line5.txt
├── 16-answer.txt
├── 2-answer.txt
├── 22-answer.txt
├── 27-answer.txt
├── 3-answer.txt
├── 4-answer.txt
├── 5-answer.txt
├── 0-answer.txt
├── 10-answer.txt
├── 104-line3.txt
├── 104-line4.txt
├── 105-line1.txt
├── 106-line4.txt
├── 11-answer.txt
├── 12-answer.txt
├── 13-answer.txt
├── 20-answer.txt
├── 21-answer.txt
├── 23-answer.txt
├── 24-answer.txt
├── 25-answer.txt
├── 26-answer.txt
├── 28-answer.txt
├── 6-answer.txt
├── 7-answer.txt
├── 8-answer.txt
├── 9-answer.txt
├── 14-answer.txt
├── 15-answer.txt
├── 17-answer.txt
├── 18-answer.txt
├── README.md
├── 19-copy_list.py
├── 100-magic_string.py
└── 101-locked_class.py
├── 0x00-python-hello_world
├── README.md
├── 0-run
├── 1-run_inline
├── 9-easter_egg.py
├── main.py
├── 4-print_float.py
├── 2-print.py
├── 3-print_number.py
├── 102-magic_calculation.py
├── 5-print_string.py
├── cycle
├── 101-compile
├── 6-concat.py
├── 100-write.py
├── 8-concat_edges.py
├── 7-edges.py
├── lists.h
├── 10-check_cycle.c
├── 10-main.c
└── 10-linked_lists.c
├── 0x05-python-exceptions
├── README.md
├── 5-raise_exception.py
├── 6-raise_exception_msg.py
├── 1-safe_print_integer.py
├── 101-safe_function.py
├── 3-safe_print_division.py
├── 0-safe_print_list.py
├── 100-safe_print_integer_err.py
├── 2-safe_print_list_integers.py
├── 102-magic_calculation.py
├── 4-list_division.py
└── 103-python.c
├── 0x11-python-network_1
├── README.md
├── 6-post_email.py
├── 1-hbtn_header.py
├── 10-my_github.py
├── 2-post_email.py
├── 4-hbtn_status.py
├── 5-hbtn_header.py
├── 7-error_code.py
├── 8-json_api.py
├── 0-hbtn_status.py
├── 3-error_code.py
└── 100-github_commits.py
├── README.md
├── 0x0A-python-inheritance
├── README.md
├── 5-base_geometry.py
├── 6-base_geometry.py
├── 1-my_list.py
├── 0-lookup.py
├── 100-my_int.py
├── 11-square.py
├── 10-square.py
├── 2-is_same_class.py
├── 101-add_attribute.py
├── 4-inherits_from.py
├── 3-is_kind_of_class.py
├── tests
│ ├── 2-is_same_class.txt
│ ├── 7-base_geometry.txt
│ └── 1-my_list.txt
├── 8-rectangle.py
├── 7-base_geometry.py
└── 9-rectangle.py
├── 0x12-javascript-warm_up
├── README.md
├── 100-let_me_const.js
├── 13-add.js
├── 4-concat.js
├── 0-javascript_is_amazing.js
├── 102-add_me_maybe.js
├── 3-value_argument.js
├── 101-call_me_moby.js
├── 12-object.js
├── 6-multi_languages_loop.js
├── 5-to_integer.js
├── 1-multi_languages.js
├── 9-add.js
├── 2-arguments.js
├── 8-square.js
├── 11-second_biggest.js
├── 7-multi_c.js
├── 103-object_fct.js
└── 10-factorial.js
├── 0x02-python-import_modules
├── README.md
├── 101-easy_print.py
├── 103-fast_alphabet.py
├── 0-add.py
├── 4-hidden_discovery.py
├── 5-variable_load.py
├── 102-magic_calculation.py
├── 2-args.py
├── 1-calculation.py
├── 3-infinite_add.py
└── 100-my_calculator.py
├── 0x15-javascript-web_jquery
├── README.md
├── 2-script.js
├── 5-script.js
├── 6-script.js
├── 4-script.js
├── 0-script.js
├── 7-script.js
├── 3-script.js
├── 9-script.js
├── 8-script.js
├── 100-script.js
├── 101-script.js
├── 102-script.js
├── 103-script.js
└── 1-script.js
├── 0x08-python-more_classes
├── README.md
├── 0-rectangle.py
├── 101-nqueens.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
├── 0x14-javascript-web_scraping
├── README.md
├── 5-request_store.js
├── 2-statuscode.js
├── 0-readme.js
├── 1-writeme.js
├── 3-starwars_title.js
├── 6-completed_tasks.js
├── 4-starwars_count.js
├── 100-starwars_characters.js
└── 101-starwars_characters.js
├── 0x03-python-data_structures
├── README.md
├── 12-switch.py
├── 11-delete_at.py
├── 5-no_c.py
├── 0-print_list_integer.py
├── 8-multiple_returns.py
├── 1-element_at.py
├── 2-replace_in_list.py
├── 4-new_in_list.py
├── 3-print_reversed_list_integer.py
├── 6-print_matrix_integer.py
├── 9-max_integer.py
├── 10-divisible_by_2.py
├── 7-add_tuple.py
├── lists.h
├── 100-print_python_list_info.c
└── 13-is_palindrome.c
├── 0x01-python-if_else_loops_functions
├── README.md
├── 10-add.py
├── 11-pow.py
├── 2-print_alphabet.py
├── 4-print_hexa.py
├── 9-print_last_digit.py
├── 7-islower.py
├── 101-remove_char_at.py
├── 3-print_alphabt.py
├── 102-magic_calculation.py
├── 5-print_comb2.py
├── 100-print_tebahpla.py
├── 0-positive_or_negative.py
├── 8-uppercase.py
├── 6-print_comb3.py
├── 12-fizzbuzz.py
├── 1-last_digit.py
├── lists.h
└── 13-insert_number.c
├── 0x04-python-more_data_structures
├── README.md
├── 3-common_elements.py
├── 11-multiply_list_map.py
├── 101-square_matrix_map.py
├── 5-number_keys.py
├── 0-square_matrix_simple.py
├── 4-only_diff_elements.py
├── 8-simple_delete.py
├── 9-multiply_by_2.py
├── 7-update_dictionary.py
├── 2-uniq_add.py
├── 6-print_sorted_dictionary.py
├── 1-search_replace.py
├── 102-complex_delete.py
├── 100-weight_average.py
├── 10-best_score.py
├── 12-roman_to_int.py
└── 103-python.c
├── 0x0F-python-object_relational_mapping
├── README.md
├── 6-model_state.py
├── 0-select_states.py
├── 1-filter_states.py
├── 3-my_safe_filter_states.py
├── 2-my_filter_states.py
├── model_state.py
├── 14-model_city_fetch_by_state.py
├── 5-filter_cities.py
├── 7-model_state_fetch_all.py
├── 9-model_state_filter_a.py
├── 8-model_state_fetch_first.py
├── 12-model_state_update_id_2.py
├── 11-model_state_insert.py
├── 13-model_state_delete_a.py
├── 4-cities_by_state.py
├── model_city.py
└── 10-model_state_my_get.py
└── 0x13-javascript_objects_scopes_closures
├── README.md
├── 100-data.js
├── 0-rectangle.js
├── 9-logme.js
├── 10-converter.js
├── 8-main.js
├── 100-map.js
├── 2-rectangle.js
├── 5-square.js
├── 1-rectangle.js
├── 7-occurrences.js
├── 3-rectangle.js
├── 8-esrever.js
├── 6-square.js
└── 4-rectangle.js
/0x06-python-classes/102-square.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/0x07-python-test_driven_development/102-python.c:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/0x0B-python-input_output/tests/7-add_item.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/0x0C-python-almost_a_circle/models/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/0x07-python-test_driven_development/100-matrix_mul.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/0x09-python-everything_is_object/1-answer.txt:
--------------------------------------------------------------------------------
1 | id
2 |
--------------------------------------------------------------------------------
/0x09-python-everything_is_object/103-line1.txt:
--------------------------------------------------------------------------------
1 | 0
2 |
--------------------------------------------------------------------------------
/0x09-python-everything_is_object/103-line2.txt:
--------------------------------------------------------------------------------
1 | 0
2 |
--------------------------------------------------------------------------------
/0x09-python-everything_is_object/104-line1.txt:
--------------------------------------------------------------------------------
1 | 1
2 |
--------------------------------------------------------------------------------
/0x09-python-everything_is_object/104-line2.txt:
--------------------------------------------------------------------------------
1 | 1
2 |
--------------------------------------------------------------------------------
/0x09-python-everything_is_object/104-line5.txt:
--------------------------------------------------------------------------------
1 | 1
2 |
--------------------------------------------------------------------------------
/0x09-python-everything_is_object/106-line1.txt:
--------------------------------------------------------------------------------
1 | 1
2 |
--------------------------------------------------------------------------------
/0x09-python-everything_is_object/106-line2.txt:
--------------------------------------------------------------------------------
1 | 0
2 |
--------------------------------------------------------------------------------
/0x09-python-everything_is_object/106-line3.txt:
--------------------------------------------------------------------------------
1 | No
2 |
--------------------------------------------------------------------------------
/0x09-python-everything_is_object/106-line5.txt:
--------------------------------------------------------------------------------
1 | 1
2 |
--------------------------------------------------------------------------------
/0x09-python-everything_is_object/16-answer.txt:
--------------------------------------------------------------------------------
1 | 1
2 |
--------------------------------------------------------------------------------
/0x09-python-everything_is_object/2-answer.txt:
--------------------------------------------------------------------------------
1 | No
2 |
--------------------------------------------------------------------------------
/0x09-python-everything_is_object/22-answer.txt:
--------------------------------------------------------------------------------
1 | No
2 |
--------------------------------------------------------------------------------
/0x09-python-everything_is_object/27-answer.txt:
--------------------------------------------------------------------------------
1 | No
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 |
--------------------------------------------------------------------------------
/0x00-python-hello_world/README.md:
--------------------------------------------------------------------------------
1 | 0. Run Python file
2 |
--------------------------------------------------------------------------------
/0x05-python-exceptions/README.md:
--------------------------------------------------------------------------------
1 | Python - Exceptions
2 |
--------------------------------------------------------------------------------
/0x07-python-test_driven_development/101-lazy_matrix_mul.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/0x09-python-everything_is_object/0-answer.txt:
--------------------------------------------------------------------------------
1 | type
2 |
--------------------------------------------------------------------------------
/0x09-python-everything_is_object/10-answer.txt:
--------------------------------------------------------------------------------
1 | True
2 |
--------------------------------------------------------------------------------
/0x09-python-everything_is_object/104-line3.txt:
--------------------------------------------------------------------------------
1 | Yes
2 |
--------------------------------------------------------------------------------
/0x09-python-everything_is_object/104-line4.txt:
--------------------------------------------------------------------------------
1 | Yes
2 |
--------------------------------------------------------------------------------
/0x09-python-everything_is_object/105-line1.txt:
--------------------------------------------------------------------------------
1 | 262
2 |
--------------------------------------------------------------------------------
/0x09-python-everything_is_object/106-line4.txt:
--------------------------------------------------------------------------------
1 | Yes
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/20-answer.txt:
--------------------------------------------------------------------------------
1 | Yes
2 |
--------------------------------------------------------------------------------
/0x09-python-everything_is_object/21-answer.txt:
--------------------------------------------------------------------------------
1 | Yes
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/28-answer.txt:
--------------------------------------------------------------------------------
1 | Yes
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 |
--------------------------------------------------------------------------------
/0x0C-python-almost_a_circle/models/README.md:
--------------------------------------------------------------------------------
1 | # models
2 |
--------------------------------------------------------------------------------
/0x11-python-network_1/README.md:
--------------------------------------------------------------------------------
1 | # Python - Network
2 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # alx-higher_level_programming
2 | > python
3 |
--------------------------------------------------------------------------------
/0x06-python-classes/README.md:
--------------------------------------------------------------------------------
1 | Python - Classes and Objects
2 |
--------------------------------------------------------------------------------
/0x07-python-test_driven_development/tests/100-matrix_mul.txt:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/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/17-answer.txt:
--------------------------------------------------------------------------------
1 | [1, 2, 3, 4]
2 |
--------------------------------------------------------------------------------
/0x09-python-everything_is_object/18-answer.txt:
--------------------------------------------------------------------------------
1 | [1, 2, 3]
2 |
--------------------------------------------------------------------------------
/0x0A-python-inheritance/README.md:
--------------------------------------------------------------------------------
1 | # Python - Inheritance
2 |
--------------------------------------------------------------------------------
/0x0B-python-input_output/README.md:
--------------------------------------------------------------------------------
1 | # python-input_output
2 |
--------------------------------------------------------------------------------
/0x12-javascript-warm_up/README.md:
--------------------------------------------------------------------------------
1 | # JavaScript - Warm up
2 |
--------------------------------------------------------------------------------
/0x00-python-hello_world/0-run:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | python3 $PYFILE
3 |
--------------------------------------------------------------------------------
/0x02-python-import_modules/README.md:
--------------------------------------------------------------------------------
1 | Python - import & modules
2 |
--------------------------------------------------------------------------------
/0x07-python-test_driven_development/tests/101-lazy_matrix_mul.txt:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/0x0C-python-almost_a_circle/README.md:
--------------------------------------------------------------------------------
1 | # Python - Almost a circle
2 |
--------------------------------------------------------------------------------
/0x15-javascript-web_jquery/README.md:
--------------------------------------------------------------------------------
1 | # javascript-web_jquery
2 |
--------------------------------------------------------------------------------
/0x08-python-more_classes/README.md:
--------------------------------------------------------------------------------
1 | Python - More Classes and Objects
2 |
--------------------------------------------------------------------------------
/0x0C-python-almost_a_circle/tests/README.md:
--------------------------------------------------------------------------------
1 | # python-almost_a_circle
2 |
--------------------------------------------------------------------------------
/0x14-javascript-web_scraping/README.md:
--------------------------------------------------------------------------------
1 | # JavaScript - Web scraping
2 |
--------------------------------------------------------------------------------
/0x00-python-hello_world/1-run_inline:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | python3 -c "$PYCODE"
3 |
--------------------------------------------------------------------------------
/0x00-python-hello_world/9-easter_egg.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | import this
3 |
--------------------------------------------------------------------------------
/0x09-python-everything_is_object/README.md:
--------------------------------------------------------------------------------
1 | Python - Everything is object
2 |
--------------------------------------------------------------------------------
/0x00-python-hello_world/main.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | print("Best School")
3 |
--------------------------------------------------------------------------------
/0x03-python-data_structures/README.md:
--------------------------------------------------------------------------------
1 | Python - Data Structures: Lists, Tuples
2 |
--------------------------------------------------------------------------------
/0x07-python-test_driven_development/README.md:
--------------------------------------------------------------------------------
1 | Python - Test-driven development
2 |
--------------------------------------------------------------------------------
/0x12-javascript-warm_up/100-let_me_const.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 |
3 | myVar = 333;
4 |
--------------------------------------------------------------------------------
/0x01-python-if_else_loops_functions/README.md:
--------------------------------------------------------------------------------
1 | Python - if/else, loops, functions
2 |
3 |
--------------------------------------------------------------------------------
/0x04-python-more_data_structures/README.md:
--------------------------------------------------------------------------------
1 | Python - More Data Structures: Set, Dictionary
2 |
--------------------------------------------------------------------------------
/0x0F-python-object_relational_mapping/README.md:
--------------------------------------------------------------------------------
1 | # 0x0F-python-object_relational_mapping
2 |
--------------------------------------------------------------------------------
/0x13-javascript_objects_scopes_closures/README.md:
--------------------------------------------------------------------------------
1 | # javascript_objects_scopes_closures
2 |
--------------------------------------------------------------------------------
/0x01-python-if_else_loops_functions/10-add.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | def add(a, b):
3 | return (a+b)
4 |
--------------------------------------------------------------------------------
/0x13-javascript_objects_scopes_closures/100-data.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 | exports.list = [1, 2, 3, 4, 5];
3 |
--------------------------------------------------------------------------------
/0x01-python-if_else_loops_functions/11-pow.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | def pow(a, b):
3 | return (a ** b)
4 |
--------------------------------------------------------------------------------
/0x00-python-hello_world/4-print_float.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | number = 3.14159
3 | print(f"Float: {number:.2f}")
4 |
--------------------------------------------------------------------------------
/0x05-python-exceptions/5-raise_exception.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | def raise_exception():
3 | raise TypeError
4 |
--------------------------------------------------------------------------------
/0x09-python-everything_is_object/19-copy_list.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | def copy_list(lis):
3 | return lis[:]
4 |
--------------------------------------------------------------------------------
/0x00-python-hello_world/2-print.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | print('\"Programming is like building a multilingual puzzle')
3 |
--------------------------------------------------------------------------------
/0x00-python-hello_world/3-print_number.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | number = 98
3 | print(f"{number:d} Battery street")
4 |
--------------------------------------------------------------------------------
/0x02-python-import_modules/101-easy_print.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | __import__("sys").stdout.write("#pythoniscool\n")
3 |
--------------------------------------------------------------------------------
/0x02-python-import_modules/103-fast_alphabet.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | import string
3 | print(string.ascii_uppercase)
4 |
--------------------------------------------------------------------------------
/0x12-javascript-warm_up/13-add.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 |
3 | exports.add = function (a, b) {
4 | return (a + b);
5 | };
6 |
--------------------------------------------------------------------------------
/0x12-javascript-warm_up/4-concat.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 |
3 | console.log(`${process.argv[2]} is ${process.argv[3]}`);
4 |
--------------------------------------------------------------------------------
/0x15-javascript-web_jquery/2-script.js:
--------------------------------------------------------------------------------
1 | $('#red_header').on('click', () => {
2 | $('header').css('color', 'red');
3 | });
4 |
--------------------------------------------------------------------------------
/0x00-python-hello_world/102-magic_calculation.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | def magic_calculation(a, b):
3 | return (98 + a**b)
4 |
--------------------------------------------------------------------------------
/0x00-python-hello_world/5-print_string.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | str = "Holberton School"
3 | print(str*3)
4 | print(str[:9])
5 |
--------------------------------------------------------------------------------
/0x00-python-hello_world/cycle:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mukuvi/alx-higher_level_programming/HEAD/0x00-python-hello_world/cycle
--------------------------------------------------------------------------------
/0x13-javascript_objects_scopes_closures/0-rectangle.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 |
3 | module.exports = class Rectangle {
4 |
5 | };
6 |
--------------------------------------------------------------------------------
/0x15-javascript-web_jquery/5-script.js:
--------------------------------------------------------------------------------
1 | $('#add_item').on('click', () => {
2 | $('.my_list').append('
Item');
3 | });
4 |
--------------------------------------------------------------------------------
/0x15-javascript-web_jquery/6-script.js:
--------------------------------------------------------------------------------
1 | $('#update_header').on('click', () => {
2 | $('header').text('New Header!!!');
3 | });
4 |
--------------------------------------------------------------------------------
/0x15-javascript-web_jquery/4-script.js:
--------------------------------------------------------------------------------
1 | $('#toggle_header').on('click', () => {
2 | $('header').toggleClass('red green');
3 | });
4 |
--------------------------------------------------------------------------------
/0x00-python-hello_world/101-compile:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | python3 -m py_compile "$PYFILE"
3 | cp __pycache__/* "$PYFILE"c
4 | rm -rf __pycache__
5 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/0x12-javascript-warm_up/0-javascript_is_amazing.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 |
3 | const myVar = 'JavaScript is amazing';
4 | console.log(myVar);
5 |
--------------------------------------------------------------------------------
/0x01-python-if_else_loops_functions/2-print_alphabet.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | for c in range(97, 123):
3 | print("{:c}".format(c), end="")
4 |
--------------------------------------------------------------------------------
/0x05-python-exceptions/6-raise_exception_msg.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | def raise_exception_msg(message=""):
3 | raise NameError(message)
4 |
--------------------------------------------------------------------------------
/0x01-python-if_else_loops_functions/4-print_hexa.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | for num in range(0, 99):
3 | print("{0} = {1}".format(num, hex(num)))
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 |
--------------------------------------------------------------------------------
/0x04-python-more_data_structures/3-common_elements.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | def common_elements(set_1, set_2):
3 | return ([x for x in set_2 if x in set_1])
4 |
--------------------------------------------------------------------------------
/0x09-python-everything_is_object/100-magic_string.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | def magic_string(lis=[]):
3 | lis += ["BestSchool"]
4 | return ", ".join(lis)
5 |
--------------------------------------------------------------------------------
/0x01-python-if_else_loops_functions/9-print_last_digit.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | def print_last_digit(i):
3 | print(abs(i) % 10, end="")
4 | return (abs(i) % 10)
5 |
--------------------------------------------------------------------------------
/0x00-python-hello_world/100-write.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | import sys
3 | sys.stderr.write("and that piece of art is useful - Dora Korpar, 2015-10-19\n")
4 | sys.exit(1)
5 |
--------------------------------------------------------------------------------
/0x13-javascript_objects_scopes_closures/9-logme.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 | let count = 0;
3 | exports.logMe = function (item) {
4 | console.log(`${count++}: ${item}`);
5 | };
6 |
--------------------------------------------------------------------------------
/0x15-javascript-web_jquery/0-script.js:
--------------------------------------------------------------------------------
1 | document.querySelector('header').style.color = 'red';
2 | // console.log($('header').hasClass('red'));
3 | // $('header').addClass('red');
4 |
--------------------------------------------------------------------------------
/0x04-python-more_data_structures/11-multiply_list_map.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | def multiply_list_map(my_list=[], number=0):
3 | return (list(map(lambda x: x * number, my_list)))
4 |
--------------------------------------------------------------------------------
/0x12-javascript-warm_up/102-add_me_maybe.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 |
3 | exports.addMeMaybe = function (number, theFunction) {
4 | number += 1;
5 | return (theFunction(number));
6 | };
7 |
--------------------------------------------------------------------------------
/0x12-javascript-warm_up/3-value_argument.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 |
3 | if (process.argv[2]) {
4 | console.log(process.argv[2]);
5 | } else {
6 | console.log('No argument');
7 | }
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 x: list(map(lambda y: y**2, x)), matrix))
4 |
--------------------------------------------------------------------------------
/0x01-python-if_else_loops_functions/7-islower.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | def islower(c):
3 | if ord(c) >= 97 and ord(c) <= 122:
4 | return True
5 | else:
6 | return False
7 |
--------------------------------------------------------------------------------
/0x06-python-classes/0-square.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 0-square.py
3 |
4 | """Define a class Square."""
5 |
6 |
7 | class Square:
8 | """Represent a square."""
9 | pass
10 |
--------------------------------------------------------------------------------
/0x12-javascript-warm_up/101-call_me_moby.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 |
3 | exports.callMeMoby = function (x, theFunction) {
4 | while (x > 0) {
5 | theFunction();
6 | x -= 1;
7 | }
8 | };
9 |
--------------------------------------------------------------------------------
/0x13-javascript_objects_scopes_closures/10-converter.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 | exports.converter = function (base) {
3 | return function (dec) {
4 | return dec.toString(base);
5 | };
6 | };
7 |
--------------------------------------------------------------------------------
/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("{0} + {1} = {2}".format(a, b, add(a, b)))
7 |
--------------------------------------------------------------------------------
/0x0A-python-inheritance/5-base_geometry.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 |
4 | """ Base class """
5 |
6 |
7 | class BaseGeometry:
8 | """BaseGeometry as the base class"""
9 |
10 | pass
11 |
--------------------------------------------------------------------------------
/0x01-python-if_else_loops_functions/101-remove_char_at.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | def remove_char_at(str, n):
3 | if n < 0:
4 | return (str)
5 | return (str[:n] + str[n+1:])
6 |
7 |
--------------------------------------------------------------------------------
/0x01-python-if_else_loops_functions/3-print_alphabt.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | for letter in range(97, 123):
3 | if chr(letter) != 'q' and chr(letter) != 'e':
4 | print("{}".format(chr(letter)), end="")
5 |
--------------------------------------------------------------------------------
/0x12-javascript-warm_up/12-object.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 |
3 | const myObject = {
4 | type: 'object',
5 | value: 12
6 | };
7 | console.log(myObject);
8 | myObject.value = 89;
9 | console.log(myObject);
10 |
--------------------------------------------------------------------------------
/0x15-javascript-web_jquery/7-script.js:
--------------------------------------------------------------------------------
1 | $.get('https://swapi-api.alx-tools.com/api/people/5/?format=json', (response, code) => {
2 | // console.log(response);
3 | $('#character').text(response.name);
4 | });
5 |
--------------------------------------------------------------------------------
/0x07-python-test_driven_development/__pycache__/0-add_integer.cpython-39.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mukuvi/alx-higher_level_programming/HEAD/0x07-python-test_driven_development/__pycache__/0-add_integer.cpython-39.pyc
--------------------------------------------------------------------------------
/0x08-python-more_classes/0-rectangle.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 0-rectangle.py
3 | """Defines a Rectangle class.
4 | """
5 |
6 |
7 | class Rectangle:
8 | """Represent a rectangle.
9 | """
10 | pass
11 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/0x04-python-more_data_structures/5-number_keys.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 5-number_keys.py
3 |
4 |
5 | def number_keys(a_dictionary):
6 | """Return the number of keys in a dictionary."""
7 | return (len(a_dictionary))
8 |
--------------------------------------------------------------------------------
/0x07-python-test_driven_development/__pycache__/2-matrix_divided.cpython-39.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mukuvi/alx-higher_level_programming/HEAD/0x07-python-test_driven_development/__pycache__/2-matrix_divided.cpython-39.pyc
--------------------------------------------------------------------------------
/0x13-javascript_objects_scopes_closures/8-main.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 | const esrever = require('./8-esrever').esrever;
3 |
4 | console.log(esrever([1, 2, 3, 4, 5]));
5 | console.log(esrever(["School", 89, { id: 12 }, "String"]));
6 |
--------------------------------------------------------------------------------
/0x01-python-if_else_loops_functions/5-print_comb2.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | for number in range(0, 100):
3 | if number == 99:
4 | print("{}".format(number))
5 | else:
6 | print("{:02}".format(number), end=", ")
7 |
--------------------------------------------------------------------------------
/0x12-javascript-warm_up/6-multi_languages_loop.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 |
3 | const complements = ['C is fun', 'Python is cool', 'JavaScript is amazing'];
4 | for (const complement of complements) {
5 | console.log(complement);
6 | }
7 |
--------------------------------------------------------------------------------
/0x02-python-import_modules/4-hidden_discovery.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | import hidden_4
3 | if __name__ == "__main__":
4 | names = dir(hidden_4)
5 | for name in names:
6 | if name[:2] != "__":
7 | print(name)
8 |
--------------------------------------------------------------------------------
/0x12-javascript-warm_up/5-to_integer.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 |
3 | const parsedVal = parseInt(process.argv[2]);
4 | if (!isNaN(parsedVal)) {
5 | console.log(`My number: ${parsedVal}`);
6 | } else {
7 | console.log('Not a number');
8 | }
9 |
--------------------------------------------------------------------------------
/0x01-python-if_else_loops_functions/100-print_tebahpla.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | i = 0
3 | for num in range(122, 96, -1):
4 | print("{0}".format(chr(num - i)), end="")
5 | if i == 0:
6 | i = 32
7 | else:
8 | i = 0
9 |
--------------------------------------------------------------------------------
/0x12-javascript-warm_up/1-multi_languages.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 |
3 | const c = 'C is fun';
4 | const py = 'Python is cool';
5 | const js = 'JavaScript is amazing';
6 |
7 | console.log(c);
8 | console.log(py);
9 | console.log(js);
10 |
--------------------------------------------------------------------------------
/0x13-javascript_objects_scopes_closures/100-map.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 |
3 | const origList = require('./100-data').list;
4 |
5 | const newList = origList.map((elem, idx) => elem * idx);
6 |
7 | console.log(origList);
8 | console.log(newList);
9 |
--------------------------------------------------------------------------------
/0x15-javascript-web_jquery/3-script.js:
--------------------------------------------------------------------------------
1 | $('#red_header').on('click', () => {
2 | if ($('header').hasClass('red')){
3 | console.log('Its already red mate')
4 | } else{
5 | $('header').addClass('red');
6 | }
7 | });
8 |
--------------------------------------------------------------------------------
/0x03-python-data_structures/11-delete_at.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | def delete_at(my_list=[], idx=0):
3 | if idx < 0 or idx > (len(my_list) - 1):
4 | return my_list
5 | new_list = my_list
6 | del new_list[idx]
7 | return new_list
8 |
--------------------------------------------------------------------------------
/0x05-python-exceptions/1-safe_print_integer.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | def safe_print_integer(value):
3 | try:
4 | print("{:d}".format(value))
5 | return True
6 | except (ValueError, TypeError, NameError):
7 | return False
8 |
--------------------------------------------------------------------------------
/0x12-javascript-warm_up/9-add.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 |
3 | function add (a, b) {
4 | return (a + b);
5 | }
6 |
7 | const arg1 = parseInt(process.argv[2]);
8 | const arg2 = parseInt(process.argv[3]);
9 |
10 | console.log(add(arg1, arg2));
11 |
--------------------------------------------------------------------------------
/0x04-python-more_data_structures/0-square_matrix_simple.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | def square_matrix_simple(matrix=[]):
4 | """ Compute the square value of all integers of a matrix"""
5 | return ([[col * col for col in row] for row in matrix])
6 |
--------------------------------------------------------------------------------
/0x04-python-more_data_structures/4-only_diff_elements.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 4-only_diff_elements.py
3 |
4 |
5 | def only_diff_elements(set_1, set_2):
6 | """Return a set of all elements present in only one set."""
7 | return (set_1 ^ set_2)
8 |
--------------------------------------------------------------------------------
/0x13-javascript_objects_scopes_closures/2-rectangle.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 |
3 | module.exports = class Rectangle {
4 | constructor (w, h) {
5 | if ((w > 0) && (h > 0)) {
6 | [this.width, this.height] = [w, h];
7 | }
8 | }
9 | };
10 |
--------------------------------------------------------------------------------
/0x13-javascript_objects_scopes_closures/5-square.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 |
3 | const Rectangle = require('./4-rectangle');
4 |
5 | module.exports = class Square extends Rectangle {
6 | constructor (size) {
7 | super(size, size);
8 | }
9 | };
10 |
--------------------------------------------------------------------------------
/0x03-python-data_structures/5-no_c.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 5-no_c.py
3 |
4 |
5 | def no_c(my_string):
6 | """Removes all characters c and C from a string."""
7 | copy = [x for x in my_string if x != 'c' and x != 'C']
8 | return ("".join(copy))
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:66] + str[106:112] + str[:6]
5 | print(str)
6 |
--------------------------------------------------------------------------------
/0x02-python-import_modules/5-variable_load.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 5-variable_load.py
3 |
4 |
5 | if __name__ == "__main__":
6 | """Print the value of variable a from variable_load_5."""
7 | from variable_load_5 import a
8 |
9 | print(a)
10 |
--------------------------------------------------------------------------------
/0x04-python-more_data_structures/8-simple_delete.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | def simple_delete(a_dictionary, key=""):
3 | if key in a_dictionary.keys():
4 | del a_dictionary[key]
5 | return a_dictionary
6 | else:
7 | return a_dictionary
8 |
--------------------------------------------------------------------------------
/0x13-javascript_objects_scopes_closures/1-rectangle.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 |
3 | module.exports = class Rectangle {
4 | constructor (w, h) {
5 | if (!(w < 1) || (h < 1)) {
6 | this.width = w;
7 | this.height = h;
8 | }
9 | }
10 | };
11 |
--------------------------------------------------------------------------------
/0x15-javascript-web_jquery/9-script.js:
--------------------------------------------------------------------------------
1 | $(document).ready(function () {
2 | $.get('https://hellosalut.stefanbohacek.dev/?lang=fr', (response, statusCode) => {
3 | // console.log(response)
4 | $('#hello').text(response['hello']);
5 | });
6 | });
7 |
--------------------------------------------------------------------------------
/0x03-python-data_structures/0-print_list_integer.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 0-print_list_integer.py
3 |
4 |
5 | def print_list_integer(my_list=[]):
6 | """Print all integers of a list."""
7 | for i in range(len(my_list)):
8 | print("{:d}".format(my_list[i]))
9 |
--------------------------------------------------------------------------------
/0x03-python-data_structures/8-multiple_returns.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | def multiple_returns(sentence):
3 | "Return the length of a tuple and the first element"
4 | if not sentence:
5 | return (0, None)
6 | return (len(tuple(sentence)), tuple(sentence)[0])
7 |
--------------------------------------------------------------------------------
/0x04-python-more_data_structures/9-multiply_by_2.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 9-multiple_by_2.py
3 |
4 |
5 | def multiply_by_2(a_dictionary):
6 | """Return a new dictionary with all values multipled by 2."""
7 | return ({k: a_dictionary[k] * 2 for k in a_dictionary})
8 |
--------------------------------------------------------------------------------
/0x14-javascript-web_scraping/5-request_store.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 |
3 | const req = require('request');
4 | const fs = require('fs');
5 | const url = process.argv[2];
6 | const Fname = process.argv[3];
7 | req
8 | .get(url)
9 | .pipe(fs.createWriteStream(Fname));
10 |
--------------------------------------------------------------------------------
/0x12-javascript-warm_up/2-arguments.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 |
3 | if (!process.argv[2]) {
4 | console.log('No argument');
5 | } else if ((process.argv[2]) && (!process.argv[3])) {
6 | console.log('Argument found');
7 | } else {
8 | console.log('Arguments found');
9 | }
10 |
--------------------------------------------------------------------------------
/0x12-javascript-warm_up/8-square.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 |
3 | const size = parseInt(process.argv[2]);
4 |
5 | if (!isNaN(size)) {
6 | for (let i = 0; i < size; i++) {
7 | console.log('X'.repeat(size));
8 | }
9 | } else {
10 | console.log('Missing size');
11 | }
12 |
--------------------------------------------------------------------------------
/0x14-javascript-web_scraping/2-statuscode.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 |
3 | const request = require('request');
4 | const url = process.argv[2];
5 | request
6 | .get(url)
7 | .on('response', function (response) {
8 | console.log('code: ' + response.statusCode);
9 | });
10 |
--------------------------------------------------------------------------------
/0x03-python-data_structures/1-element_at.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 1-element_at.py
3 |
4 |
5 | def element_at(my_list, idx):
6 | """Retrive an element from a list."""
7 | if idx < 0 or idx > (len(my_list) - 1):
8 | return None
9 | return (my_list[idx])
10 |
--------------------------------------------------------------------------------
/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 | return fct(*args)
8 | except Exception as i:
9 | sys.stderr.write("Exception: {}\n".format(i))
10 | return None
11 |
--------------------------------------------------------------------------------
/0x04-python-more_data_structures/7-update_dictionary.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 7-update_dictionary.py
3 |
4 |
5 | def update_dictionary(a_dictionary, key, value):
6 | """Replace or add key/value pairs in a dictionary."""
7 | a_dictionary[key] = value
8 | return (a_dictionary)
9 |
--------------------------------------------------------------------------------
/0x14-javascript-web_scraping/0-readme.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 |
3 | const fs = require('fs');
4 | const fname = process.argv[2];
5 | fs.readFile(fname, 'utf-8', function (err, lo) {
6 | if (err) {
7 | console.log(err);
8 | } else {
9 | console.log(lo);
10 | }
11 | });
12 |
--------------------------------------------------------------------------------
/0x11-python-network_1/6-post_email.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | """
3 | used requests models
4 | """
5 |
6 | if __name__ == '__main__':
7 | import requests
8 | import sys
9 | para = {"email": sys.argv[2]}
10 | r = requests.post(sys.argv[1], data=para)
11 | print(r.text)
12 |
--------------------------------------------------------------------------------
/0x04-python-more_data_structures/2-uniq_add.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 2-uniq_add.py
3 |
4 |
5 | def uniq_add(my_list=[]):
6 | """Add all unique integers in a list (once for each integer)."""
7 | result = 0
8 | for x in set(my_list):
9 | result += x
10 | return (result)
11 |
--------------------------------------------------------------------------------
/0x04-python-more_data_structures/6-print_sorted_dictionary.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 6-print_sorted_dictionary.py
3 |
4 |
5 | def print_sorted_dictionary(a_dictionary):
6 | """Print a dictionary by ordered keys."""
7 | [print("{}: {}".format(k, a_dictionary[k])) for k in sorted(a_dictionary)]
8 |
--------------------------------------------------------------------------------
/0x00-python-hello_world/7-edges.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | word = "Holberton"
3 | word_first_3 = word[:3]
4 | word_last_2 = word[-2:]
5 | middle_word = word[1:-1]
6 | print("First 3 letters: {}".format(word_first_3))
7 | print("Last 2 letters: {}".format(word_last_2))
8 | print("Middle word: {}".format(middle_word))
9 |
--------------------------------------------------------------------------------
/0x01-python-if_else_loops_functions/0-positive_or_negative.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | import random
3 | number = random.randint(-10, 10)
4 | if (number > 0):
5 | print(f"{number:d} is positive")
6 | elif (number < 0):
7 | print(f"{number:d} is negative")
8 | else:
9 | print(f"{number:d} is zero")
10 |
--------------------------------------------------------------------------------
/0x01-python-if_else_loops_functions/8-uppercase.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | def uppercase(str):
3 | """Print str in uppercase"""
4 | for char in str:
5 | if ord(char) >= 97 and ord(char) <= 122:
6 | char = chr(ord(char) - 32)
7 | print("{0}".format(char), end="")
8 | print("")
9 |
--------------------------------------------------------------------------------
/0x05-python-exceptions/3-safe_print_division.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | def safe_print_division(a, b):
3 | try:
4 | result = a / b
5 | except (TypeError, ZeroDivisionError):
6 | result = None
7 | finally:
8 | print("Inside result: {}".format(result))
9 | return result
10 |
--------------------------------------------------------------------------------
/0x0A-python-inheritance/6-base_geometry.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 |
4 | """ Base class """
5 |
6 |
7 | class BaseGeometry:
8 | """BaseGeometry as the base class"""
9 |
10 | def area(self):
11 | """Lets raise an exception """
12 | raise Exception("area() is not implemented")
13 |
--------------------------------------------------------------------------------
/0x0A-python-inheritance/1-my_list.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 |
4 | """MyList class"""
5 |
6 |
7 | class MyList(list):
8 | """My list class inheritting list"""
9 |
10 | def print_sorted(self):
11 | """Print a list sorted in ascending order"""
12 | print(sorted(self, reverse=False))
13 |
--------------------------------------------------------------------------------
/0x12-javascript-warm_up/11-second_biggest.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 | if (process.argv.length <= 3) {
3 | console.log(0);
4 | } else {
5 | const numberArgs = process.argv.map(Number)
6 | .slice(2, process.argv.length)
7 | .sort((x, y) => x - y);
8 | console.log(numberArgs[numberArgs.length - 2]);
9 | }
10 |
--------------------------------------------------------------------------------
/0x01-python-if_else_loops_functions/6-print_comb3.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | for digit1 in range(0, 10):
3 | for digit2 in range(digit1 + 1, 10):
4 | if digit1 == 8 and digit2 == 9:
5 | print("{}{}".format(digit1, digit2))
6 | else:
7 | print("{}{}".format(digit1, digit2), end=", ")
8 |
--------------------------------------------------------------------------------
/0x12-javascript-warm_up/7-multi_c.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 |
3 | let numberOfTimes = parseInt(process.argv[2]);
4 | if (!isNaN(numberOfTimes)) {
5 | while (numberOfTimes > 0) {
6 | console.log('C is fun');
7 | numberOfTimes -= 1;
8 | }
9 | } else {
10 | console.log('Missing number of occurrences');
11 | }
12 |
--------------------------------------------------------------------------------
/0x13-javascript_objects_scopes_closures/7-occurrences.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 |
3 | exports.nbOccurences = function (list, searchElement) {
4 | let occurences = 0;
5 | for (const elem of list) {
6 | if (elem === searchElement) {
7 | occurences += 1;
8 | }
9 | }
10 | return (occurences);
11 | };
12 |
--------------------------------------------------------------------------------
/0x03-python-data_structures/2-replace_in_list.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 2-replace_in_list.py
3 |
4 |
5 | def replace_in_list(my_list, idx, element):
6 | """Replace an element of a list at a specific position."""
7 | if idx >= 0 and idx < len(my_list):
8 | my_list[idx] = element
9 | return (my_list)
10 |
--------------------------------------------------------------------------------
/0x15-javascript-web_jquery/8-script.js:
--------------------------------------------------------------------------------
1 | $.get('https://swapi-api.alx-tools.com/api/films/?format=json', function (response, statusCode) {
2 | const rdata = response.results;
3 | for (let i = 0; rdata.length > 0; i++) {
4 | $('#list_movies').append(`${rdata[i].title}`);
5 | console.log(rdata[i].title);
6 | }
7 | });
8 |
--------------------------------------------------------------------------------
/0x0B-python-input_output/8-class_to_json.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """class to JSON function."""
4 |
5 |
6 | def class_to_json(obj):
7 | """Return the dictionary representation 's class
8 | Args:
9 | obj(object) -> Any object
10 | Returns:
11 | obj.__dict__."""
12 | return obj.__dict__
13 |
--------------------------------------------------------------------------------
/0x15-javascript-web_jquery/100-script.js:
--------------------------------------------------------------------------------
1 | /* with jQuery
2 | $(document).ready(function () {
3 | $('header').css('color', 'red');
4 | console.log($('header').text())
5 | });
6 | */
7 |
8 | // without jQuery
9 | document.addEventListener('DOMContentLoaded', () => {
10 | document.querySelector('header').style.color = 'red';
11 | });
12 |
--------------------------------------------------------------------------------
/0x03-python-data_structures/4-new_in_list.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | def new_in_list(my_list, idx, element):
3 | """Return new list with item at position idx set to elelement"""
4 | if idx < 0 or idx > (len(my_list) - 1):
5 | return my_list
6 | new_list = [item for item in my_list]
7 | new_list[idx] = element
8 | return new_list
9 |
--------------------------------------------------------------------------------
/0x0B-python-input_output/3-to_json_string.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """ Function to serialize an object to JSON"""
4 |
5 |
6 | import json
7 |
8 |
9 | def to_json_string(my_obj):
10 | """Serialize an object to JSON
11 | Args:
12 | my_obj(object) -> Any serializable object
13 | """
14 | return (json.dumps(my_obj))
15 |
--------------------------------------------------------------------------------
/0x12-javascript-warm_up/103-object_fct.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 | const myObject = {
3 | type: 'object',
4 | value: 12
5 | };
6 | console.log(myObject);
7 | myObject.incr = () => { myObject.value++; };
8 | myObject.incr();
9 | console.log(myObject);
10 | myObject.incr();
11 | console.log(myObject);
12 | myObject.incr();
13 | console.log(myObject);
14 |
--------------------------------------------------------------------------------
/0x03-python-data_structures/3-print_reversed_list_integer.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | def print_reversed_list_integer(my_list=[]):
3 | """ prints all integers of a list, in reverse order."""
4 | if not my_list:
5 | pass
6 | else:
7 | my_list.reverse()
8 | for item in my_list:
9 | print('{:d}'.format(item))
10 |
--------------------------------------------------------------------------------
/0x0A-python-inheritance/0-lookup.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 |
4 | """Look up function"""
5 |
6 |
7 | def lookup(obj):
8 | """Function to return all attributes and method of
9 | an object
10 | Args:
11 | obj(object of any class) -> The object in question
12 | Returns:
13 | list
14 | """
15 | return dir(obj)
16 |
--------------------------------------------------------------------------------
/0x14-javascript-web_scraping/1-writeme.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 |
3 | const fs = require('fs');
4 | const Firstarg = process.argv[2];
5 | const Secondarg = process.argv[3];
6 | fs.writeFileSync(Firstarg, Secondarg, 'utf-8', function (error, log) {
7 | if (error) {
8 | console.log(error);
9 | } else {
10 | console.log(log);
11 | }
12 | });
13 |
--------------------------------------------------------------------------------
/0x09-python-everything_is_object/101-locked_class.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 101-locked_class.py
3 | """Defines a locked class."""
4 |
5 |
6 | class LockedClass:
7 | """
8 | Prevent the user from instantiating new LockedClass attributes
9 | for anything but attributes called 'first_name'.
10 | """
11 |
12 | __slots__ = ["first_name"]
13 |
--------------------------------------------------------------------------------
/0x05-python-exceptions/0-safe_print_list.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | def safe_print_list(my_list=[], x=0):
3 | count = 0
4 | for i in range(x):
5 | try:
6 | print("{}".format(my_list[i]), end="")
7 | except IndexError:
8 | pass
9 | else:
10 | count += 1
11 | print()
12 | return (count)
13 |
--------------------------------------------------------------------------------
/0x05-python-exceptions/100-safe_print_integer_err.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | import sys
3 |
4 |
5 | def safe_print_integer_err(value):
6 | try:
7 | print("{:d}".format(value))
8 | return True
9 | except (ValueError, NameError, TypeError) as err:
10 | print("Exception: {}".format(err), file=sys.stderr)
11 | return False
12 |
--------------------------------------------------------------------------------
/0x11-python-network_1/1-hbtn_header.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | """
3 | fetch X-Request-Id from header response with url
4 | """
5 |
6 | if __name__ == '__main__':
7 | import urllib.request
8 | import sys
9 | with urllib.request.urlopen(sys.argv[1]) as response:
10 | content = response.getheader('X-Request-Id')
11 |
12 | print(content)
13 |
--------------------------------------------------------------------------------
/0x0C-python-almost_a_circle/tests/test_base.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | from models.base import Base
3 | import unittest
4 |
5 | """Base class test suites"""
6 |
7 |
8 | class TestBase(unittest.TestCase):
9 | """Testing the Base class"""
10 |
11 | def test_no_args(self):
12 | """Test Base with no args"""
13 | self.assertEqual(Base().id, 1)
14 |
--------------------------------------------------------------------------------
/0x12-javascript-warm_up/10-factorial.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 |
3 | function factorial (number) {
4 | if (number === 1) {
5 | return (1);
6 | } else {
7 | return (number * factorial(number - 1));
8 | }
9 | }
10 |
11 | const value = process.argv[2];
12 | if (isNaN(value)) {
13 | console.log('1');
14 | } else {
15 | console.log(factorial(value));
16 | }
17 |
--------------------------------------------------------------------------------
/0x14-javascript-web_scraping/3-starwars_title.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 |
3 | const req = require('request');
4 | const url = 'https://swapi-api.hbtn.io/api/films/';
5 | const id = process.argv[2];
6 | req.get(url + id, function (error, res, body) {
7 | if (error) {
8 | console.log(error);
9 | } else {
10 | console.log(JSON.parse(body).title);
11 | }
12 | });
13 |
--------------------------------------------------------------------------------
/0x05-python-exceptions/2-safe_print_list_integers.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | def safe_print_list_integers(my_list=[], x=0):
3 | count = 0
4 | for i in range(0, x):
5 | try:
6 | print("{:d}".format(my_list[i]), end="")
7 | count += 1
8 | except (ValueError, TypeError):
9 | continue
10 | print("")
11 | return count
12 |
--------------------------------------------------------------------------------
/0x06-python-classes/1-square.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 1-square.py
3 |
4 | """Define a class Square."""
5 |
6 |
7 | class Square:
8 | """Represent a square."""
9 |
10 | def __init__(self, size):
11 | """Initialize a new Square.
12 |
13 | Args:
14 | size (int): The size of the new square.
15 | """
16 | self.__size = size
17 |
--------------------------------------------------------------------------------
/0x15-javascript-web_jquery/101-script.js:
--------------------------------------------------------------------------------
1 | $(document).ready(function () {
2 | $('#add_item').on('click', () => {
3 | $('.my_list').append('Item');
4 | });
5 |
6 | $('#remove_item').on('click', () => {
7 | $('.my_list').find('li').last().remove();
8 | });
9 |
10 | $('#clear_list').on('click', () => {
11 | $('.my_list').remove();
12 | });
13 | });
14 |
--------------------------------------------------------------------------------
/0x01-python-if_else_loops_functions/12-fizzbuzz.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | def fizzbuzz():
3 | for num in range(1, 101):
4 | if num % 15 == 0:
5 | print("FizzBuzz", end=" ")
6 | elif num % 5 == 0:
7 | print('Buzz', end=" ")
8 | elif num % 3 == 0:
9 | print("Fizz", end=" ")
10 | else:
11 | print(num, end=" ")
12 |
--------------------------------------------------------------------------------
/0x03-python-data_structures/6-print_matrix_integer.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | def print_matrix_integer(matrix=[[]]):
3 | """Print a matrix of integers"""
4 | for i in range(0, len(matrix)):
5 | for j in range(0, len(matrix[i])):
6 | if not j == 0:
7 | print(" ", end='')
8 | print("{:d}".format(matrix[i][j]), end='')
9 | print()
10 |
--------------------------------------------------------------------------------
/0x0C-python-almost_a_circle/tests/0-test_base.txt:
--------------------------------------------------------------------------------
1 | ======================
2 | base.py module test suites
3 | =====================
4 |
5 | >>> from models.base import Base
6 |
7 | >>> b1 = Base()
8 |
9 | >>> b1.id
10 | 1
11 |
12 | >>> b2 = Base()
13 |
14 | >>> b2.id
15 | 2
16 |
17 | >>> b3 = Base()
18 |
19 | >>> b3.id
20 | 3
21 |
22 | >>> b5 = Base(id=5)
23 |
24 | >>> b5.id
25 | 5
26 |
--------------------------------------------------------------------------------
/0x02-python-import_modules/102-magic_calculation.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 |
4 | def magic_calculation(a, b):
5 | """Does a task based on a bytcode"""
6 | from magic_calculation_102 import add, sub
7 |
8 | if a < b:
9 | c = add(a, b)
10 | for i in range(4, 6):
11 | c = add(c, i)
12 | return (c)
13 | else:
14 | return (sub(a, b))
15 |
--------------------------------------------------------------------------------
/0x0C-python-almost_a_circle/tests/0-main.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """ 0-main """
4 | from models.base import Base
5 |
6 |
7 | if __name__ == "__main__":
8 | b1 = Base()
9 | print(b1.id)
10 |
11 | b2 = Base()
12 | print(b2.id)
13 |
14 | b3 = Base()
15 | print(b3.id)
16 |
17 | b4 = Base(7)
18 | print(b4.id)
19 |
20 | b5 = Base()
21 | print(b5.id)
22 |
--------------------------------------------------------------------------------
/0x03-python-data_structures/9-max_integer.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 9-max_integer.py
3 |
4 |
5 | def max_integer(my_list=[]):
6 | """Find the biggest integer of a list."""
7 | if len(my_list) == 0:
8 | return (None)
9 |
10 | big = my_list[0]
11 | for i in range(len(my_list)):
12 | if my_list[i] > big:
13 | big = my_list[i]
14 |
15 | return (big)
16 |
--------------------------------------------------------------------------------
/0x02-python-import_modules/2-args.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | import sys
3 | if __name__ == "__main__":
4 |
5 | args = len(sys.argv) - 1
6 | if args == 0:
7 | print("0 arguments.")
8 | elif args == 1:
9 | print("1 argument:")
10 | else:
11 | print("{} arguments:".format(args))
12 | for i in range(args):
13 | print("{0}: {1}".format(i + 1, sys.argv[i + 1]))
14 |
--------------------------------------------------------------------------------
/0x04-python-more_data_structures/1-search_replace.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 1-search_replace.py
3 |
4 |
5 | def search_replace(my_list, search, replace):
6 | """Replace all occurrences of an element by another in a new list."""
7 | new_list = my_list[:]
8 | for i in range(len(new_list)):
9 | if new_list[i] == search:
10 | new_list[i] = replace
11 | return (new_list)
12 |
--------------------------------------------------------------------------------
/0x05-python-exceptions/102-magic_calculation.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | def magic_calculation(a, b):
3 | res = 0
4 | for i in range(1, 3):
5 | try:
6 | if (i > a):
7 | raise Exception("Too far")
8 | else:
9 | res += (a ** b) / i
10 | except Exception as e:
11 | res = b + a
12 | break
13 | return (res)
14 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/0x01-python-if_else_loops_functions/1-last_digit.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | import random
3 | number = random.randint(-10000, 10000)
4 | digit = abs(number) % 10
5 | if number < 0:
6 | digit = -digit
7 | print("Last digit of {} is {} and is ".format(number, digit), end="")
8 | if digit > 5:
9 | print("greater than 5")
10 | elif digit == 0:
11 | print("0")
12 | else:
13 | print("less than 6 and not 0")
14 |
--------------------------------------------------------------------------------
/0x02-python-import_modules/3-infinite_add.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | if __name__ == "__main__":
3 | from sys import argv
4 | total = 0
5 | if len(argv) - 1 == 0:
6 | print("{}".format(0))
7 | elif len(argv) - 1 == 1:
8 | print("{}".format(argv[1]))
9 | else:
10 | for num in range(1, len(argv)):
11 | total += int(argv[num])
12 | print("{}".format(total))
13 |
--------------------------------------------------------------------------------
/0x03-python-data_structures/10-divisible_by_2.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 10-divisible_by_2.py
3 |
4 |
5 | def divisible_by_2(my_list=[]):
6 | """Find all multiples of 2 in a list."""
7 | multiples = []
8 | for i in range(len(my_list)):
9 | if my_list[i] % 2 == 0:
10 | multiples.append(True)
11 | else:
12 | multiples.append(False)
13 |
14 | return (multiples)
15 |
--------------------------------------------------------------------------------
/0x13-javascript_objects_scopes_closures/3-rectangle.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 |
3 | module.exports = class Rectangle {
4 | constructor (w, h) {
5 | if ((w > 0) && (h > 0)) {
6 | [this.width, this.height] = [w, h];
7 | }
8 | }
9 |
10 | print () {
11 | let sizeY = this.height;
12 | while (sizeY > 0) {
13 | console.log('X'.repeat(this.width));
14 | sizeY -= 1;
15 | }
16 | }
17 | };
18 |
--------------------------------------------------------------------------------
/0x0B-python-input_output/0-read_file.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """Read a file and print its content to stdout"""
4 |
5 |
6 | def read_file(filename=""):
7 | """Read 's content
8 | Args:
9 | filename(str) -> the name of the file
10 | Returns:
11 | None
12 | """
13 | if filename:
14 | with open(filename, encoding="utf-8") as f:
15 | print(f.read(), end="")
16 |
--------------------------------------------------------------------------------
/0x0B-python-input_output/6-load_from_json_file.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """Deserialize an JSON from a file"""
4 |
5 |
6 | import json
7 |
8 |
9 | def load_from_json_file(filename):
10 | """Create an object from JSON
11 | Args:
12 | filename(str) -> The filename holding JSON
13 | """
14 | if filename:
15 | with open(filename, 'r', encoding="utf-8") as f:
16 | return json.load(f)
17 |
--------------------------------------------------------------------------------
/0x0F-python-object_relational_mapping/6-model_state.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | """Start link class to table in database
3 | """
4 | import sys
5 | from model_state import Base, State
6 |
7 | from sqlalchemy import (create_engine)
8 |
9 | if __name__ == "__main__":
10 | engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}'.format(sys.argv[1], sys.argv[2], sys.argv[3]), pool_pre_ping=True)
11 | Base.metadata.create_all(engine)
12 |
--------------------------------------------------------------------------------
/0x00-python-hello_world/lists.h:
--------------------------------------------------------------------------------
1 | #ifndef LISTS_H
2 | #define LISTS_H
3 | #include
4 |
5 | typedef struct listint_s
6 | {
7 | int n;
8 | struct listint_s *next;
9 | } listint_t;
10 |
11 | /** function prototypes **/
12 | size_t print_listint(const listint_t *h);
13 | listint_t *add_nodeint(listint_t **head, const int n);
14 | void free_listint(listint_t *head);
15 | int check_cycle(listint_t *list);
16 |
17 | #endif /* LISTS_H */
18 |
--------------------------------------------------------------------------------
/0x04-python-more_data_structures/102-complex_delete.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 102-complex_delete.py
3 |
4 |
5 | def complex_delete(a_dictionary, value):
6 | """Delete keys with a specific value in a dictionary."""
7 | while value in a_dictionary.values():
8 | for k, v in a_dictionary.items():
9 | if v == value:
10 | del a_dictionary[k]
11 | break
12 |
13 | return (a_dictionary)
14 |
--------------------------------------------------------------------------------
/0x0A-python-inheritance/100-my_int.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """MyInt class that inherits from int"""
4 |
5 |
6 | class MyInt(int):
7 | """MyInt class with != and == interchanged"""
8 | def __eq__(self, value):
9 | """Override == opeartor with != behavior."""
10 | return self.real != value
11 |
12 | def __ne__(self, value):
13 | """Override != operator with == behavior."""
14 | return self.real == value
15 |
--------------------------------------------------------------------------------
/0x0B-python-input_output/4-from_json_string.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """Function to unserialize a JSON string to python object"""
4 |
5 |
6 | import json
7 |
8 |
9 | def from_json_string(my_str):
10 | """Unserialize
11 | Args:
12 | my_str(str) -> JSON string to unserialize
13 | Returns:
14 | unserialized object repesentation of my_str
15 | """
16 | if my_str:
17 | return json.loads(my_str)
18 |
--------------------------------------------------------------------------------
/0x04-python-more_data_structures/100-weight_average.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 100-weight_average.py
3 |
4 |
5 | def weight_average(my_list=[]):
6 | """Return the weighted average of all integers in a list of tuples."""
7 | if not isinstance(my_list, list) or len(my_list) == 0:
8 | return (0)
9 |
10 | avg = 0
11 | size = 0
12 | for tup in my_list:
13 | avg += (tup[0] * tup[1])
14 | size += tup[1]
15 | return (avg / size)
16 |
--------------------------------------------------------------------------------
/0x13-javascript_objects_scopes_closures/8-esrever.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 |
3 | /*
4 | Ok, this is by far the worst algorithim I've written,
5 | with a time Complexity of O(n)
6 |
7 | Ill have to optimize this one :(:(:(
8 | */
9 | exports.esrever = function (list) {
10 | const listLen = list.length;
11 | const newList = [];
12 |
13 | for (let i = listLen; i >= 0; i--) {
14 | newList.push(list[i]);
15 | }
16 | return (newList.slice(1, newList.length));
17 | };
18 |
--------------------------------------------------------------------------------
/0x0B-python-input_output/5-save_to_json_file.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """Serialize an object and write to a file"""
4 |
5 |
6 | import json
7 |
8 |
9 | def save_to_json_file(my_obj, filename):
10 | """Serialize an object to JSON and write to a file
11 | Args:
12 | my_obj(object) -> Any serializable object
13 | file_name(str) -> The file to write to
14 | """
15 | with open(filename, "w", encoding="utf-8") as f:
16 | json.dump(my_obj, f)
17 |
--------------------------------------------------------------------------------
/0x0A-python-inheritance/11-square.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """Defines a Rectangle subclass Square."""
4 | Rectangle = __import__('9-rectangle').Rectangle
5 |
6 |
7 | class Square(Rectangle):
8 | """ Square Class """
9 | def __init__(self, size):
10 | """ size init"""
11 | self.__size = size
12 | super().__init__(self.__size, self.__size)
13 |
14 | def __str__(self):
15 | return ("[Square] " + str(self.__size) + "/" + str(self.__size))
16 |
--------------------------------------------------------------------------------
/0x13-javascript_objects_scopes_closures/6-square.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 | const ParentSquare = require('./5-square');
3 |
4 | module.exports = class Square extends ParentSquare {
5 | // constructor (size) {
6 | // super(size, size);
7 | // }
8 |
9 | charPrint (c) {
10 | if (c !== undefined) {
11 | for (let i = 0; i < this.width; i++) {
12 | console.log(String(c).repeat(this.width));
13 | }
14 | } else {
15 | this.print();
16 | }
17 | }
18 | };
19 |
--------------------------------------------------------------------------------
/0x11-python-network_1/10-my_github.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """
4 | takes GitHub credentials (username and password)
5 | """
6 |
7 | if __name__ == '__main__':
8 | import sys
9 | import requests
10 | url = "https://api.github.com/user"
11 | username = sys.argv[1]
12 | password = sys.argv[2]
13 | info = (username, password)
14 | r = requests.get(url, auth=info)
15 | try:
16 | print(r.json()['id'])
17 | except Exception:
18 | print('None')
19 |
--------------------------------------------------------------------------------
/0x11-python-network_1/2-post_email.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | """
3 | sends a POST request
4 | """
5 |
6 | if __name__ == '__main__':
7 | import urllib.request
8 | import sys
9 | url = sys.argv[1]
10 | value = {"email": sys.argv[2]}
11 | data = urllib.parse.urlencode(value)
12 | data = data.encode("ascii")
13 | req = urllib.request.Request(url, data)
14 | with urllib.request.urlopen(req) as response:
15 | info = response.read()
16 | print(info.decode("ascii"))
17 |
--------------------------------------------------------------------------------
/0x0C-python-almost_a_circle/models/base.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """
4 | Almost a circle Project
5 | Preparing for the AirBnB Clone project
6 | """
7 | import json
8 | import os.path
9 | import csv
10 |
11 |
12 | class Base:
13 | """Base class"""
14 | __nb_objects = 0
15 |
16 | def __init__(self, id=None):
17 | if id is not None:
18 | self.id = id
19 | else:
20 | self.__class__.__nb_objects += 1
21 | self.id = self.__class__.__nb_objects
22 |
--------------------------------------------------------------------------------
/0x15-javascript-web_jquery/102-script.js:
--------------------------------------------------------------------------------
1 | $(document).ready(function () {
2 | $('input#btn_translate').on('click', () => {
3 | const langCode = $('input#language_code').val();
4 | const API_URL = `https://hellosalut.stefanbohacek.dev/?lang=${langCode}`;
5 | // console.log($('input#language_code').val());
6 | // console.log(langCode);
7 | // console.log(API_URL);
8 | $.get(API_URL, (reponse, statusCode) => {
9 | $('div#hello').text(reponse.hello);
10 | });
11 | });
12 | });
13 |
--------------------------------------------------------------------------------
/0x0A-python-inheritance/10-square.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """Rectangle subclass Square."""
4 | Rectangle = __import__('9-rectangle').Rectangle
5 |
6 |
7 | class Square(Rectangle):
8 | """Represent a square."""
9 |
10 | def __init__(self, size):
11 | """Initialize a new square.
12 | Args:
13 | size (int) -> The size of the new square.
14 | """
15 | self.integer_validator("size", size)
16 | super().__init__(size, size)
17 | self.__size = size
18 |
--------------------------------------------------------------------------------
/0x0A-python-inheritance/2-is_same_class.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 |
4 | """Returns true is an object is an instance of a class"""
5 |
6 |
7 | def is_same_class(obj, a_class):
8 | """ Returns True if object is instance of class ;
9 | otherwise False.
10 | Args:
11 | obj -> the object in question
12 | a_class -> the class to compared against
13 | Returns:
14 | True if type(obj) == a_class; False otherwise
15 | """
16 | return isinstance(obj, a_class) and type(obj) == a_class
17 |
--------------------------------------------------------------------------------
/0x0B-python-input_output/7-add_item.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """Add all arguments to a list and save them to a .json"""
4 |
5 |
6 | import sys
7 |
8 |
9 | if __name__ == "__main__":
10 | save_to_json_file = __import__('5-save_to_json_file').save_to_json_file
11 | load_from_json_file = \
12 | __import__('6-load_from_json_file').load_from_json_file
13 | try:
14 | save_to_json_file(sys.argv[1:], "add_item.json")
15 | except FileNotFoundError:
16 | save_to_json_file([], "add_item.json")
17 |
--------------------------------------------------------------------------------
/0x03-python-data_structures/7-add_tuple.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 7-add_tuple.py
3 |
4 |
5 | def add_tuple(tuple_a=(), tuple_b=()):
6 | """Add two tuples."""
7 | if len(tuple_a) < 2:
8 | if len(tuple_a) == 0:
9 | tuple_a = 0, 0
10 | else:
11 | tuple_a = tuple_a[0], 0
12 | if len(tuple_b) < 2:
13 | if len(tuple_b) == 0:
14 | tuple_b = 0, 0
15 | else:
16 | tuple_b = tuple_b[0], 0
17 |
18 | return (tuple_a[0] + tuple_b[0], tuple_a[1] + tuple_b[1])
19 |
--------------------------------------------------------------------------------
/0x06-python-classes/2-square.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 2-square.py
3 |
4 | """Define a class Square."""
5 |
6 |
7 | class Square:
8 | """Represent a square."""
9 |
10 | def __init__(self, size=0):
11 | """Initialize a new Square.
12 |
13 | Args:
14 | __size (int): The __size of the new square.
15 | """
16 | if not isinstance(size, int):
17 | raise TypeError("size must be an integer")
18 | elif size < 0:
19 | raise ValueError("size must be >= 0")
20 | self.__size = size
21 |
--------------------------------------------------------------------------------
/0x0F-python-object_relational_mapping/0-select_states.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | """
3 | Lists all states from the database hbtn_0e_0_usa.
4 | Usage: ./0-select_states.py
5 |
6 |
7 | """
8 | import sys
9 | import MySQLdb
10 |
11 |
12 | if __name__ == "__main__":
13 | db = MySQLdb.connect(user=sys.argv[1], passwd=sys.argv[2], db=sys.argv[3])
14 | c = db.cursor()
15 | c.execute("SELECT * FROM `states`")
16 | [print(state) for state in c.fetchall()]
17 |
--------------------------------------------------------------------------------
/0x00-python-hello_world/10-check_cycle.c:
--------------------------------------------------------------------------------
1 | #include "lists.h"
2 |
3 | /**
4 | * check_cycle - checks if a linked list contains a cycle
5 | * @list: linked list to check
6 | *
7 | * Return: 1 if the list has a cycle, 0 if it doesn't
8 | */
9 | int check_cycle(listint_t *list)
10 | {
11 | listint_t *slow = list;
12 | listint_t *fast = list;
13 |
14 | if (!list)
15 | return (0);
16 |
17 | while (slow && fast && fast->next)
18 | {
19 | slow = slow->next;
20 | fast = fast->next->next;
21 | if (slow == fast)
22 | return (1);
23 | }
24 |
25 | return (0);
26 | }
27 |
--------------------------------------------------------------------------------
/0x04-python-more_data_structures/10-best_score.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 10-best_score.py
3 |
4 |
5 | def best_score(a_dictionary):
6 | """Returns a key with the biggest integer value.
7 | Checks if a thing is a dicrionary with the is instance method"""
8 | if not isinstance(a_dictionary, dict) or len(a_dictionary) == 0:
9 | return None
10 |
11 | ret = list(a_dictionary.keys())[0]
12 | big = a_dictionary[ret]
13 | for k, v in a_dictionary.items():
14 | if v > big:
15 | big = v
16 | ret = k
17 | return (ret)
18 |
--------------------------------------------------------------------------------
/0x0A-python-inheritance/101-add_attribute.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """Function that adds attributes to object if possible"""
4 |
5 |
6 | def add_attribute(objct, attribute, value):
7 | """Add attribute to an object if possible
8 | Args:
9 | objct(object) -> The object to be added an attribute
10 | attribute(str) -> Name of the attribute to add to objct
11 | value(object) -> The value of the atttribute
12 | """
13 | if not hasattr(objct, "__dict__"):
14 | raise TypeError("can't add new attribute")
15 | setattr(objct, attribute, value)
16 |
--------------------------------------------------------------------------------
/0x05-python-exceptions/4-list_division.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | def list_division(my_list_1, my_list_2, list_length):
3 | results = []
4 | for i in range(0, list_length):
5 | try:
6 | res = my_list_1[i] / my_list_2[i]
7 | except TypeError:
8 | print("wrong type")
9 | res = 0
10 | except ZeroDivisionError:
11 | print("division by 0")
12 | res = 0
13 | except IndexError:
14 | print("out of range")
15 | res = 0
16 | finally:
17 | results.append(res)
18 | return results
19 |
--------------------------------------------------------------------------------
/0x14-javascript-web_scraping/6-completed_tasks.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 |
3 | const req = require('request');
4 | const url = process.argv[2];
5 | req.get(url, function (err, res, body) {
6 | if (err) {
7 | console.log(err);
8 | } else {
9 | const data = JSON.parse(body);
10 | const completed = {};
11 | for (const i of data) {
12 | if (i.completed === true) {
13 | if (i.userId in completed) {
14 | completed[i.userId]++;
15 | } else {
16 | completed[i.userId] = 1;
17 | }
18 | }
19 | }
20 | console.log(completed);
21 | }
22 | });
23 |
--------------------------------------------------------------------------------
/0x11-python-network_1/4-hbtn_status.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """
4 | get https://alx-intranet.hbtn.io/status using
5 | requests and print the response to stdout
6 | """
7 |
8 | from requests import get
9 |
10 |
11 | def get_alx_intranet(url='https://alx-intranet.hbtn.io/status'):
12 | """
13 | Send a GET request to the url
14 | and print the reponse
15 | """
16 | res = get(url)
17 | print("Body response:")
18 | print("\t- type: {}".format(str(res).__class__))
19 | print("\t- content: {}".format(res.text))
20 |
21 |
22 | if __name__ == "__main__":
23 | get_alx_intranet()
24 |
--------------------------------------------------------------------------------
/0x14-javascript-web_scraping/4-starwars_count.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 | const request = require('request');
3 | const API_URL = process.argv[2];
4 | let movieCount = 0;
5 |
6 | request(API_URL, (error, response, body) => {
7 | if (error) {
8 | console.error(error);
9 | }
10 | const results = JSON.parse(body).results;
11 | for (const filmIdx in results) {
12 | const filmChars = results[filmIdx].characters;
13 | for (const charIndex in filmChars) {
14 | if (filmChars[charIndex].includes('18')) {
15 | movieCount += 1;
16 | }
17 | }
18 | }
19 | console.log(movieCount);
20 | });
21 |
--------------------------------------------------------------------------------
/0x0A-python-inheritance/4-inherits_from.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 4-inherits_from.py
3 | """Defines an inherited class-checking function.
4 | """
5 |
6 |
7 | def inherits_from(obj, a_class):
8 | """Checks if an object is an inherited instance of a class.
9 | Args:
10 | obj (any): The object to check.
11 | a_class (type): The class to match the type of obj to.
12 | Returns:
13 | If obj is an inherited instance of a_class - True.
14 | Otherwise - False.
15 | """
16 | if issubclass(type(obj), a_class) and type(obj) != a_class:
17 | return True
18 | return False
19 |
--------------------------------------------------------------------------------
/0x15-javascript-web_jquery/103-script.js:
--------------------------------------------------------------------------------
1 | $(document).ready(function () {
2 | const langCode = $('input#language_code').val();
3 | const API_URL = `https://hellosalut.stefanbohacek.dev/?lang=${langCode}`;
4 | $('input#btn_translate').on('click kepress', (event) => {
5 | // console.log($('input#language_code').val());
6 | // console.log(langCode);
7 | // console.log(API_URL);
8 | if (event.type === 'click' || (event.type === 'keypress' && event.keyCode === 13)) {
9 | $.get(API_URL, (reponse, statusCode) => {
10 | $('div#hello').text(reponse.hello);
11 | });
12 | }
13 | });
14 | });
15 |
--------------------------------------------------------------------------------
/0x0A-python-inheritance/3-is_kind_of_class.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 3-is_kind_of_class.py
3 | """Defines a class and inherited class-checking function"""
4 |
5 |
6 | def is_kind_of_class(obj, a_class):
7 | """Check if an object is an instance or inherited instance of a class
8 |
9 | Args:
10 | obj (any): The object to check
11 | a_class (type): The class to match the type of obj to
12 | Returns:
13 | If obj is an instance or inherited instance of a_class - True
14 | Otherwise False
15 | """
16 | if isinstance(obj, a_class):
17 | return True
18 | return False
19 |
--------------------------------------------------------------------------------
/0x0B-python-input_output/9-student.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """Student class to represent a student"""
4 |
5 |
6 | class Student:
7 | """Defining student class """
8 | def __init__(self, first_name, last_name, age):
9 | """Student constructor
10 | Args:
11 | first_name(str)
12 | last_name(str)
13 | age(str)
14 | """
15 | self.first_name = first_name
16 | self.last_name = last_name
17 | self.age = age
18 |
19 | def to_json(self):
20 | """ Retrive information about an instance to json"""
21 | return self.__dict__
22 |
--------------------------------------------------------------------------------
/0x0B-python-input_output/12-pascal_triangle.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """Function to print pascal's triangle upto level """
4 |
5 |
6 | def pascal_triangle(n):
7 | """Pascal's Triangle of size n.
8 | Returns a list of lists of integers representing the triangle.
9 | """
10 | if n <= 0:
11 | return []
12 |
13 | triangles = [[1]]
14 | while len(triangles) != n:
15 | tri = triangles[-1]
16 | temp = [1]
17 | for i in range(len(tri) - 1):
18 | temp.append(tri[i] + tri[i + 1])
19 | temp.append(1)
20 | triangles.append(temp)
21 | return triangles
22 |
--------------------------------------------------------------------------------
/0x0B-python-input_output/2-append_write.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """ Function to append to a file"""
4 |
5 |
6 | def append_write(filename="", text=""):
7 | """Append to
8 | Args:
9 | filename(str) -> Name of the file to append to
10 | text(str) -> Content to append
11 | Returns:
12 | Number of characters written
13 | """
14 | if filename:
15 | with open(filename, "a", encoding="utf-8") as f:
16 | pre_content = f.tell()
17 | f.write(text)
18 | post_content = f.tell()
19 | return post_content - pre_content
20 |
--------------------------------------------------------------------------------
/0x0F-python-object_relational_mapping/1-filter_states.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | """
3 | # Lists all states with a name starting with N from the database hbtn_0e_0_usa.
4 | # Usage: ./1-filter_states.py \
5 | # \
6 | #
7 | """
8 | import sys
9 | import MySQLdb
10 |
11 | if __name__ == "__main__":
12 | db = MySQLdb.connect(user=sys.argv[1], passwd=sys.argv[2], db=sys.argv[3])
13 | c = db.cursor()
14 | c.execute("SELECT * FROM `states` ORDER BY `id`")
15 | [print(state) for state in c.fetchall() if state[1][0] == "N"]
16 |
--------------------------------------------------------------------------------
/0x14-javascript-web_scraping/100-starwars_characters.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 |
3 | const req = require('request');
4 | const id = process.argv[2];
5 | const url = 'https://swapi-api.hbtn.io/api/films/';
6 | req.get(url + id, function (error, res, body) {
7 | if (error) {
8 | console.log(error);
9 | }
10 | const data = JSON.parse(body);
11 | const dd = data.characters;
12 | for (const i of dd) {
13 | req.get(i, function (error, res, body1) {
14 | if (error) {
15 | console.log(error);
16 | }
17 | const data1 = JSON.parse(body1);
18 | console.log(data1.name);
19 | });
20 | }
21 | });
22 |
--------------------------------------------------------------------------------
/0x03-python-data_structures/lists.h:
--------------------------------------------------------------------------------
1 | #ifndef LISTS_H
2 | #define LISTS_H
3 | #include
4 | #include
5 | /**
6 | * struct listint_s - singly linked list
7 | * @n: integer
8 | * @next: points to the next node
9 | *
10 | * Description: singly linked list node structure
11 | * for project
12 | */
13 | typedef struct listint_s
14 | {
15 | int n;
16 | struct listint_s *next;
17 | } listint_t;
18 |
19 | size_t print_listint(const listint_t *h);
20 | listint_t *add_nodeint_end(listint_t **head, const int n);
21 | void free_listint(listint_t *head);
22 |
23 | int is_palindrome(listint_t **head);
24 |
25 | #endif /* LISTS_H */
26 |
--------------------------------------------------------------------------------
/0x01-python-if_else_loops_functions/lists.h:
--------------------------------------------------------------------------------
1 | #ifndef LISTS_H
2 | #define LISTS_H
3 |
4 | #include
5 |
6 | /**
7 | * struct listint_s - singly linked list
8 | * @n: integer
9 | * @next: points to the next node
10 | *
11 | * Description: singly linked list node structure
12 | * for Holberton project
13 | */
14 | typedef struct listint_s
15 | {
16 | int n;
17 | struct listint_s *next;
18 | } listint_t;
19 |
20 | size_t print_listint(const listint_t *h);
21 | listint_t *add_nodeint_end(listint_t **head, const int n);
22 | void free_listint(listint_t *head);
23 | listint_t *insert_node(listint_t **head, int number);
24 |
25 | #endif /* LISTS_H */
26 |
--------------------------------------------------------------------------------
/0x15-javascript-web_jquery/1-script.js:
--------------------------------------------------------------------------------
1 | $('header').css('color', 'red');
2 | /*
3 | const addButton = $('.add-item');
4 | let taskNo = 1;
5 | addButton.on('click', function (){
6 | const itemsList = $('.items');
7 | if (taskNo >= 0){
8 | $('.items').append(` Task ${taskNo}`);
9 | taskNo += 1;
10 | } else {
11 | $('.items').append(` Task 0`);
12 | taskNo += 1;
13 | }
14 | console.log(itemsList.html())
15 | });
16 |
17 |
18 | const deleteButton = $('.delete-item')
19 |
20 | deleteButton.on('click', function () {
21 | $('.items').find('li').last().remove()
22 | taskNo -= 1
23 | })
24 | */
25 |
--------------------------------------------------------------------------------
/0x11-python-network_1/5-hbtn_header.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """
4 | send a GET request to a the url provided
5 | as an Argument to the script and print the
6 | X-Request-Id value of the header
7 | """
8 |
9 |
10 | from requests import get
11 | from sys import argv
12 |
13 |
14 | def get_alx_intranet(url):
15 | """
16 | Send a GET request to the url
17 | and print the X-Request-Id header value
18 | """
19 | if url:
20 | try:
21 | return get(url).headers.get('X-Request-Id')
22 | except Exception as e:
23 | return e
24 |
25 |
26 | if __name__ == "__main__":
27 | print(get_alx_intranet(argv[1]))
28 |
--------------------------------------------------------------------------------
/0x11-python-network_1/7-error_code.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | """Send a request to the url and print the response"""
3 |
4 | from requests import get
5 | from sys import argv
6 |
7 |
8 | def request_header_property(url: str) -> str:
9 | """
10 | Send a request to the URL specified and
11 | get the response and handle exceptions
12 | Args:
13 | url (str): The URL to query
14 | """
15 | response = get(url)
16 | if int(response.status_code) >= 400:
17 | return ("Error code: {}".format(response.status_code))
18 |
19 | return response.text
20 |
21 |
22 | if __name__ == "__main__":
23 | print(request_header_property(argv[1]))
24 |
--------------------------------------------------------------------------------
/0x11-python-network_1/8-json_api.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """
4 | POST request to http://0.0.0.0:5000/search_user
5 | """
6 |
7 | if __name__ == '__main__':
8 | import requests
9 | import sys
10 | url = "http://0.0.0.0:5000/search_user"
11 | try:
12 | ar = sys.argv[1]
13 | except Exception:
14 | ar = ""
15 | q = {"q": ar}
16 | r = requests.post(url, data=q)
17 | try:
18 | result = r.json()
19 | except Exception:
20 | print("Not a valid JSON")
21 | exit()
22 | try:
23 | print("[{}] {}".format(result['id'], result['name']))
24 | except Exception:
25 | print("No result")
26 |
--------------------------------------------------------------------------------
/0x0A-python-inheritance/tests/2-is_same_class.txt:
--------------------------------------------------------------------------------
1 | =======================
2 | How to Use 2-is_same_class.py
3 | =======================
4 |
5 | This module defines a function ```is_same_class``` that asserts if a object is an instance of the class
6 |
7 | ==========
8 | Test
9 | ===========
10 |
11 | >>> is_same_class = __import__('2-is_same_class').is_same_class
12 |
13 | >>> is_same_class()
14 | Traceback (most recent call last):
15 | ...
16 | TypeError: is_same_class() missing 2 required positional arguments: 'obj' and 'a_class'
17 |
18 | >>> is_same_class("John", str)
19 | True
20 |
21 | >>> is_same_class(1, int)
22 | True
23 |
24 | >>> is_same_class(1, float)
25 | False
26 |
--------------------------------------------------------------------------------
/0x11-python-network_1/0-hbtn_status.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | """get https://alx-intranet.hbtn.io/status"""
3 | from urllib import request, error
4 |
5 | if __name__ == "__main__":
6 | url = "https://alx-intranet.hbtn.io/status"
7 | try:
8 | with request.urlopen(url) as response:
9 | response = response.read()
10 | print("Body response:")
11 | print("\t- type: {}".format(type(response)))
12 | print("\t- content: {}".format(response))
13 | print("\t- utf8 content: {}".format(response.decode('utf-8')))
14 | except error.URLError:
15 | print("Cannot connect to https://alx-intranet.hbtn.io/status")
16 |
--------------------------------------------------------------------------------
/0x0B-python-input_output/1-write_file.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """ Function to write to a file"""
4 |
5 |
6 | def write_file(filename="", text=""):
7 | """Write to overriding
8 | Args:
9 | filename(str) -> Name of the file to write to
10 | text(str) -> Content to write
11 | Returns:
12 | Number of characters written
13 | """
14 | if filename:
15 | with open(filename, "w", encoding="utf-8") as file_to_write:
16 | original_content = file_to_write.tell()
17 | file_to_write.write(text)
18 | new_content = file_to_write.tell()
19 | return new_content - original_content
20 |
--------------------------------------------------------------------------------
/0x13-javascript_objects_scopes_closures/4-rectangle.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 |
3 | module.exports = class Rectangle {
4 | constructor (w, h) {
5 | if ((w > 0) && (h > 0)) {
6 | [this.width, this.height] = [w, h];
7 | }
8 | }
9 |
10 | print () {
11 | let sizeY = this.height;
12 | while (sizeY > 0) {
13 | console.log('X'.repeat(this.width));
14 | sizeY -= 1;
15 | }
16 | }
17 |
18 | rotate () {
19 | const tempHeight = this.height;
20 | this.height = this.width;
21 | this.width = tempHeight;
22 | }
23 |
24 | double () {
25 | [this.width, this.height] = [this.width, this.height]
26 | .map(prop => prop * 2);
27 | }
28 | };
29 |
--------------------------------------------------------------------------------
/0x0A-python-inheritance/8-rectangle.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """Rectangle class that inherits from BaseGeometry."""
4 | BaseGeometry = __import__('7-base_geometry').BaseGeometry
5 |
6 |
7 | class Rectangle(BaseGeometry):
8 | """Represent a rectangle using BaseGeometry."""
9 |
10 | def __init__(self, width, height):
11 | """Intialize a new Rectangle.
12 | Args:
13 | width (int) -> width of the new Rectangle.
14 | height (int) -> height of the new Rectangle.
15 | """
16 | super().integer_validator("width", width)
17 | self.__width = width
18 | super().integer_validator("height", height)
19 | self.__height = height
20 |
--------------------------------------------------------------------------------
/0x03-python-data_structures/100-print_python_list_info.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | /**
5 | * print_python_list_info - Print some basic info about Python lists
6 | * @p: PyObject
7 | *
8 | * Return: Nothing
9 | */
10 | void print_python_list_info(PyObject *p)
11 | {
12 | PyObject *item;
13 | PyListObject *list = (PyListObject *)p;
14 | int i, size, alloc;
15 |
16 | size = Py_SIZE(p);
17 | alloc = list->allocated;
18 | printf("[*] Size of the Python List = %d\n", size);
19 | printf("[*] Allocated = %d\n", alloc);
20 |
21 | for (i = 0; i < size; i++)
22 | {
23 | item = PyList_GetItem(p, i);
24 | printf("Element %d: %s\n", i, Py_TYPE(item)->tp_name);
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/0x06-python-classes/3-square.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 3-square.py
3 |
4 | """Define a class Square."""
5 |
6 |
7 | class Square:
8 | """Represent a square."""
9 |
10 | def __init__(self, __size=0):
11 | """Initialize a new square.
12 |
13 | Args:
14 | __size (int): The __size of the new square.
15 | """
16 | if not isinstance(__size, int):
17 | raise TypeError("__size must be an integer")
18 | elif __size < 0:
19 | raise ValueError("__size must be >= 0")
20 | self.__size = __size
21 |
22 | def area(self):
23 | """Return the current area of the square."""
24 | return (self.__size * self.__size)
25 |
--------------------------------------------------------------------------------
/0x11-python-network_1/3-error_code.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | """Send a request to the url and print the response"""
3 |
4 | from urllib import request, error
5 | from sys import argv
6 |
7 |
8 | def request_header_property(url: str) -> str:
9 | """
10 | Send a request to the URL specified and
11 | get the response and handle exceptions
12 | Args:
13 | url (str): The URL to query
14 | """
15 | try:
16 | with request.urlopen(url) as response:
17 | return response.read().decode('utf-8')
18 | except error.HTTPError as e:
19 | return "Error code: {}".format(e.code)
20 |
21 |
22 | if __name__ == "__main__":
23 | print(request_header_property(argv[1]))
24 |
--------------------------------------------------------------------------------
/0x04-python-more_data_structures/12-roman_to_int.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | def roman_to_int(roman_string):
3 | """ converts a Roman numeral to an integer."""
4 | romans = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
5 | if (not roman_string) or (not isinstance(roman_string, str)):
6 | return 0
7 |
8 | number = len(roman_string)
9 | value_int = romans[roman_string[number-1]]
10 | for i in range(number - 1, 0, -1):
11 | current_value = romans[roman_string[i]]
12 | previous_value = romans[roman_string[i-1]]
13 |
14 | if previous_value >= current_value:
15 | value_int += previous_value
16 | else:
17 | value_int -= previous_value
18 |
19 | return value_int
20 |
--------------------------------------------------------------------------------
/0x0B-python-input_output/100-append_after.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """Insert a string of text, after each line matching the search term"""
4 |
5 |
6 | def append_after(filename="", search_string="", new_string=""):
7 | """Insert after everly line that has
8 | Args:
9 | filename(str) -> Name of the file
10 | search_string(str) -> string to match
11 | new_string(str) -> string to append
12 | """
13 | text_string = ""
14 | with open(filename) as f_read:
15 | for line in f_read:
16 | text_string += line
17 | if search_string in line:
18 | text_string += new_string
19 | with open(filename, "w") as f_write:
20 | f_write.write(text_string)
21 |
--------------------------------------------------------------------------------
/0x0F-python-object_relational_mapping/3-my_safe_filter_states.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | """
3 | # Displays all values in the states table of the database hbtn_0e_0_usa
4 | # whose name matches that supplied as argument.
5 | # Safe from SQL injections.
6 | # Usage: ./3-my_safe_filter_states.py \
7 | # \
8 | # \
9 | #
10 | """
11 | import sys
12 | import MySQLdb
13 |
14 | if __name__ == "__main__":
15 | db = MySQLdb.connect(user=sys.argv[1], passwd=sys.argv[2], db=sys.argv[3])
16 | c = db.cursor()
17 | c.execute("SELECT * FROM `states`")
18 | [print(state) for state in c.fetchall() if state[1] == sys.argv[4]]
19 |
--------------------------------------------------------------------------------
/0x0F-python-object_relational_mapping/2-my_filter_states.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | """
3 | # Displays all values in the states table of the database hbtn_0e_0_usa
4 | # whose name matches that supplied as argument.
5 | # Usage: ./2-my_filter_states.py \
6 | # \
7 | # \
8 | #
9 |
10 | """
11 | import sys
12 | import MySQLdb
13 |
14 | if __name__ == "__main__":
15 | db = MySQLdb.connect(user=sys.argv[1], passwd=sys.argv[2], db=sys.argv[3])
16 | c = db.cursor()
17 | c.execute("SELECT * \
18 | FROM `states` \
19 | WHERE BINARY `name` = '{}'".format(sys.argv[4]))
20 | [print(state) for state in c.fetchall()]
21 |
--------------------------------------------------------------------------------
/0x07-python-test_driven_development/0-add_integer.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | def add_integer(a, b=98):
3 | """Function return the result of addition of a and b
4 | Args:
5 | a(int) -> The first arg, must be passed
6 | b(int) -> The second arg, if not passed, 98 is assumed to be the value
7 | Returns an int
8 | """
9 | try:
10 | if not (isinstance(a, int)) and not isinstance(a, float):
11 | raise TypeError("a must be an integer")
12 | elif not (isinstance(b, int)) and not isinstance(b, float):
13 | raise TypeError("b must be an integer")
14 | else:
15 | if isinstance(a, float) or isinstance(b, float):
16 | return (int(a) + int(b))
17 | return a + b
18 | except Exception as e:
19 | return (e)
20 |
--------------------------------------------------------------------------------
/0x0F-python-object_relational_mapping/model_state.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | """
3 | Defines the state model, containing the State class and
4 | """
5 | from sqlalchemy import create_engine, Integer, Column, String
6 | from sqlalchemy.orm import declarative_base
7 |
8 | engine = create_engine('mysql+mysqldb://root:root@localhost/hbtn_0e_6_usa')
9 | Base = declarative_base()
10 |
11 |
12 | class State(Base):
13 | """
14 | State class
15 | id -> state.id
16 | name -> state.name
17 | """
18 | __tablename__ = 'states'
19 | id = Column(Integer, primary_key=True,
20 | nullable=False, unique=True,
21 | autoincrement=True)
22 | name = Column(String(128), nullable=False)
23 |
24 | def __repr__(self):
25 | return "{}: {}".format(self.id, self.name)
26 |
--------------------------------------------------------------------------------
/0x07-python-test_driven_development/3-say_my_name.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """Print the last and first name and run a bunch of tests to fool the checker"""
4 |
5 |
6 | def say_my_name(first_name, last_name=""):
7 | """Function to return formated name
8 | Args:
9 | first_name (str) -> The first name
10 | last_name (str) -> The last name
11 | Returns:
12 | 'My name is '
13 | """
14 | try:
15 | if not isinstance(first_name, str):
16 | raise TypeError("first_name must be a string")
17 | if not isinstance(last_name, str):
18 | raise TypeError("last_name must be a string")
19 | else:
20 | return ("My name is {} {}".format(first_name, last_name))
21 | except Exception as ex:
22 | return (ex)
23 |
--------------------------------------------------------------------------------
/0x0F-python-object_relational_mapping/14-model_city_fetch_by_state.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | """
3 | prints all City objects from the database hbtn_0e_14_usa
4 | """
5 |
6 | import sys
7 | from venv import create
8 | from sqlalchemy import create_engine, true
9 | from sqlalchemy.orm import sessionmaker
10 | from model_state import State
11 | from model_city import City
12 |
13 | if __name__ == "__main__":
14 | engine = create_engine("mysql+mysqldb://{}:{}@localhost/{}".format(
15 | sys.argv[1], sys.argv[2], sys.argv[3]), pool_pre_ping=True)
16 | session_maker = sessionmaker(bind=engine)
17 | session = session_maker()
18 |
19 | for city, state in session.query(City, State)\
20 | .filter(City.state_id == State.id)\
21 | .order_by(City.id):
22 | print("{}: ({}) {}".format(state.name, city.id, city.name))
23 |
--------------------------------------------------------------------------------
/0x07-python-test_driven_development/5-text_indentation.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | def text_indentation(text):
3 | try:
4 | if not isinstance(text, str):
5 | raise TypeError("text must be a string")
6 | else:
7 | c = 0
8 | while c < len(text) and text[c] == ' ':
9 | c += 1
10 | # Dont know what I did right here
11 | while c < len(text):
12 | print(text[c], end="")
13 | if text[c] == "\n" or text[c] in ".?:":
14 | if text[c] in ".?:":
15 | print("\n")
16 | c += 1
17 | while c < len(text) and text[c] == ' ':
18 | c += 1
19 | continue
20 | c += 1
21 | except Exception as exc:
22 | return (exc)
23 |
--------------------------------------------------------------------------------
/0x0F-python-object_relational_mapping/5-filter_cities.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | """
3 | # Displays all cities of a given state from the
4 | # states table of the database hbtn_0e_4_usa.
5 | # Safe from SQL injections.
6 | # Usage: ./5-filter_cities.py \
7 | # \
8 | # \
9 | #
10 | """
11 | import sys
12 | import MySQLdb
13 |
14 | if __name__ == "__main__":
15 | db = MySQLdb.connect(user=sys.argv[1], passwd=sys.argv[2], db=sys.argv[3])
16 | c = db.cursor()
17 | c.execute("SELECT * FROM `cities` as `c` \
18 | INNER JOIN `states` as `s` \
19 | ON `c`.`state_id` = `s`.`id` \
20 | ORDER BY `c`.`id`")
21 | print(", ".join([ct[2] for ct in c.fetchall() if ct[4] == sys.argv[4]]))
22 |
--------------------------------------------------------------------------------
/0x08-python-more_classes/101-nqueens.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 101-nqueens.py
3 | """Solves the N-queens puzzle.
4 |
5 | Determines all possible solutions to placing N
6 | N non-attacking queens on an NxN chessboard.
7 |
8 | Example:
9 | $ ./101-nqueens.py N
10 |
11 | N must be an integer greater than or equal to 4.
12 |
13 | Attributes:
14 | board (list): A list of lists representing the chessboard.
15 | solutions (list): A list of lists containing solutions.
16 |
17 | Solutions are represented in the format [[r, c], [r, c], [r, c], [r, c]]
18 | where `r` and `c` represent the row and column, respectively, where a
19 | queen must be placed on the chessboard.
20 | """
21 | import sys
22 |
23 |
24 | def init_board(n):
25 | """Initialize an `n`x`n` sized chessboard with 0's.
26 | """
27 | board = [['' for col in range(n)] for row in range(n)]
28 | return board
29 |
--------------------------------------------------------------------------------
/0x0F-python-object_relational_mapping/7-model_state_fetch_all.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | """
3 | # Lists all State objects from the database hbtn_0e_6_usa.
4 | # Usage: ./7-model_state_fetch_all.py /
5 | # /
6 | #
7 | """
8 | import sys
9 | from sqlalchemy import create_engine
10 | from sqlalchemy.orm import sessionmaker
11 | from model_state import State
12 |
13 | if __name__ == "__main__":
14 | engine = create_engine("mysql+mysqldb://{}:{}@localhost/{}"
15 | .format(sys.argv[1], sys.argv[2], sys.argv[3]),
16 | pool_pre_ping=True)
17 | Session = sessionmaker(bind=engine)
18 | session = Session()
19 |
20 | for state in session.query(State).order_by(State.id):
21 | print("{}: {}".format(state.id, state.name))
22 |
--------------------------------------------------------------------------------
/0x0A-python-inheritance/7-base_geometry.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 |
4 | """ Base class """
5 |
6 |
7 | class BaseGeometry:
8 | """BaseGeometry as the base class"""
9 |
10 | def area(self):
11 | """Lets raise an exception """
12 | raise Exception("area() is not implemented")
13 |
14 | def integer_validator(self, name, value):
15 | """Validate name and value
16 | Args:
17 | name(string)
18 | value(int)
19 | Raises:
20 | TypeError: if not isinstance(value, int)
21 | ValueError: if value <= 0
22 | """
23 | try:
24 | if type(value) != int:
25 | raise TypeError("{} must be an integer".format(name))
26 | if value <= 0:
27 | raise ValueError("{} must be greater than 0".format(name))
28 | except Exception as e:
29 | return e
30 |
--------------------------------------------------------------------------------
/0x02-python-import_modules/100-my_calculator.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | from calculator_1 import add, sub, mul, div
3 | import sys
4 |
5 | if __name__ == '__main__':
6 | if len(sys.argv) != 4:
7 | print("Usage: ./100-my_calculator.py ")
8 | sys.exit(1)
9 | else:
10 | opcode = str(sys.argv[2])
11 | a = int(sys.argv[1])
12 | b = int(sys.argv[3])
13 |
14 | if opcode == '+':
15 | print("{0} + {1} = {2}".format(a, b, add(a, b)))
16 | elif opcode == '-':
17 | print("{0} - {1} = {2}".format(a, b, sub(a, b)))
18 | elif opcode == '*':
19 | print("{0} * {1} = {2}".format(a, b, mul(a, b)))
20 | elif opcode == '/':
21 | print("{0} / {1} = {2}".format(a, b, div(a, b)))
22 | else:
23 | print("Unknown operator. Available operators: +, -, * and /")
24 | sys.exit(1)
25 |
--------------------------------------------------------------------------------
/0x07-python-test_driven_development/4-print_square.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | def print_square(size):
3 | """ Function to print squares of '#'
4 | Args:
5 | size(int/float) -> number of "#"'s to print
6 | -> Must be an int or a float >= 0
7 | Returns nothing except if an exception occured,
8 | in which case the exception raised is returned
9 | """
10 | try:
11 | if not isinstance(size, int):
12 | raise TypeError("size must be an integer")
13 | elif size < 0:
14 | raise ValueError("size must be >= 0")
15 | elif isinstance(size, float) and size < 0:
16 | raise ValueError("size must be an integer")
17 | else:
18 | for row in range(size):
19 | for column in range(size):
20 | print("#", end="")
21 | print()
22 | except Exception as e:
23 | return (e)
24 |
--------------------------------------------------------------------------------
/0x0B-python-input_output/10-student.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """Student class to represent a student"""
4 |
5 |
6 | class Student:
7 | """Defining student class """
8 | def __init__(self, first_name, last_name, age):
9 | """Student constructor
10 | Args:
11 | first_name(str)
12 | last_name(str)
13 | age(str)
14 | """
15 | self.first_name = first_name
16 | self.last_name = last_name
17 | self.age = age
18 |
19 | def to_json(self, attrs=None):
20 | """ Retrive information about an instance to json
21 | Args:
22 | attrs(list) -> List of attribute to be retrieved
23 | """
24 | if (type(attrs) == list and
25 | all(type(element) == str for element in attrs)):
26 | return {key: getattr(self, key)
27 | for key in attrs if hasattr(self, key)}
28 | return self.__dict__
29 |
--------------------------------------------------------------------------------
/0x0F-python-object_relational_mapping/9-model_state_filter_a.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | """
3 | # Lists all State objects that contain the letter a
4 | # from the database hbtn_0e_6_usa.
5 | # Usage: ./9-model_state_filter_a.py /
6 | # /
7 | #
8 | """
9 | import sys
10 | from sqlalchemy import create_engine
11 | from sqlalchemy.orm import sessionmaker
12 | from model_state import State
13 |
14 | if __name__ == "__main__":
15 | engine = create_engine("mysql+mysqldb://{}:{}@localhost/{}"
16 | .format(sys.argv[1], sys.argv[2], sys.argv[3]),
17 | pool_pre_ping=True)
18 | Session = sessionmaker(bind=engine)
19 | session = Session()
20 |
21 | for state in session.query(State).order_by(State.id):
22 | if "a" in state.name:
23 | print("{}: {}".format(state.id, state.name))
24 |
--------------------------------------------------------------------------------
/0x11-python-network_1/100-github_commits.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """
4 | holberton interview :
5 | Write a Python script that takes 2 arguments in order to solve this challenge.
6 | The first argument will be the repository name
7 | The second argument will be the owner name
8 | You must use the packages requests and sys
9 | You are not allowed to import packages other than requests and sys
10 | You don’t need to check arguments passed to the script (number or type)
11 | """
12 |
13 | if __name__ == '__main__':
14 | import sys
15 | import requests
16 | repo_name = sys.argv[1]
17 | owner_name = sys.argv[2]
18 | repo_info = owner_name + "/" + repo_name
19 | url = "https://api.github.com/repos/" + repo_info + "/commits"
20 | r = requests.get(url)
21 | top = r.json()[:10]
22 | for i in top:
23 | el = i['sha']
24 | author = i['commit']['author']['name']
25 | print('{}: {}'.format(el, author))
26 |
--------------------------------------------------------------------------------
/0x0F-python-object_relational_mapping/8-model_state_fetch_first.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | """
3 | # Prints the first State object from the database hbtn_0e_6_usa.
4 | # Usage: ./8-model_state_fetch_first.py /
5 | # /
6 | #
7 | """
8 | import sys
9 | from sqlalchemy import create_engine
10 | from sqlalchemy.orm import sessionmaker
11 | from model_state import State
12 |
13 | if __name__ == "__main__":
14 | engine = create_engine("mysql+mysqldb://{}:{}@localhost/{}"
15 | .format(sys.argv[1], sys.argv[2], sys.argv[3]),
16 | pool_pre_ping=True)
17 | Session = sessionmaker(bind=engine)
18 | session = Session()
19 |
20 | state = session.query(State).order_by(State.id).first()
21 | if state is None:
22 | print("Nothing")
23 | else:
24 | print("{}: {}".format(state.id, state.name))
25 |
--------------------------------------------------------------------------------
/0x01-python-if_else_loops_functions/13-insert_number.c:
--------------------------------------------------------------------------------
1 | #include "lists.h"
2 | /**
3 | * insert_node - Inserts a number into a sorted singly-linked list.
4 | * @head: A pointer the head of the linked list.
5 | * @number: The number to insert.
6 | *
7 | * Return: If the function fails - NULL.
8 | * Otherwise - a pointer to the new node.
9 | */
10 | listint_t *insert_node(listint_t **head, int number)
11 | {
12 | listint_t *new_node = malloc(sizeof(listint_t)), *_head = *head;
13 | listint_t *prev = _head;
14 | if (!new_node)
15 | return (NULL);
16 | new_node->n = number;
17 | if (!_head)
18 | {
19 | new_node->next = _head, *head = new_node;
20 | return (new_node);
21 | }
22 | while (_head->next)
23 | {
24 | if (_head->n < number)
25 | prev = _head, _head = _head->next;
26 | else
27 | break;
28 | }
29 | new_node->next = (_head->next) ? _head : NULL;
30 | if (prev == _head)
31 | *head = new_node;
32 | else
33 | {
34 | if (_head->next)
35 | prev->next = new_node;
36 | else
37 | _head->next = new_node;
38 | }
39 | return (new_node);
40 | }
41 |
--------------------------------------------------------------------------------
/0x0F-python-object_relational_mapping/12-model_state_update_id_2.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """
4 | Module to perfom simple queries on the model_state model
5 | using and ORM - SQLAlchemy
6 | """
7 | from model_state import Base, State
8 | from sqlalchemy import create_engine
9 | from sqlalchemy.orm import sessionmaker
10 | import sys
11 |
12 |
13 | def connect_and_query(user: str, passwd: str, dbase: str) -> None:
14 |
15 | """
16 | Connect to the database and make queries using ORM
17 | """
18 | try:
19 | engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}'
20 | .format(user, passwd, dbase))
21 | Session = sessionmaker(bind=engine)
22 | state_session = Session()
23 | state = state_session.query(State).filter_by(id=2).first()
24 | state.name = "New Mexico"
25 | state_session.commit()
26 |
27 | except Exception as e:
28 | return e
29 |
30 |
31 | if __name__ == "__main__":
32 | connect_and_query(sys.argv[1], sys.argv[2], sys.argv[3])
33 |
--------------------------------------------------------------------------------
/0x0F-python-object_relational_mapping/11-model_state_insert.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """
4 | Module to perfom simple queries on the model_state model
5 | using and ORM - SQLAlchemy
6 | """
7 | from model_state import Base, State
8 | from sqlalchemy import create_engine
9 | from sqlalchemy.orm import sessionmaker
10 | import sys
11 |
12 |
13 | def connect_and_query(user: str, passwd: str, dbase: str) -> None:
14 |
15 | """
16 | Connect to the database and make queries using ORM
17 | """
18 | try:
19 | engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}'
20 | .format(user, passwd, dbase))
21 | Session = sessionmaker(bind=engine)
22 | state_session = Session()
23 |
24 | lousiana = State(name="Louisiana")
25 | state_session.add(lousiana)
26 | state_session.commit()
27 | print(lousiana.id)
28 | except Exception as e:
29 | return e
30 |
31 |
32 | if __name__ == "__main__":
33 | connect_and_query(sys.argv[1], sys.argv[2], sys.argv[3])
34 |
--------------------------------------------------------------------------------
/0x0F-python-object_relational_mapping/13-model_state_delete_a.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """
4 | Module to perfom simple queries on the model_state model
5 | using and ORM - SQLAlchemy
6 | """
7 | from model_state import Base, State
8 | from sqlalchemy import create_engine
9 | from sqlalchemy.orm import sessionmaker
10 | import sys
11 |
12 |
13 | def connect_and_query(user: str, passwd: str, dbase: str) -> None:
14 |
15 | """
16 | Connect to the database and make queries using ORM
17 | """
18 | try:
19 | engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}'
20 | .format(user, passwd, dbase))
21 | Session = sessionmaker(bind=engine)
22 | session = Session()
23 | states = session.query(State).filter(State.name.like('%a%')).all()
24 | [session.delete(state) for state in states]
25 | session.commit()
26 |
27 | except Exception as e:
28 | return e
29 |
30 |
31 | if __name__ == "__main__":
32 | connect_and_query(sys.argv[1], sys.argv[2], sys.argv[3])
33 |
--------------------------------------------------------------------------------
/0x06-python-classes/4-square.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | """class Square that defines a square"""
3 |
4 |
5 | class Square():
6 | """Implementing the square class"""
7 |
8 | def __init__(self, size=0):
9 | self.__size = size
10 |
11 | @property
12 | def size(self):
13 | """Get the value of size
14 | Args:
15 | None
16 | Returns:
17 | __size
18 | """
19 | return self.__size
20 |
21 | @size.setter
22 | def size(self, value):
23 | """Set the value of the square
24 | Args:
25 | value (int)
26 | Returns:
27 | None
28 | """
29 | if (not isinstance(value, int)):
30 | raise TypeError("size must be an integer")
31 | elif (value < 0):
32 | raise ValueError("size must be >= 0")
33 | self.__size = value
34 |
35 | def area(self):
36 | """Compute and Return area
37 | Args:
38 | None
39 | Returns
40 | __size x 4
41 | """
42 | return self.__size ** 2
43 |
--------------------------------------------------------------------------------
/0x0A-python-inheritance/9-rectangle.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """Rectangle class that inherits from BaseGeometry."""
4 | BaseGeometry = __import__('7-base_geometry').BaseGeometry
5 |
6 |
7 | class Rectangle(BaseGeometry):
8 | """Represent a rectangle using BaseGeometry."""
9 |
10 | def __init__(self, width, height):
11 | """Intialize a new Rectangle.
12 | Args:
13 | width (int) -> width of the new Rectangle.
14 | height (int) -> height of the new Rectangle.
15 | """
16 | super().integer_validator("width", width)
17 | self.__width = width
18 | super().integer_validator("height", height)
19 | self.__height = height
20 |
21 | def area(self):
22 | """Return the area of the rectangle."""
23 | return self.__width * self.__height
24 |
25 | def __str__(self):
26 | """Return the print() and str() representation of a Rectangle."""
27 | string = "[" + str(self.__class__.__name__) + "] "
28 | string += str(self.__width) + "/" + str(self.__height)
29 | return string
30 |
--------------------------------------------------------------------------------
/0x0B-python-input_output/11-student.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """Student class to represent a student"""
4 |
5 |
6 | class Student:
7 | """Defining student class """
8 | def __init__(self, first_name, last_name, age):
9 | """Student constructor
10 | Args:
11 | first_name(str)
12 | last_name(str)
13 | age(str)
14 | """
15 | self.first_name = first_name
16 | self.last_name = last_name
17 | self.age = age
18 |
19 | def to_json(self, attrs=None):
20 | """ Retrive information about an instance to json
21 | Args:
22 | attrs(list) -> List of attribute to be retrieved
23 | """
24 | if (type(attrs) == list and
25 | all(type(element) == str for element in attrs)):
26 | return {key: getattr(self, key)
27 | for key in attrs if hasattr(self, key)}
28 | return self.__dict__
29 |
30 | def reload_from_json(self, json):
31 | """Replace attributes of the object with k-v pair in the json """
32 | for key, value in json.items():
33 | setattr(self, key, value)
34 |
--------------------------------------------------------------------------------
/0x0F-python-object_relational_mapping/4-cities_by_state.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """
4 | Lists all cities from the cities table of database hbtn_0e_0_usa.
5 | Usage: ./0-select_states.py \
6 | \
7 |
8 | """
9 | import sys
10 | import MySQLdb as db
11 |
12 |
13 | def connect_and_query() -> None:
14 |
15 | """Connect to the database and execute query"""
16 | try:
17 | cnx = db.connect(user=sys.argv[1], passwd=sys.argv[2], db=sys.argv[3])
18 | cursor = cnx.cursor(cursorclass=db.cursors.Cursor)
19 | cursor.execute('SELECT city.id, city.name, state.name\
20 | FROM cities as city\
21 | INNER JOIN states as state\
22 | ON city.state_id = state.id\
23 | ORDER BY city.id ASC;')
24 | cities = cursor.fetchall()
25 |
26 | for city in cities:
27 | print(city)
28 |
29 | cursor.close()
30 | cnx.close()
31 | except Exception as e:
32 | return (e)
33 |
34 |
35 | if __name__ == "__main__":
36 | connect_and_query()
37 |
--------------------------------------------------------------------------------
/0x07-python-test_driven_development/tests/4-print_square.txt:
--------------------------------------------------------------------------------
1 | ===============================
2 | 4-print_square.py
3 | ==============================
4 |
5 | Usage:
6 | The print_square function takes one argument
7 | a) size(int) -> The size of the square.
8 | -> Must be an int or a float >= 0
9 | and prints the square to standard output
10 | Tests:
11 |
12 | >>> print_square = __import__('4-print_square').print_square
13 |
14 | >>> print_square(3)
15 | ###
16 | ###
17 | ###
18 |
19 | >>> print_square(2.0)
20 | TypeError('size must be an integer')
21 |
22 | >>> print_square(name)
23 | Traceback (most recent call last):
24 | ...
25 | NameError: name 'name' is not defined
26 |
27 | >>> print_square()
28 | Traceback (most recent call last):
29 | ...
30 | TypeError: print_square() missing 1 required positional argument: 'size'
31 |
32 | >>> print_square(None)
33 | TypeError('size must be an integer')
34 |
35 | >>> print_square(0)
36 |
37 |
38 | >>> print_square(-1)
39 | ValueError('size must be >= 0')
40 |
41 | >>> print_square(3.1)
42 | TypeError('size must be an integer')
43 |
--------------------------------------------------------------------------------
/0x0F-python-object_relational_mapping/model_city.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | """
3 | Defines a state model that contain the class definition
4 | of a City and an instance Base = declarative_base()
5 | """
6 | from lib2to3.pytree import Base
7 | from sre_parse import State
8 | from unicodedata import name
9 | from sqlalchemy import Column, ForeignKey, Integer, String, null
10 | from sqlalchemy.ext.declarative import declarative_base
11 |
12 | Base = declarative_base()
13 |
14 |
15 | class City(Base):
16 | """
17 | inherits from Base (imported from model_state)
18 | links to the MySQL table cities
19 |
20 | class attribute id that represents a column of
21 | an auto-generated, unique integer, can't be null and is a primary key
22 |
23 | class attribute name that represents a column
24 | of a string of 128 characters and can't be null
25 |
26 | class attribute state_id that represents a column
27 | of an integer, can't be null and is a foreign key to states.id
28 |
29 | """
30 | __tablename__ = "cities"
31 | id = Column(Integer, primary_key=True)
32 | name = Column(String(128), nullable=False)
33 | state_id = Column(Integer, ForeignKey("states.id"), nullable=False)
34 |
--------------------------------------------------------------------------------
/0x06-python-classes/5-square.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | """class Square that defines a square"""
3 |
4 |
5 | class Square():
6 | """Implementing the square class"""
7 |
8 | def __init__(self, size=0):
9 | self.__size = size
10 |
11 | @property
12 | def size(self):
13 | """Get the value of size
14 | Args:
15 | None
16 | Returns:
17 | __size
18 | """
19 | return self.__size
20 |
21 | @size.setter
22 | def size(self, value):
23 | """Set the value of the square
24 | Args:
25 | value (int)
26 | Returns:
27 | None
28 | """
29 | if (not isinstance(value, int)):
30 | raise TypeError("size must be an integer")
31 | elif (value < 0):
32 | raise ValueError("size must be >= 0")
33 | self.__size = value
34 |
35 | def area(self):
36 | """Compute and Return area
37 | Args:
38 | None
39 | Returns
40 | __size x 4
41 | """
42 | return self.__size ** 2
43 |
44 | def my_print(self):
45 | if not self.__size:
46 | print("")
47 | for i in range(self.__size):
48 | print("#" * self.__size)
49 |
--------------------------------------------------------------------------------
/0x00-python-hello_world/10-main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include "lists.h"
5 |
6 | /**
7 | * main - check the code
8 | *
9 | * Return: Always 0.
10 | */
11 | int main(void)
12 | {
13 | listint_t *head;
14 | listint_t *current;
15 | listint_t *temp;
16 | int i;
17 |
18 | head = NULL;
19 | add_nodeint(&head, 0);
20 | add_nodeint(&head, 1);
21 | add_nodeint(&head, 2);
22 | add_nodeint(&head, 3);
23 | add_nodeint(&head, 4);
24 | add_nodeint(&head, 98);
25 | add_nodeint(&head, 402);
26 | add_nodeint(&head, 1024);
27 | print_listint(head);
28 |
29 | if (check_cycle(head) == 0)
30 | printf("Linked list has no cycle\n");
31 | else if (check_cycle(head) == 1)
32 | printf("Linked list has a cycle\n");
33 |
34 | current = head;
35 | for (i = 0; i < 4; i++)
36 | current = current->next;
37 | temp = current->next;
38 | current->next = head;
39 |
40 | if (check_cycle(head) == 0)
41 | printf("Linked list has no cycle\n");
42 | else if (check_cycle(head) == 1)
43 | printf("Linked list has a cycle\n");
44 |
45 | current = head;
46 | for (i = 0; i < 4; i++)
47 | current = current->next;
48 | current->next = temp;
49 |
50 | free_listint(head);
51 |
52 | return (0);
53 | }
54 |
55 |
--------------------------------------------------------------------------------
/0x0F-python-object_relational_mapping/10-model_state_my_get.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """
4 | Module to perfom simple queries on the model_state model
5 | using an ORM - SQLAlchemy
6 | """
7 | from model_state import Base, State
8 | from sqlalchemy import create_engine
9 | from sqlalchemy.orm import sessionmaker
10 | import sys
11 |
12 |
13 | def connect_and_query(user: str, passwd: str, dbase: str, search: str) -> None:
14 |
15 | """
16 | Connect to the database and make queries using ORM
17 | Args:
18 | user (str): mysql user
19 | passwd (str): mysql password for `user`
20 | dbase (str): Database to use
21 | search (str): State to search for
22 | """
23 | try:
24 | engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}'
25 | .format(user, passwd, dbase))
26 | Session = sessionmaker(bind=engine)
27 | state_session = Session()
28 | states = state_session.query(State).order_by(State.id).all()
29 |
30 | for state in states:
31 | if state.name == search:
32 | print(state.id)
33 | break
34 | else:
35 | print("Not found")
36 | except Exception as e:
37 | return e
38 |
39 |
40 | if __name__ == "__main__":
41 | connect_and_query(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
42 |
--------------------------------------------------------------------------------
/0x14-javascript-web_scraping/101-starwars_characters.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/node
2 | const request = require('request');
3 |
4 | const movieId = process.argv[2];
5 | const baseUrl = 'https://swapi-api.alx-tools.com/api/films/';
6 | const fullUrl = baseUrl.concat(movieId);
7 |
8 | request(fullUrl, (error, response, body) => {
9 | if (!error) {
10 | const characters = JSON.parse(body).characters;
11 | // Create a variable to store the number of characters processed
12 | let charactersProcessed = 0;
13 | // Create an empty array to store the character names
14 | const characterNames = [];
15 | characters.forEach((characterUrl) => {
16 | request(characterUrl, (error, response, body) => {
17 | if (!error) {
18 | const charName = JSON.parse(body).name;
19 | // Add the character name to the array
20 | characterNames.push(charName);
21 | }
22 | // Increment the charactersProcessed variable
23 | charactersProcessed++;
24 | // Check if all characters have been processed
25 | if (charactersProcessed === characters.length) {
26 | // Log the character names when all characters have been processed
27 | characterNames.forEach((actor) => {
28 | console.log(actor);
29 | });
30 | }
31 | });
32 | });
33 | } else {
34 | console.log(error);
35 | }
36 | });
37 |
--------------------------------------------------------------------------------
/0x07-python-test_driven_development/tests/0-add_integer.txt:
--------------------------------------------------------------------------------
1 | **********************************
2 | How to use the 0-add_integer.py
3 | **********************************
4 | This module defines a function for adding integers
5 |
6 |
7 | usage
8 | *******
9 | '''add_integer(a, b) returns the a + b '''
10 |
11 | >>> add_integer = __import__('0-add_integer').add_integer
12 | >>> add_integer(1,3)
13 | 4
14 |
15 | >>> add_integer(1, -2)
16 | -1
17 |
18 | >>> add_integer(-1, 2)
19 | 1
20 |
21 | >>> add_integer(-1, -1)
22 | -2
23 |
24 | >>> add_integer(None)
25 | TypeError('a must be an integer')
26 |
27 | >>> add_integer("string", 12)
28 | TypeError('a must be an integer')
29 |
30 | >> add_integer(12, "string")
31 | TypeError('b must be an integer')
32 |
33 | >>> add_integer(12, None)
34 | TypeError('b must be an integer')
35 |
36 | >>> add_integer(None, 12)
37 | TypeError('a must be an integer')
38 |
39 | >>> add_integer(2.0, 1)
40 | 3
41 |
42 | >>> add_integer(2.0, 3.1)
43 | 5
44 |
45 | >>> add_integer(2.5, 2.5)
46 | 4
47 |
48 | >>> add_integer(1, 2.7)
49 | 3
50 |
51 | >>> add_integer(2.0, "string")
52 | TypeError('b must be an integer')
53 |
54 | >>> add_integer(2.1, None)
55 | TypeError('b must be an integer')
56 |
57 | >>> add_integer(2.1, [1,2,3,4])
58 | TypeError('b must be an integer')
59 |
60 | >>> add_integer(float(2), int(3))
61 | 5
62 |
63 | >>> add_integer("Hello", "World")
64 | TypeError('a must be an integer')
65 |
--------------------------------------------------------------------------------
/0x07-python-test_driven_development/2-matrix_divided.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """Matrix divisor function"""
4 |
5 |
6 | def matrix_divided(matrix, div):
7 | """Divide all elements of a matrix.
8 | Args:
9 | matrix (list): A list of lists of ints or floats.
10 | div (int/float): The divisor.
11 | Raises:
12 | TypeError: If the matrix contains non-numbers.
13 | TypeError: If the matrix contains rows of different sizes.
14 | TypeError: If div is not an int or float.
15 | ZeroDivisionError: If div is 0.
16 | Returns:
17 | A new matrix representing the result of the division.
18 | """
19 | if (not isinstance(matrix, list) or matrix == [] or
20 | not all(isinstance(row, list) for row in matrix) or
21 | not all((isinstance(ele, int) or isinstance(ele, float))
22 | for ele in [num for row in matrix for num in row])):
23 | raise TypeError("matrix must be a matrix (list of lists) of "
24 | "integers/floats")
25 |
26 | if not all(len(row) == len(matrix[0]) for row in matrix):
27 | raise TypeError("Each row of the matrix must have the same size")
28 |
29 | if not isinstance(div, int) and not isinstance(div, float):
30 | raise TypeError("div must be a number")
31 |
32 | if div == 0:
33 | raise ZeroDivisionError("division by zero")
34 |
35 | return ([list(map(lambda x: round(x / div, 2), row)) for row in matrix])
36 |
--------------------------------------------------------------------------------
/0x08-python-more_classes/1-rectangle.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | """Defining my rectangle class"""
3 |
4 |
5 | class Rectangle:
6 | """Rectangle class with setters and getters"""
7 | def __init__(self, width=0, height=0):
8 | """Initialize a new Rectangle.
9 | Args:
10 | width (int) -> The width of the new rectangle.
11 | height (int)-> The height of the new rectangle.
12 | """
13 | self.width = width
14 | self.height = height
15 |
16 | @property
17 | def width(self):
18 | """Get the width of the rectangle."""
19 | return self.__width
20 |
21 | @width.setter
22 | def width(self, value):
23 | if not isinstance(value, 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 | """Height Getter
32 | Args:
33 | None
34 | Returns:
35 | self.__height"""
36 | return self.__height
37 |
38 | @height.setter
39 | def height(self, value):
40 | """Height Setter
41 | Args:
42 | value(int) -> The new value of the height
43 | """
44 | if not isinstance(value, int):
45 | raise TypeError("height must be an integer")
46 | if value < 0:
47 | raise ValueError("height must be >= 0")
48 | self.__height = value
49 |
--------------------------------------------------------------------------------
/0x00-python-hello_world/10-linked_lists.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include "lists.h"
4 |
5 | /**
6 | * print_listint - prints all elements of a listint_t list
7 | * @h: pointer to head of list
8 | * Return: number of nodes
9 | */
10 | size_t print_listint(const listint_t *h)
11 | {
12 | const listint_t *current;
13 | unsigned int n; /* number of nodes */
14 |
15 | current = h;
16 | n = 0;
17 | while (current != NULL)
18 | {
19 | printf("%i\n", current->n);
20 | current = current->next;
21 | n++;
22 | }
23 |
24 | return (n);
25 | }
26 |
27 | /**
28 | * add_nodeint - adds a new node at the beginning of a listint_t list
29 | * @head: pointer to a pointer of the start of the list
30 | * @n: integer to be included in node
31 | * Return: address of the new element or NULL if it fails
32 | */
33 | listint_t *add_nodeint(listint_t **head, const int n)
34 | {
35 | listint_t *new;
36 |
37 | new = malloc(sizeof(listint_t));
38 | if (new == NULL)
39 | return (NULL);
40 |
41 | new->n = n;
42 | new->next = *head;
43 | *head = new;
44 |
45 | return (new);
46 | }
47 |
48 | /**
49 | * free_listint - frees a listint_t list
50 | * @head: pointer to list to be freed
51 | * Return: void
52 | */
53 | void free_listint(listint_t *head)
54 | {
55 | listint_t *current;
56 |
57 | while (head != NULL)
58 | {
59 | current = head;
60 | head = head->next;
61 | free(current);
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/0x03-python-data_structures/13-is_palindrome.c:
--------------------------------------------------------------------------------
1 | #include "lists.h"
2 |
3 | listint_t *reverse_listint(listint_t **head);
4 | int is_palindrome(listint_t **head);
5 |
6 | /**
7 | * reverse_listint - Reverses a singly-linked listint_t list.
8 | * @head: A pointer to the starting node of the list to reverse.
9 | *
10 | * Return: A pointer to the head of the reversed list.
11 | */
12 | listint_t *reverse_listint(listint_t **head)
13 | {
14 | listint_t *node = *head, *next, *prev = NULL;
15 |
16 | while (node)
17 | {
18 | next = node->next;
19 | node->next = prev;
20 | prev = node;
21 | node = next;
22 | }
23 |
24 | *head = prev;
25 | return (*head);
26 | }
27 |
28 | /**
29 | * is_palindrome - Checks if a singly linked list is a palindrome.
30 | * @head: A pointer to the head of the linked list.
31 | *
32 | * Return: If the linked list is not a palindrome - 0.
33 | * If the linked list is a palindrome - 1.
34 | */
35 | int is_palindrome(listint_t **head)
36 | {
37 | listint_t *tmp, *rev, *mid;
38 | size_t size = 0, i;
39 |
40 | if (*head == NULL || (*head)->next == NULL)
41 | return (1);
42 |
43 | tmp = *head;
44 | while (tmp)
45 | {
46 | size++;
47 | tmp = tmp->next;
48 | }
49 |
50 | tmp = *head;
51 | for (i = 0; i < (size / 2) - 1; i++)
52 | tmp = tmp->next;
53 |
54 | if ((size % 2) == 0 && tmp->n != tmp->next->n)
55 | return (0);
56 |
57 | tmp = tmp->next->next;
58 | rev = reverse_listint(&tmp);
59 | mid = rev;
60 |
61 | tmp = *head;
62 | while (rev)
63 | {
64 | if (tmp->n != rev->n)
65 | return (0);
66 | tmp = tmp->next;
67 | rev = rev->next;
68 | }
69 | reverse_listint(&mid);
70 |
71 | return (1);
72 | }
73 |
--------------------------------------------------------------------------------
/0x08-python-more_classes/2-rectangle.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 2-rectangle.py
3 | """Defines a Rectangle class.
4 | """
5 |
6 |
7 | class Rectangle:
8 | """Represent a rectangle.
9 | """
10 |
11 | def __init__(self, width=0, height=0):
12 | """Initialize a new Rectangle.
13 |
14 | Args:
15 | width (int): The width of the new rectangle.
16 | height (int): The height of the new rectangle.
17 | """
18 | self.width = width
19 | self.height = height
20 |
21 | @property
22 | def width(self):
23 | """Get/set the width of the Rectangle."""
24 | return self.__width
25 |
26 | @width.setter
27 | def width(self, value):
28 | if not isinstance(value, int):
29 | raise TypeError("width must be an integer")
30 | if value < 0:
31 | raise ValueError("width must be >= 0")
32 | self.__width = value
33 |
34 | @property
35 | def height(self):
36 | """Get/set the height of the Rectangle."""
37 | return self.__height
38 |
39 | @height.setter
40 | def height(self, value):
41 | if not isinstance(value, int):
42 | raise TypeError("height must be an integer")
43 | if value < 0:
44 | raise ValueError("height must be >= 0")
45 | self.__height = value
46 |
47 | def area(self):
48 | """Return the area of the Rectangle."""
49 | return (self.__width * self.__height)
50 |
51 | def perimeter(self):
52 | """Return the perimeter of the Rectangle."""
53 | if self.__width == 0 or self.__height == 0:
54 | return (0)
55 | return ((self.__width * 2) + (self.__height * 2))
56 |
--------------------------------------------------------------------------------
/0x04-python-more_data_structures/103-python.c:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | void print_python_list(PyObject *p);
4 | void print_python_bytes(PyObject *p);
5 |
6 | /**
7 | * print_python_list - Prints basic info about Python lists.
8 | * @p: A PyObject list object.
9 | */
10 | void print_python_list(PyObject *p)
11 | {
12 | int size, alloc, i;
13 | const char *type;
14 | PyListObject *list = (PyListObject *)p;
15 | PyVarObject *var = (PyVarObject *)p;
16 |
17 | size = var->ob_size;
18 | alloc = list->allocated;
19 |
20 | printf("[*] Python list info\n");
21 | printf("[*] Size of the Python List = %d\n", size);
22 | printf("[*] Allocated = %d\n", alloc);
23 |
24 | for (i = 0; i < size; i++)
25 | {
26 | type = list->ob_item[i]->ob_type->tp_name;
27 | printf("Element %d: %s\n", i, type);
28 | if (strcmp(type, "bytes") == 0)
29 | print_python_bytes(list->ob_item[i]);
30 | }
31 | }
32 |
33 | /**
34 | * print_python_bytes - Prints basic info about Python byte objects.
35 | * @p: A PyObject byte object.
36 | */
37 | void print_python_bytes(PyObject *p)
38 | {
39 | unsigned char i, size;
40 | PyBytesObject *bytes = (PyBytesObject *)p;
41 |
42 | printf("[.] bytes object info\n");
43 | if (strcmp(p->ob_type->tp_name, "bytes") != 0)
44 | {
45 | printf(" [ERROR] Invalid Bytes Object\n");
46 | return;
47 | }
48 |
49 | printf(" size: %ld\n", ((PyVarObject *)p)->ob_size);
50 | printf(" trying string: %s\n", bytes->ob_sval);
51 |
52 | if (((PyVarObject *)p)->ob_size > 10)
53 | size = 10;
54 | else
55 | size = ((PyVarObject *)p)->ob_size + 1;
56 |
57 | printf(" first %d bytes: ", size);
58 | for (i = 0; i < size; i++)
59 | {
60 | printf("%02hhx", bytes->ob_sval[i]);
61 | if (i == (size - 1))
62 | printf("\n");
63 | else
64 | printf(" ");
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/0x0B-python-input_output/101-stats.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """Reads from standard input and computes metrics.
4 | After every ten lines or the input of a keyboard interruption (CTRL + C),
5 | prints the following statistics:
6 | - Total file size up to that point.
7 | - Count of read status codes up to that point.
8 | """
9 |
10 |
11 | def print_stats(size, status_codes):
12 | """Print accumulated metrics.
13 | Args:
14 | size (int): The accumulated read file size.
15 | status_codes (dict): The accumulated count of status codes.
16 | """
17 | print("File size: {}".format(size))
18 | for key in sorted(status_codes):
19 | print("{}: {}".format(key, status_codes[key]))
20 |
21 |
22 | if __name__ == "__main__":
23 | import sys
24 |
25 | size = 0
26 | status_codes = {}
27 | valid_codes = ['200', '301', '400', '401', '403', '404', '405', '500']
28 | count = 0
29 |
30 | try:
31 | for line in sys.stdin:
32 | if count == 10:
33 | print_stats(size, status_codes)
34 | count = 1
35 | else:
36 | count += 1
37 |
38 | line = line.split()
39 |
40 | try:
41 | size += int(line[-1])
42 | except (IndexError, ValueError):
43 | pass
44 |
45 | try:
46 | if line[-2] in valid_codes:
47 | if status_codes.get(line[-2], -1) == -1:
48 | status_codes[line[-2]] = 1
49 | else:
50 | status_codes[line[-2]] += 1
51 | except IndexError:
52 | pass
53 |
54 | print_stats(size, status_codes)
55 |
56 | except KeyboardInterrupt:
57 | print_stats(size, status_codes)
58 | raise
59 |
--------------------------------------------------------------------------------
/0x06-python-classes/6-square.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | """Square class to represent a square"""
3 |
4 |
5 | class Square():
6 | """square class with it's size and proper validation"""
7 |
8 | def __init__(self, size=0, position=(0, 0)):
9 | """"Initialize data"""
10 | self.size = size
11 | self.position = position
12 |
13 | @property
14 | def size(self):
15 | """"get size"""
16 | return self.__size
17 |
18 | @property
19 | def position(self):
20 | """"get position"""
21 | return self.__position
22 |
23 | @size.setter
24 | def size(self, value):
25 | """"set size"""
26 | if (type(value) is not int):
27 | raise TypeError("size must be an integer")
28 | elif (value < 0):
29 | raise ValueError("size must be >= 0")
30 | else:
31 | self.__size = value
32 |
33 | @position.setter
34 | def position(self, value):
35 | """"set position"""
36 | if (not isinstance(value, tuple)):
37 | raise TypeError("position must be a tuple of 2 positive integers")
38 | elif (len(value) != 2):
39 | raise TypeError("position must be a tuple of 2 positive integers")
40 | elif (type(value[0]) is not int) or (type(value[1]) is not int):
41 | raise TypeError("position must be a tuple of 2 positive integers")
42 | elif (value[0] < 0) or (value[1] < 0):
43 | raise TypeError("position must be a tuple of 2 positive integers")
44 | else:
45 | self.__position = value
46 |
47 | def area(self):
48 | """"get area of the square"""
49 | return self.size ** 2
50 |
51 | def my_print(self):
52 | """print the square"""
53 | if self.size == 0:
54 | print()
55 | else:
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-test_driven_development/tests/5-text_indentation.txt:
--------------------------------------------------------------------------------
1 |
2 | ===============================
3 | 5-text_indentation.py
4 | ==============================
5 |
6 | Usage:
7 | The text_indentation function takes one argument
8 | a) text(str) -> The string to be printed
9 | -> Raises TypeError if its not a string
10 |
11 | and prints it to standard output, replacing every ".", ":" or "?" with double "\n"
12 |
13 | Test:
14 | >>> text_indentation = __import__('5-text_indentation').text_indentation
15 |
16 | >>> text_indentation(32)
17 | TypeError('text must be a string')
18 |
19 | >>> text_indentation("I hate John Doe")
20 | I hate John Doe
21 |
22 | >>> text_indentation("Python Test are awesome")
23 | Python Test are awesome
24 |
25 | >>> text_indentation("This one should break.")
26 | This one should break.
27 |
28 |
29 | >>> text_indentation()
30 | Traceback (most recent call last):
31 | ...
32 | TypeError: text_indentation() missing 1 required positional argument: 'text'
33 |
34 | >>> text_indentation(None)
35 | TypeError('text must be a string')
36 |
37 | >>> text_indentation("Did you say you love her?")
38 | Did you say you love her?
39 |
40 |
41 | >>> text_indentation("Hello. Itsfoss here. Wanna see something cool?")
42 | Hello.
43 |
44 | Itsfoss here.
45 |
46 | Wanna see something cool?
47 |
48 |
49 | >>> text_indentation(":")
50 | :
51 |
52 |
53 | >> text_indentation("?.:")
54 | ?
55 |
56 | .
57 |
58 | :
59 |
60 |
61 | >>> text_indentation(str("30"))
62 | 30
63 |
64 | >>> text_indentation("? 90 Days of Docker?")
65 | ?
66 |
67 | 90 Days of Docker?
68 |
69 |
70 | >>> text_indentation("Are you a robot:?.")
71 | Are you a robot:
72 |
73 | ?
74 |
75 | .
76 |
77 |
78 |
--------------------------------------------------------------------------------
/0x07-python-test_driven_development/tests/3-say_my_name.txt:
--------------------------------------------------------------------------------
1 |
2 | ===============================
3 | 3-say_my_name.py
4 | ===============================
5 |
6 | Usage:
7 | The say_my_name function takes two arguments when called
8 | a) first_name (a string) -> The first name
9 | b) last_name (a string) -> The last name, if nothing is passed, an empty string is assumed
10 | and returns a string "My name is "
11 |
12 | Test cases:
13 | >>> say_my_name = __import__('3-say_my_name').say_my_name
14 |
15 | >>> say_my_name("John", "Doe")
16 | 'My name is John Doe'
17 |
18 | >>> say_my_name("Bruce", "Willies")
19 | 'My name is Bruce Willies'
20 |
21 | >>> say_my_name(12, "Python")
22 | TypeError('first_name must be a string')
23 |
24 | >>> say_my_name("Santa", 23)
25 | TypeError('last_name must be a string')
26 |
27 | >>> say_my_name(["var", "Random"], "Claus")
28 | TypeError('first_name must be a string')
29 |
30 | >>> say_my_name(23.09, 234)
31 | TypeError('first_name must be a string')
32 |
33 | >>> say_my_name(23.09, "Sam Smith")
34 | TypeError('first_name must be a string')
35 |
36 | >>> say_my_name("Sam Smith", 23.98)
37 | TypeError('last_name must be a string')
38 |
39 | >>> say_my_name(None)
40 | TypeError('first_name must be a string')
41 |
42 | >>> say_my_name("Julien", "Barbier")
43 | 'My name is Julien Barbier'
44 |
45 | >>> say_my_name("Fred", None)
46 | TypeError('last_name must be a string')
47 |
48 | >>> say_my_name(None, None)
49 | TypeError('first_name must be a string')
50 |
51 | >>> say_my_name()
52 | Traceback (most recent call last):
53 | ...
54 | TypeError: say_my_name() missing 1 required positional argument: 'first_name'
55 |
56 | >>> say_my_name(name, "Doe")
57 | Traceback (most recent call last):
58 | ...
59 | NameError: name 'name' is not defined
60 |
61 | >>> say_my_name(str(30), str(32))
62 | 'My name is 30 32'
63 |
64 | >>> say_my_name("", "Doup")
65 | 'My name is Doup'
66 |
67 |
--------------------------------------------------------------------------------
/0x06-python-classes/100-singly_linked_list.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | class Node:
3 | """Node of a singly linked list"""
4 | def __init__(self, data, next_node=None):
5 | self.__data = data
6 | self.__next_node = next_node
7 |
8 | @property
9 | def data(self):
10 | return self.__data
11 |
12 | @data.setter
13 | def data(self, value):
14 | if (not isinstance(value, int)):
15 | raise TypeError("data must be an integer")
16 | else:
17 | self.__data = value
18 |
19 | @property
20 | def next_node(self):
21 | return self.__next_node
22 |
23 | @next_node.setter
24 | def next_node(self, value):
25 | if (not isinstance(value, Node) or value is not None):
26 | raise TypeError("next_node must be a Node Object")
27 | else:
28 | self.__next_node = value
29 |
30 |
31 | class SinglyLinkedList:
32 | """Represent a singly-linked list."""
33 |
34 | def __init__(self):
35 | """Initalize a new SinglyLinkedList."""
36 | self.__head = None
37 |
38 | def sorted_insert(self, value):
39 | """Insert a new Node to the SinglyLinkedList.
40 | The node is inserted into the list at the correct
41 | ordered numerical position.
42 | Args:
43 | value (Node): The new Node to insert.
44 | """
45 | new = Node(value)
46 | if self.__head is None:
47 | new.next_node = None
48 | self.__head = new
49 | elif self.__head.data > value:
50 | new.next_node = self.__head
51 | self.__head = new
52 | else:
53 | tmp = self.__head
54 | while (tmp.next_node is not None and
55 | tmp.next_node.data < value):
56 | tmp = tmp.next_node
57 | new.next_node = tmp.next_node
58 | tmp.next_node = new
59 |
60 | def __str__(self):
61 | """Implementing how print(SinglyLinkedList)."""
62 | values = []
63 | tmp = self.__head
64 | while tmp is not None:
65 | values.append(str(tmp.data))
66 | tmp = tmp.next_node
67 | return ('\n'.join(values))
68 |
--------------------------------------------------------------------------------
/0x08-python-more_classes/3-rectangle.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 3-rectangle.py
3 | """Defines a Rectangle class.
4 | """
5 |
6 |
7 | class Rectangle:
8 | """Represent a rectangle.
9 | """
10 |
11 | def __init__(self, width=0, height=0):
12 | """Initialize a new Rectangle.
13 |
14 | Args:
15 | width (int): The width of the new rectangle.
16 | height (int): The height of the new rectangle.
17 | """
18 | self.width = width
19 | self.height = height
20 |
21 | @property
22 | def width(self):
23 | """Get/set the width of the Rectangle."""
24 | return self.__width
25 |
26 | @width.setter
27 | def width(self, value):
28 | if not isinstance(value, int):
29 | raise TypeError("width must be an integer")
30 | if value < 0:
31 | raise ValueError("width must be >= 0")
32 | self.__width = value
33 |
34 | @property
35 | def height(self):
36 | """Get/set the height of the Rectangle.
37 | """
38 | return self.__height
39 |
40 | @height.setter
41 | def height(self, value):
42 | if not isinstance(value, 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 area(self):
49 | """Return the area of the Rectangle."""
50 | return (self.__width * self.__height)
51 |
52 | def perimeter(self):
53 | """Return the perimeter of the Rectangle."""
54 | if self.__width == 0 or self.__height == 0:
55 | return (0)
56 | return ((self.__width * 2) + (self.__height * 2))
57 |
58 | def __str__(self):
59 | """Return the printable representation of the Rectangle.
60 |
61 | Represents the rectangle with the # character.
62 | """
63 | if self.__width == 0 or self.__height == 0:
64 | return ("")
65 |
66 | rect = []
67 | for i in range(self.__height):
68 | [rect.append('#') for j in range(self.__width)]
69 | if i != self.__height - 1:
70 | rect.append("\n")
71 | return ("".join(rect))
72 |
--------------------------------------------------------------------------------
/0x08-python-more_classes/4-rectangle.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 4-rectangle.py
3 | """Defines a Rectangle class.
4 | """
5 |
6 |
7 | class Rectangle:
8 | """Represent a rectangle.
9 | """
10 |
11 | def __init__(self, width=0, height=0):
12 | """Initialize a new Rectangle.
13 |
14 | Args:
15 | width (int): The width of the new rectangle.
16 | height (int): The height of the new rectangle.
17 | """
18 | self.width = width
19 | self.height = height
20 |
21 | @property
22 | def width(self):
23 | """Get/set the width of the Rectangle.
24 | """
25 | return self.__width
26 |
27 | @width.setter
28 | def width(self, value):
29 | if not isinstance(value, int):
30 | raise TypeError("width must be an integer")
31 | if value < 0:
32 | raise ValueError("width must be >= 0")
33 | self.__width = value
34 |
35 | @property
36 | def height(self):
37 | """Get/set the height of the Rectangle.
38 | """
39 | return self.__height
40 |
41 | @height.setter
42 | def height(self, value):
43 | if not isinstance(value, int):
44 | raise TypeError("height must be an integer")
45 | if value < 0:
46 | raise ValueError("height must be >= 0")
47 | self.__height = value
48 |
49 | def area(self):
50 | """Return the area of the Rectangle.
51 | """
52 | return (self.__width * self.__height)
53 |
54 | def perimeter(self):
55 | """Return the perimeter of the Rectangle.
56 | """
57 | if self.__width == 0 or self.__height == 0:
58 | return (0)
59 | return ((self.__width * 2) + (self.__height * 2))
60 |
61 | def __str__(self):
62 | """Return the printable representation of the Rectangle.
63 |
64 | Represents the rectangle with the # character.
65 | """
66 | if self.__width == 0 or self.__height == 0:
67 | return ("")
68 |
69 | rect = []
70 | for i in range(self.__height):
71 | [rect.append('#') for j in range(self.__width)]
72 | if i != self.__height - 1:
73 | rect.append("\n")
74 | return ("".join(rect))
75 |
76 | def __repr__(self):
77 | """Return the string representation of the Rectangle.
78 | """
79 | rect = "Rectangle(" + str(self.__width)
80 | rect += ", " + str(self.__height) + ")"
81 | return (rect)
82 |
--------------------------------------------------------------------------------
/0x06-python-classes/101-square.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 101-square.py
3 | """Define a class Square."""
4 |
5 |
6 | class Square:
7 | """Represent a square."""
8 |
9 | def __init__(self, size=0, position=(0, 0)):
10 | """Initialize a new square.
11 |
12 | Args:
13 | size (int): The size of the new square.
14 | position (int, int): The position of the new square.
15 | """
16 | self.__size = size
17 | self.position = position
18 |
19 | @property
20 | def size(self):
21 | """Get/set the current size of the square."""
22 | return (self.__size)
23 |
24 | @size.setter
25 | def size(self, value):
26 | if not isinstance(value, int):
27 | raise TypeError("size must be an integer")
28 | elif value < 0:
29 | raise ValueError("size must be >= 0")
30 | self.__size = value
31 |
32 | @property
33 | def position(self):
34 | """Get/set the current position of the square."""
35 | return (self.__position)
36 |
37 | @position.setter
38 | def position(self, value):
39 | if (not isinstance(value, tuple) or
40 | len(value) != 2 or
41 | not all(isinstance(num, int) for num in value) or
42 | not all(num >= 0 for num in value)):
43 | raise TypeError("position must be a tuple of 2 positive integers")
44 | self.__position = value
45 |
46 | def area(self):
47 | """Return the current area of the square."""
48 | return (self.__size * self.__size)
49 |
50 | def my_print(self):
51 | """Print the square with the # character."""
52 | if self.__size == 0:
53 | print("")
54 | return
55 |
56 | [print("") for i in range(0, self.__position[1])]
57 | for i in range(0, self.__size):
58 | [print(" ", end="") for j in range(0, self.__position[0])]
59 | [print("#", end="") for k in range(0, self.__size)]
60 | print("")
61 |
62 | def __str__(self):
63 | """Define the print() representation of a Square."""
64 | if self.__size != 0:
65 | [print("") for i in range(0, self.__position[1])]
66 | for i in range(0, self.__size):
67 | [print(" ", end="") for j in range(0, self.__position[0])]
68 | [print("#", end="") for k in range(0, self.__size)]
69 | if i != self.__size - 1:
70 | print("")
71 | return ("")
72 |
--------------------------------------------------------------------------------
/0x08-python-more_classes/5-rectangle.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 5-rectangle.py
3 | """Defines a Rectangle class.
4 | """
5 |
6 |
7 | class Rectangle:
8 | """Represent a rectangle.
9 | """
10 |
11 | def __init__(self, width=0, height=0):
12 | """Initialize a new Rectangle.
13 |
14 | Args:
15 | width (int): The width of the new rectangle.
16 | height (int): The height of the new rectangle.
17 | """
18 | self.width = width
19 | self.height = height
20 |
21 | @property
22 | def width(self):
23 | """Get/set the width of the Rectangle.
24 | """
25 | return self.__width
26 |
27 | @width.setter
28 | def width(self, value):
29 | if not isinstance(value, int):
30 | raise TypeError("width must be an integer")
31 | if value < 0:
32 | raise ValueError("width must be >= 0")
33 | self.__width = value
34 |
35 | @property
36 | def height(self):
37 | """Get/set the height of the Rectangle.
38 | """
39 | return self.__height
40 |
41 | @height.setter
42 | def height(self, value):
43 | if not isinstance(value, int):
44 | raise TypeError("height must be an integer")
45 | if value < 0:
46 | raise ValueError("height must be >= 0")
47 | self.__height = value
48 |
49 | def area(self):
50 | """Return the area of the Rectangle."""
51 | return (self.__width * self.__height)
52 |
53 | def perimeter(self):
54 | """Return the perimeter of the Rectangle.
55 | """
56 | if self.__width == 0 or self.__height == 0:
57 | return (0)
58 | return ((self.__width * 2) + (self.__height * 2))
59 |
60 | def __str__(self):
61 | """Return the printable representation of the Rectangle.
62 |
63 | Represents the rectangle with the # character.
64 | """
65 | if self.__width == 0 or self.__height == 0:
66 | return ("")
67 |
68 | rect = []
69 | for i in range(self.__height):
70 | [rect.append('#') for j in range(self.__width)]
71 | if i != self.__height - 1:
72 | rect.append("\n")
73 | return ("".join(rect))
74 |
75 | def __repr__(self):
76 | """Return the string representation of the Rectangle.
77 | """
78 | rect = "Rectangle(" + str(self.__width)
79 | rect += ", " + str(self.__height) + ")"
80 | return (rect)
81 |
82 | def __del__(self):
83 | """Print a message for every deletion of a Rectangle.
84 | """
85 | print("Bye rectangle...")
86 |
--------------------------------------------------------------------------------
/0x07-python-test_driven_development/tests/6-max_integer_test.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """Unit test for max_integer function"""
4 |
5 | import unittest
6 | max_integer = __import__('6-max-integer').max_integer
7 |
8 |
9 | class TestMaxInteger(unittest.TestCase):
10 | """Defining unit tests for max_integer function"""
11 | def test_maxinteger_sorted(self):
12 | """Test for a sorted list"""
13 | self.assertEqual(max_integer([1, 2, 3, 4]), 4)
14 |
15 | def test_maxinteger_unsorted(self):
16 | """Tests for an unsorted list"""
17 | self.assertEqual(max_integer([1, 3, 4, 2]), 4)
18 |
19 | def test_maxinteger_reverse(self):
20 | """"Tests for a reverse sorted lists"""
21 | self.assertEqual(max_integer([4, 3, 2, 1]), 4)
22 |
23 | def test_maxinteger_empty(self):
24 | """"Test for empty list"""
25 | self.assertEqual(max_integer([]), None)
26 |
27 | def test_maxinteger_nan(self):
28 | """Test for NaN values in the list"""
29 | self.assertEqual(max_integer(["1", "2", "3", "4"]), "4")
30 |
31 | def test_maxinteger_string(self):
32 | """Test for a string"""
33 | self.assertEqual(max_integer("John Doe"), "o")
34 |
35 | def test_maxinteger_floats(self):
36 | """Test for floats"""
37 | self.assertEqual(max_integer([1.2, 3.1, 2.5, 4.9]), 4.9)
38 |
39 | def test_maxinteger_one(self):
40 | """Tesf for one element"""
41 | self.assertEqual(max_integer([7]), 7)
42 |
43 | def test_maxinteger_none(self):
44 | """Test for none object"""
45 | self.assertRaises(TypeError, max_integer, None)
46 |
47 | def test_maxinteger_negatives(self):
48 | """Test for negative numbers"""
49 | self.assertEqual(max_integer([-1, -3, -5, -7]), -1)
50 |
51 | def test_maxinteger_same(self):
52 | """Test for a list with the same elements"""
53 | self.assertEqual(max_integer([5, 5, 5, 5]), 5)
54 |
55 | def test_maxinteger_nested(self):
56 | """Test for a nested list"""
57 | self.assertRaises(TypeError, max_integer, [[1, 2, 3], [1], 4])
58 |
59 | def test_maxinteger_zero(self):
60 | """Test for a list with only one zero"""
61 | self.assertEqual(max_integer([0]), 0)
62 |
63 | def test_maxinteger_all_zero(self):
64 | """Test for a list with all elements zero"""
65 | self.assertEqual(max_integer([0, 0, 0, 0]), 0)
66 |
67 | def test_maxinteger_int_floats(self):
68 | """Test for int and floats"""
69 | self.assertEqual(max_integer([1.53, 15.5, -9, 15, 6]), 15.5)
70 |
71 |
72 | if __name__ == '__main__':
73 | unittest.main()
74 |
--------------------------------------------------------------------------------
/0x08-python-more_classes/6-rectangle.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 6-rectangle.py
3 | """Defines a Rectangle class."""
4 |
5 |
6 | class Rectangle:
7 | """Represent a rectangle.
8 |
9 | Attributes:
10 | number_of_instances (int): The number of Rectangle instances.
11 | """
12 |
13 | number_of_instances = 0
14 |
15 | def __init__(self, width=0, height=0):
16 | """Initialize a new Rectangle.
17 |
18 | Args:
19 | width (int): The width of the new rectangle.
20 | height (int): The height of the new rectangle.
21 | """
22 | type(self).number_of_instances += 1
23 | self.width = width
24 | self.height = height
25 |
26 | @property
27 | def width(self):
28 | """Get/set the width of the Rectangle."""
29 | return self.__width
30 |
31 | @width.setter
32 | def width(self, value):
33 | if not isinstance(value, int):
34 | raise TypeError("width must be an integer")
35 | if value < 0:
36 | raise ValueError("width must be >= 0")
37 | self.__width = value
38 |
39 | @property
40 | def height(self):
41 | """Get/set the height of the Rectangle."""
42 | return self.__height
43 |
44 | @height.setter
45 | def height(self, value):
46 | if not isinstance(value, int):
47 | raise TypeError("height must be an integer")
48 | if value < 0:
49 | raise ValueError("height must be >= 0")
50 | self.__height = value
51 |
52 | def area(self):
53 | """Return the area of the Rectangle."""
54 | return (self.__width * self.__height)
55 |
56 | def perimeter(self):
57 | """Return the perimeter of the Rectangle."""
58 | if self.__width == 0 or self.__height == 0:
59 | return (0)
60 | return ((self.__width * 2) + (self.__height * 2))
61 |
62 | def __str__(self):
63 | """Return the printable representation of the Rectangle.
64 |
65 | Represents the rectangle with the # character.
66 | """
67 | if self.__width == 0 or self.__height == 0:
68 | return ("")
69 |
70 | rect = []
71 | for i in range(self.__height):
72 | [rect.append('#') for j in range(self.__width)]
73 | if i != self.__height - 1:
74 | rect.append("\n")
75 | return ("".join(rect))
76 |
77 | def __repr__(self):
78 | """Return the string representation of the Rectangle."""
79 | rect = "Rectangle(" + str(self.__width)
80 | rect += ", " + str(self.__height) + ")"
81 | return (rect)
82 |
83 | def __del__(self):
84 | """Print a message for every deletion of a Rectangle."""
85 | type(self).number_of_instances -= 1
86 | print("Bye rectangle...")
87 |
--------------------------------------------------------------------------------
/0x05-python-exceptions/103-python.c:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | void print_python_list(PyObject *p);
4 | void print_python_bytes(PyObject *p);
5 | void print_python_float(PyObject *p);
6 |
7 | /**
8 | * print_python_list - Prints basic info about Python lists.
9 | * @p: A PyObject list object.
10 | */
11 | void print_python_list(PyObject *p)
12 | {
13 | Py_ssize_t size, alloc, i;
14 | const char *type;
15 | PyListObject *list = (PyListObject *)p;
16 | PyVarObject *var = (PyVarObject *)p;
17 |
18 | size = var->ob_size;
19 | alloc = list->allocated;
20 |
21 | fflush(stdout);
22 |
23 | printf("[*] Python list info\n");
24 | if (strcmp(p->ob_type->tp_name, "list") != 0)
25 | {
26 | printf(" [ERROR] Invalid List Object\n");
27 | return;
28 | }
29 |
30 | printf("[*] Size of the Python List = %ld\n", size);
31 | printf("[*] Allocated = %ld\n", alloc);
32 |
33 | for (i = 0; i < size; i++)
34 | {
35 | type = list->ob_item[i]->ob_type->tp_name;
36 | printf("Element %ld: %s\n", i, type);
37 | if (strcmp(type, "bytes") == 0)
38 | print_python_bytes(list->ob_item[i]);
39 | else if (strcmp(type, "float") == 0)
40 | print_python_float(list->ob_item[i]);
41 | }
42 | }
43 |
44 | /**
45 | * print_python_bytes - Prints basic info about Python byte objects.
46 | * @p: A PyObject byte object.
47 | */
48 | void print_python_bytes(PyObject *p)
49 | {
50 | Py_ssize_t size, i;
51 | PyBytesObject *bytes = (PyBytesObject *)p;
52 |
53 | fflush(stdout);
54 |
55 | printf("[.] bytes object info\n");
56 | if (strcmp(p->ob_type->tp_name, "bytes") != 0)
57 | {
58 | printf(" [ERROR] Invalid Bytes Object\n");
59 | return;
60 | }
61 |
62 | printf(" size: %ld\n", ((PyVarObject *)p)->ob_size);
63 | printf(" trying string: %s\n", bytes->ob_sval);
64 |
65 | if (((PyVarObject *)p)->ob_size >= 10)
66 | size = 10;
67 | else
68 | size = ((PyVarObject *)p)->ob_size + 1;
69 |
70 | printf(" first %ld bytes: ", size);
71 | for (i = 0; i < size; i++)
72 | {
73 | printf("%02hhx", bytes->ob_sval[i]);
74 | if (i == (size - 1))
75 | printf("\n");
76 | else
77 | printf(" ");
78 | }
79 | }
80 |
81 | /**
82 | * print_python_float - Prints basic info about Python float objects.
83 | * @p: A PyObject float object.
84 | */
85 | void print_python_float(PyObject *p)
86 | {
87 | char *buffer = NULL;
88 |
89 | PyFloatObject *float_obj = (PyFloatObject *)p;
90 |
91 | fflush(stdout);
92 |
93 | printf("[.] float object info\n");
94 | if (strcmp(p->ob_type->tp_name, "float") != 0)
95 | {
96 | printf(" [ERROR] Invalid Float Object\n");
97 | return;
98 | }
99 |
100 | buffer = PyOS_double_to_string(float_obj->ob_fval, 'r', 0,
101 | Py_DTSF_ADD_DOT_0, NULL);
102 | printf(" value: %s\n", buffer);
103 | PyMem_Free(buffer);
104 | }
105 |
--------------------------------------------------------------------------------
/0x08-python-more_classes/7-rectangle.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 7-rectangle.py
3 | """Defines a Rectangle class.
4 | """
5 |
6 |
7 | class Rectangle:
8 | """Represent a rectangle.
9 |
10 | Attributes:
11 | number_of_instances (int): The number of Rectangle instances.
12 | print_symbol (any): The symbol used for string representation.
13 | """
14 |
15 | number_of_instances = 0
16 | print_symbol = "#"
17 |
18 | def __init__(self, width=0, height=0):
19 | """Initialize a new Rectangle.
20 |
21 | Args:
22 | width (int): The width of the new rectangle.
23 | height (int): The height of the new rectangle.
24 | """
25 | type(self).number_of_instances += 1
26 | self.width = width
27 | self.height = height
28 |
29 | @property
30 | def width(self):
31 | """Get/set the width of the Rectangle.
32 | """
33 | return self.__width
34 |
35 | @width.setter
36 | def width(self, value):
37 | if not isinstance(value, int):
38 | raise TypeError("width must be an integer")
39 | if value < 0:
40 | raise ValueError("width must be >= 0")
41 | self.__width = value
42 |
43 | @property
44 | def height(self):
45 | """Get/set the height of the Rectangle.
46 | """
47 | return self.__height
48 |
49 | @height.setter
50 | def height(self, value):
51 | if not isinstance(value, int):
52 | raise TypeError("height must be an integer")
53 | if value < 0:
54 | raise ValueError("height must be >= 0")
55 | self.__height = value
56 |
57 | def area(self):
58 | """Return the area of the Rectangle.
59 | """
60 | return (self.__width * self.__height)
61 |
62 | def perimeter(self):
63 | """Return the perimeter of the Rectangle.
64 | """
65 | if self.__width == 0 or self.__height == 0:
66 | return (0)
67 | return ((self.__width * 2) + (self.__height * 2))
68 |
69 | def __str__(self):
70 | """Return the printable representation of the Rectangle.
71 |
72 | Represents the rectangle with the # character.
73 | """
74 | if self.__width == 0 or self.__height == 0:
75 | return ("")
76 |
77 | rect = []
78 | for i in range(self.__height):
79 | [rect.append(str(self.print_symbol)) for j in range(self.__width)]
80 | if i != self.__height - 1:
81 | rect.append("\n")
82 | return ("".join(rect))
83 |
84 | def __repr__(self):
85 | """Return the string representation of the Rectangle.
86 | """
87 | rect = "Rectangle(" + str(self.__width)
88 | rect += ", " + str(self.__height) + ")"
89 | return (rect)
90 |
91 | def __del__(self):
92 | """Print a message for every deletion of a Rectangle.
93 | """
94 | type(self).number_of_instances -= 1
95 | print("Bye rectangle...")
96 |
--------------------------------------------------------------------------------
/0x0C-python-almost_a_circle/models/square.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # square.py
3 | """Defines the square class
4 | """
5 | from models.rectangle import Rectangle
6 |
7 |
8 | class Square(Rectangle):
9 | """Class Square inherits from Rectangle
10 | Args:
11 | size, x=0, y=0, id=None
12 | Raisses:
13 | """
14 |
15 | def __init__(self, size, x=0, y=0, id=None):
16 | """Intiates the square object
17 | """
18 |
19 | super().__init__(size, size, x, y, id)
20 |
21 | def __str__(self):
22 | """string representation of the square object
23 | """
24 |
25 | return "[Square] ({}) {}/{} - {}".format(self.id,
26 | self._Rectangle__x,
27 | self._Rectangle__y,
28 | self._Rectangle__width)
29 |
30 | @property
31 | def size(self):
32 | """returns the size of the object
33 | """
34 |
35 | return self._Rectangle__width
36 |
37 | @size.setter
38 | def size(self, size):
39 | """sets the new width and height
40 | """
41 |
42 | self.width = size
43 | self.height = size
44 |
45 | def update(self, *args, **kwargs):
46 | """Update the Rectangle.
47 | Args:
48 | *args (ints): New attribute values.
49 | - 1st argument represents id attribute
50 | - 2nd argument represents size attribute
51 | - 3rd argument represents x attribute
52 | - 4th argument represents y attribute
53 | **kwargs (dict): New key/value pairs of attributes.
54 | """
55 |
56 | new_args = [self.id,
57 | self._Rectangle__width,
58 | self._Rectangle__x, self._Rectangle__y]
59 | if len(args) == 0 or args is None:
60 | if len(kwargs) == 0:
61 | return
62 | else:
63 | try:
64 | new_args[0] = kwargs['id']
65 | except KeyError:
66 | pass
67 | try:
68 | new_args[1] = kwargs['size']
69 | except KeyError:
70 | pass
71 | try:
72 | new_args[2] = kwargs['x']
73 | except KeyError:
74 | pass
75 | try:
76 | new_args[3] = kwargs['y']
77 | except KeyError:
78 | pass
79 | else:
80 | for x in range(len(args)):
81 | if x < len(new_args):
82 | new_args[x] = args[x]
83 | self.__init__(new_args[1],
84 | new_args[2],
85 | new_args[3],
86 | new_args[0])
87 |
88 | def to_dictionary(self):
89 | """Returns a dictionary representation of the the
90 | object"""
91 |
92 | obj_dic = {
93 | "id": self.id,
94 | "size": self.width,
95 | "x": self.x,
96 | "y": self.y
97 | }
98 | return obj_dic
99 |
--------------------------------------------------------------------------------
/0x08-python-more_classes/8-rectangle.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 8-rectangle.py
3 | """Defines a Rectangle class.
4 | """
5 |
6 |
7 | class Rectangle:
8 | """Represent a rectangle.
9 |
10 | Attributes:
11 | number_of_instances (int): The number of Rectangle instances.
12 | print_symbol (any): The symbol used for string representation.
13 | """
14 |
15 | number_of_instances = 0
16 | print_symbol = "#"
17 |
18 | def __init__(self, width=0, height=0):
19 | """Initialize a new Rectangle.
20 |
21 | Args:
22 | width (int): The width of the new rectangle.
23 | height (int): The height of the new rectangle.
24 | """
25 | type(self).number_of_instances += 1
26 | self.width = width
27 | self.height = height
28 |
29 | @property
30 | def width(self):
31 | """Get/set the width of the Rectangle.
32 | """
33 | return self.__width
34 |
35 | @width.setter
36 | def width(self, value):
37 | if not isinstance(value, int):
38 | raise TypeError("width must be an integer")
39 | if value < 0:
40 | raise ValueError("width must be >= 0")
41 | self.__width = value
42 |
43 | @property
44 | def height(self):
45 | """Get/set the height of the Rectangle.
46 | """
47 | return self.__height
48 |
49 | @height.setter
50 | def height(self, value):
51 | if not isinstance(value, int):
52 | raise TypeError("height must be an integer")
53 | if value < 0:
54 | raise ValueError("height must be >= 0")
55 | self.__height = value
56 |
57 | def area(self):
58 | """Return the area of the Rectangle.
59 | """
60 | return (self.__width * self.__height)
61 |
62 | def perimeter(self):
63 | """Return the perimeter of the Rectangle.
64 | """
65 | if self.__width == 0 or self.__height == 0:
66 | return (0)
67 | return ((self.__width * 2) + (self.__height * 2))
68 |
69 | @staticmethod
70 | def bigger_or_equal(rect_1, rect_2):
71 | """Return the Rectangle with the greater area.
72 |
73 | Args:
74 | rect_1 (Rectangle): The first Rectangle.
75 | rect_2 (Rectangle): The second Rectangle.
76 | Raises:
77 | TypeError: If either of rect_1 or rect_2 is not a Rectangle.
78 | """
79 | if not isinstance(rect_1, Rectangle):
80 | raise TypeError("rect_1 must be an instance of Rectangle")
81 | if not isinstance(rect_2, Rectangle):
82 | raise TypeError("rect_2 must be an instance of Rectangle")
83 | if rect_1.area() >= rect_2.area():
84 | return (rect_1)
85 | return (rect_2)
86 |
87 | def __str__(self):
88 | """Return the printable representation of the Rectangle.
89 |
90 | Represents the rectangle with the # character.
91 | """
92 | if self.__width == 0 or self.__height == 0:
93 | return ("")
94 |
95 | rect = []
96 | for i in range(self.__height):
97 | [rect.append(str(self.print_symbol)) for j in range(self.__width)]
98 | if i != self.__height - 1:
99 | rect.append("\n")
100 | return ("".join(rect))
101 |
102 | def __repr__(self):
103 | """Return the string representation of the Rectangle.
104 | """
105 | rect = "Rectangle(" + str(self.__width)
106 | rect += ", " + str(self.__height) + ")"
107 | return (rect)
108 |
109 | def __del__(self):
110 | """Print a message for every deletion of a Rectangle.
111 | """
112 | type(self).number_of_instances -= 1
113 | print("Bye rectangle...")
114 |
--------------------------------------------------------------------------------
/0x0A-python-inheritance/tests/7-base_geometry.txt:
--------------------------------------------------------------------------------
1 | Instantiation
2 | =============
3 |
4 | ``BaseGeometry`` includes no attributes, and accordingly is initialized
5 | with no arguments.
6 |
7 | ::
8 |
9 | >>> BaseGeometry = __import__('7-base_geometry').BaseGeometry
10 | >>> bg = BaseGeometry()
11 | >>> type(bg)
12 |
13 |
14 | ::
15 |
16 | >>> print(bg) # doctest: +ELLIPSIS
17 | <7-base_geometry.BaseGeometry object at ...>
18 |
19 | In fact, any arguments supplied to an instantiation of ``BaseGeometry`` results
20 | in a TypeError.
21 |
22 | ::
23 |
24 | >>> bg = BaseGeometry(None)
25 | Traceback (most recent call last):
26 | TypeError: BaseGeometry() takes no arguments
27 |
28 | Methods
29 | =======
30 |
31 | ``BaseGeometry`` features two methods - ``area(self)`` and
32 | ``integer_validator(self, name, value)``. ``area(...)`` is not yet
33 | implemented.
34 |
35 | ::
36 |
37 | >>> bg = BaseGeometry()
38 | >>> print(bg.area) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
39 | >
41 |
42 | ::
43 |
44 | >>> bg.area()
45 | Traceback (most recent call last):
46 | Exception: area() is not implemented
47 |
48 | The second method, ``integer_validator(...)``, validates the integer value
49 | of a paramter. The first parameter, ``name``, is the name of the argument to
50 | check. The second argument, ``value``, is the argument to check.
51 |
52 | ::
53 |
54 | >>> print(bg.integer_validator) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
55 | >
57 |
58 | If ``value`` is a valid integer, the function does nothing.
59 |
60 | ::
61 |
62 |
63 | >>> bg.integer_validator("valid number", 1)
64 |
65 | But, if ``value`` is not an integer, a ``TypeError`` is raised.
66 |
67 | ::
68 |
69 | >>> bg.integer_validator("invalid number", "number")
70 | TypeError('invalid number must be an integer')
71 |
72 |
73 | ::
74 |
75 | >>> bg.integer_validator("another invalid", True)
76 | TypeError('another invalid must be an integer')
77 |
78 | ::
79 |
80 | >>> bg.integer_validator("invalid tuple", (1,))
81 | TypeError('invalid tuple must be an integer')
82 |
83 | ::
84 |
85 | >>> bg.integer_validator("and another", [3])
86 | TypeError('and another must be an integer')
87 |
88 |
89 | ::
90 |
91 | >>> bg.integer_validator("more invalid testing", {3, 4})
92 | TypeError('more invalid testing must be an integer')
93 |
94 |
95 | ::
96 |
97 | >>> bg.integer_validator("absolutely every possible invalid", None)
98 | TypeError('absolutely every possible invalid must be an integer')
99 |
100 | And if ``value`` is an integer, but less than or equal to zero, a ValueError
101 | is raised.
102 |
103 | ::
104 |
105 | >>> bg.integer_validator("invalid int", -1)
106 | ValueError('invalid int must be greater than 0')
107 |
108 | ::
109 |
110 | >>> bg.integer_validator("invalid int", 0)
111 | ValueError('invalid int must be greater than 0')
112 |
113 | Both ``name`` and ``value`` must be provided. Otherwise, a TypeError is raised.
114 |
115 | ::
116 |
117 | >>> bg.integer_validator() # doctest: +NORMALIZE_WHITESPACE
118 | Traceback (most recent call last):
119 | TypeError: integer_validator() missing 2 required positional arguments:
120 | 'name' and 'value'
121 |
122 | ::
123 |
124 | >>> bg.integer_validator(None) # doctest: +NORMALIZE_WHITESPACE
125 | Traceback (most recent call last):
126 | TypeError: integer_validator() missing 1 required positional argument:
127 | 'value'
128 |
129 | The method assumes the paramter ``name`` will be a string, but ``name`` of any
130 | type will be printed.
131 |
132 | ::
133 |
134 | >>> bg.integer_validator({"a": 1}, (1, 2))
135 | TypeError("{'a': 1} must be an integer")
136 |
--------------------------------------------------------------------------------
/0x08-python-more_classes/9-rectangle.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # 9-rectangle.py
3 | """Defines a Rectangle class.
4 | """
5 |
6 |
7 | class Rectangle:
8 | """Represent a rectangle.
9 |
10 | Attributes:
11 | number_of_instances (int): The number of Rectangle instances.
12 | print_symbol (any): The symbol used for string representation.
13 | """
14 |
15 | number_of_instances = 0
16 | print_symbol = "#"
17 |
18 | def __init__(self, width=0, height=0):
19 | """Initialize a new Rectangle.
20 |
21 | Args:
22 | width (int): The width of the new rectangle.
23 | height (int): The height of the new rectangle.
24 | """
25 | type(self).number_of_instances += 1
26 | self.width = width
27 | self.height = height
28 |
29 | @property
30 | def width(self):
31 | """Get/set the width of the Rectangle.
32 | """
33 | return self.__width
34 |
35 | @width.setter
36 | def width(self, value):
37 | if not isinstance(value, int):
38 | raise TypeError("width must be an integer")
39 | if value < 0:
40 | raise ValueError("width must be >= 0")
41 | self.__width = value
42 |
43 | @property
44 | def height(self):
45 | """Get/set the height of the Rectangle.
46 | """
47 | return self.__height
48 |
49 | @height.setter
50 | def height(self, value):
51 | if not isinstance(value, int):
52 | raise TypeError("height must be an integer")
53 | if value < 0:
54 | raise ValueError("height must be >= 0")
55 | self.__height = value
56 |
57 | def area(self):
58 | """Return the area of the Rectangle.
59 | """
60 | return (self.__width * self.__height)
61 |
62 | def perimeter(self):
63 | """Return the perimeter of the Rectangle.
64 | """
65 | if self.__width == 0 or self.__height == 0:
66 | return (0)
67 | return ((self.__width * 2) + (self.__height * 2))
68 |
69 | @staticmethod
70 | def bigger_or_equal(rect_1, rect_2):
71 | """Return the Rectangle with the greater area.
72 |
73 | Args:
74 | rect_1 (Rectangle): The first Rectangle.
75 | rect_2 (Rectangle): The second Rectangle.
76 | Raises:
77 | TypeError: If either of rect_1 or rect_2 is not a Rectangle.
78 | """
79 | if not isinstance(rect_1, Rectangle):
80 | raise TypeError("rect_1 must be an instance of Rectangle")
81 | if not isinstance(rect_2, Rectangle):
82 | raise TypeError("rect_2 must be an instance of Rectangle")
83 | if rect_1.area() >= rect_2.area():
84 | return (rect_1)
85 | return (rect_2)
86 |
87 | @classmethod
88 | def square(cls, size=0):
89 | """Return a new Rectangle with width and height equal to size.
90 |
91 | Args:
92 | size (int): The width and height of the new Rectangle.
93 | """
94 | return (cls(size, size))
95 |
96 | def __str__(self):
97 | """Return the printable representation of the Rectangle.
98 |
99 | Represents the rectangle with the # character.
100 | """
101 | if self.__width == 0 or self.__height == 0:
102 | return ("")
103 |
104 | rect = []
105 | for i in range(self.__height):
106 | [rect.append(str(self.print_symbol)) for j in range(self.__width)]
107 | if i != self.__height - 1:
108 | rect.append("\n")
109 | return ("".join(rect))
110 |
111 | def __repr__(self):
112 | """Return the string representation of the Rectangle.
113 | """
114 | rect = "Rectangle(" + str(self.__width)
115 | rect += ", " + str(self.__height) + ")"
116 | return (rect)
117 |
118 | def __del__(self):
119 | """Print a message for every deletion of a Rectangle.
120 | """
121 | type(self).number_of_instances -= 1
122 | print("Bye rectangle...")
123 |
--------------------------------------------------------------------------------
/0x0A-python-inheritance/tests/1-my_list.txt:
--------------------------------------------------------------------------------
1 |
2 | =======================
3 | How to Use 1-my_list.py
4 | =======================
5 |
6 | This module defines a class ``MyList`` that inherits from ``list``.
7 |
8 | Instantiation
9 | =============
10 |
11 | ``MyList`` can be instantiated with no arguments, which will return
12 | an empty list:
13 |
14 | ::
15 |
16 | >>> MyList = __import__('1-my_list').MyList
17 | >>> my_list = MyList()
18 | >>> type(my_list)
19 |
20 |
21 | ::
22 |
23 | >>> print(my_list)
24 | []
25 |
26 | Or a single argument, which must be an iterable object.
27 |
28 | ::
29 |
30 | >>> my_list = MyList([1, 2, 3])
31 | >>> print(my_list)
32 | [1, 2, 3]
33 |
34 | ::
35 |
36 | >>> my_list = MyList(None)
37 | Traceback (most recent call last):
38 | TypeError: 'NoneType' object is not iterable
39 |
40 |
41 | A ``TypeError`` will be raised for any more than one instantiation arguments.
42 |
43 | ::
44 |
45 | >>> my_list = MyList([1, 2], [3, 4])
46 | Traceback (most recent call last):
47 | TypeError: list expected at most 1 argument, got 2
48 |
49 | Usage
50 | =====
51 |
52 | ``MyList`` is an inherited ``list`` class, and thus features the same methods.
53 | For instance, elements can be added to a ``MyList`` with the ``append()`` method.
54 |
55 | ::
56 |
57 | >>> my_list = MyList()
58 | >>> my_list.append(1)
59 | >>> my_list.append(2)
60 | >>> my_list.append(3)
61 | >>> print(my_list)
62 | [1, 2, 3]
63 |
64 | Replaced with indexing:
65 |
66 | ::
67 |
68 | >>> my_list[0] = 5
69 | >>> print(my_list)
70 | [5, 2, 3]
71 |
72 | And removed with the ``remove()`` method.
73 |
74 | ::
75 |
76 | >>> my_list.remove(5)
77 | >>> print(my_list)
78 | [2, 3]
79 |
80 | See the documentation on Python lists for more built-in methods.
81 |
82 | ``print_sorted`` Method
83 | =======================
84 |
85 | ``MyList`` implements a single method - a public instance method
86 | ``print_sorted(self)``.
87 |
88 | ::
89 |
90 | >>> my_list = MyList()
91 | >>> print(my_list.print_sorted)
92 |
93 |
94 | The method takes no arguments - a TypeError will be raised if an argument is
95 | provided.
96 |
97 | ::
98 |
99 | >>> my_list.print_sorted(1)
100 | Traceback (most recent call last):
101 | TypeError: print_sorted() takes 1 positional argument but 2 were given
102 |
103 | The method prints the list in ascending sorted order.
104 |
105 | ::
106 |
107 | >>> my_list.append(1)
108 | >>> my_list.append(4)
109 | >>> my_list.append(2)
110 | >>> my_list.append(3)
111 | >>> my_list.append(5)
112 | >>> print(my_list)
113 | [1, 4, 2, 3, 5]
114 |
115 | ::
116 |
117 | >>> my_list.print_sorted()
118 | [1, 2, 3, 4, 5]
119 |
120 | The order of the original list is not altered after a call to the method.
121 |
122 | ::
123 |
124 | >>> print(my_list)
125 | [1, 4, 2, 3, 5]
126 |
127 | Note that lists of strings are sorted lexographically.
128 |
129 | ::
130 |
131 | >>> my_list = MyList()
132 | >>> my_list.append("Brennan")
133 | >>> my_list.append("Poppy")
134 | >>> my_list.append("School")
135 | >>> my_list.append("Holberton")
136 | >>> my_list.append("Betty")
137 | >>> print(my_list)
138 | ['Brennan', 'Poppy', 'School', 'Holberton', 'Betty']
139 |
140 | ::
141 |
142 | >>> my_list.print_sorted()
143 | ['Betty', 'Brennan', 'Holberton', 'Poppy', 'School']
144 |
145 | Another friendly reminder that the original list is unaltered :)
146 |
147 | ::
148 |
149 | >>> print(my_list)
150 | ['Brennan', 'Poppy', 'School', 'Holberton', 'Betty']
151 |
152 | Nothing to sort with empty lists.
153 |
154 | ::
155 |
156 | >>> my_list = MyList()
157 | >>> my_list.print_sorted()
158 | []
159 |
160 | If ``print_sorted(...)`` is called on a list of different types, a TypeError
161 | will be raised.
162 |
163 | ::
164 |
165 | >>> my_list = MyList([1, "Betty", "Holberton", 5])
166 | >>> my_list.print_sorted()
167 | Traceback (most recent call last):
168 | TypeError: '<' not supported between instances of 'str' and 'int'
169 |
--------------------------------------------------------------------------------
/0x07-python-test_driven_development/tests/2-matrix_divided.txt:
--------------------------------------------------------------------------------
1 |
2 | Usage
3 | =====
4 |
5 | ``matrix_divided(...)`` returns a new matrix that is a copy of the parameter
6 | ``matrix`` with all elements divided by ``div``.
7 |
8 | ::
9 |
10 | >>> matrix_divided = __import__('2-matrix_divided').matrix_divided
11 | >>> matrix = [
12 | ... [3, 6, 9],
13 | ... [12, 15, 18]
14 | ... ]
15 | >>> print(matrix_divided(matrix, 3))
16 | [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]
17 |
18 | Note that quotients are rounded to a maximum of two decimal places.
19 |
20 | ::
21 |
22 | >>> matrix = [
23 | ... [1, 2, 3],
24 | ... [4, 5, 6]
25 | ... ]
26 | >>> print(matrix_divided(matrix, 3))
27 | [[0.33, 0.67, 1.0], [1.33, 1.67, 2.0]]
28 |
29 | The original matrix is left unchanged.
30 |
31 | ::
32 |
33 | >>> print(matrix)
34 | [[1, 2, 3], [4, 5, 6]]
35 |
36 | The function can also handle floating-point numbers.
37 |
38 | ::
39 |
40 | >>> matrix = [
41 | ... [1.1, -2.2, 3.3],
42 | ... [4.4, 5.5, -6.6]
43 | ... ]
44 | >>> print(matrix_divided(matrix, 3))
45 | [[0.37, -0.73, 1.1], [1.47, 1.83, -2.2]]
46 |
47 | Integers and floats can be combined.
48 |
49 | ::
50 |
51 | >>> matrix = [
52 | ... [1, -2.2, 3, 4.4, 5],
53 | ... [-6.6, 7.00, 8, 9.999, 10]
54 | ... ]
55 | >>> print(matrix_divided(matrix, 3))
56 | [[0.33, -0.73, 1.0, 1.47, 1.67], [-2.2, 2.33, 2.67, 3.33, 3.33]]
57 |
58 | Invalid Matrices
59 | ==============
60 |
61 | The parameter ``matrix`` must be a list of lists consisting of either ints or
62 | floats. If ``matrix`` is not a list, a TypeError is raised.
63 |
64 | ::
65 |
66 | >>> matrix = "not a list"
67 | >>> print(matrix_divided(matrix, 3))
68 | Traceback (most recent call last):
69 | TypeError: matrix must be a matrix (list of lists) of integers/floats
70 |
71 | ::
72 |
73 | >>> matrix = None
74 | >>> print(matrix_divided(matrix, 3))
75 | Traceback (most recent call last):
76 | TypeError: matrix must be a matrix (list of lists) of integers/floats
77 |
78 | Note that an empty list will raise the TypeError.
79 |
80 | ::
81 |
82 | >>> matrix = []
83 | >>> print(matrix_divided(matrix, 3))
84 | Traceback (most recent call last):
85 | TypeError: matrix must be a matrix (list of lists) of integers/floats
86 |
87 | But an empty list of lists will succeed.
88 |
89 | ::
90 |
91 | >>> matrix = [[]]
92 | >>> print(matrix_divided(matrix, 3))
93 | [[]]
94 |
95 | An identical TypeError is raised if ``matrix`` is not specifically a list of
96 | lists.
97 |
98 | ::
99 |
100 | >>> matrix = [1, 2, 3]
101 | >>> print(matrix_divided(matrix, 3))
102 | Traceback (most recent call last):
103 | TypeError: matrix must be a matrix (list of lists) of integers/floats
104 |
105 | The same TypeError is raised yet again if any elements in ``matrix`` are
106 | neither ints nor floats.
107 |
108 | ::
109 |
110 | >>> matrix = [
111 | ... [1, 2, 3],
112 | ... [4, "not a number", 6]
113 | ... ]
114 | >>> print(matrix_divided(matrix, 3))
115 | Traceback (most recent call last):
116 | TypeError: matrix must be a matrix (list of lists) of integers/floats
117 |
118 |
119 | Finally, all the rows in ``matrix`` must be the same size. If any rows are
120 | of different sizes, a new TypeError is raised.
121 |
122 | ::
123 |
124 | >>> matrix = [
125 | ... [1, 2, 3, 4],
126 | ... [5, 6, 7]
127 | ... ]
128 | >>> print(matrix_divided(matrix, 3))
129 | Traceback (most recent call last):
130 | TypeError: Each row of the matrix must have the same size
131 |
132 | Invalid Divisors
133 | ================
134 |
135 | The parameter ``div`` must be either an int or float. Otherwise, a TypeError
136 | is raised.
137 |
138 | ::
139 |
140 | >>> matrix = [
141 | ... [1, 2, 3],
142 | ... [4, 5, 6]
143 | ... ]
144 | >>> print(matrix_divided(matrix, "not a number"))
145 | Traceback (most recent call last):
146 | TypeError: div must be a number
147 |
148 | ::
149 |
150 | >>> print(matrix_divided(matrix, None))
151 | Traceback (most recent call last):
152 | TypeError: div must be a number
153 |
154 | ``div`` must also be non-zero. Otherwise, a ZeroDivisionError is raised.
155 |
156 | ::
157 |
158 | >>> print(matrix_divided(matrix, 0))
159 | Traceback (most recent call last):
160 | ZeroDivisionError: division by zero
161 |
--------------------------------------------------------------------------------
/0x0C-python-almost_a_circle/models/rectangle.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # rectangle.py
3 | """Defines a rectangle class."""
4 | from models.base import Base
5 |
6 |
7 | class Rectangle(Base):
8 | """Represent a rectangle."""
9 |
10 | def __init__(self, width, height, x=0, y=0, id=None):
11 | """Initialize a new Rectangle.
12 | Args:
13 | width (int): The width of the new Rectangle.
14 | height (int): The height of the new Rectangle.
15 | x (int): The x coordinate of the new Rectangle.
16 | y (int): The y coordinate of the new Rectangle.
17 | id (int): The identity of the new Rectangle.
18 | Raises:
19 | TypeError: If either of width or height is not an int.
20 | ValueError: If either of width or height <= 0.
21 | TypeError: If either of x or y is not an int.
22 | ValueError: If either of x or y < 0.
23 | """
24 |
25 | # Validate variables
26 |
27 | # Validate width
28 | if type(width) != int:
29 | raise TypeError("width must be an integer")
30 | if width <= 0:
31 | raise ValueError("width must be > 0")
32 |
33 | # validate height
34 | if type(height) != int:
35 | raise TypeError("height must be an integer")
36 | if height <= 0:
37 | raise ValueError("height must be > 0")
38 |
39 | # validate x
40 | if type(x) != int:
41 | raise TypeError("x must be an integer")
42 | if x < 0:
43 | raise ValueError("x must be >= 0")
44 |
45 | # validate y
46 | if type(y) != int:
47 | raise TypeError("y must be an integer")
48 | if y < 0:
49 | raise ValueError("y must be >= 0")
50 |
51 | super().__init__(id)
52 | self.__width = width
53 | self.__height = height
54 | self.__x = x
55 | self.__y = y
56 |
57 | @property
58 | def width(self):
59 | """width getter function
60 | """
61 |
62 | return self.__width
63 |
64 | @width.setter
65 | def width(self, width):
66 | """Sets the width attribute
67 | """
68 |
69 | if type(width) != int:
70 | raise TypeError("width must be an integer")
71 | if width <= 0:
72 | raise ValueError("width must be > 0")
73 | self.__width = width
74 |
75 | @property
76 | def height(self):
77 | """height getter function
78 | """
79 |
80 | return self.__height
81 |
82 | @height.setter
83 | def height(self, height):
84 | """Sets the height attribute
85 | """
86 |
87 | if type(height) != int:
88 | raise TypeError("height must be an integer")
89 | if height <= 0:
90 | raise ValueError("height must be > 0")
91 | self.__height = height
92 |
93 | @property
94 | def x(self):
95 | """x getter function
96 | """
97 |
98 | return self.__x
99 |
100 | @x.setter
101 | def x(self, x):
102 | """Sets the x attribute
103 | """
104 |
105 | if type(x) != int:
106 | raise TypeError("x must be an integer")
107 | if x < 0:
108 | raise ValueError("x must be >= 0")
109 | self.__x = x
110 |
111 | @property
112 | def y(self):
113 | """y getter function
114 | """
115 |
116 | return self.__y
117 |
118 | @y.setter
119 | def y(self, y):
120 | """Sets the x attribute
121 | """
122 |
123 | if type(y) != int:
124 | raise TypeError("y must be an integer")
125 | if y < 0:
126 | raise ValueError("y must be >= 0")
127 | self.__y = y
128 |
129 | def area(self):
130 | """Returns the area of the current
131 | rectangle"""
132 |
133 | return self.__width * self.__height
134 |
135 | def display(self):
136 | """prints the rectangle
137 | """
138 |
139 | if self.__width == 0 or self.__height == 0:
140 | print()
141 | return
142 |
143 | if self.__y != 0:
144 | print("\n" * (self.__y - 1))
145 | for y in range(self.__height):
146 | if self.__x != 0:
147 | print(" " * self.__x, end="")
148 | print("#" * self.__width)
149 |
150 | def __str__(self):
151 | """string representaaion of the class
152 | """
153 |
154 | return "[Rectangle] ({}) {}/{} - {}/{}".format(self.id,
155 | self.__x,
156 | self.__y,
157 | self.__width,
158 | self.__height)
159 |
160 | def update(self, *args, **kwargs):
161 | """Update the Rectangle.
162 | Args:
163 | *args (ints): New attribute values.
164 | - 1st argument represents id attribute
165 | - 2nd argument represents width attribute
166 | - 3rd argument represent height attribute
167 | - 4th argument represents x attribute
168 | - 5th argument represents y attribute
169 | **kwargs (dict): New key/value pairs of attributes.
170 | """
171 |
172 | new_args = [self.id, self.__width, self.__height, self.__x, self.__y]
173 | if len(args) == 0 or args is None:
174 | if len(kwargs) == 0:
175 | return
176 | else:
177 | try:
178 | new_args[0] = kwargs['id']
179 | except KeyError:
180 | pass
181 | try:
182 | new_args[1] = kwargs['width']
183 | except KeyError:
184 | pass
185 | try:
186 | new_args[2] = kwargs['height']
187 | except KeyError:
188 | pass
189 | try:
190 | new_args[3] = kwargs['x']
191 | except KeyError:
192 | pass
193 | try:
194 | new_args[4] = kwargs['y']
195 | except KeyError:
196 | pass
197 | else:
198 | for x in range(len(args)):
199 | if x < len(new_args):
200 | new_args[x] = args[x]
201 | self.__init__(new_args[1],
202 | new_args[2],
203 | new_args[3],
204 | new_args[4],
205 | new_args[0])
206 |
207 | def to_dictionary(self):
208 | """Returns a dictionary representation of the the
209 | object"""
210 |
211 | obj_dic = {
212 | "id": self.id,
213 | "width": self.width,
214 | "height": self.height,
215 | "x": self.x,
216 | "y": self.y
217 | }
218 | return obj_dic
219 |
--------------------------------------------------------------------------------