Add support for negative numbers in sum_of_digits function
まだ誰も着手していません。
評価
調査の方向性
sum_of_digits.py または関連するファイルを開き、sum_of_digits 関数と整数入力の現在の処理を確認してください。負の値とゼロを含む、記載されたケースを検証し、ドキュメントまたは例が含まれている場合は更新してください。負の入力が既存のケースを壊すことなく、その絶対値の各桁の合計を返すようになれば完了です。
索引モデルが issue の本文から書いたものです。
説明
🐛 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
- 主要言語
- Python
- スター
- 35.4k
- フォーク
- 12.9k
- 平均マージ
- 2時間 37分
- マージ済み PR(30日)
- 1
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
geekcomputers/Python のほかの issue
-
難易度 2/5 1〜3時間 初心者へのやさしさ 85/100
geekcomputers/Python#3205 · コメント 3 件 ·
-
難易度 2/5 1〜3時間 初心者へのやさしさ 74/100
geekcomputers/Python#3188 · コメント 3 件 ·
-
[BUG] shapchat オープン
難易度 5/5 1週間以上 初心者へのやさしさ 10/100
geekcomputers/Python#3214 · コメント 5 件 ·
-
Test of an Issue オープン
難易度 5/5 1週間以上 初心者へのやさしさ 10/100
geekcomputers/Python#3209 · コメント 5 件 ·
-
Add a feature by AI オープン
難易度 5/5 1週間以上 初心者へのやさしさ 10/100
geekcomputers/Python#3185 ·
geekcomputers/Python の issue をすべて見る
似ている issue
-
documentation help wanted
難易度 2/5 1〜3時間 初心者へのやさしさ 90/100
-
難易度 2/5 1〜3時間 初心者へのやさしさ 90/100
simonw/sqlite-utils#872 ·
-
難易度 2/5 1〜3時間 初心者へのやさしさ 88/100
-
難易度 2/5 1〜3時間 初心者へのやさしさ 82/100
-
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100