Hey guys I have a code like this
def add_sum(n):
numStr = str(n)
sum = 0
for i in range(len(num_str)):
sum += int(numStr[])
return sum
print(add_sum(546))
I want the answer to be this way.
output: 5 + 4 + 6 = 15
How can I make this work for me?
add_sum = lambda number: sum([int(x) for x in str(number)])
If you wanna do it the string conversion way
Edit: I assume you were referring to the loop, when you mentioned "recursion"?
If you want to loop over digits of a number, you can also use module 10 and divide the number each time.
A solution with recursion that does not convert int to str (which is kind of an expensive operation):
def add_sum(n):
return 0 if n == 0 else n % 10 + add_sum(n // 10)
If you prefer a solution without recursion:
def add_sum(n):
result = 0
while n != 0:
result += n % 10
n //= 10
return result
If you want to convert int to str:
def add_sum(n):
return sum(map(int, str(n)))
You can try this non-recursive code.
def add_sum(n):
temp = list(str(n))
ans = 0
for i in temp:
ans += int(i)
print(f"{' + '.join(temp)} = {ans}")
for i in range(3):
num = int(input())
add_sum(num)
Output:
546
5 + 4 + 6 = 15
258
2 + 5 + 8 = 15
6985
6 + 9 + 8 + 5 = 28
You can try this
def add_sum(n):
numStr = str(n)
sum1 = 0
for i in range(len(numStr)):
sum1 += int(numStr[i])
return ' + '.join([str(x) for x in n]),sum1
i,j=add_sum('546')
print(i,'=',j)
This also works
def add(num):
num_ = str(num)
if (len(num_) == 1):
return int(num)
else:
x = add(num_[1:])
return (x + int(num_[0]))
def add_sum(n):
numStr = str(n)
sum = 0
for i in range(len(numStr)):
sum += int(numStr[i])
return sum
print(add_sum(546))
This is the correct version of your code!
You can use your function With recursion like this!
def add_sum(n, sum=0):
if n == 0:
return sum
else:
sum += n % 10
return add_sum(int(n/10), sum)
print(add_sum(546))
here you go! sol. with recursion
def add_sum(n, sum=0, orignal=0):
if n == 0:
return(f"{orignal} => {' + '.join(str(orignal))} = {sum}")
elif orignal == 0:
orignal = n
sum += n % 10
else:
sum += n % 10
return add_sum(int(n/10), sum, orignal)
print(add_sum(54236))
Output:
54236 => 5 + 4 + 2 + 3 + 6 = 20
Related
Question: Why is the output 11 not 12?
i+4+i+3+i+2 = 1+4+1+3+1+2 = 12
Code:
def factorial(n):
i = 1
while n >= 1:
#I changed the signs from * to + after getting the factorial from * method.
i = i * n --> i = i + n
n = n - 1
return i
print factorial(4)
11
To get expected i+4 + i+3 + i+2 and result 12 you need
def factorial(n):
result = 0
i = 1
while n > 1:
result += i + n
n = n - 1
return result
print(factorial(4))
I add to new variable result so I don't change i and it is 1 all the time.
I also use > instead of >= so it ends after i+2 and it doesn't add i+1
def factorial(n):
i = 1
while n >= 1:
#I changed the signs from * to + after getting the factorial from * method.
print(i)
i = i + n
n = n - 1
return i
print(factorial(4))
If you print i, you will find i has changed after first loop.
So the output should be 1+4+3+2+1=11
(Posted on behalf of the question author).
Tips from me to solve the problem: 1. understand the concept of loop 2. try to print the answer on your own - i=5, n=3, i=8, n=2, i=10, n=1, i=11
I am trying to write a program that will print all the primes within a given range. I have written it, the output is almost okay, it prints primes, but for some reason it prints 4, which is not a prime...
Any assistant will be most appreciated !
def primes():
start = int(input("Enter the starting number: "))
end = int(input("Enter the ending number: "))
num = 0
i = 0
ctr = 0
for num in range(start,end+1,1):
ctr = 0
for i in range(2,num//2,1):
if num % i == 0 :
ctr = ctr + 1
break
if (ctr==0 and num != 1):
print(num)
for i in range(2,num//2,1):
Lets check this snippet of code when num = 4,it becomes
for i in range(2,2,1):
Now we see the problem.
Solution..?
for i in range(2,(num//2)+1,1):
The following methods are all possible prime checkers you might use to check within your range:
def isPrime(Number): # slow
return 2 in [Number, 2 ** Number % Number]
def isprime(n): # out of memory errors with big numbers
"""check if integer n is a prime"""
# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return False
# 2 is the only even prime number
if n == 2:
return True
# all other even numbers are not primes
if not n & 1:
return False
# range starts with 3 and only needs to go up the squareroot of n
# for all odd numbers
for x in range(3, int(n ** 0.5) + 1, 2):
if n % x == 0:
return False
return True
def is_prime(n): # Best until now
if n == 2 or n == 3:
return True
if n < 2 or n % 2 == 0:
return False
if n < 9:
return True
if n % 3 == 0:
return False
r = int(n ** 0.5)
f = 5
while f <= r:
# print '\t', f
if n % f == 0:
return False
if n % (f + 2) == 0:
return False
f += 6
return True
for i in range(2,num//2,1):
Above line is wrong. You are iterating from 2 to num / 2 - 1.
You should iterate from 2 to sqrt(num). (range(2, int(math.sqrt(n)) + 1))
Alternatively you can do a special check for 2 and modify your range to range(3, int(math.sqrt(n) + 1, 2)
So this is a cs assignment, and I wrote code that works for 2 out of the 9 test cases (which are unknown), but I don't know why it won't work/pass any other ones. I understand I should try to figure out how to do this on my own, and I have tried, but I am really lost and need help!
"Write a file named credit_card.py containing a single function, check. Check accepts a single input – a positive integer. It returns True if the integer represents a valid credit card number. As with all functions that return a bool value, if it does not return True it should return False.
Credit card numbers have what is called a check digit. This is a simple way of detecting common mis-typings of card numbers. The algorithm is as follows:
Form a sum of every other digit, including the right-most digit; so 5490123456789128 (5490123456789128) sums to 4 + 0 + 2 + 4 + 6 + 8 + 1 + 8 = 33.
Double each remaining digit, then sum all the digits that creates it; the remaining digits (5 9 1 3 5 7 9 2) in our example (5490123456789128) double to 10 18 2 6 10 14 18 4, which sums to 1+0 + 1+8 + 2 + 6 + 1+0 + 1+4 + 1+8 + 4 = 37
Add the two sums above (33 + 37 = 70)
If the result is a multiple of 10 (i.e., its last digit is 0) then it was a valid credit card number."
def check(x):
num1 = 0
num2 = 0
if x < 0:
return False
for i in str(x) [1::2]:
num1 += int(i)
return num1
for i in str(x) [0::2]:
num2 += int(int(i * 2) % 10) + int(int(i * 2) / 10)
return num2
check_digit = num1 + num2
if check_digit % 10 == 0:
return True
else:
return False
def check(x):
if x[0] == '-': # x is [str], "x < 0" is wrong
return False
try:
nums = map(int, x)
except Exception:
return False
sum1 = 0
sum2 = 0
for i in nums[1::2]:
sum1 += int(i)
for i in nums[0::2]:
sum2 += ((i * 2) % 10 + (i * 2) / 10) # i is [str], "i * 2" is wrong
check_digit = sum1 + sum2
if check_digit % 10 == 0:
return True
else:
return False
Here is the problem:
Surprisingly there are only three numbers that can be written as the
sum of fourth powers of their digits:
1634 = 1^4 + 6^4 + 3^4 + 4^4
8208 = 8^4 + 2^4 + 0^4 + 8^4
9474 = 9^4 + 4^4 + 7^4 + 4^4
As 1 = 1^4 is not a sum it is not included.
The sum of these numbers is 1634 + 8208 + 9474 = 19316.
Find the sum of all the numbers that can be written as the sum of
fifth powers of their digits.
And here is my code:
summ = 0
digit_sum = 0
i = 0
while i < 1000000:
j = list(str(i))
for x in j:
digit = int(x) ** 5
digit_sum += digit
if digit_sum == i:
summ += i
print(i)
else:
digit_sum = 0
i += 1
print(summ)
Can anyone find out that why I miss a value 4151 which should be one of the correct answer?
The problem in your code is you forgot to reset the digit_sum when you got an answer.
Put digit_sum = 0 before j = list(str(i)). You also start with i = 0. I suggest to start with i = 10 since the first 2 digit number is 10.
use this:
[i for i in range(10, 1000000) if i == sum(int(d) ** 5 for d in str(i))]
equivalent with:
[4150, 4151, 54748, 92727, 93084, 194979]
using sum:
sum(i for i in range(10, 1000000) if i == sum(int(d) ** 5 for d in str(i)))
equivalent with:
443839
4150 is also in solutions. The digit_sum is not set to 0 before 4151 step. You should set digit_sum = 0 in each step.
summ = 0
i = 10
while i < 1000000:
digit_sum = 0
j = list(str(i))
for x in j:
digit = int(x) ** 5
digit_sum += digit
if digit_sum == i:
summ += i
print(i)
i += 1
print(summ)
The answer to your question is that you don't reset digit_sum every time, only when digit_sum != i. If you remove the else statement, it should work correctly.
if digit_sum == i:
summ += i
print(i)
digit_sum = 0
i += 1
EDIT: I know I can import factorials but I'm doing this as an exercise
Trying to get the factor of a given number with a function in Python.
For example:
factorial(4) = 4 * 3 * 2 * 1 = 24
def factorial(x):
n = x
while n >= 0:
x = n * (n - 1)
n -= 1
return x
try like this: to make your code work
def factorial(x):
n = 1 # this will store the factorial value
while x > 0:
n = n*x
x -= 1
return n
you got many advice on comments follow it
A good way of approaching this would be using recursion where a function calls itself. See Function for Factorial in Python
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
But in your case your return statement actually breaks out of the while loop. So if you pass in 5 you get 20 back which is obviously not 5! (5 factorial).
Instead, try this:
def factorial(x):
n = 1
while x > 1:
n *= x
x -= 1
return n
print (factorial(5))
But do have a go at the recursive approach.
If you really want to cheat try:
import math
math.factorial(n)
I present an even shorter code for recursive factorial calculation. Not sure if it is faster or slower than other approaches:
def fac(n):
return 1 if n==1 else n*fac(n-1)
fac(10)
3628800
def factorial(n):
total = 1
for num in range(2,n+1):
total *= num
return total
input:
n = 10
print(str(n) + "! = ", end = '')
def factorial(n):
'''
print factorial number in human way
'''
if n < 0:
return 'factorial() not defined for negative values'
if n == 0:
return 1
if n == 1:
print('', n, ' =', end = ' ')
return 1
else:
print('', n, '*', end = '')
return n * factorial(n - 1)
print(factorial(n))
output:
10! = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 = 3628800