geekcomputers / geekcomputers/Python
Add support for negative numbers in sum_of_digits function
Nessuno ha ancora preso questa issue.
- Lingua principale
- Python
- Stelle
- 35.4k
- Fork
- 12.9k
- Merge medio
- 2h 37m
- PR unite (30g)
- 1
Descrizione
🐛 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
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Apri sum_of_digits.py o il file pertinente e individua la funzione sum_of_digits e la sua gestione attuale degli input interi. Verifica i casi elencati, inclusi i valori negativi e zero, e aggiorna la documentazione o gli esempi, se inclusi; il lavoro è completato quando gli input negativi restituiscono la somma delle cifre del loro valore assoluto senza compromettere i casi esistenti.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- backend
- Tipo di issue
- Bug
- Difficoltà
- 2/5
- Tempo stimato
- 1-3 ore
- Stato di attività
- Tranquilla
- Chiarezza
- Specificata chiaramente
- Idoneità per principianti
- 74/100