From 7a8ebd4510c39fb7c07d828f1f220f2a6a8e5bc3 Mon Sep 17 00:00:00 2001 From: Morpheus Date: Tue, 3 Mar 2026 10:24:26 +0900 Subject: [PATCH] style: fix code formatting issues All changes were made so that PEP 8 is followed. Fixes include: - Added missing (and removed extra) blank lines (end of file and around classes and functions) - Added missing spaces between `#`s for comments - Added missing spaces around operators (arithmetic, comparison, commas, dict colons, etc.) - Removed redundant parentheses - Use double-quotes for docstrings instead of single-quotes - Removed spaces around keyword argument equal signs - Fixed incorrect indentations Note: line lengths (which are supposed to stay below 79 characters) were ignored for now --- basics/01_introduction/01_hello_world.py | 2 +- .../04_mad_libs_story_generator.py | 2 ++ basics/02_variables_types/01_arithmetic.py | 2 +- basics/02_variables_types/05_square_input.py | 2 +- .../06_convert_inches_cm.py | 4 ++- .../02_variables_types/07_global_variable.py | 5 ++- .../02_variables_types/08_input_validation.py | 4 +-- basics/02_variables_types/09_typecasting.py | 9 +++-- basics/02_variables_types/10_union_types.py | 21 ++++++----- basics/02_variables_types/11_operators.py | 26 +++++++------- .../12_celsius_fahrenheit.py | 6 ++-- .../02_variables_types/13_escape_sequences.py | 2 +- basics/03_control_flow/01_if_else.py | 3 +- .../03_control_flow/04_multiplication_loop.py | 6 ++-- basics/03_control_flow/051_hello_10_times.py | 1 - basics/03_control_flow/05_reverse_table.py | 3 +- basics/03_control_flow/06_greet_names.py | 5 +-- basics/03_control_flow/08_pattern_pyramid.py | 6 ++-- .../09_pattern_hollow_square.py | 4 +-- .../03_control_flow/10_if_else_challenges.py | 35 ++++++++++--------- basics/04_functions/01_functions_basics.py | 1 + basics/04_functions/02_arguments_return.py | 3 +- basics/04_functions/03_find_greatest.py | 6 ++-- basics/04_functions/04_print_pattern.py | 16 ++++----- basics/04_functions/05_print_table.py | 6 ++-- basics/04_functions/06_default_arguments.py | 7 ++-- basics/04_functions/08_sum_while.py | 4 +-- basics/04_functions/11_factorial_recursive.py | 4 +-- basics/05_data_structures/01_list_basics.py | 15 ++++---- basics/05_data_structures/02_list_fruits.py | 12 +++---- basics/05_data_structures/03_list_sum.py | 12 +++---- basics/05_data_structures/04_list_remove.py | 5 +-- basics/05_data_structures/05_list_slicing.py | 26 +++++++------- .../05_data_structures/07_list_comp_table.py | 2 +- basics/05_data_structures/08_list_join.py | 4 +-- basics/05_data_structures/09_list_methods.py | 25 ++++++------- .../10_tuple_immutability.py | 4 +-- basics/05_data_structures/11_tuple_methods.py | 19 +++++----- basics/05_data_structures/12_set_unique.py | 8 ++--- basics/05_data_structures/13_set_values.py | 6 ++-- basics/05_data_structures/14_sets_basics.py | 9 +++-- basics/05_data_structures/15_set_methods.py | 4 --- basics/05_data_structures/16_dict_basics.py | 4 +-- basics/05_data_structures/17_dict_friends.py | 16 ++++----- .../05_data_structures/18_dict_translator.py | 14 ++++---- basics/05_data_structures/19_enumerate.py | 5 ++- .../20_enumerate_examples.py | 4 +-- basics/05_data_structures/21_tuple_count.py | 6 ++-- .../05_data_structures/31_weather_logger.py | 2 ++ basics/06_strings/01_greet_input.py | 4 +-- basics/06_strings/02_string_methods.py | 26 +++++++------- basics/06_strings/03_string_format.py | 8 ++--- basics/06_strings/04_string_slicing.py | 18 +++++----- .../06_strings/05_string_slicing_practice.py | 16 ++++----- basics/06_strings/06_letter_template.py | 4 +-- basics/06_strings/07_doublespace.py | 27 +++++++------- basics/06_strings/09_join_challenge.py | 2 +- basics/07_file_handling/02_file_readlines.py | 1 - basics/07_file_handling/03_file_multiple.py | 2 -- basics/07_file_handling/04_file_numbers.py | 2 -- basics/07_file_handling/07_file_find_word.py | 6 ---- basics/07_file_handling/08_file_search_log.py | 2 +- basics/07_file_handling/09_file_delete.py | 3 +- basics/07_file_handling/11_file_copy.py | 10 +----- basics/07_file_handling/12_file_replace.py | 1 - basics/07_file_handling/13_file_censor.py | 3 -- basics/08_oop/02_class_calculator.py | 1 + basics/08_oop/03_class_constructor.py | 9 +++-- basics/08_oop/05_class_programmer.py | 2 +- basics/08_oop/07_operator_overloading.py | 4 ++- basics/08_oop/08_oop_examples.py | 5 ++- basics/08_oop/10_inheritance_multilevel.py | 4 ++- basics/08_oop/11_inheritance_vector.py | 25 +++++-------- basics/08_oop/12_inheritance_super.py | 13 ++++--- basics/08_oop/15_complex_numbers.py | 2 ++ basics/08_oop/16_salary_increment.py | 19 ++++------ basics/09_error_handling/01_try_except.py | 1 + .../09_error_handling/02_raise_exception.py | 3 +- .../exception_handling_try_except.py | 1 + .../exception_raise_example.py | 1 + basics/10_advanced/01_lambda.py | 5 +++ basics/10_advanced/02_map_filter_reduce.py | 2 ++ basics/10_advanced/03_filter_divisible.py | 10 +++--- basics/10_advanced/04_reduce_maximum.py | 4 ++- basics/10_advanced/06_module_custom.py | 3 +- basics/10_advanced/07_module_pyjokes.py | 1 - basics/10_advanced/08_match_case.py | 10 +++--- basics/10_advanced/09_walrus_operator.py | 9 ++--- basics/10_advanced/10_text_to_speech.py | 2 +- .../10_advanced/filter_divisible_by_five.py | 9 +++-- .../functional_map_filter_reduce.py | 4 ++- basics/10_advanced/lambda_functions.py | 5 +++ basics/10_advanced/match_case_statement.py | 6 ++-- basics/10_advanced/module_add_function.py | 1 + basics/10_advanced/walrus_operator_example.py | 7 ++-- .../1000_programs/medium/1134_armstrong.py | 9 ++--- ...st_common_ancestor_of_a_binary_tree_iii.py | 5 ++- .../1000_programs/medium/1815_fresh_donuts.py | 2 ++ .../1000_programs/medium/1870_min_speed.py | 6 +++- .../WEIGHT-LOADING/supplementary.py | 1 - .../01_transformer_architecture.py | 19 +++++----- llm_fundamentals/data/simple-tokenizer.py | 14 ++++---- llm_fundamentals/data/supplementary.py | 2 +- .../fine_tuning/01_fine_tuning.py | 4 --- .../pre_training/02_run_named_file.py | 2 +- .../pre_training/03_run_pretrained.py | 2 +- .../pre_training/04_pretraining_helpers.py | 2 +- .../weight_loading/01_weight_loading.py | 2 +- .../weight_loading/02_run_inference.py | 3 +- .../weight_loading/03_gpt_download.py | 2 +- .../weight_loading/04_weight_helpers.py | 2 +- 111 files changed, 395 insertions(+), 382 deletions(-) diff --git a/basics/01_introduction/01_hello_world.py b/basics/01_introduction/01_hello_world.py index eef8c1d..6344ea6 100644 --- a/basics/01_introduction/01_hello_world.py +++ b/basics/01_introduction/01_hello_world.py @@ -1,2 +1,2 @@ print("ram") -print("Hello World") \ No newline at end of file +print("Hello World") diff --git a/basics/01_introduction/04_mad_libs_story_generator.py b/basics/01_introduction/04_mad_libs_story_generator.py index 97868db..f93e03f 100644 --- a/basics/01_introduction/04_mad_libs_story_generator.py +++ b/basics/01_introduction/04_mad_libs_story_generator.py @@ -1,5 +1,6 @@ """ This program generates a fun story by asking the user for different types of words""" + def mad_libs_story(): # Ask the user for words name = input("Enter a name: ") @@ -25,6 +26,7 @@ def mad_libs_story(): # Print the story print(story) + # Run the story generator if __name__ == "__main__": mad_libs_story() diff --git a/basics/02_variables_types/01_arithmetic.py b/basics/02_variables_types/01_arithmetic.py index e14f6b6..19b518f 100644 --- a/basics/02_variables_types/01_arithmetic.py +++ b/basics/02_variables_types/01_arithmetic.py @@ -1,4 +1,4 @@ # Addition of Two Numbers first_number = int(input("Enter the Number : ")) second_number = int(input("Enter the Number : ")) -print(f"Addition of {first_number} and {second_number} is {first_number + second_number}") \ No newline at end of file +print(f"Addition of {first_number} and {second_number} is {first_number + second_number}") diff --git a/basics/02_variables_types/05_square_input.py b/basics/02_variables_types/05_square_input.py index d5d9d5c..ca8a579 100644 --- a/basics/02_variables_types/05_square_input.py +++ b/basics/02_variables_types/05_square_input.py @@ -1,2 +1,2 @@ number = int(input("Enter the First Number : ")) -print(f"Square of {number} is {number ** 2}") \ No newline at end of file +print(f"Square of {number} is {number ** 2}") diff --git a/basics/02_variables_types/06_convert_inches_cm.py b/basics/02_variables_types/06_convert_inches_cm.py index 3217edf..383d05f 100644 --- a/basics/02_variables_types/06_convert_inches_cm.py +++ b/basics/02_variables_types/06_convert_inches_cm.py @@ -1,9 +1,11 @@ # Write a python function which converts inches to cms + def inch_cm(n): inch = n * 2.54 return inch + n = int(input("Enter the Number : ")) ch = inch_cm(n) -print(ch) \ No newline at end of file +print(ch) diff --git a/basics/02_variables_types/07_global_variable.py b/basics/02_variables_types/07_global_variable.py index 42aa08f..c06fdd8 100644 --- a/basics/02_variables_types/07_global_variable.py +++ b/basics/02_variables_types/07_global_variable.py @@ -1,8 +1,11 @@ a = 1000 + + def code(): - global a #The global keyword allows a function to modify a global variable. + global a # The global keyword allows a function to modify a global variable. a = 12 print(a) + code() print(a) diff --git a/basics/02_variables_types/08_input_validation.py b/basics/02_variables_types/08_input_validation.py index 62f0783..97224e9 100644 --- a/basics/02_variables_types/08_input_validation.py +++ b/basics/02_variables_types/08_input_validation.py @@ -1,3 +1,3 @@ -user_input = input(12) #Type of Input() +user_input = input(12) # Type of Input() input_type = type(user_input) -print(input_type) \ No newline at end of file +print(input_type) diff --git a/basics/02_variables_types/09_typecasting.py b/basics/02_variables_types/09_typecasting.py index 72a5cd2..42f2d35 100644 --- a/basics/02_variables_types/09_typecasting.py +++ b/basics/02_variables_types/09_typecasting.py @@ -1,15 +1,14 @@ print("1.") -a = "12.009" #String -b = float(a) #String to Float +a = "12.009" # String +b = float(a) # String to Float print(type(b)) print("2.") -a = "12b" #String -"""b = float(a) """ #Error-Occured @TypeError +a = "12b" # String +"""b = float(a) """ # Error-Occured @TypeError print(type(b)) print("3.") z = "123" b = int(z) print(type(b)) - diff --git a/basics/02_variables_types/10_union_types.py b/basics/02_variables_types/10_union_types.py index 4856867..bc4b7c3 100644 --- a/basics/02_variables_types/10_union_types.py +++ b/basics/02_variables_types/10_union_types.py @@ -1,15 +1,20 @@ -#Maybe the Program not work but you just see the types like how union used in the program by import typing +# Maybe the Program not work but you just see the types like how union used +# in the program by import typing from typing import List, Union, Tuple -def sum(a:Union[int,str],b:int) -> int: - sum = a+b + + +def sum(a: Union[int, str], b: int) -> int: + sum = a + b return sum -a = sum(2,3) -print(a) +a = sum(2, 3) +print(a) -n : int = 5 +n: int = 5 name: str = "Harry" -def sum(a: int, b: int) -> int: - return a+b \ No newline at end of file + + +def sum(a: int, b: int) -> int: + return a + b diff --git a/basics/02_variables_types/11_operators.py b/basics/02_variables_types/11_operators.py index 348dfbc..a68bdbd 100644 --- a/basics/02_variables_types/11_operators.py +++ b/basics/02_variables_types/11_operators.py @@ -1,22 +1,22 @@ -#Comparison Operator -a=(4/2)==2 +# Comparison Operator +a = (4/2) == 2 print(a) -#Assignment Operator +# Assignment Operator a = 20 -a=a+10 # or a += 10 +a = a + 10 # or a += 10 print(a) -#Logical Operators +# Logical Operators print("\n") print("Truth Table of 'or'") -print("True or True : ",True or True) -print("True or False: ",True or False) -print("False or False: ",False or False) -print("False or True: ",False or True) +print("True or True : ", True or True) +print("True or False: ", True or False) +print("False or False: ", False or False) +print("False or True: ", False or True) print("\n") print("Truth Table of 'and'") -print("True and True : ",True and True) -print("True and False: ",True and False) -print("False and False: ",False and False) -print("False and True: ",False and True) \ No newline at end of file +print("True and True : ", True and True) +print("True and False: ", True and False) +print("False and False: ", False and False) +print("False and True: ", False and True) diff --git a/basics/02_variables_types/12_celsius_fahrenheit.py b/basics/02_variables_types/12_celsius_fahrenheit.py index 393e652..247b684 100644 --- a/basics/02_variables_types/12_celsius_fahrenheit.py +++ b/basics/02_variables_types/12_celsius_fahrenheit.py @@ -3,17 +3,17 @@ def checktemp(c): f = (c * 9/5) + 32 return f"{f}° Farenheit" + + l = [] count = 0 while True: a = int(input("Enter the Temperature in Celcius : ")) l.append(a) - count+=1 + count += 1 if(count==1): break a = l[0] print(f"Your Number :{a}") faren = checktemp(a) print(faren) - - diff --git a/basics/02_variables_types/13_escape_sequences.py b/basics/02_variables_types/13_escape_sequences.py index 192863c..beb775e 100644 --- a/basics/02_variables_types/13_escape_sequences.py +++ b/basics/02_variables_types/13_escape_sequences.py @@ -4,4 +4,4 @@ # If we use double quote or single quote with "\" it act as same Class = "How are you ? \"hope you are fine\" " Roll = 'How are you ? \'hope you are fine\' ' -print(name,Class,Roll) \ No newline at end of file +print(name, Class, Roll) diff --git a/basics/03_control_flow/01_if_else.py b/basics/03_control_flow/01_if_else.py index 9bb0e27..2be9667 100644 --- a/basics/03_control_flow/01_if_else.py +++ b/basics/03_control_flow/01_if_else.py @@ -8,4 +8,5 @@ elif age < 0: print("I think you come from the Past!") else: - print("You are a Junior") \ No newline at end of file + print("You are a Junior") + \ No newline at end of file diff --git a/basics/03_control_flow/04_multiplication_loop.py b/basics/03_control_flow/04_multiplication_loop.py index 39e6e36..0cc5106 100644 --- a/basics/03_control_flow/04_multiplication_loop.py +++ b/basics/03_control_flow/04_multiplication_loop.py @@ -1,14 +1,14 @@ # Write a program to print multiplication table of a given number using loops. -#Using ForLoops +# Using ForLoops number = int(input("Enter the number : ")) for multiplier in range(10): print(f"{number} * {multiplier + 1} = {number * (multiplier + 1)} ") counter = 1 -#Using WhileLoops +# Using WhileLoops number = int(input("Enter the number : ")) -while(counter < 11): +while counter < 11: print(f"{number} * {counter} = {number * counter}") counter = counter + 1 diff --git a/basics/03_control_flow/051_hello_10_times.py b/basics/03_control_flow/051_hello_10_times.py index 3c4af04..fa7ffd4 100644 --- a/basics/03_control_flow/051_hello_10_times.py +++ b/basics/03_control_flow/051_hello_10_times.py @@ -2,4 +2,3 @@ for i in range(10): print("Hello World") - diff --git a/basics/03_control_flow/05_reverse_table.py b/basics/03_control_flow/05_reverse_table.py index a661afe..85ae4de 100644 --- a/basics/03_control_flow/05_reverse_table.py +++ b/basics/03_control_flow/05_reverse_table.py @@ -1,3 +1,4 @@ number = int(input("Enter Your Number :")) for multiplier in range(1, 11): - print(f"{number}*{11 - multiplier}={number * (11 - multiplier)}") \ No newline at end of file + print(f"{number}*{11 - multiplier}={number * (11 - multiplier)}") + \ No newline at end of file diff --git a/basics/03_control_flow/06_greet_names.py b/basics/03_control_flow/06_greet_names.py index 10b421e..f06518a 100644 --- a/basics/03_control_flow/06_greet_names.py +++ b/basics/03_control_flow/06_greet_names.py @@ -3,7 +3,8 @@ l = ["Harry", "Soham", "Sachin", "Rahul","Harish","Hetbe","Rajesh","Harish Meheta"]""" -names_list = ["Harry", "Soham", "Sachin", "Rahul","Harish","Hetbe","Rajesh","Harish Meheta"] +names_list = ["Harry", "Soham", "Sachin", "Rahul", "Harish", "Hetbe", "Rajesh", + "Harish Meheta"] for name in names_list: - if(name.startswith("H")): + if name.startswith("H"): print(f"Greet Sended to {name}") diff --git a/basics/03_control_flow/08_pattern_pyramid.py b/basics/03_control_flow/08_pattern_pyramid.py index 78f7f69..ccd4b6b 100644 --- a/basics/03_control_flow/08_pattern_pyramid.py +++ b/basics/03_control_flow/08_pattern_pyramid.py @@ -6,6 +6,6 @@ rows = int(input("Enter the Number : ")) for row in range(1, rows + 1): - print(" "* (rows - row), end="") - print("*"* (2 * row - 1), end="") - print(" ") \ No newline at end of file + print(" " * (rows - row), end="") + print("*" * (2 * row - 1), end="") + print(" ") diff --git a/basics/03_control_flow/09_pattern_hollow_square.py b/basics/03_control_flow/09_pattern_hollow_square.py index e27e0a4..38eb0e6 100644 --- a/basics/03_control_flow/09_pattern_hollow_square.py +++ b/basics/03_control_flow/09_pattern_hollow_square.py @@ -7,10 +7,10 @@ size = int(input("Enter the Number :")) for row in range(1, size + 1): - if(row == 1 or row == size): + if row == 1 or row == size: print(f"*" * size, end="") else: print(f"*", end="") print(f" " * (size - 2), end="") print(f"*", end="") - print("") \ No newline at end of file + print("") diff --git a/basics/03_control_flow/10_if_else_challenges.py b/basics/03_control_flow/10_if_else_challenges.py index 56fd777..0ef2149 100644 --- a/basics/03_control_flow/10_if_else_challenges.py +++ b/basics/03_control_flow/10_if_else_challenges.py @@ -1,4 +1,5 @@ """QuestionNo1. Write a program to find the greatest of four numbers entered by the user.""" + user_input = input("Enter Four Number ") first_num = user_input.split(" ").pop(0) second_num = user_input.split(" ").pop(1) @@ -9,13 +10,13 @@ second_num = int(second_num) third_num = int(third_num) fourth_num = int(fourth_num) -if(first_num >= second_num and first_num >= third_num and first_num >= fourth_num): +if first_num >= second_num and first_num >= third_num and first_num >= fourth_num: print(f"{first_num}") -elif(second_num >= second_num and second_num >= third_num and third_num >= fourth_num): +elif second_num >= second_num and second_num >= third_num and third_num >= fourth_num: print(f"{second_num}") -elif(third_num >= second_num and third_num >= third_num and third_num >= fourth_num): +elif third_num >= second_num and third_num >= third_num and third_num >= fourth_num: print(f"{third_num}") -elif(fourth_num >= first_num and fourth_num >= third_num and fourth_num >= second_num): +elif fourth_num >= first_num and fourth_num >= third_num and fourth_num >= second_num: print(f"{fourth_num}") else: print("Invalid Number ! Choose Any Valid Number") @@ -32,9 +33,9 @@ science_marks = marks_input.split(" ").pop(2) print(f"Your Report") total_marks = int(maths_marks) + int(social_science_marks) + int(science_marks) -if(total_marks > 120): +if total_marks > 120: print(f"\tYour Marks {total_marks} Out of 300") - if(int(maths_marks) >= 33 and int(social_science_marks) >= 33 and int(science_marks) >= 33): + if int(maths_marks) >= 33 and int(social_science_marks) >= 33 and int(science_marks) >= 33: print(f"You Passes\nMathematics : {maths_marks}\nSocial Science : {social_science_marks}\nScience : {science_marks}") else: print("Go and Study !") @@ -54,7 +55,7 @@ characters or not.""" username = input("Enter your Username : ") -if(len(username) < 10): +if len(username) < 10: print("Less than 10 characters ") else: print("More than or Equals to 10 characters ") @@ -67,15 +68,15 @@ user_name = input("Enter Your Name : ") name_count = names_list.count(user_name) print(name_count) -if(name_count == 0): +if name_count == 0: print("Not Present ") -elif(name_count != 0): +elif name_count != 0: print("Present") else: print("Bla Bla Bla") # type2 -if(user_name in names_list): +if user_name in names_list: print("Yes") else: print("no") @@ -91,15 +92,15 @@ <=50 => Failed""" student_marks = int(input("Enter your Marks : ")) -if(student_marks >= 90 and student_marks <= 100): +if student_marks >= 90 and student_marks <= 100: print(f"{student_marks}% Excellent") -elif(student_marks >= 80 and student_marks < 90): +elif student_marks >= 80 and student_marks < 90: print(f"{student_marks}% Grade A") -elif(student_marks >= 70 and student_marks < 80): +elif student_marks >= 70 and student_marks < 80: print(f"{student_marks}% Grade C") -elif(student_marks >= 60 and student_marks < 70): +elif student_marks >= 60 and student_marks < 70: print(f"{student_marks}% Grade D") -elif(student_marks <= 50): +elif student_marks <= 50: print(f"{student_marks}% You Failed") else: print(" Invalid Try again") @@ -108,8 +109,8 @@ """QuestionNo6. Write a program to find out whether a given post is talking about "Harry" or not.""" post_content = input("Enter Your Post : ").split(" ") -if("harry".lower() in post_content.lower()): +if "harry".lower() in post_content.lower(): result = "Yes Present" else: result = "No Not-Present" -print(post_content) \ No newline at end of file +print(post_content) diff --git a/basics/04_functions/01_functions_basics.py b/basics/04_functions/01_functions_basics.py index 8814f8b..f2a5406 100644 --- a/basics/04_functions/01_functions_basics.py +++ b/basics/04_functions/01_functions_basics.py @@ -5,5 +5,6 @@ def add(): total = first_number + second_number print(total) + for iteration in range(1, 6): add() diff --git a/basics/04_functions/02_arguments_return.py b/basics/04_functions/02_arguments_return.py index a155d34..e927a5e 100644 --- a/basics/04_functions/02_arguments_return.py +++ b/basics/04_functions/02_arguments_return.py @@ -1,8 +1,9 @@ -#Function With Arguments and Using of Return +# Function With Arguments and Using of Return def avg(first_num, second_num, message): total = first_num + second_num return f"{total} {message}" + result = avg(message="kidding", first_num=3, second_num=4) print(result) diff --git a/basics/04_functions/03_find_greatest.py b/basics/04_functions/03_find_greatest.py index f1eaf93..d69ef23 100644 --- a/basics/04_functions/03_find_greatest.py +++ b/basics/04_functions/03_find_greatest.py @@ -9,13 +9,15 @@ def greatest(first_num, second_num, third_num): return f"{third_num} is Greater among {first_num} and {second_num}" else: return f"Invalid Numbers : {first_num}{second_num}{third_num} " + + count = 0 numbers_list = [] while True: number = int(input("Enter the Numbers : ")) numbers_list.append(number) count += 1 - if(count == 3): + if count == 3: break print(f"ok! I Found Your Numbers : {numbers_list}") first_num = numbers_list[0] @@ -23,5 +25,3 @@ def greatest(first_num, second_num, third_num): third_num = numbers_list[2] result = greatest(first_num, second_num, third_num) print(f"{result}") - - diff --git a/basics/04_functions/04_print_pattern.py b/basics/04_functions/04_print_pattern.py index f4b4279..788df46 100644 --- a/basics/04_functions/04_print_pattern.py +++ b/basics/04_functions/04_print_pattern.py @@ -1,18 +1,21 @@ -''' +""" Write a python function to print first n lines of the following pattern: *** ** --> for n = 3 * -''' +""" + # Type1 def pattern_recursive(rows): - if(rows == 0): + if rows == 0: return else: print("*" * rows) pattern_recursive(rows - 1) + + result = pattern_recursive(3) @@ -21,12 +24,7 @@ def pattern_iterative(total_rows): for row in range(1, total_rows + 1): print(f"*" * ((total_rows + 1) - row)) + total_rows = int(input("Enter the 'n' : ")) pattern_iterative(total_rows) - - - - - - \ No newline at end of file diff --git a/basics/04_functions/05_print_table.py b/basics/04_functions/05_print_table.py index 0d608ae..30558a9 100644 --- a/basics/04_functions/05_print_table.py +++ b/basics/04_functions/05_print_table.py @@ -1,9 +1,9 @@ # Write a python function to print multiplication table of a given number. def print_table(number): multiplier = 1 - while (multiplier < 11): - print (f"{number} * {multiplier} = {number * multiplier} ") + while multiplier < 11: + print(f"{number} * {multiplier} = {number * multiplier} ") multiplier += 1 -print_table(number=3) \ No newline at end of file +print_table(number=3) diff --git a/basics/04_functions/06_default_arguments.py b/basics/04_functions/06_default_arguments.py index 350b021..2599618 100644 --- a/basics/04_functions/06_default_arguments.py +++ b/basics/04_functions/06_default_arguments.py @@ -1,8 +1,9 @@ -#Default Arguments +# Default Arguments def sum(first_num, second_num, message="All is Well"): total = first_num + second_num return f"Your Sum is : {total} and {message}" -result = (sum(24, 36)) -print(result) \ No newline at end of file + +result = sum(24, 36) +print(result) diff --git a/basics/04_functions/08_sum_while.py b/basics/04_functions/08_sum_while.py index 6d44443..b974e1e 100644 --- a/basics/04_functions/08_sum_while.py +++ b/basics/04_functions/08_sum_while.py @@ -3,7 +3,7 @@ limit = int(input("Enter the Number : ")) counter = 1 total_sum = 0 -while(counter < limit + 1): +while counter < limit + 1: total_sum += counter counter += 1 -print(total_sum) \ No newline at end of file +print(total_sum) diff --git a/basics/04_functions/11_factorial_recursive.py b/basics/04_functions/11_factorial_recursive.py index 21fce71..fdb18af 100644 --- a/basics/04_functions/11_factorial_recursive.py +++ b/basics/04_functions/11_factorial_recursive.py @@ -1,10 +1,10 @@ # Factorial Number def factorial(n): - if(n == 0 or n == 1): + if n == 0 or n == 1: return 1 else: return n * factorial(n - 1) -result = factorial(n = int(input("Enter a Number : "))) +result = factorial(n=int(input("Enter a Number : "))) print(result) diff --git a/basics/05_data_structures/01_list_basics.py b/basics/05_data_structures/01_list_basics.py index d166b6f..641cb36 100644 --- a/basics/05_data_structures/01_list_basics.py +++ b/basics/05_data_structures/01_list_basics.py @@ -1,8 +1,9 @@ -#Lists -foods_list = ["biriyani","Panner",200,False,12,True,439895487.54879954,23.222,90,"ramji-krishnaji"] #Lists are mutable -print(foods_list[0]) #Print the first item from the list +# Lists +foods_list = ["biriyani", "Panner", 200, False, 12, True, 439895487.54879954, + 23.222, 90, "ramji-krishnaji"] # Lists are mutable +print(foods_list[0]) # Print the first item from the list -#Mutability Check +# Mutability Check foods_list[0] = "radheradhe" print(foods_list) """ @@ -10,8 +11,8 @@ """ # Strings food_string = "ramji" -print(food_string[0]) #Print the first item from the String +print(food_string[0]) # Print the first item from the String -#Immutability Check -food_string[0] = "radhe2radhe" #error +# Immutability Check +food_string[0] = "radhe2radhe" # error print(food_string) diff --git a/basics/05_data_structures/02_list_fruits.py b/basics/05_data_structures/02_list_fruits.py index fa795d9..670deb6 100644 --- a/basics/05_data_structures/02_list_fruits.py +++ b/basics/05_data_structures/02_list_fruits.py @@ -1,9 +1,8 @@ -#1. Write a program to store a fruit in a list entered by the user. -fruit_name = input("Enter a Fruit Name : ") #User input the 7 fruits -fruits_list = [] #Creates a Blank list -fruits_list.append(fruit_name) #Append the userinput fruits in the empty list -print(fruits_list) #Print the list - +# 1. Write a program to store a fruit in a list entered by the user. +fruit_name = input("Enter a Fruit Name : ") # User input the 7 fruits +fruits_list = [] # Creates a Blank list +fruits_list.append(fruit_name) # Append the userinput fruits in the empty list +print(fruits_list) # Print the list # 2. Write a program to store seven fruits in a list entered by the user. @@ -23,4 +22,3 @@ fruits_list.append(fruit6) fruits_list.append(fruit7) print(fruits_list) - diff --git a/basics/05_data_structures/03_list_sum.py b/basics/05_data_structures/03_list_sum.py index 6e0de54..293076d 100644 --- a/basics/05_data_structures/03_list_sum.py +++ b/basics/05_data_structures/03_list_sum.py @@ -1,20 +1,20 @@ # Write a program to sum a list with 4 numbers. -#Complex Method +# Complex Method -numbers_list = [12,12,12,34] #Empty List +numbers_list = [12, 12, 12, 34] # Empty List """ Pop each element and return its value & simultaneouly store for all four numbers and store in addlist Variable """ sum_result = numbers_list.pop() + numbers_list.pop() + numbers_list.pop() + numbers_list.pop() -print(f"Sum of Elements : {sum_result}") #Print Addlist Variable -print(numbers_list) #Print the Original List +print(f"Sum of Elements : {sum_result}") # Print Addlist Variable +print(numbers_list) # Print the Original List # Or -#Simple Build-In-Method +# Simple Build-In-Method -numbers_list = [12,12,12,12,12] +numbers_list = [12, 12, 12, 12, 12] print(sum(numbers_list)) diff --git a/basics/05_data_structures/04_list_remove.py b/basics/05_data_structures/04_list_remove.py index 56c0469..e2f13a8 100644 --- a/basics/05_data_structures/04_list_remove.py +++ b/basics/05_data_structures/04_list_remove.py @@ -3,6 +3,7 @@ time. """ + def remove_and_strip(string_list, word): cleaned_list = [] for item in string_list: @@ -11,5 +12,5 @@ def remove_and_strip(string_list, word): return cleaned_list -string_list = ["Ram","Shyam","Gyan",'Pyan',"Myan","an"] -print(remove_and_strip(string_list, "an")) \ No newline at end of file +string_list = ["Ram", "Shyam", "Gyan", 'Pyan', "Myan", "an"] +print(remove_and_strip(string_list, "an")) diff --git a/basics/05_data_structures/05_list_slicing.py b/basics/05_data_structures/05_list_slicing.py index aa867b8..5d57921 100644 --- a/basics/05_data_structures/05_list_slicing.py +++ b/basics/05_data_structures/05_list_slicing.py @@ -1,14 +1,12 @@ -#List Slicing Questions - -numbers_list = [10, 20, 30, 40, 50, 60, 70] #QuestionNo1 -print(numbers_list[5:1:-1]) #[60,50,40,30] -print(numbers_list[-2:2:-2]) #[60,40] -print(numbers_list[100:]) #Blank - -numbers_list = [1, 2, 3, 4, 5] #QuestionNo2 -numbers_list[1:4] = [20, 30]#SubQuestion1 -print(numbers_list) #[1,20,30,5] -numbers_list[::2] = [100, 200, 300]#SubQuestion2 -print(numbers_list) #[100,200,300,4,5] - - +# List Slicing Questions + +numbers_list = [10, 20, 30, 40, 50, 60, 70] # QuestionNo1 +print(numbers_list[5:1:-1]) # [60, 50, 40, 30] +print(numbers_list[-2:2:-2]) # [60, 40] +print(numbers_list[100:]) # Blank + +numbers_list = [1, 2, 3, 4, 5] # QuestionNo2 +numbers_list[1:4] = [20, 30] # SubQuestion1 +print(numbers_list) # [1, 20, 30, 5] +numbers_list[::2] = [100, 200, 300] # SubQuestion2 +print(numbers_list) # [100, 200, 300, 4, 5] diff --git a/basics/05_data_structures/07_list_comp_table.py b/basics/05_data_structures/07_list_comp_table.py index 3e2cfbc..dba9afb 100644 --- a/basics/05_data_structures/07_list_comp_table.py +++ b/basics/05_data_structures/07_list_comp_table.py @@ -5,4 +5,4 @@ number = int(input("Enter the n : ")) multiplication_table = [multiplier * number for multiplier in range(11)] -print(f"{multiplication_table}") \ No newline at end of file +print(f"{multiplication_table}") diff --git a/basics/05_data_structures/08_list_join.py b/basics/05_data_structures/08_list_join.py index f76970a..ebf627c 100644 --- a/basics/05_data_structures/08_list_join.py +++ b/basics/05_data_structures/08_list_join.py @@ -1,3 +1,3 @@ -fruits_list = ["Apple","Banana","Mango","Orange","Watermelon"] +fruits_list = ["Apple", "Banana", "Mango", "Orange", "Watermelon"] result = ",".join(fruits_list) -print(result,type(result)) \ No newline at end of file +print(result, type(result)) diff --git a/basics/05_data_structures/09_list_methods.py b/basics/05_data_structures/09_list_methods.py index 3cb3bdc..7199dcb 100644 --- a/basics/05_data_structures/09_list_methods.py +++ b/basics/05_data_structures/09_list_methods.py @@ -1,12 +1,13 @@ -#List Methods -string_list = ["ram","gyan",1111.222,444,"33","Ramit sioeo","ram","ram"] -string_list.append("sita gita") #Append object to the end of the list. -count_result = string_list.count("ram")#Return number of occurrences of value. -string_list.extend("slice")#Extend list by appending elements from the iterable. -index_result = string_list.index("ram") #Return first index of value. -string_list.insert(1,"sita")#Insert object before index. -popped_item = string_list.pop(2)#Remove and return item at index (default last). -string_list.remove("ram") #Remove first occurrence of value. -string_list.reverse() #reverse the list -string_list.sort() #Sort the list in ascending order and return None. -print(count_result, index_result, string_list, popped_item) #print and return value (if possible) \ No newline at end of file +# List Methods +string_list = ["ram", "gyan", 1111.222, 444, "33", "Ramit sioeo", "ram", "ram"] +string_list.append("sita gita") # Append object to the end of the list. +count_result = string_list.count("ram") # Return number of occurrences of value. +string_list.extend( + "slice") # Extend list by appending elements from the iterable. +index_result = string_list.index("ram") # Return first index of value. +string_list.insert(1, "sita") # Insert object before index. +popped_item = string_list.pop(2) # Remove and return item at index (default last). +string_list.remove("ram") # Remove first occurrence of value. +string_list.reverse() # reverse the list +string_list.sort() # Sort the list in ascending order and return None. +print(count_result, index_result, string_list, popped_item) # print and return value (if possible) diff --git a/basics/05_data_structures/10_tuple_immutability.py b/basics/05_data_structures/10_tuple_immutability.py index 86431c3..abc7a35 100644 --- a/basics/05_data_structures/10_tuple_immutability.py +++ b/basics/05_data_structures/10_tuple_immutability.py @@ -1,4 +1,4 @@ # Check that a tuple type cannot be changed in python -immutable_tuple = ("ram",False,True,222.222) -immutable_tuple[2] = 23 #Error of 'tuple' object does not support item assignment \ No newline at end of file +immutable_tuple = ("ram", False, True, 222.222) +immutable_tuple[2] = 23 # Error of 'tuple' object does not support item assignment diff --git a/basics/05_data_structures/11_tuple_methods.py b/basics/05_data_structures/11_tuple_methods.py index 157df5f..f5d7074 100644 --- a/basics/05_data_structures/11_tuple_methods.py +++ b/basics/05_data_structures/11_tuple_methods.py @@ -1,13 +1,12 @@ """ Tuple """ -empty_tuple = () #Blank Tuple -print(type(empty_tuple)) #Check the type of the variable -print(empty_tuple) #Prints the Blank Tuple +empty_tuple = () # Blank Tuple +print(type(empty_tuple)) # Check the type of the variable +print(empty_tuple) # Prints the Blank Tuple - -tuple1 = ("Hello","12345",False,"Ram","Ram") #tuple1 -tuple2 = (1222.22,False,24224.4224,"String") #tuple2 -print(tuple1.count("Hello")) #--> Return number of occurrences of value. -print(tuple1.index("Ram")) #-->Return first index of value. -print(len(tuple1)) #-->Return the number of items in a container. -print(tuple1 + tuple2) #-->Concatenation of two tuples \ No newline at end of file +tuple1 = ("Hello", "12345", False, "Ram", "Ram") # tuple1 +tuple2 = (1222.22, False, 24224.4224, "String") # tuple2 +print(tuple1.count("Hello")) # --> Return number of occurrences of value. +print(tuple1.index("Ram")) # -->Return first index of value. +print(len(tuple1)) # -->Return the number of items in a container. +print(tuple1 + tuple2) # -->Concatenation of two tuples diff --git a/basics/05_data_structures/12_set_unique.py b/basics/05_data_structures/12_set_unique.py index 656b98a..868392d 100644 --- a/basics/05_data_structures/12_set_unique.py +++ b/basics/05_data_structures/12_set_unique.py @@ -1,7 +1,7 @@ -#Write a program to input eight numbers from the user and display all the unique numbers (once). +# Write a program to input eight numbers from the user and display all the unique numbers (once). -unique_numbers_set = set() #Empty Set -user_input = input("Enter 8 Numbers :") #Takes Input +unique_numbers_set = set() # Empty Set +user_input = input("Enter 8 Numbers :") # Takes Input number = user_input.split(" ").pop(0) unique_numbers_set.add(number) number = user_input.split(" ").pop(1) @@ -18,6 +18,6 @@ unique_numbers_set.add(number) number = user_input.split(" ").pop(7) unique_numbers_set.add(number) -print(unique_numbers_set) #print the Updated Set +print(unique_numbers_set) # print the Updated Set diff --git a/basics/05_data_structures/13_set_values.py b/basics/05_data_structures/13_set_values.py index 65b86ba..bd70014 100644 --- a/basics/05_data_structures/13_set_values.py +++ b/basics/05_data_structures/13_set_values.py @@ -1,11 +1,11 @@ -'''Question1.What will be the length of following set s: +"""Question1.What will be the length of following set s: s = set() s.add(20) s.add(20.0) -s.add('20') # length of s after these operations?''' +s.add('20') # length of s after these operations?""" unique_set = set() unique_set.add(20) unique_set.add(20.0) unique_set.add('20') -print(len(unique_set), unique_set) #length will be 2 as both float and integer cant be assign (unique) +print(len(unique_set), unique_set) # length will be 2 as both float and integer cant be assign (unique) diff --git a/basics/05_data_structures/14_sets_basics.py b/basics/05_data_structures/14_sets_basics.py index edfda80..23aebbf 100644 --- a/basics/05_data_structures/14_sets_basics.py +++ b/basics/05_data_structures/14_sets_basics.py @@ -6,10 +6,9 @@ 4. There is no way to change items in sets. """ - -numbers_set = {12,2,32,3} #--> Set -print(type(numbers_set)) #Print the type of variable +numbers_set = {12, 2, 32, 3} #--> Set +print(type(numbers_set)) #Print the type of variable # For Empty Set -numbers_set = set() #--Empty Set Created -print(type(numbers_set)) #Print the type of variable \ No newline at end of file +numbers_set = set() #--Empty Set Created +print(type(numbers_set)) #Print the type of variable diff --git a/basics/05_data_structures/15_set_methods.py b/basics/05_data_structures/15_set_methods.py index bb4c3fb..33afc54 100644 --- a/basics/05_data_structures/15_set_methods.py +++ b/basics/05_data_structures/15_set_methods.py @@ -32,7 +32,3 @@ set1.update(set2, set3, set4) # Add all elements from other sets print(set1) # Print the final set - - - - diff --git a/basics/05_data_structures/16_dict_basics.py b/basics/05_data_structures/16_dict_basics.py index afdee7c..a7f66b9 100644 --- a/basics/05_data_structures/16_dict_basics.py +++ b/basics/05_data_structures/16_dict_basics.py @@ -12,7 +12,7 @@ print(dictionary_data.items()) # View all key-value pairs print(dictionary_data["l1"]) # Access value by key print(dictionary_data.keys()) # Get all keys -print(dictionary_data.values()) # Get all values +print(dictionary_data.values()) # Get all values print(dictionary_data.get("Rama")) # Safe access (returns None if key missing) dictionary_data.update({"Ram": 33.333}) # Update existing key @@ -26,4 +26,4 @@ print(dictionary_data.setdefault(("Stunt", 12422))) print(dictionary_data.clear()) # Remove all items -print(dictionary_data) # Print the dictionary \ No newline at end of file +print(dictionary_data) # Print the dictionary diff --git a/basics/05_data_structures/17_dict_friends.py b/basics/05_data_structures/17_dict_friends.py index f9e1d2c..d212520 100644 --- a/basics/05_data_structures/17_dict_friends.py +++ b/basics/05_data_structures/17_dict_friends.py @@ -1,5 +1,5 @@ -'''Question1.Create an empty dictionary. Allow 4 friends to enter their favorite language as -value and use key as their names. Assume that the names are unique.''' +"""Question1.Create an empty dictionary. Allow 4 friends to enter their favorite language as +value and use key as their names. Assume that the names are unique.""" # Answer Type 1 friends_languages = {} @@ -35,9 +35,9 @@ shyam_language = input("Enter your Favourite Programming Language : ") gita_language = input("Enter your Favourite Programming Language : ") ritu_language = input("Enter your Favourite Programming Language : ") -friends_languages = {"Ram":None,"Shyam":None,"Gita":None,"Ritu":None} -friends_languages.update({'Ram':ram_language}) -friends_languages.update({'Shyam':shyam_language}) -friends_languages.update({'Gita':gita_language}) -friends_languages.update({'Ritu':ritu_language}) -print(friends_languages) \ No newline at end of file +friends_languages = {"Ram": None, "Shyam": None, "Gita": None, "Ritu": None} +friends_languages.update({'Ram': ram_language}) +friends_languages.update({'Shyam': shyam_language}) +friends_languages.update({'Gita': gita_language}) +friends_languages.update({'Ritu': ritu_language}) +print(friends_languages) diff --git a/basics/05_data_structures/18_dict_translator.py b/basics/05_data_structures/18_dict_translator.py index c60e54e..5135f01 100644 --- a/basics/05_data_structures/18_dict_translator.py +++ b/basics/05_data_structures/18_dict_translator.py @@ -3,16 +3,16 @@ # Concept 1 to do : (easy to understand) " Takes two input() from user " -hindi_english_dict = {"Bhagwaan":"God","Kalyan":"Growth","Seb":"Apple","Kela":"Banana","Tufan ka Devta":"God of Thunder ? Thor"} +hindi_english_dict = {"Bhagwaan": "God", "Kalyan": "Growth", "Seb": "Apple", "Kela": "Banana", "Tufan ka Devta": "God of Thunder ? Thor"} hindi_word = input("Enter a Hindi Word : ") english_word = input("Enter the English word for that hindi Word : ") -hindi_english_dict.update({hindi_word:english_word}) +hindi_english_dict.update({hindi_word: english_word}) print(hindi_english_dict) # Concept 2 to do :(complex) " Takes Single input but takes both hindi-english translation words" -hindi_english_dict = {"Bhagwaan":"God","Kalyan":"Growth","Seb":"Apple","Kela":"Banana","Tufan ka Devta":"God of Thunder ? Thor"} # A Dictionary +hindi_english_dict = {"Bhagwaan": "God", "Kalyan": "Growth", "Seb": "Apple", "Kela": "Banana", "Tufan ka Devta": "God of Thunder ? Thor"} # A Dictionary user_input = input("Enter a Hindi Word and also give its English translation : ") #Takes input() from user -hindi_word = user_input.split(" ").pop(0) #if the user gives "ram" and "shyam" then this split make it list of strings then the pop() delete the first element and return it and we just capture that return value and store it in a variable -english_word = user_input.split(" ").pop(1) #same for second variable -hindi_english_dict.update({hindi_word:english_word}) #Just put the stored values in the update position -print(hindi_english_dict) #Print the dictionary +hindi_word = user_input.split(" ").pop(0) # if the user gives "ram" and "shyam" then this split make it list of strings then the pop() delete the first element and return it and we just capture that return value and store it in a variable +english_word = user_input.split(" ").pop(1) # same for second variable +hindi_english_dict.update({hindi_word: english_word}) # Just put the stored values in the update position +print(hindi_english_dict) # Print the dictionary diff --git a/basics/05_data_structures/19_enumerate.py b/basics/05_data_structures/19_enumerate.py index 995c267..7989a85 100644 --- a/basics/05_data_structures/19_enumerate.py +++ b/basics/05_data_structures/19_enumerate.py @@ -1,5 +1,5 @@ -#Before Using emumerate -items_list = ["Hello",23,False,True,45,"Ram"] +# Before Using emumerate +items_list = ["Hello", 23, False, True, 45, "Ram"] index = 0 for item in items_list: print(f"The item number at index {index} is {item}") @@ -9,4 +9,3 @@ for index, item in enumerate(items_list): print(f"The item number at index {index} is {item}") - diff --git a/basics/05_data_structures/20_enumerate_examples.py b/basics/05_data_structures/20_enumerate_examples.py index d1f6a31..32c5f7b 100644 --- a/basics/05_data_structures/20_enumerate_examples.py +++ b/basics/05_data_structures/20_enumerate_examples.py @@ -3,7 +3,7 @@ function. """ -items_list = [12,23,45,"Hello","Raj Shamani","Mr Beast","Virat kohli","Dhoni","Ben 10"] +items_list = [12, 23, 45, "Hello", "Raj Shamani", "Mr Beast", "Virat kohli", "Dhoni", "Ben 10"] for index, item in enumerate(items_list): if index == 2 or index == 4 or index == 6: - print(f"Index : {index},Values : {item}") \ No newline at end of file + print(f"Index : {index}, Values : {item}") diff --git a/basics/05_data_structures/21_tuple_count.py b/basics/05_data_structures/21_tuple_count.py index 6a5f6af..eb6c6db 100644 --- a/basics/05_data_structures/21_tuple_count.py +++ b/basics/05_data_structures/21_tuple_count.py @@ -1,5 +1,5 @@ # Write a program to count the number of zeros in the following tuple: -#Simple Method -zero_count = (7, 0, 8, 0, 0, 9).count(0) # Variable "a" contains a tuple of numbers , and use count method to count Zeros -print(zero_count) #Print the sum +# Simple Method +zero_count = (7, 0, 8, 0, 0, 9).count(0) # Variable "a" contains a tuple of numbers, and use count method to count Zeros +print(zero_count) # Print the sum diff --git a/basics/05_data_structures/31_weather_logger.py b/basics/05_data_structures/31_weather_logger.py index 3f09ba6..394b781 100644 --- a/basics/05_data_structures/31_weather_logger.py +++ b/basics/05_data_structures/31_weather_logger.py @@ -2,6 +2,7 @@ import asyncio from datetime import datetime + async def main() -> None: """ Main function to: @@ -47,5 +48,6 @@ async def main() -> None: print(f"The hottest day was {hottest_day}") print(f"The average temperature is {avg_temp:.2f}°F") # formatted to 2 decimals + if __name__ == '__main__': asyncio.run(main()) diff --git a/basics/06_strings/01_greet_input.py b/basics/06_strings/01_greet_input.py index 63fe187..65121c3 100644 --- a/basics/06_strings/01_greet_input.py +++ b/basics/06_strings/01_greet_input.py @@ -1,4 +1,4 @@ # Write a python program to display a user entered name followed by Good Afternoon using input () function. -name=input("Enter Your Name : ") #takes user input -print(f"Good Afternoon {name}") #print the name with Good Afternoon \ No newline at end of file +name = input("Enter Your Name : ") # takes user input +print(f"Good Afternoon {name}") # print the name with Good Afternoon diff --git a/basics/06_strings/02_string_methods.py b/basics/06_strings/02_string_methods.py index 13064de..86fa149 100644 --- a/basics/06_strings/02_string_methods.py +++ b/basics/06_strings/02_string_methods.py @@ -1,15 +1,15 @@ -#String Functions +# String Functions name = "ram is a good good Boy 2323" -print(name.capitalize()) #Make the first letter of the word uppercase -print(name.count("good")) #Counts the given string -print(name.endswith("Boy")) #check that the given String ends with Boy or not -print(name.startswith("Ram")) #check that the given String Starts with Ram or not -print(name.find("good")) #return the index of the first occurence of the given Str -print(name.index("good")) #return the index of the first occurence of the given Str -print(name.isalnum()) #check the given string is alpha-numeric or not -print(name.isspace()) #if the str is empty and minimum there will be one character then return true else false -print(name.upper()) #Return a copy of the string converted to uppercase. -print(name.title()) #Return a version of the string where each word is titlecased -print(name.split()) #Return a list of the substrings in the string, using sep as the separator string. -print(name.isupper()) #Return True if the string is an uppercase string, False otherwise. +print(name.capitalize()) # Make the first letter of the word uppercase +print(name.count("good")) # Counts the given string +print(name.endswith("Boy")) # check that the given String ends with Boy or not +print(name.startswith("Ram")) # check that the given String Starts with Ram or not +print(name.find("good")) # return the index of the first occurence of the given Str +print(name.index("good")) # return the index of the first occurence of the given Str +print(name.isalnum()) # check the given string is alpha-numeric or not +print(name.isspace()) # if the str is empty and minimum there will be one character then return true else false +print(name.upper()) # Return a copy of the string converted to uppercase. +print(name.title()) # Return a version of the string where each word is titlecased +print(name.split()) # Return a list of the substrings in the string, using sep as the separator string. +print(name.isupper()) # Return True if the string is an uppercase string, False otherwise. diff --git a/basics/06_strings/03_string_format.py b/basics/06_strings/03_string_format.py index 17ba122..993acca 100644 --- a/basics/06_strings/03_string_format.py +++ b/basics/06_strings/03_string_format.py @@ -1,7 +1,7 @@ -''' +""" Formats the values inside the string into a desired output. template.format(p1,p2...) -''' +""" -print("{} is a Good boy and {} is a Bad boy".format("Raghav","Rajesh")) -print("{} is my friend and {} loves me alot".format("X","Y")) \ No newline at end of file +print("{} is a Good boy and {} is a Bad boy".format("Raghav", "Rajesh")) +print("{} is my friend and {} loves me alot".format("X", "Y")) diff --git a/basics/06_strings/04_string_slicing.py b/basics/06_strings/04_string_slicing.py index ba0241e..01cb07e 100644 --- a/basics/06_strings/04_string_slicing.py +++ b/basics/06_strings/04_string_slicing.py @@ -1,16 +1,16 @@ # String-Slicing text_string = "Hello World" -print(text_string[-5:-1]) #Worl -print(text_string[6:10]) #Worl +print(text_string[-5:-1]) # Worl +print(text_string[6:10]) # Worl -print(text_string[:]) #Prints the Whole String -print(text_string[:10]) #If in the beginning there is blank then consider as Zero -print(text_string[0:]) #If in the end there is blank then consider as len-1 +print(text_string[:]) # Prints the Whole String +print(text_string[:10]) # If in the beginning there is blank then consider as Zero +print(text_string[0:]) # If in the end there is blank then consider as len-1 -#With Skip -print(text_string[::2]) #HloWrd -print(text_string[2:-1:-3]) #Blank -print(text_string[::4]) #Hor +# With Skip +print(text_string[::2]) # HloWrd +print(text_string[2:-1:-3]) # Blank +print(text_string[::4]) # Hor diff --git a/basics/06_strings/05_string_slicing_practice.py b/basics/06_strings/05_string_slicing_practice.py index 7c8b60e..9cbd26b 100644 --- a/basics/06_strings/05_string_slicing_practice.py +++ b/basics/06_strings/05_string_slicing_practice.py @@ -1,10 +1,10 @@ text_string = "Programming is awesome and challenging!" -print(text_string[2:15:2]) #ormigi -print(text_string[-8:-2:2]) #lnig -print(text_string[::4]) #priiwmnhen -print(text_string[25:5:-4]) #deesn -print(text_string[-1:-20:-3]) #!iea am -print(text_string[12::-2]) #igimrop -print(text_string[-5:8:-1]) #gnellahc dna emosewa si gn -print(text_string[1::5][::-2]) #blank \ No newline at end of file +print(text_string[2:15:2]) # ormigi +print(text_string[-8:-2:2]) # lnig +print(text_string[::4]) # priiwmnhen +print(text_string[25:5:-4]) # deesn +print(text_string[-1:-20:-3]) # !iea am +print(text_string[12::-2]) # igimrop +print(text_string[-5:8:-1]) # gnellahc dna emosewa si gn +print(text_string[1::5][::-2]) # blank \ No newline at end of file diff --git a/basics/06_strings/06_letter_template.py b/basics/06_strings/06_letter_template.py index 1503bc8..81cdd8e 100644 --- a/basics/06_strings/06_letter_template.py +++ b/basics/06_strings/06_letter_template.py @@ -12,8 +12,8 @@ ''' name_replaced = letter_template.replace("<|Name|>", user_name) date_replaced = name_replaced.replace("<|Date|>", date) -name_length = len(user_name) # Count for name length -final_count = 25 + name_length # Count for name +name_length = len(user_name) # Count for name length +final_count = 25 + name_length # Count for name output_start = name_replaced[:final_count] output_end = date_replaced[final_count:] # print(output_end) diff --git a/basics/06_strings/07_doublespace.py b/basics/06_strings/07_doublespace.py index 942bbea..1977f5a 100644 --- a/basics/06_strings/07_doublespace.py +++ b/basics/06_strings/07_doublespace.py @@ -1,24 +1,21 @@ # 1.Write a program to detect double space in a string. -string = input("Enter a String : ") #UserInput - +string = input("Enter a String : ") # UserInput """if it returns -1 means there is no double space in the given string but, if there is double space it returns teh index of the double space""" -print(string.find(" ")) - - -#2.Write a program to Detect and Count double space in a string. - -string1 = input("Enter a String : ") #UserInput -finaloutput = string1.count(" ") #Counts the Spaces +print(string.find(" ")) +# 2.Write a program to Detect and Count double space in a string. -#Print how many double-spaces occur's in the user-defined string1. -print(f"In Your String there is {finaloutput} double Spaces !") +string1 = input("Enter a String : ") # UserInput +finaloutput = string1.count(" ") # Counts the Spaces +# Print how many double-spaces occur's in the user-defined string1. +print(f"In Your String there is {finaloutput} double Spaces !") -#3.Replace the double space from problem 3 with single spaces. +# 3.Replace the double space from problem 3 with single spaces. -string1 = input("Enter a String : ") #UserInput -finaloutput = string1.replace(" "," ") #Counts the double spaces and replace with single Spaces -print(finaloutput) #Prints the output \ No newline at end of file +string1 = input("Enter a String : ") # UserInput +finaloutput = string1.replace(" ", + " ") # Counts the double spaces and replace with single Spaces +print(finaloutput) # Prints the output diff --git a/basics/06_strings/09_join_challenge.py b/basics/06_strings/09_join_challenge.py index 619ed68..8546b29 100644 --- a/basics/06_strings/09_join_challenge.py +++ b/basics/06_strings/09_join_challenge.py @@ -5,4 +5,4 @@ multiplication_table = [str(7 * multiplier) for multiplier in range(1, 11)] vertical_string = f"\n".join(multiplication_table) -print(vertical_string) \ No newline at end of file +print(vertical_string) diff --git a/basics/07_file_handling/02_file_readlines.py b/basics/07_file_handling/02_file_readlines.py index 870084a..b28f314 100644 --- a/basics/07_file_handling/02_file_readlines.py +++ b/basics/07_file_handling/02_file_readlines.py @@ -22,4 +22,3 @@ all_lines = file_handle.readlines() print(all_lines) file_handle.close() - diff --git a/basics/07_file_handling/03_file_multiple.py b/basics/07_file_handling/03_file_multiple.py index 434346c..0d53a74 100644 --- a/basics/07_file_handling/03_file_multiple.py +++ b/basics/07_file_handling/03_file_multiple.py @@ -10,5 +10,3 @@ pass except FileNotFoundError: print("\n\t\t\t\t\tFile Not Found\n") - - diff --git a/basics/07_file_handling/04_file_numbers.py b/basics/07_file_handling/04_file_numbers.py index aa966f0..0a50993 100644 --- a/basics/07_file_handling/04_file_numbers.py +++ b/basics/07_file_handling/04_file_numbers.py @@ -8,5 +8,3 @@ with open("Tables.py") as read_file: print(read_file.read()) - - diff --git a/basics/07_file_handling/07_file_find_word.py b/basics/07_file_handling/07_file_find_word.py index b216cd9..12c186c 100644 --- a/basics/07_file_handling/07_file_find_word.py +++ b/basics/07_file_handling/07_file_find_word.py @@ -10,9 +10,3 @@ print(f"Twinkle Found {word_count} times") else: print("Twinkle not Found") - - - - - - diff --git a/basics/07_file_handling/08_file_search_log.py b/basics/07_file_handling/08_file_search_log.py index 2480907..3617470 100644 --- a/basics/07_file_handling/08_file_search_log.py +++ b/basics/07_file_handling/08_file_search_log.py @@ -25,4 +25,4 @@ [INFO] User logged in [ERROR] python module failed to load [INFO] System shutting down -""" \ No newline at end of file +""" diff --git a/basics/07_file_handling/09_file_delete.py b/basics/07_file_handling/09_file_delete.py index 0d7b6de..f0678c1 100644 --- a/basics/07_file_handling/09_file_delete.py +++ b/basics/07_file_handling/09_file_delete.py @@ -1,4 +1,5 @@ """Write a program to wipe out the content of a file using python.""" with open("write.txt", "w") as file_handle: - file_handle.write("") \ No newline at end of file + file_handle.write("") + \ No newline at end of file diff --git a/basics/07_file_handling/11_file_copy.py b/basics/07_file_handling/11_file_copy.py index e2fd09d..c426396 100644 --- a/basics/07_file_handling/11_file_copy.py +++ b/basics/07_file_handling/11_file_copy.py @@ -7,14 +7,6 @@ def copy_file(source, destination): with open(destination, "w") as f: f.write(data) -copy_file("this.txt", "pcopy.txt") - - - - - - - - +copy_file("this.txt", "pcopy.txt") \ No newline at end of file diff --git a/basics/07_file_handling/12_file_replace.py b/basics/07_file_handling/12_file_replace.py index 2c36ed6..be7a6e2 100644 --- a/basics/07_file_handling/12_file_replace.py +++ b/basics/07_file_handling/12_file_replace.py @@ -20,5 +20,4 @@ People often underestimate the donkey, yet the donkey continues to work quietly without complaint. From farms to mountains, the donkey remains a loyal and useful animal. """ - \ No newline at end of file diff --git a/basics/07_file_handling/13_file_censor.py b/basics/07_file_handling/13_file_censor.py index 78cfe96..85a851e 100644 --- a/basics/07_file_handling/13_file_censor.py +++ b/basics/07_file_handling/13_file_censor.py @@ -21,6 +21,3 @@ but the donkey continued doing its job without complaining. Calling the effort lazy or foolish did not change how responsible the donkey really was. """ - - - diff --git a/basics/08_oop/02_class_calculator.py b/basics/08_oop/02_class_calculator.py index 91d567c..6aeba9e 100644 --- a/basics/08_oop/02_class_calculator.py +++ b/basics/08_oop/02_class_calculator.py @@ -2,6 +2,7 @@ 1. Write a class "Calculator" capable of finding square, cube and square root of a number. """ + class Calculator: def __init__(self, choose, num): self.choose = choose diff --git a/basics/08_oop/03_class_constructor.py b/basics/08_oop/03_class_constructor.py index affb68b..9306e01 100644 --- a/basics/08_oop/03_class_constructor.py +++ b/basics/08_oop/03_class_constructor.py @@ -3,18 +3,17 @@ class Animal: hand = 2 power = 100 - def __init__(self,strength,health,attack): #Dunder Method in Python Which is automatically Called + def __init__(self, strength, health, attack): # Dunder Method in Python Which is automatically Called self.strength = strength self.health = health self.attack = attack print(f"\n\tLoading ...") print(f"Strength is : {strength}\nHealth is : {health}\nAttack is : {attack}") - -Kangaroo = Animal(100,12,"100x") + + +Kangaroo = Animal(100, 12, "100x") """ a = int(input("Enter Your Strength ?/100 : ")) b = int(input("Enter Your Health ?/100 : ")) c = input("Enter Your Attack Name : ") """ - - diff --git a/basics/08_oop/05_class_programmer.py b/basics/08_oop/05_class_programmer.py index 850db5b..677d8db 100644 --- a/basics/08_oop/05_class_programmer.py +++ b/basics/08_oop/05_class_programmer.py @@ -7,7 +7,7 @@ class Programmer: Company = "Microsoft" Salary = 200000 - def __init__(self,name): + def __init__(self, name): self.name = name Rajvir = Programmer("Rajvir") diff --git a/basics/08_oop/07_operator_overloading.py b/basics/08_oop/07_operator_overloading.py index 514b26f..9d3b120 100644 --- a/basics/08_oop/07_operator_overloading.py +++ b/basics/08_oop/07_operator_overloading.py @@ -9,13 +9,15 @@ __len__() # used to set what gets displayed upon calling.__len__() or len(obj) """ -class Addition(): + +class Addition: def __init__(self, val): self.val = val def __add__(self, other): return self.val + other.val + first_number = Addition(1) second_number = Addition(9) print(first_number + second_number) diff --git a/basics/08_oop/08_oop_examples.py b/basics/08_oop/08_oop_examples.py index 6a6a1c1..e4eb631 100644 --- a/basics/08_oop/08_oop_examples.py +++ b/basics/08_oop/08_oop_examples.py @@ -1,4 +1,4 @@ -#Professional Coding +# Professional Coding class Monster(): # Class definition def __init__(self, power, health, speed): # Constructor to initialize object self._power = power # Private variable for power @@ -61,8 +61,7 @@ def Health(self, value): # Setter 3 for health print(f"Here is Your Health : {devil.Health} Power : {devil.Power} & Speed : {devil.Speed}\n") - -#Normal Coding +# Normal Coding """class Monster(): def __init__(self,Health,Power,Speed): self.health = Health diff --git a/basics/08_oop/10_inheritance_multilevel.py b/basics/08_oop/10_inheritance_multilevel.py index fceb798..00612ab 100644 --- a/basics/08_oop/10_inheritance_multilevel.py +++ b/basics/08_oop/10_inheritance_multilevel.py @@ -3,9 +3,11 @@ ‘Pets’. Add a method ‘bark’ to class ‘Dog’. """ -class Animals(): + +class Animals: pass + class Pets(Animals): pass diff --git a/basics/08_oop/11_inheritance_vector.py b/basics/08_oop/11_inheritance_vector.py index c5c6907..b2243e7 100644 --- a/basics/08_oop/11_inheritance_vector.py +++ b/basics/08_oop/11_inheritance_vector.py @@ -1,6 +1,8 @@ """ Create a class (Vector2d) and use it to create another class representing a Vector3d. """ + + class Vector2d: def __init__(self, number, value): self.number = number @@ -13,8 +15,6 @@ def value(self): else: print(f"------> None Value! \"Your Value Must be greater than 0\"") - - @value.setter def value(self, new_value): if new_value <= 0: @@ -23,16 +23,13 @@ def value(self, new_value): self._value = new_value - class Vector3d(Vector2d): - def __init__(self, number, value): - super().__init__(number, value) - if value < 0: - value = 0 - self.addition_result = number + value - print(f"Addition of {number} and {value} is {self.addition_result}") - - + def __init__(self, number, value): + super().__init__(number, value) + if value < 0: + value = 0 + self.addition_result = number + value + print(f"Addition of {number} and {value} is {self.addition_result}") vector_instance = Vector3d(12, -99) @@ -40,8 +37,4 @@ def __init__(self, number, value): vector_instance.value = 32 print("Updated Value : ", vector_instance.value) vector_instance.value = -9 -print("Value : " , vector_instance.value) - - - - +print("Value : ", vector_instance.value) diff --git a/basics/08_oop/12_inheritance_super.py b/basics/08_oop/12_inheritance_super.py index 2fb14f1..9af9293 100644 --- a/basics/08_oop/12_inheritance_super.py +++ b/basics/08_oop/12_inheritance_super.py @@ -1,14 +1,15 @@ -class LivingThings(): +class LivingThings: isLive = 122 def __init__(self): - super().__init__() #Call My Father (: (super().__init__() is used in a child class to call the constructor of its parent class so that parent class data members are initialized.) + super().__init__() # Call My Father (: (super().__init__() is used in a child class to call the constructor of its parent class so that parent class data members are initialized.) print(f"LivingThings Constructor Called ! ") - @classmethod #--->The @classmethod decorator is used to work with class variables (class values) using the class (cls) instead of instance variables (self).” + @classmethod # --->The @classmethod decorator is used to work with class variables (class values) using the class (cls) instead of instance variables (self).” def CanHearSound(self): print(f"We Are Hear Sound {self.isLive}") - + + class HumanBeings(LivingThings): def __init__(self): @@ -18,6 +19,7 @@ def __init__(self): def Intelligent(): print("Most Intelligent ? ") + class Animals(HumanBeings): def __init__(self): @@ -27,6 +29,7 @@ def __init__(self): def Powerful(): print("Powerful") + Ram = LivingThings() Ram.isLive = 12 -Ram.CanHearSound() \ No newline at end of file +Ram.CanHearSound() diff --git a/basics/08_oop/15_complex_numbers.py b/basics/08_oop/15_complex_numbers.py index 30db9e1..ba0c880 100644 --- a/basics/08_oop/15_complex_numbers.py +++ b/basics/08_oop/15_complex_numbers.py @@ -3,6 +3,7 @@ operators '+' and '*' which adds and multiplies them. """ + class Complex(): def __init__(self, real_part, imaginary_part): self.real_part = real_part @@ -14,6 +15,7 @@ def __add__(self, other_complex): def __str__(self): return f"{self.real_part} + {self.imaginary_part}i" + complex_number1 = Complex(1, 2) complex_number2 = Complex(3, 4) print(complex_number1 + complex_number2) diff --git a/basics/08_oop/16_salary_increment.py b/basics/08_oop/16_salary_increment.py index 444861d..d6ff212 100644 --- a/basics/08_oop/16_salary_increment.py +++ b/basics/08_oop/16_salary_increment.py @@ -5,8 +5,8 @@ """ -class Employee(): - def __init__(self,salary=0,increment=0): +class Employee: + def __init__(self, salary=0, increment=0): self._salary = salary self.increment = increment @@ -15,14 +15,14 @@ def SalaryAfterIncrement(self): return self._salary + (self._salary * (self.increment/100)) @SalaryAfterIncrement.setter - def SalaryAfterIncrement(self,real_salary): + def SalaryAfterIncrement(self, real_salary): if real_salary <= 5000: self.increment = 10 elif real_salary >= 20000 and real_salary < 50000: self.increment = 5 - elif real_salary >=50000: + elif real_salary >= 50000: self.increment = 2 else: @@ -31,16 +31,11 @@ def SalaryAfterIncrement(self,real_salary): self._salary = real_salary -#Output +# Output Rajesh = Employee() Rajesh.SalaryAfterIncrement = 50000 -print(Rajesh.SalaryAfterIncrement) #Output 51000 +print(Rajesh.SalaryAfterIncrement) # Output 51000 Rajesh.SalaryAfterIncrement = 5000 -print(Rajesh.SalaryAfterIncrement) #Output 5500 - - - - - +print(Rajesh.SalaryAfterIncrement) # Output 5500 diff --git a/basics/09_error_handling/01_try_except.py b/basics/09_error_handling/01_try_except.py index 6fcacaa..e62c960 100644 --- a/basics/09_error_handling/01_try_except.py +++ b/basics/09_error_handling/01_try_except.py @@ -2,6 +2,7 @@ def divide_numbers(numerator: int, denominator: int) -> float: result = numerator / denominator return result + try: num1 = int(input("Enter the Number: ")) num2 = int(input("Enter the Number: ")) diff --git a/basics/09_error_handling/02_raise_exception.py b/basics/09_error_handling/02_raise_exception.py index 0bc0c39..d894d25 100644 --- a/basics/09_error_handling/02_raise_exception.py +++ b/basics/09_error_handling/02_raise_exception.py @@ -2,9 +2,10 @@ def divide_numbers(numerator: int, denominator: int) -> float: division_result = numerator / denominator return division_result + num1 = int(input("Enter the Number : ")) num2 = int(input("Enter the Number : ")) if num2 == 0: raise ZeroDivisionError("Hehe") division_result = divide_numbers(num1, num2) -print(f"\nOutput : {round(division_result, 2)}") \ No newline at end of file +print(f"\nOutput : {round(division_result, 2)}") diff --git a/basics/09_error_handling/exception_handling_try_except.py b/basics/09_error_handling/exception_handling_try_except.py index 7163809..001469b 100644 --- a/basics/09_error_handling/exception_handling_try_except.py +++ b/basics/09_error_handling/exception_handling_try_except.py @@ -2,6 +2,7 @@ def divide_numbers(first_num: int, second_num: int) -> int: result = first_num / second_num return result + try: first_number = int(input("Enter the Number: ")) second_number = int(input("Enter the Number: ")) diff --git a/basics/09_error_handling/exception_raise_example.py b/basics/09_error_handling/exception_raise_example.py index 0f63598..f96b3fd 100644 --- a/basics/09_error_handling/exception_raise_example.py +++ b/basics/09_error_handling/exception_raise_example.py @@ -2,6 +2,7 @@ def divide_numbers(first_num: int, second_num: int) -> int: division_result = first_num / second_num return division_result + first_number = int(input("Enter the Number : ")) second_number = int(input("Enter the Number : ")) if second_number == 0: diff --git a/basics/10_advanced/01_lambda.py b/basics/10_advanced/01_lambda.py index 10e98cc..777b21a 100644 --- a/basics/10_advanced/01_lambda.py +++ b/basics/10_advanced/01_lambda.py @@ -2,12 +2,17 @@ def add(first_num, second_num): total = first_num + second_num return total + + result = add(2, 9) print(result) + def calculate_square(number): squared_result = number * number return squared_result + + result = calculate_square(9) print(result) diff --git a/basics/10_advanced/02_map_filter_reduce.py b/basics/10_advanced/02_map_filter_reduce.py index d7d695c..d7c61bf 100644 --- a/basics/10_advanced/02_map_filter_reduce.py +++ b/basics/10_advanced/02_map_filter_reduce.py @@ -17,6 +17,8 @@ def is_even(number): if number % 2 == 0: return True return False + + even_numbers = filter(is_even, numbers_list) print(list(even_numbers)) diff --git a/basics/10_advanced/03_filter_divisible.py b/basics/10_advanced/03_filter_divisible.py index f35086b..de5c27f 100644 --- a/basics/10_advanced/03_filter_divisible.py +++ b/basics/10_advanced/03_filter_divisible.py @@ -3,11 +3,13 @@ """ numbers_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + + def is_divisible_by_five(number): - if((number % 5) == 0): - return True - return False + if (number % 5) == 0: + return True + return False + filtered_numbers = filter(is_divisible_by_five, numbers_list) print(list(filtered_numbers)) - diff --git a/basics/10_advanced/04_reduce_maximum.py b/basics/10_advanced/04_reduce_maximum.py index b4da700..0d929dd 100644 --- a/basics/10_advanced/04_reduce_maximum.py +++ b/basics/10_advanced/04_reduce_maximum.py @@ -5,6 +5,8 @@ from functools import reduce numbers_list = [23, 23, 56, 87, 34, 776, 4443, 3, 33, 222, 533, 2, 22, 2] + + def find_maximum(num1, num2): if num1 > num2: return num1 @@ -15,7 +17,7 @@ def find_maximum(num1, num2): else: pass + maximum_value = reduce(find_maximum, numbers_list) print(maximum_value) - diff --git a/basics/10_advanced/06_module_custom.py b/basics/10_advanced/06_module_custom.py index eec8927..f3a20c0 100644 --- a/basics/10_advanced/06_module_custom.py +++ b/basics/10_advanced/06_module_custom.py @@ -2,6 +2,7 @@ def add_numbers(first_num, second_num): total = first_num + second_num print(total) + first_number = int(input("Enter the Number : ")) second_number = int(input("Enter the Number : ")) -add_numbers(first_number, second_number) \ No newline at end of file +add_numbers(first_number, second_number) diff --git a/basics/10_advanced/07_module_pyjokes.py b/basics/10_advanced/07_module_pyjokes.py index ac3796a..ebaf976 100644 --- a/basics/10_advanced/07_module_pyjokes.py +++ b/basics/10_advanced/07_module_pyjokes.py @@ -1,4 +1,3 @@ import pyjokes joke = pyjokes.get_joke() print(joke) - diff --git a/basics/10_advanced/08_match_case.py b/basics/10_advanced/08_match_case.py index c63a2b4..f23d3c4 100644 --- a/basics/10_advanced/08_match_case.py +++ b/basics/10_advanced/08_match_case.py @@ -1,4 +1,4 @@ -#1. +# 1. def check_val(val): match val: case 1: @@ -9,12 +9,12 @@ def check_val(val): return "99" case _: return "aagye line me" - -print(check_val(int(input("Enter between this [1 or 404 or 99] : ")))) +print(check_val(int(input("Enter between this [1 or 404 or 99] : ")))) + -#2. +# 2. def http_status(status): match status: case 200: @@ -27,4 +27,4 @@ def http_status(status): return "Unknown status" -print(http_status(5007)) \ No newline at end of file +print(http_status(5007)) diff --git a/basics/10_advanced/09_walrus_operator.py b/basics/10_advanced/09_walrus_operator.py index 19e69d3..9e39cda 100644 --- a/basics/10_advanced/09_walrus_operator.py +++ b/basics/10_advanced/09_walrus_operator.py @@ -1,4 +1,4 @@ -#Normal +# Normal while True: x = int(input("Enter the Number : ")) if x == 3: @@ -6,15 +6,12 @@ break -#Using Walrus +# Using Walrus while (x := int(input("Enter the Number : "))) != 3: continue print(x) -#Using Walrus Operator +# Using Walrus Operator while (x := int(input("Enter the Number : "))) != 3: pass print(x) - - - diff --git a/basics/10_advanced/10_text_to_speech.py b/basics/10_advanced/10_text_to_speech.py index bc38c21..3760073 100644 --- a/basics/10_advanced/10_text_to_speech.py +++ b/basics/10_advanced/10_text_to_speech.py @@ -1,4 +1,5 @@ import pyttsx3 + engine = pyttsx3.init() engine.say("""Johny, Johny! Yes, Papa @@ -9,4 +10,3 @@ Open your mouth! hm hm hm !""") engine.runAndWait() - diff --git a/basics/10_advanced/filter_divisible_by_five.py b/basics/10_advanced/filter_divisible_by_five.py index 53ea17c..de5c27f 100644 --- a/basics/10_advanced/filter_divisible_by_five.py +++ b/basics/10_advanced/filter_divisible_by_five.py @@ -3,10 +3,13 @@ """ numbers_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + + def is_divisible_by_five(number): - if((number % 5) == 0): - return True - return False + if (number % 5) == 0: + return True + return False + filtered_numbers = filter(is_divisible_by_five, numbers_list) print(list(filtered_numbers)) diff --git a/basics/10_advanced/functional_map_filter_reduce.py b/basics/10_advanced/functional_map_filter_reduce.py index d7d695c..a703c5e 100644 --- a/basics/10_advanced/functional_map_filter_reduce.py +++ b/basics/10_advanced/functional_map_filter_reduce.py @@ -2,8 +2,8 @@ 🚫 filter → "keep some items" ➕ reduce → "collapse into one""" - from functools import reduce + numbers_list = [1, 2, 3, 4, 5, 6] # Example of Map @@ -17,6 +17,8 @@ def is_even(number): if number % 2 == 0: return True return False + + even_numbers = filter(is_even, numbers_list) print(list(even_numbers)) diff --git a/basics/10_advanced/lambda_functions.py b/basics/10_advanced/lambda_functions.py index b196195..5d253fa 100644 --- a/basics/10_advanced/lambda_functions.py +++ b/basics/10_advanced/lambda_functions.py @@ -2,12 +2,17 @@ def add_numbers(first_num, second_num): total = first_num + second_num return total + + result = add_numbers(2, 9) print(result) + def calculate_square(number): squared_result = number * number return squared_result + + result = calculate_square(9) print(result) diff --git a/basics/10_advanced/match_case_statement.py b/basics/10_advanced/match_case_statement.py index ff7ad44..2a638a4 100644 --- a/basics/10_advanced/match_case_statement.py +++ b/basics/10_advanced/match_case_statement.py @@ -1,4 +1,4 @@ -#1. +# 1. def check_value(input_value): match input_value: case 1: @@ -10,11 +10,11 @@ def check_value(input_value): case _: return "aagye line me" -print(check_value(int(input("Enter between this [1 or 404 or 99] : ")))) +print(check_value(int(input("Enter between this [1 or 404 or 99] : ")))) -#2. +# 2. def get_http_status(status_code): match status_code: case 200: diff --git a/basics/10_advanced/module_add_function.py b/basics/10_advanced/module_add_function.py index 9fce4ce..f3a20c0 100644 --- a/basics/10_advanced/module_add_function.py +++ b/basics/10_advanced/module_add_function.py @@ -2,6 +2,7 @@ def add_numbers(first_num, second_num): total = first_num + second_num print(total) + first_number = int(input("Enter the Number : ")) second_number = int(input("Enter the Number : ")) add_numbers(first_number, second_number) diff --git a/basics/10_advanced/walrus_operator_example.py b/basics/10_advanced/walrus_operator_example.py index fc2142f..e943ede 100644 --- a/basics/10_advanced/walrus_operator_example.py +++ b/basics/10_advanced/walrus_operator_example.py @@ -1,17 +1,16 @@ -#Normal +# Normal while True: user_number = int(input("Enter the Number : ")) if user_number == 3: print(user_number) break - -#Using Walrus +# Using Walrus while (user_number := int(input("Enter the Number : "))) != 3: continue print(user_number) -#Using Walrus Operator +# Using Walrus Operator while (user_number := int(input("Enter the Number : "))) != 3: pass print(user_number) diff --git a/exercises/1000_programs/medium/1134_armstrong.py b/exercises/1000_programs/medium/1134_armstrong.py index 550635a..8133d21 100644 --- a/exercises/1000_programs/medium/1134_armstrong.py +++ b/exercises/1000_programs/medium/1134_armstrong.py @@ -2,6 +2,7 @@ An Armstrong number is a number that equals the sum of its own digits each raised to the power of the total number of digits. """ + # we return the number of digits in n def get_digits(n): digits_count = 0 @@ -12,15 +13,15 @@ def get_digits(n): return digits_count + n = int(input("Enter a number: ")) # we assume that the user is going to give an int -total_of_digits = get_digits(n) # we get the total of digits in n -aux = n # we need to store the value to make the final comparation +total_of_digits = get_digits(n) # we get the total of digits in n +aux = n # we need to store the value to make the final comparation sum = 0 while n > 0: - digit = n % 10 # get the last digit + digit = n % 10 # get the last digit sum += pow(digit, total_of_digits) n //= 10 print(sum == aux) - diff --git a/exercises/1000_programs/medium/1650_lowest_common_ancestor_of_a_binary_tree_iii.py b/exercises/1000_programs/medium/1650_lowest_common_ancestor_of_a_binary_tree_iii.py index 66428f2..c78fd5d 100644 --- a/exercises/1000_programs/medium/1650_lowest_common_ancestor_of_a_binary_tree_iii.py +++ b/exercises/1000_programs/medium/1650_lowest_common_ancestor_of_a_binary_tree_iii.py @@ -5,6 +5,7 @@ def __init__(self, val): self.right = None self.parent = None + def lowest_common_ancestor(p: 'Node', q: 'Node') -> 'Node': """ Find the lowest common ancestor of two nodes in a binary tree @@ -24,6 +25,7 @@ def lowest_common_ancestor(p: 'Node', q: 'Node') -> 'Node': return a + if __name__ == "__main__": # Example Setup: # 3 @@ -48,4 +50,5 @@ def lowest_common_ancestor(p: 'Node', q: 'Node') -> 'Node': result = lowest_common_ancestor(node6, node2) print(f"Input Nodes: {node6.val}, {node2.val}") - print(f"LCA Output: {result.val if result else 'None'}") \ No newline at end of file + print(f"LCA Output: {result.val if result else 'None'}") + \ No newline at end of file diff --git a/exercises/1000_programs/medium/1815_fresh_donuts.py b/exercises/1000_programs/medium/1815_fresh_donuts.py index af2acdc..ab93626 100644 --- a/exercises/1000_programs/medium/1815_fresh_donuts.py +++ b/exercises/1000_programs/medium/1815_fresh_donuts.py @@ -1,5 +1,6 @@ from functools import lru_cache + def maxHappyGroups(batchSize, groups): # Time Complexity: O(k^m) where k is batchSize and m is number of groups # Space Complexity: O(batchSize) @@ -49,6 +50,7 @@ def dfs(current_rem, counts): happy_groups += dfs(0, tuple(remainder_counts)) return happy_groups + # Driver Code if __name__ == "__main__": print(f"Test 1: {maxHappyGroups(3, [1,2,3,4,5,6])}") # Expected: 4 diff --git a/exercises/1000_programs/medium/1870_min_speed.py b/exercises/1000_programs/medium/1870_min_speed.py index 29352df..e5633f3 100644 --- a/exercises/1000_programs/medium/1870_min_speed.py +++ b/exercises/1000_programs/medium/1870_min_speed.py @@ -1,5 +1,6 @@ import math + def minSpeedOnTime(dist, hour): # If it's impossible to cover all trains even at infinite speed # (need at least 1 hour per train except the last one) @@ -21,8 +22,11 @@ def minSpeedOnTime(dist, hour): else: left = mid + 1 return ans + + # Driver code to test locally if __name__ == "__main__": print(minSpeedOnTime([1,3,2], 6)) # Expected: 1 print(minSpeedOnTime([1,3,2], 2.7)) # Expected: 3 - print(minSpeedOnTime([1,3,2], 1.9)) # Expected: -1 \ No newline at end of file + print(minSpeedOnTime([1,3,2], 1.9)) # Expected: -1 + \ No newline at end of file diff --git a/llm_fundamentals/WEIGHT-LOADING/supplementary.py b/llm_fundamentals/WEIGHT-LOADING/supplementary.py index 11c9a3e..f5bbe17 100644 --- a/llm_fundamentals/WEIGHT-LOADING/supplementary.py +++ b/llm_fundamentals/WEIGHT-LOADING/supplementary.py @@ -13,4 +13,3 @@ def __init__(self, txt, tokenizer, max_length, stride): # Tokenize the entire text token_ids = tokenizer.encode(txt, allowed_special={" - diff --git a/llm_fundamentals/architecture/01_transformer_architecture.py b/llm_fundamentals/architecture/01_transformer_architecture.py index 1002e7f..a9a63af 100644 --- a/llm_fundamentals/architecture/01_transformer_architecture.py +++ b/llm_fundamentals/architecture/01_transformer_architecture.py @@ -6,14 +6,15 @@ GPT_CONFIG_500M = { "vocab_size": 200256, # Vocabulary size - "context_length": 1024, # Context length - "emb_dim": 768, # Embedding dimension - "n_heads": 12, # Number of attention heads - "n_layers": 12, # Number of layers - "drop_rate": 0.0, # Dropout rate - "qkv_bias": False # Query-Key-Value bias + "context_length": 1024, # Context length + "emb_dim": 768, # Embedding dimension + "n_heads": 12, # Number of attention heads + "n_layers": 12, # Number of layers + "drop_rate": 0.0, # Dropout rate + "qkv_bias": False # Query-Key-Value bias } + class GPTModel(nn.Module): def __init__(self, cfg): super().__init__() @@ -39,7 +40,8 @@ def forward(self, in_idx): x = self.final_norm(x) logits = self.out_head(x) return logits - + + tokenizer = tiktoken.get_encoding("o200k_base") batch = [] @@ -89,6 +91,7 @@ def generate_text_simple(model, idx, max_new_tokens, context_size): return idx + model.eval(); @@ -107,4 +110,4 @@ def generate_text_simple(model, idx, max_new_tokens, context_size): # print("Output:", out) # print("Output length:", len(out[0])) decoded_text = tokenizer.decode(out.squeeze(0).tolist()) -print(decoded_text) \ No newline at end of file +print(decoded_text) diff --git a/llm_fundamentals/data/simple-tokenizer.py b/llm_fundamentals/data/simple-tokenizer.py index 7f93f2f..fb91e26 100644 --- a/llm_fundamentals/data/simple-tokenizer.py +++ b/llm_fundamentals/data/simple-tokenizer.py @@ -6,7 +6,7 @@ preprocessed = re.split(r'([,.:;?_!"()\']|--|\s)', raw_text) preprocessed = [item.strip() for item in preprocessed if item.strip()] all_words = sorted(set(preprocessed)) -vocab = {token:String for String,token in enumerate(all_words)} +vocab = {token: String for String, token in enumerate(all_words)} # print("Vocab Size", (vocab)) #token:String """ @@ -17,13 +17,14 @@ break """ + class SimpleTokenizerV1: - def __init__(self,vocab): + def __init__(self, vocab): self.str_to_int = vocab - self.int_to_str = {i:s for s,i in vocab.items()} + self.int_to_str = {i: s for s, i in vocab.items()} - def encode(self,text): - preprocessed = re.split(r'([,.:;?_!"()\'] | -- |\s)',text) + def encode(self, text): + preprocessed = re.split(r'([,.:;?_!"()\'] | -- |\s)', text) preprocessed = [item.strip() for item in preprocessed if item.strip()] ids = [self.str_to_int[s] for s in preprocessed] return ids @@ -34,6 +35,7 @@ def decode(self, ids): text = re.sub(r'\s+([,.?!"()\'])', r'\1', text) return text + tokenizer = SimpleTokenizerV1(vocab) Text = """ verified in The Possession of the enemy the enemy @@ -51,7 +53,7 @@ def decode(self, ids): print(f"\tDecoded Text :-\n\n{text}") print() - + dataloader = create_dataloader_v1(raw_text, batch_size=8, max_length=4, stride=4, shuffle=False) diff --git a/llm_fundamentals/data/supplementary.py b/llm_fundamentals/data/supplementary.py index 177342c..ca11149 100644 --- a/llm_fundamentals/data/supplementary.py +++ b/llm_fundamentals/data/supplementary.py @@ -45,4 +45,4 @@ def create_dataloader_v1(txt, batch_size=4, max_length=256, num_workers=num_workers ) - return dataloader \ No newline at end of file + return dataloader diff --git a/llm_fundamentals/fine_tuning/01_fine_tuning.py b/llm_fundamentals/fine_tuning/01_fine_tuning.py index 7642912..5660e0c 100644 --- a/llm_fundamentals/fine_tuning/01_fine_tuning.py +++ b/llm_fundamentals/fine_tuning/01_fine_tuning.py @@ -39,7 +39,3 @@ def format_input(entry): for i in tqdm(range(len(test_data))): response = llm.generate(test_data[i]) test_data[i]["base_model"] = response - - - - diff --git a/llm_fundamentals/pre_training/02_run_named_file.py b/llm_fundamentals/pre_training/02_run_named_file.py index a66c796..81c5f61 100644 --- a/llm_fundamentals/pre_training/02_run_named_file.py +++ b/llm_fundamentals/pre_training/02_run_named_file.py @@ -15,4 +15,4 @@ model = GPTModel(GPT_CONFIG_500M) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model.load_state_dict(torch.load("model.pth", map_location=device)) -model.eval() \ No newline at end of file +model.eval() diff --git a/llm_fundamentals/pre_training/03_run_pretrained.py b/llm_fundamentals/pre_training/03_run_pretrained.py index c85ed01..fd4f6d9 100644 --- a/llm_fundamentals/pre_training/03_run_pretrained.py +++ b/llm_fundamentals/pre_training/03_run_pretrained.py @@ -32,4 +32,4 @@ def token_ids_to_text(token_ids, tokenizer): max_new_tokens=10, context_size=GPT_CONFIG_500M["context_length"] ) -print("Output text:\n", token_ids_to_text(token_ids, tokenizer)) \ No newline at end of file +print("Output text:\n", token_ids_to_text(token_ids, tokenizer)) diff --git a/llm_fundamentals/pre_training/04_pretraining_helpers.py b/llm_fundamentals/pre_training/04_pretraining_helpers.py index 091270d..cddd781 100644 --- a/llm_fundamentals/pre_training/04_pretraining_helpers.py +++ b/llm_fundamentals/pre_training/04_pretraining_helpers.py @@ -305,4 +305,4 @@ def generate_text_simple(model, idx, max_new_tokens, context_size): # Append sampled index to the running sequence idx = torch.cat((idx, idx_next), dim=1) # (batch, n_tokens+1) - return idx \ No newline at end of file + return idx diff --git a/llm_fundamentals/weight_loading/01_weight_loading.py b/llm_fundamentals/weight_loading/01_weight_loading.py index 551ed8f..b346738 100644 --- a/llm_fundamentals/weight_loading/01_weight_loading.py +++ b/llm_fundamentals/weight_loading/01_weight_loading.py @@ -128,4 +128,4 @@ def load_weights_into_gpt(gpt, params): context_size=GPT_CONFIG_355M["context_length"] ) -print("Output text:\n", token_ids_to_text(token_ids, tokenizer)) \ No newline at end of file +print("Output text:\n", token_ids_to_text(token_ids, tokenizer)) diff --git a/llm_fundamentals/weight_loading/02_run_inference.py b/llm_fundamentals/weight_loading/02_run_inference.py index c2ab29a..553f654 100644 --- a/llm_fundamentals/weight_loading/02_run_inference.py +++ b/llm_fundamentals/weight_loading/02_run_inference.py @@ -3,4 +3,5 @@ llm.generate("What do Llamas eat?") result = llm.generate("What do Llamas eat?", stream=True, max_new_tokens=200) for e in result: - print(e, end="", flush=True) \ No newline at end of file + print(e, end="", flush=True) + \ No newline at end of file diff --git a/llm_fundamentals/weight_loading/03_gpt_download.py b/llm_fundamentals/weight_loading/03_gpt_download.py index e50b282..e01fe20 100644 --- a/llm_fundamentals/weight_loading/03_gpt_download.py +++ b/llm_fundamentals/weight_loading/03_gpt_download.py @@ -125,4 +125,4 @@ def load_gpt2_params_from_tf_ckpt(ckpt_path, settings): last_key = variable_name_parts[-1] target_dict[last_key] = variable_array - return params \ No newline at end of file + return params diff --git a/llm_fundamentals/weight_loading/04_weight_helpers.py b/llm_fundamentals/weight_loading/04_weight_helpers.py index 4497886..6d76c33 100644 --- a/llm_fundamentals/weight_loading/04_weight_helpers.py +++ b/llm_fundamentals/weight_loading/04_weight_helpers.py @@ -304,4 +304,4 @@ def generate_text_simple(model, idx, max_new_tokens, context_size): # Append sampled index to the running sequence idx = torch.cat((idx, idx_next), dim=1) # (batch, n_tokens+1) - return idx \ No newline at end of file + return idx