Repository navigation
Fixed Issue #1772: Added a math folder to the Algorithms_and_Data_Structures section. - #1786
Conversation
|
👋 Thank you for opening this pull request! We're excited to review your contribution. Please give us a moment, and we'll get back to you shortly! Feel free to join our community on Discord to discuss more! |
|
✅ PR validation passed! Syncing labels and assignees from the linked issue... |
WalkthroughAdds six new Math modules under Algorithms_and_Data_Structures/Maths providing CLI input helpers and core functions for Reverse Integer, Pow(x,n), Integer sqrt (floor), Count of Matches, k-beauty, and Fascinating Number. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor User
participant CLI as "Module CLI"
participant Core as "Core Function"
User->>CLI: Provide input via prompts
CLI->>Core: Call core(input)
alt valid computation
Core-->>CLI: Return result
CLI-->>User: Print formatted output
else invalid input / edge
Core-->>CLI: Return handled value or raise
CLI-->>User: Print handled output / error
end
rect rgba(198,235,197,0.25)
Note right of CLI: Applies to modules: `reverse_integer`, `pow(x,n)`, `sqrt`, `count_of_matches`, `k_beauty`, `fascinating`
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Assessment against linked issues
Suggested labels
Suggested reviewers
Poem
✨ Finishing Touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
|
✅ PR validation passed! Syncing labels and assignees from the linked issue... |
1 similar comment
|
✅ PR validation passed! Syncing labels and assignees from the linked issue... |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (7)
Algorithms_and_Data_Structures/Maths/count_of_matches.py (1)
5-15: Use O(1) formula and validate input.The iterative simulation is correct but unnecessary; total matches in a knockout is max(n-1, 0). Also guard against negative n.
-def tournament_matches(n): - total_matches = 0 - while n > 1: - if n % 2 == 0: - matches = n // 2 - n = matches - else: - matches = (n - 1) // 2 - n = matches + 1 - total_matches += matches - return total_matches +def tournament_matches(n): + if n < 0: + raise ValueError("n must be non-negative") + return max(n - 1, 0)Algorithms_and_Data_Structures/Maths/reverse_integer.py (2)
1-4: Remove unused parameter and simplify input helper.n is unused; align with other modules’ input_value pattern.
-def input_array(arr, n): # Not needed for single integer, but keeping format - num = int(input("Enter integer x: ")) - arr.append(num) +def input_value(): + return int(input("Enter integer x: "))
23-29: Simplify CLI: no need for list scaffolding.This also removes the ARG001 warning.
-if __name__ == "__main__": - nums = [] - input_array(nums, 1) - display_array(nums) - x = nums[0] # Extract integer from list - result = reverse_integer(x) # Pass the integer, not the list - print(f"Reversed integer is: {result}") +if __name__ == "__main__": + x = input_value() + print(f"Reversed integer is: {reverse_integer(x)}")Algorithms_and_Data_Structures/Maths/sqrt.py (1)
5-20: Validate non-negative input and avoid duplicate multiplication.Minor guard for x < 0 and micro-opt to store mid*mid.
def sqrt_floor(x): - if x < 2: + if x < 0: + raise ValueError("x must be non-negative") + if x < 2: return x # sqrt(0)=0, sqrt(1)=1 - - left, right = 1, x + left, right = 1, x ans = 1 while left <= right: - mid = (left + right) // 2 - if mid * mid == x: + mid = (left + right) // 2 + sq = mid * mid + if sq == x: return mid - elif mid * mid < x: + elif sq < x: ans = mid left = mid + 1 else: right = mid - 1 return ansAlgorithms_and_Data_Structures/Maths/fascinating.py (3)
1-3: Harden interactive input and add typingCurrent
int(input(...))will crash on non-integers; also add return type for clarity. Loop with a friendly reprompt keeps UX consistent with the 3‑digit constraint.-def input_value(): - n = int(input("Enter 3-digit integer n: ")) - return n +def input_value() -> int: + while True: + try: + n = int(input("Enter 3-digit integer n: ")) + except ValueError: + print("Invalid input. Please enter a 3-digit integer.") + continue + if 100 <= n <= 999: + return n + print("Please enter a 3-digit integer between 100 and 999.")
8-8: Micro: use f-string for readabilitySlightly cleaner and avoids multiple
str(...)calls.- concat_str = str(n) + str(2*n) + str(3*n) + concat_str = f"{n}{2*n}{3*n}"
14-17: Drop redundant newline in print
- print(f"Is {n} fascinating? {result}\n") + print(f"Is {n} fascinating? {result}")
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (6)
Algorithms_and_Data_Structures/Maths/count_of_matches.py(1 hunks)Algorithms_and_Data_Structures/Maths/fascinating.py(1 hunks)Algorithms_and_Data_Structures/Maths/k_beauty.py(1 hunks)Algorithms_and_Data_Structures/Maths/pow(x,n).py(1 hunks)Algorithms_and_Data_Structures/Maths/reverse_integer.py(1 hunks)Algorithms_and_Data_Structures/Maths/sqrt.py(1 hunks)
🧰 Additional context used
🧬 Code graph analysis (5)
Algorithms_and_Data_Structures/Maths/count_of_matches.py (2)
Algorithms_and_Data_Structures/Maths/fascinating.py (1)
input_value(1-3)Algorithms_and_Data_Structures/Maths/sqrt.py (1)
input_value(1-3)
Algorithms_and_Data_Structures/Maths/sqrt.py (2)
Algorithms_and_Data_Structures/Maths/count_of_matches.py (1)
input_value(1-3)Algorithms_and_Data_Structures/Maths/fascinating.py (1)
input_value(1-3)
Algorithms_and_Data_Structures/Maths/k_beauty.py (1)
Algorithms_and_Data_Structures/Maths/pow(x,n).py (1)
input_values(1-4)
Algorithms_and_Data_Structures/Maths/fascinating.py (2)
Algorithms_and_Data_Structures/Maths/count_of_matches.py (1)
input_value(1-3)Algorithms_and_Data_Structures/Maths/sqrt.py (1)
input_value(1-3)
Algorithms_and_Data_Structures/Maths/pow(x,n).py (1)
Algorithms_and_Data_Structures/Maths/k_beauty.py (1)
input_values(1-4)
🪛 Ruff (0.12.2)
Algorithms_and_Data_Structures/Maths/reverse_integer.py
1-1: Unused function argument: n
(ARG001)
🔇 Additional comments (3)
Algorithms_and_Data_Structures/Maths/reverse_integer.py (1)
8-21: Core reverse logic looks good and handles 32-bit bounds.Algorithms_and_Data_Structures/Maths/pow(x,n).py (1)
1-1: Rename Algorithms_and_Data_Structures/Maths/pow(x,n).py → Algorithms_and_Data_Structures/Maths/pow_x_n.pyParentheses break Python imports; repository search found no direct imports of pow(x,n).py — rename to pow_x_n.py and update any external/dynamic references (notebooks, scripts, CI, docs).
Algorithms_and_Data_Structures/Maths/fascinating.py (1)
5-12: LGTM: Correct fascinating-number logicValidates 3-digit input, concatenates n, 2n, 3n, and checks uniqueness and length; the combination of
len == 9and set equality correctly enforces “each 1–9 exactly once.” Early'0'check is fine.
| def pow_func(x, n): | ||
| if n == 0: | ||
| return 1 | ||
| if n < 0: | ||
| x = 1 / x | ||
| n = -n | ||
| result = 1 | ||
| while n > 0: | ||
| if n % 2 == 1: | ||
| result *= x | ||
| x *= x | ||
| n //= 2 | ||
| return result |
There was a problem hiding this comment.
Fix division-by-zero for 0 base with negative exponent.
When x == 0 and n < 0, line 10 raises ZeroDivisionError. Handle explicitly and return 0 for x == 0, n > 0.
def pow_func(x, n):
if n == 0:
return 1
+ if x == 0:
+ if n < 0:
+ raise ZeroDivisionError("0 cannot be raised to a negative power")
+ return 0
if n < 0:
x = 1 / x
n = -n
result = 1
while n > 0:
if n % 2 == 1:
result *= x
x *= x
n //= 2
return result📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| def pow_func(x, n): | |
| if n == 0: | |
| return 1 | |
| if n < 0: | |
| x = 1 / x | |
| n = -n | |
| result = 1 | |
| while n > 0: | |
| if n % 2 == 1: | |
| result *= x | |
| x *= x | |
| n //= 2 | |
| return result | |
| def pow_func(x, n): | |
| if n == 0: | |
| return 1 | |
| if x == 0: | |
| if n < 0: | |
| raise ZeroDivisionError("0 cannot be raised to a negative power") | |
| return 0 | |
| if n < 0: | |
| x = 1 / x | |
| n = -n | |
| result = 1 | |
| while n > 0: | |
| if n % 2 == 1: | |
| result *= x | |
| x *= x | |
| n //= 2 | |
| return result |
🤖 Prompt for AI Agents
In Algorithms_and_Data_Structures/Maths/pow(x,n).py around lines 6 to 18, the
code does x = 1 / x for n < 0 which raises ZeroDivisionError when x == 0; fix by
handling x == 0 before any inversion: if x == 0 and n > 0 return 0, and if x ==
0 and n <= 0 raise a clear ZeroDivisionError (or ValueError) indicating 0 cannot
be raised to a non-positive power; only after these checks perform the n < 0
inversion and proceed with the fast exponentiation loop.
|
✅ PR validation passed! Syncing labels and assignees from the linked issue... |
|
✅ PR validation passed! Syncing labels and assignees from the linked issue... |
|
✅ PR validation passed! Syncing labels and assignees from the linked issue... |
|
✅ PR validation passed! Syncing labels and assignees from the linked issue... |
|
@UTSAVS26 I have resolved the issue. |
|
✅ PR validation passed! Syncing labels and assignees from the linked issue... |
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
Algorithms_and_Data_Structures/Maths/pow(x,n).py (1)
10-13: Use ZeroDivisionError for 0 to negative exponent (matches math semantics).Aligns with prior feedback and user expectations.
- if x == 0: - raise ValueError("0 cannot be raised to a negative exponent") + if x == 0: + raise ZeroDivisionError("0 cannot be raised to a negative exponent")
🧹 Nitpick comments (9)
Algorithms_and_Data_Structures/Maths/k_beauty.py (3)
1-4: Add return type annotation for input helper for consistency.Other modules annotate these helpers; do the same here.
-def input_values(): +def input_values() -> tuple[int, int]: num = int(input("Enter integer num: ")) k = int(input("Enter substring length k: ")) return num, k
8-9: Minor: shorten error message (Ruff TRY003).Tiny style nit; message is fine, but shorter is okay too.
- raise ValueError("k must be a positive integer") + raise ValueError("k must be > 0")
20-23: Optional: make CLI friendlier on bad input.Catching ValueError avoids a traceback for users.
if __name__ == "__main__": - num, k = input_values() - result = k_beauty(num, k) - print(f"The k-beauty of {num} with k = {k} is: {result}\n") + try: + num, k = input_values() + result = k_beauty(num, k) + print(f"The k-beauty of {num} with k = {k} is: {result}\n") + except ValueError as e: + print(f"Error: {e}")Algorithms_and_Data_Structures/Maths/sqrt.py (1)
15-19: Avoid recomputing mid*mid.Small perf/readability win in the loop.
- if mid * mid == x: + mid_sq = mid * mid + if mid_sq == x: return mid - elif mid * mid < x: + elif mid_sq < x: ans = mid left = mid + 1Algorithms_and_Data_Structures/Maths/pow(x,n).py (3)
6-6: Annotate return type.Function may return float for negative exponents.
-def pow_func(x: int, n: int): +def pow_func(x: int, n: int) -> float:
22-25: Optional: handle exceptions in CLI.Gracefully report invalid cases.
if __name__ == "__main__": - x, n = input_values() - power = pow_func(x, n) - print(f"Result of pow({x},{n}): {power}\n") + try: + x, n = input_values() + power = pow_func(x, n) + print(f"Result of pow({x},{n}): {power}\n") + except Exception as e: + print(f"Error: {e}")
1-1: Consider renaming file to avoid parentheses in path.pow_x_n.py is shell/import friendly.
Algorithms_and_Data_Structures/Maths/reverse_integer.py (2)
4-5: Print scalar instead of list for input echo.Small UX tweak.
-def display_array(arr): - print(f"\nInput integer is: {arr}") +def display_array(x: int): + print(f"\nInput integer is: {x}")And update call site:
- display_array([x]) + display_array(x)
1-3: Add type hints and minor style nit.Annotate reverse_integer and prefer
while x:idiom.-def input_value() -> int: +def input_value() -> int: return int(input("Enter integer x: ")) -def reverse_integer(x): +def reverse_integer(x: int) -> int: @@ - while x != 0: + while x:Also applies to: 7-7, 13-13
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (4)
Algorithms_and_Data_Structures/Maths/k_beauty.py(1 hunks)Algorithms_and_Data_Structures/Maths/pow(x,n).py(1 hunks)Algorithms_and_Data_Structures/Maths/reverse_integer.py(1 hunks)Algorithms_and_Data_Structures/Maths/sqrt.py(1 hunks)
🧰 Additional context used
🧬 Code graph analysis (4)
Algorithms_and_Data_Structures/Maths/k_beauty.py (1)
Algorithms_and_Data_Structures/Maths/pow(x,n).py (1)
input_values(1-4)
Algorithms_and_Data_Structures/Maths/reverse_integer.py (3)
Algorithms_and_Data_Structures/Maths/sqrt.py (1)
input_value(1-3)Algorithms_and_Data_Structures/Maths/fascinating.py (1)
input_value(1-3)Algorithms_and_Data_Structures/Maths/count_of_matches.py (1)
input_value(1-3)
Algorithms_and_Data_Structures/Maths/pow(x,n).py (1)
Algorithms_and_Data_Structures/Maths/k_beauty.py (1)
input_values(1-4)
Algorithms_and_Data_Structures/Maths/sqrt.py (3)
Algorithms_and_Data_Structures/Maths/reverse_integer.py (1)
input_value(1-2)Algorithms_and_Data_Structures/Maths/fascinating.py (1)
input_value(1-3)Algorithms_and_Data_Structures/Maths/count_of_matches.py (1)
input_value(1-3)
🪛 Ruff (0.12.2)
Algorithms_and_Data_Structures/Maths/k_beauty.py
9-9: Avoid specifying long messages outside the exception class
(TRY003)
Algorithms_and_Data_Structures/Maths/pow(x,n).py
11-11: Avoid specifying long messages outside the exception class
(TRY003)
Algorithms_and_Data_Structures/Maths/sqrt.py
1-1: SyntaxError: Unexpected indentation
5-5: SyntaxError: Expected a statement
🔇 Additional comments (2)
Algorithms_and_Data_Structures/Maths/k_beauty.py (1)
6-18: Core logic looks correct and robust (handles negatives and k bounds).Validates k, uses abs(num) for slices, skips zero divisors, and counts divisors correctly.
Algorithms_and_Data_Structures/Maths/reverse_integer.py (1)
7-20: Reverse logic with 32-bit overflow checks looks solid.Handles sign, overflow, and returns 0 on overflow as expected.
| @@ -0,0 +1,27 @@ | |||
| def input_value() -> int: | |||
There was a problem hiding this comment.
Fix leading indentation causing SyntaxError.
Top-level def must not be indented.
- def input_value() -> int:
+def input_value() -> int:📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| def input_value() -> int: | |
| def input_value() -> int: |
🧰 Tools
🪛 Ruff (0.12.2)
1-1: SyntaxError: Unexpected indentation
🤖 Prompt for AI Agents
In Algorithms_and_Data_Structures/Maths/sqrt.py around line 1, the top-level
function definition is incorrectly indented; remove the leading indentation so
"def input_value() -> int:" starts at column 0 (no preceding spaces or tabs).
Ensure subsequent function body lines are indented consistently (using 4 spaces)
relative to the def, and run a quick syntax check (python -m py_compile) to
confirm the SyntaxError is resolved.
|
@UTSAVS26 hi, if you could review this as the checks have successfully passed. |
Pull Request for PyVerse 💡
Requesting to submit a pull request to the PyVerse repository.
Issue Title
Please enter the title of the issue related to your pull request.
Add a Math folder to the 'Algorithms_and_Data_Structures' folder.
Info about the Related Issue
What's the goal of the project?
All things python.
Name
Please mention your name.
Muskan Singh
GitHub ID
Please mention your GitHub ID.
muskansngh07
Email ID
Please mention your email ID for further communication.
muskansngh15@gmail.com
Identify Yourself
Mention in which program you are contributing (e.g., WoB, GSSOC, SSOC, SWOC).
GSSoC
Closes
Enter the issue number that will be closed through this PR.
Closes: #1772
Describe the Add-ons or Changes You've Made
Give a clear description of what you have added or modified.
Added a Maths folder to the
Algorithms_and_Data_Structuressection of the repository, which includes the following codes:Type of Change
Select the type of change:
How Has This Been Tested?
Describe how your changes have been tested.
Tested on VS Code.
Checklist
Please confirm the following:
Summary by CodeRabbit