geekcomputers / geekcomputers/Python

Add support for negative numbers in sum_of_digits function

オープン 初心者向け
#3,060 コメント 1 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

主要言語
Python
スター
35.4k
フォーク
12.9k
平均マージ
2時間 37分
マージ済み PR(30日)
1

説明

🐛 Current Behavior
The sum_of_digits() function currently only works with non-negative integers. When a negative number is passed, it enters an infinite loop or produces incorrect results.

python:

Current implementation fails with negative numbers

sum_of_digits(-123) # Does not work correctly

✅ Expected Behavior
The function should handle negative numbers by computing the sum of digits using the absolute value.

python
sum_of_digits(-123) # Should return 6 (1 + 2 + 3)
sum_of_digits(-456) # Should return 15 (4 + 5 + 6)

💡 Proposed Solution
Add abs() to handle negative numbers in the sum_of_digits function:

def sum_of_digits(n: int) -> int:
"""
Compute the sum of the digits of an integer.

Args:
    n: An integer (negative values are converted to absolute).

Returns:
    Sum of digits of the absolute value of the number.

Examples:
    >>> sum_of_digits(123)
    6
    >>> sum_of_digits(-789)
    24
"""
n = abs(n)  # Handle negative numbers
total = 0

while n > 0:
    total += n % 10
    n //= 10

return total

📋 Additional Improvements (Optional)

Update docstring to clarify behavior with negative numbers
Add doctests for negative numbers
Update main() to display absolute value when input is negative:

python
abs_display = f" (absolute value: {abs(number)})" if number < 0 else ""
print(f"The sum of the digits of {number}{abs_display} is: {result}")

🧪 Test Cases

sum_of_digits(123) → 6
sum_of_digits(-123) → 6
sum_of_digits(0) → 0
sum_of_digits(-999) → 27

sum_of_digits.py (or the relevant file name)

🏷️ Labels
enhancement, good first issue, bug

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

sum_of_digits.py または関連するファイルを開き、sum_of_digits 関数と整数入力の現在の処理を確認してください。負の値とゼロを含む、記載されたケースを検証し、ドキュメントまたは例が含まれている場合は更新してください。負の入力が既存のケースを壊すことなく、その絶対値の各桁の合計を返すようになれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
backend
issue の種類
バグ
難易度
2/5
見積もり時間
1〜3時間
活発さ
静か
明瞭さ
明確に書かれている
初心者へのやさしさ
74/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。