Create a function that calculates the sum of a series - python

# 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

Related

Writing code for main function in order to find sum of digits in a number

I need to write a short program that asks for positive integer, reads the number and then prints results of operations by both functions.
I've already written both fuctions which look like this:
def sumdigits(n):
sum = 0
while (n != 0):
sum = sum + (n % 10)
n = n//10
return sum
n = int(input("enternumber: "))
print(sumdigits(n))
def sumdigits(no):
return 0 if no == 0 else int(no % 10) + sumdigits(int(no / 10))
n = int(input("enternumber: "))
print(sumdigits(n))
The thing that I struggle with is merging these two together in order to make 1 general complex function that will show results of both functions.
One option is to use inner functions. For example:
def sumdigits(n):
def loop(n):
sum = 0
while (n != 0):
sum = sum + (n % 10)
n = n//10
return sum
def recurse(n):
return 0 if n == 0 else int(n % 10) + recurse(int(n / 10))
return loop(n), recurse(n)
n = int(input("enternumber: "))
print(sumdigits(n))

Python counting the trailing zero of factorial

Working on an example but it does not work. There must be a function which counts trailing zero in n! the factorial formula. where, n is the number for whose factorial we want to find the number of trailing zeros. Used some imports but it did not work.
My code:
def is_positive_integer(x):
try:
x = float(x)
except ValueError:
return False
else:
if x.is_integer() and x > 0:
return True
else:
return False
def trailing_zeros(num):
if is_positive_integer(num):
# The above function call has done all the sanity checks for us
# so we can just convert this into an integer here
num = int(num)
k = math.floor(math.log(num, 5))
zeros = 0
for i in range(1, k + 1):
zeros = zeros + math.floor(num/math.pow(5, i))
return zeros
else:
print("Factorial of a non-positive non-integer is undefined")
Ex:
Input: n = 5
Output: 1
Factorial of 5 is 120 which has one trailing 0.
Input: n = 20
Output: 4
Factorial of 20 is 2432902008176640000 which has
4 trailing zeroes.
Input: n = 100
Output: 24
Output must be:
Trailing 0s in n! = Count of 5s in prime factors of n!
= floor(n/5) + floor(n/25) + floor(n/125) + ....
This code can do the job, your code is very complex.
def Zeros(n):
count = 0
i = 5
while n / i >= 1:
count += int(n / i)
i *= 5
return int(count)
n = 100
print("Trailing zeros " +
"in 100! is", Zeros(n))
Output:
Trailing zeros in 100! is 24

Function doesn't return anything after giving a big number as an argument

I'm learning Python by doing Project Euler questions and am stuck on Problem #3.
I think I've found a solution that works, but when inserting the large number 600851475143 it just doesn't return anything. I believe that it just loads and loads cause even with 6008514 it takes 10 secs to return the answer.
# What is the largest prime factor of the number x?
import math
def isPrime(x):
try:
sqr = math.sqrt(x)
if x == 0 or x == 1:
return 0
for n in range (2 , int(sqr)+1):
if x % n == 0:
return 0
return 1
except:
return 'Give positive numbers.'
def largestPrimeFactor(x):
if isPrime(x) == 1:
return 'This number is prime.'
else:
largest = -1
mid = x/2
for n in range(2,int(mid)+1):
if isPrime(n):
if x % n == 0:
largest = n
if largest == -1:
return 'Enter numbers above 1.'
else:
return largest
print(largestPrimeFactor(600851475143))
This code should work:
import math
def isPrime(x):
try:
sqr = math.sqrt(x)
if x == 0 or x == 1:
return 0
n = 2
highest = x
while n < highest:
if x%n ==0:
return 0
highest = x/ n
n +=1
return 1
except:
return 'Give positive numbers.'
def largestPrimeFactor(x):
if isPrime(x) == 1:
return 'This number is prime.'
n = 2
highest = x
largest = 1
while n < highest:
if x%n == 0:
if isPrime(n):
largest = n
highest = x/n
n +=1
return largest
print(largestPrimeFactor(600851475143))
I made an optimization:
you check if every number is a factor of x while if for example 2 is not a factor of x for sure the maximum factor of x can be x/2. Hence if n is not a factor of x the maximum possible factor of x can just be x/n.
The code for large numbers just takes really long time, as pointed out by comments. I report other bugs.
Bug 1. Inappropriate use of try/except clause. It is recommended that try contains a single command and except catches the error. PEP8 also recommends specifying the type of error. Moreover, for your function, the error is never raised.
Bug 2. Redundancy. If x is not prime, you call isPrime for each value (let's call it i) from 2 to x/2. isPrime cycles for each number from 2 to sqrt(i). Therefore, isPrime(i) takes O(sqrt(i)) time, and we call it for i from 2 to x/2. Roughly, its running time is about O(x^(3/2)). Even if don't know a more optimal approach, this approach asks for memoization.
i have another way:
def Largest_Prime_Factor(n):
prime_factor = 1
i = 2
while i <= n / i:
if n % i == 0:
prime_factor = i
n /= i
else:
i += 1
if prime_factor < n:
prime_factor = n
return prime_factor
it faster than previous
try it:
import math
def maxPrimeFactors (n):
maxPrime = -1
while n % 2 == 0:
maxPrime = 2
n >>= 1
for i in range(3, int(math.sqrt(n)) + 1, 2):
while n % i == 0:
maxPrime = i
n = n / i
if n > 2:
maxPrime = n
return int(maxPrime)
n = 600851475143
print(maxPrimeFactors(n))

Sum of digits untill reach single digit

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

Designing a recursive function that uses digit_sum to calculate sum of digits

def digit_sum(n):
if n==0 or n==1:
return n
else:
return n+digit_sum(n-1)
def digital_root(n):
if n<10:
return n
else:
return digit_sum((n // 10) + n % 10)
I am trying to use digit_sum to calculate the sum of digits of digital_root can someone help me please. I am trying to use a recursive function for digital_root.
Running the file in Python shell:
digital_root(1969)
This should calculate 1+9+6+9=25 then since 25 is greater than 10 it should then calculate the sum of its digits 2+5 so that the final answer is 7.
To get the last digit of a (positive integer) number you can calculate the modulo:
last_digit = n % 10
The remainder of the number (excluding the last place) is:
rest = (n - last_digit) / 10
This should in theory be enough to split a number and add the digits:
def sum_digits(n):
if n < 10:
return n
else:
last_digit = n % 10
rest = n // 10
# or using divmod (thanks #warvariuc):
# rest, last_digit = divmod(n, 10)
return last_digit + sum_digits(rest)
sum_digits(1969) # 25
If you want to apply this recursivly until you have a value smaller than 10 you just need to call this function as long as that condition is not fulfilled:
def sum_sum_digit(n):
sum_ = sum_digit(n)
if sum_ < 10:
return sum_
else:
return sum_sum_digit(sum_)
sum_sum_digit(1969) # 7
Just if you're interested another way to calculate the sum of the digits is by converting the number to a string and then adding each character of the string:
def sum_digit(n):
return sum(map(int, str(n)))
# or as generator expression:
# return sum(int(digit) for digit in str(n))
If you really require a recursive solution without using any loops (for, while) then you can always recurse again to ensure a single digit:
def digital_root(n):
if n < 10:
return n
a, b = divmod(n, 10)
b += digital_root(a)
return digital_root(b)
>>> digital_root(1969)
7
Or you could just not recurse at all:
def digital_root(n): # n > 0
return 1+(n-1)%9
>>> digital_root(1969)
7
try this...
digitSum = 0
solution = 0
S = raw_input()
S = list(map(int, S.split()))
#print S
for i in S:
digitSum += i
#print digitSum
singleDigit = len(str(digitSum)) == 1
if singleDigit == True: solution = digitSum
while singleDigit == False:
solution = sum( [ int(str(digitSum)[i]) for i in range( 0, len(str(digitSum))) ] )
digitSum = solution
singleDigit = len(str(solution)) == 1
print(solution)

Categories

Resources