Sum of digits untill reach single digit - python

I set an algorithm which sum a number's digits but I couldn't make it till single digit. It only work for one step.
For example:
a=2, b=8
a^b=256 = 6+5+2 = 13
But I want to reach single digit, like:
a^b=256 = 6+5+2 = 13 = 3+1 = 4
Below you can see my codes.
a = int(input("Enter a value"))
b = int("Enter second value")
number = pow(a, b)
sum= 0
while float(number) / 10 >= .1:
m = number % 10
sum += m
number = number // 10
if float(number) / 10 > .1:
print(m, end=" + ")
else:
print(m, "=", sum)

Here you go:
n = 256
while n > 9:
n = sum(int(i) for i in str(n))
print(n)
So whats going on? str(n) converts n to a string, strings in python can be iterated over so we can access digit by digit. We do this in a generator, converting each digit back to a integer, int(i) for i in str(n), we use sum to sum the elements in the generator. We repeat this process until n is a single digit.
Added a solution that gives the calculation explicitly:
def sum_dig(n):
_sum = sum(int(i) for i in str(n))
explained = "+".join(list(str(n)))
return _sum, explained
n = 256
s = ""
while n > 10:
n, e = sum_dig(n)
s+= f'{e}='
s += str(n)
print(s)
yields:
2+5+6=1+3=4

you can try this.
a = int(input("Enter a value"))
b = int(input("Enter second value"))
number = pow(a, b)
result = str(a)+'^'+str(b) + ' = ' + str(number)
while number > 9:
digit_sum = sum(map(int, str(number)))
result += ' = ' + '+'.join(str(number)) + ' = ' + str(digit_sum)
number = digit_sum
print ( result )
for a=2, b=8 result:
2^8 = 256 = 2+5+6 = 13 = 1+3 = 4

This produces the output in the format OP asked for:
a = int(input("Enter a value: "))
b = int(input("Enter second value: "))
n = pow(a, b)
while n >= 10:
nums = [i for i in str(n)]
op = "+".join(nums)
n = eval(op)
print("{}={}".format(op, n))
Logic:
Store the input in an array of individual numbers as strings.
Create the summation string using "+".join(nums) - for the output print.
Calculate the sum using eval(op) which works on strings (a built-in function) - store in n.
Print the summation string and what it equals.
Output:
Enter a value: 2
Enter second value: 8
2+5+6=13
1+3=4
Enter a value: 2
Enter second value: 6
6+4=10
1+0=1
Enter a value: 2
Enter second value: 50
1+1+2+5+8+9+9+9+0+6+8+4+2+6+2+4=76
7+6=13
1+3=4

sol = 0
if (a^b)%9==0:
sol = 9
else:
sol = (a^b)%9

Related

Code that have exact function like oct() in Python

I need code that have exact function like oct() in Python but without using any other methods and functions.
I wrote this, but I think it's so large and also I don't want use range and len:
def get_oct(x):
next_step = [x]
r_mod = []
while True:
x /= 8
i = int(x)
next_step.append(i)
if int(x / 8) == 0:
break
for m in range(len(next_step)):
next_step[m] %= 8
j = int(next_step[m])
r_mod.append(j)
t_mod = r_mod[::-1]
return "0o" + "".join(str(e) for e in t_mod)
entry = int(input("Enter a number: "))
print(get_oct(entry))
If you want this to work like the built-in oct(), you need to account for zero and negative numbers. A nicer way to deal with this is to use the function divmod() the returns the result of integer division and the remainder. Just keep doing that until the value is zero:
def get_oct(x):
if x == 0: return '0o0'
prefix = '-0o' if x < 0 else '0o'
x = abs(x)
res = ''
while x:
x, rem = divmod(x, 8)
res = str(rem) + res
return (prefix + res)
assert(get_oct(80) == oct(80))
assert(get_oct(1) == oct(1))
assert(get_oct(0) == oct(0))
assert(get_oct(-2) == oct(-2))
assert(get_oct(-201920) == oct(-201920))
assert(get_oct(12345678910) == oct(12345678910))
If all that is needed is to print in octal without oct() function,string formatting could be the easiest option.
num = int(input("Enter a number: "))
print("{:o}".format(num))
Output:
Enter a number: 10
12
This is also possible with string variable
num = int(input("Enter a number: "))
s = "{:o}".format(num)
print(s)
Output:
Enter a number: 10
12

I am making a code to turn a Binary number into decimal number, This is what I have done, Can someone tell where I am wrong, (i am 1 month into Python

n = int(input("Enter the binary number : "))
n_into_str = str(n)
lenf = len(n_into_str)
def calculate(n):
ans = 0
for i in range(lenf):
z = n%10
power = 2**i
k = z*power
value = z
ans = ans + z
print(ans)
calculate(n)
You are almost good, but you need ans = ans + k and ans = ans + z, and also divide n by 10, to remove the last digit
Version that uses math operation to select digit
def calculate(n: int):
ans = 0
for i in range(len(str(n))):
z = n % 10
n = n // 10
power = 2 ** i
k = z * power
ans = ans + k
print(ans)
n = int(input("Enter the binary number : "))
calculate(n)
Version that uses string indexing to select digit
def calculate(n: str):
ans = 0
for i, digit in enumerate(reversed(n)):
power = 2 ** i
k = int(digit) * power
ans = ans + k
print(ans)
n = input("Enter the binary number : ")
calculate(n)

how do i optimise this code of finding a number X whose sum with its digit is equal to n?

Find a Number X whose sum with its digits is equal to N
n = int(input())
for i in range(n//2, n):
z = [int(x) for x in str(i)]
zz = sum(z)
if zz<=100:
ans = int(i) + int(zz)
if(int(i) + int(zz) == n) :
print(i)
tile limit is exceeding
If it can be any number, this would be a fast way to do it.
i = int(input("Your number: "))
result = ""
while i > 9:
result += "9"
i -= 9
result += str(i)
print(result)
How about
for k in range(1000):
if sum([int(i) for i in str(k)]) == k:
print(k)
But there seem to be only very few numbers with that property...

Create a function that calculates the sum of a series

# write a function called series_sum() that prompts the user for a non-negative
# interger n. If the user enters a negative the function should return None
# otherwise the function should return the sum of the following series,
# 1000 + (1/1)**2 + (1/2)**2 + (1/3)**2 + (1/4)**2 ... + (1/n)**2
def series_sum():
n = input("Please enter a number greater than 0")
The function needs to take one argument, n.
Next.... for the sum... range(1,n+1) will create an iterable object from 1 to n that you can use in a for loop. Under your else statement, create a variable 'total'.. it starts out as 1000. For each value in the range 1 to n, you'll add 1 over the value squared to total.
def series_sum():
n = input("Please enter an integer greater than 0")
n = int(n)
if n < 0:
return None
else:
numbers = range(1,n+1)
total = 1000
for number in numbers:
total = total + 1/n**2
return total
Full functionality:
def series_sum(n):
if n >= 0:
return 1000 + sum((1/x) ** 2 for x in range(1, n + 1))
Or with same functionality, but making negatives explicit:
def series_sum(n):
if n >=0:
return 1000 + sum((1/x) ** 2 for x in range(1, n + 1))
if n < 0:
return None
def series_sum():
n = input("Please enter a number greater than 0")
if type(n,str):
try:
n = int(n)
except:
print 'enter integer value'
return
if n >=0:
sum = 1000
for i in range(1,n+1):
sum += (1./i)**2
return sum
return

greatest product of consecutive digits in numbers python

My program has the purpose of determining the greatest product of a certain amount of consecutive digits. For example the program prompts the user for a string of numbers (ex 255969406) and for the size of consecutive digits (3), thus my program will determine what the greatest product of 3 consecutive digits in the number provided is, my program compiles and runs but the product returned is incorrect.
def Pro(dig,snum):
number = 1
pr = 0
for x in xrange(0,dig-1):
pr = int(snum[x])
number = pr*number
return number
def Product(dig,indx,snum):
number = 1
pr = 0
for x in xrange(1,dig):
pr = int(snum[indx+x])
number = pr*number
return number
def Main():
num = raw_input("Enter a string of digits")
dig = input("Input number of digits in group")
x = 1
val = Pro(dig,num)
grps = int(len(num)/ dig)
while x<grps:
val2= Product(dig,x,num)
if val2>val:
val = val2
x +=1
print("The max product of " + str(dig) +" consecutive digits in " + num + " is " + str(val))
if __name__ == "__main__":
Main()
You can try this out:
x = '134214257248'
m = 0
for i in range(len(x) - 2):
m = max(m, int(x[i])*int(x[i+1])*int(x[i+2]))
print m
# 2*5*7 = 70
70
EDIT: Accept any amount (n) of consecutive digits
import numpy as np
x = '134214257248'
m = 0
n = 3
for i in range(len(x) - n + 1):
m = max(m, np.prod(list(int(l) for l in x[i:i + n])))
print m
70

Categories

Resources