The sum of the digits is incorrect. Why? - python

i can't understand why the output of my code concatnates the digits instead of showing their sum:
#Get a number, and show the number of digits and the sum of the digits.
num = int(input('Enter a number: '))
j = 0
i = 1
k = 0
while i < num:
i = i*10
j += 1
k += (num - k)%i
print (f' The number has {j} digit(s), and the sum is: {k}')

Follow the code. Let's say num = 432:
i = 1 * 10 = 10
j = 0 + 1 = 1
k = 0 + (432 - 0)%10 = 2
---
i = 10 * 10 = 100
j = 1 + 1 = 2
k = 2 + (432 - 2)%100 = 2 + 32 = 34
---
i = 100 * 10 = 1000
j = 2 + 1 = 3
k = 34 + (432 - 34)%1000 = 34 + 398 = 432
This algorithm is most definitely not adding every digit. There are several ways to do what you intend in python. One way is inputting the number as a string and summing every digit casting them as integers inside a generator:
num = input('Enter a number: ')
total = sum(int(digit) for digit in num)
print(total)
If you want the number to be an integer since the beginning, you can also do this:
num = int(input('Enter a number: '))
total = 0
while num > 0:
digit = num%10
total += digit
num /= 10 # num //= 10 in python 3
print(total)

Related

How to write Python program with output like this: Limit: 18 The consecutive sum: 1 + 2 + 3 + 4 + 5 + 6 = 21

My code looks like this at the moment:
limit = int(input("Limit:"))
number = 1
sum = 1
while sum < limit:
number = number + 1
sum = sum + number
print(f"The consecutive sum:{sum}")
Add the numbers you're using in a separate list. Then use str.join() to join these numbers with a ' + '.
limit = int(input("Limit:"))
number = 1
total = number
numbers = [str(number)]
while total < limit:
number = number + 1
total = total + number
numbers.append(str(number)) # Need to convert to string here because str.join() wants a list of strings
print(f"The consecutive sum: {' + '.join(numbers)} = {total}")
Which prints the required output:
The consecutive sum: 1 + 2 + 3 + 4 + 5 + 6 = 21
limit = int(input("Limit:"))
number = 1
sum = 1
print("The consecutive sum: 1", end = " ")
while sum < limit:
number += 1
sum += number
print(f'+ {number}', end = " ")
print(f'= {sum}')
Output Will Be:
Limit:18
The consecutive sum: 1 + 2 + 3 + 4 + 5 + 6 = 21

Doubling every second digit in python

I would like to double the value of every second digit and then add up the digits that are in their tens. Finally adding all the digits together
E.g: 123456789 -> 1 4 3 8 5 12 7 16 9 -> 1 4 3 8 5 3 7 7 9 -> 47
edit: the user would input any number and the function would still work eg: 5153 -> 5 2 5 6 -> 18
-SORRY first post I'm still getting used to this-
So I would like my function to
1. Reverse the inputted number
2. Double the value of the second digit
3. Sum all the digits together
4. Check if it's divisible by 7
Here is my code so far
my testing
def checksum(num):
#print(rev)
odd_digit = ""
even_digit = ""
even_sum = 0
odd_sum = 0
total_sum = 0
if num < 10 and num != 7:
return False
else:
return True
rev = (num[::-1])
for i in range(len(rev)):
if i % 2 == 0:
odd_digit += rev[i]
else:
even_digit += rev[i]
#print(even_digit)
even_digit = int(even_digit)
while even_digit > 0:
even_digit, even_sum = even_digit//10,even_sum+(even_digit%10)
#print(even_sum)
even_sum_2 = even_sum * 2
#print(even_sum_2)
odd_digit = int(odd_digit)
while odd_digit > 0:
odd_digit, odd_sum = odd_digit//10,odd_sum+(odd_digit%10)
#print(odd_sum)
total_sum = even_sum_2 + odd_sum
#print(total_sum)
if total_sum % 7 == 0:
return True
else:
return False
print(checksum(12345678901))
Try using this sum with a map, and a list comprehension:
>>> sum(map(int,''.join([str(int(v)*2) if i%2 else v for i,v in enumerate(s)])))
47
Or use:
>>> sum([sum(map(int,str(int(v)*2))) if i%2 else int(v) for i,v in enumerate(s)])
47
sum([sum(map(int, str(i * 2))) if i % 2 == 0 else i for i in range(1, 10)])

python - adding each digit that is greater than 4

Given an integer. for each individual digit that is greater than 4, i need to add it to all the next digits that greater than 4.
For example: a = 4567; the result should be 0 + (5) + (5+6) + (5+6+7) = 34
So far in my code, I was able to get the sum for single digit only. If the integer is greater 10, it will only give the sum of the very first digit. Any idea why this happening?
def morethanfour(number):
num = 0
num = [int(d) for d in str(number)] #seperate into individual digit
total = 0
for i in range (len(num)):
if num[i] > 4:
total = sum(x for x in range(5, num[i]+1)) #adding the sum
return total
num = 9
print(morethanfour(num))
the result when num = 9 is 35 (5+6+7+8+9)
However, when num = 178, it gave me 0
Try this:
>>> def morethanfour(number):
return sum(sum(range(5,x+1)) for x in map(int,str(number)) if x>4)
>>> morethanfour(9)
35
>>> morethanfour(4567)
34
>>> morethanfour(178)
44
>>> sum(sum(num[j] for j in range(0, i+1) if num[j] > 4) for i in range(len(num)))
34

python: How to sum a series using an increment number

n = int(input('Enter n: '))
count = 1
sum = 0
number = 1
while (count <= n):
sum = sum + number
count = count + 1
number = number + 2
print('Sum =', sum)
Is it possible to use the same concept for 1 + 4 + 9 + 16 + 25 + 36 + 49 + 64 .... + n
You could use a list comprehension to make this more elegant and pythonic:
def sum_series(start, end):
return sum([i**2 for i in range(start, end+1)])
print(sum_series(1,10))
Output:
385
Or using higher order functions:
>>> sum(map(lambda x: x**2, range(1,11)))
385
Something like this should do
n = int(input('Enter n: '))
count = 1
sum = 0
while (count <= n):
sum = sum + count*count
print("{s}+".format(s=sum)
count = count + 1
print('Sum =', sum)

What is wrong with my program? Amicable program

Question 3: Amicable
Implement a function amicable that takes a positive integer n. It returns the smallest amicable number greater than n.
Two different numbers are both amicable if the sum of the proper divisors of each is equal to the other. Any number that's part of such a pair is an amicable number.
def abundant(n):
while n > 0:
a = n
k = n
y = 0
total = 0
while k > y or n == 0:
if n % k == 0:
y = n // k
if k != n:
total = total + k + y
if k == y:
total = total - y
k -=1
total = total + 1
print(total)
def abundant2(n):
b = n
x = n
y = 0
total2 = 0
while x > y or n == 0:
if n % x == 0:
y = n // x
if x != n:
total2 = total2 + x + y
if x == y:
total2 = total2 - y
x -=1
total2 = total2 + 1
print(total2)
if total == b and total2 == a:
print('Amicable!')
amicable_numbers2 = int(total2)
amicable_numbers = int(total)
else:
print('Nope')
return abundant2
n += 1
def amicable(n):
"""Return the smallest amicable number greater than positive integer n.
Every amicable number x has a buddy y different from x, such that
the sum of the proper divisors of x equals y, and
the sum of the proper divisors of y equals x.
For example, 220 and 284 are both amicable because
1 + 2 + 4 + 5 + 10 + 11 + 20 + 22 + 44 + 55 + 110 is 284, and
1 + 2 + 4 + 71 + 142 is 220
>>> amicable(5)
220
>>> amicable(220)
284
>>> amicable(284)
1184
>>> r = amicable(5000)
>>> r
5020
"""
nums = [amicable_numbers2, amicable_numbers]
nums2 = [n for n in nums if n >= amicable_numbers2 and n <= amicable_numbers]
return nums2
# return a value that is less than amicable_numbers2 and less than amicable_numbers???

Categories

Resources