Skip to content

Add doctests for sum_of_arithmetic_series function #12285

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 35 additions & 16 deletions maths/sum_of_arithmetic_series.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,42 @@
# DarkCoder
def sum_of_series(first_term: int, common_diff: int, num_of_terms: int) -> float:
# Reeka
def sum_of_ap_series(a: int, d: int, n: int) -> int:
"""
Find the sum of n terms in an arithmetic progression.
Calculates the sum of the first 'n' terms of an arithmetic progression (AP)
series with the first term 'a' and common difference 'd'.
>>> sum_of_series(1, 1, 10)
55.0
>>> sum_of_series(1, 10, 100)
49600.0
"""
total = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff)
# formula for sum of series
return total
Parameters:
a (int): The first term of the AP.
d (int): The common difference between terms.
n (int): The number of terms to sum.
Returns:
int: The sum of the first 'n' terms of the AP.
def main():
print(sum_of_series(1, 1, 10))
Examples:
>>> sum_of_ap_series(1, 1, 5) # Sum of first 5 natural numbers
15
>>> sum_of_ap_series(2, 3, 4) # Sum of 2, 5, 8, 11
26
>>> sum_of_ap_series(5, 0, 3) # Sum of 5, 5, 5
15
>>> sum_of_ap_series(1, 2, 1) # Single term AP series
1
>>> sum_of_ap_series(1, -1, 5) # Decreasing AP series
-5
>>> sum_of_ap_series(1, 1, -5) # Negative 'n' should raise an error
Traceback (most recent call last):
...
ValueError: Number of terms 'n' must be a positive integer
>>> sum_of_ap_series(1, 1, 0) # Zero terms should also raise an error
Traceback (most recent call last):
...
ValueError: Number of terms 'n' must be a positive integer
"""
if n <= 0:
raise ValueError("Number of terms 'n' must be a positive integer")

# Formula for the sum of an AP series: S_n = n/2 * (2a + (n-1) * d)
return n * (2 * a + (n - 1) * d) // 2

if __name__ == "__main__":
import doctest

doctest.testmod()
# Reeka