Sum of digit of a number using recursion in python [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 months ago.
Improve this question
Here in this program, I tried to understand but couldn't get completely.
How is this recursive function doing the sum and returning total sum of this? Please explain me in detail?
# Recursive Python3 program to
# find sum of digits of a number
# Function to check sum of
# digit using recursion
def sum_of_digit( n ):
if n < 10:
return n
return (n % 10 + sum_of_digit(n // 10)) # how this is working ?
num = 12345
result = sum_of_digit(num)
print("Sum of digits in",num,"is", result)

The best way to understand a recursive function is to dry run it.
First you need to understand what n % 10 mean is. this means the remainder of a n when divided by 10.
In this case when we divide 12345 by 10 , we get 5 as remainder.
so n % 10 part of code becomes 5.
Now, the second part is n//10 which gives you 1234 that are remaining digits.
Applying the same function again will give you 4 + sum_of_digit(123) and so on.
Even if this do not clear your confusion try, running this code on paper with some small number.

Related

What to do for this loop? Write code that assigns the average of the numbers from 1 to n (where n is a positive integer value) to the variable avg [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Write code that assigns the average of the numbers from 1 to n (where n is a positive integer value) to the variable avg. The answer is specifically asking for a for loop but idk how to start it off. Does it have to be a for x in range... or is it something else. plz help I'm just starting my first programming class and idk what to do.
I tried to enter avg = (1+n)/2 but its not excepting that and with the lesson being on for loops I'd assume I would need to make a for loop.
I think this solves your problem, although you should try to understand what is going on so you may apply your learning in the future.
Here's what I wrote:
n=int(input("Enter number: "))
avg=sum([x for x in range(1,n+1)])/len(range(1,n+1))
print(avg)
This takes input in line 1, sums all the numbers between 1 and n in line 2, and prints out the value in line 3.
To break it down: line 1 takes input. the int statement makes it into a number rather than a string, which is what normally comes out of an input.
Line 2:
This line is where the for loop comes in. I have compacted mine into a generator statement, but thats not absolutely necessary. First, the generator statement puts all the numbers 1 to n into a list. It then sums up all of the variables in the list, and assigns it to avg.
This is what it would look like uncompacted:
list_var=[]
for x in range(0,n+1): # Range returns numbers between the min and max, but not including the max. Therefore, put a +1 afterwards to ensure it includes the max.
list_var.append(x) # put the variable in the list
sum_of=sum(list_var) #sum returns the sum of all the items in the list.
avg=sum_of/len(range(1,n+1) #avg is the average (1-n)/length (which is the length of the range)
Finally, the print statement logs it to the console.
print(avg)
Ta-da
That python explanation helped clear things up more than my chapter. Ty!
total = 0
for i in range (1,n+1):
total+=i
avg = float(total)/n

Python How to get a integer using the ord function? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am having trouble with my code the main issue is I want to return 1 by using the getEquivalentNumber function but the problem is that when I run the code it gives me the result of -63 is there any way for me to improve the code to get a better result.
print('*' * 50)
user_input = input('Please enter a word. \n'
'-->')
print('*' * 50)
def getEquivalentNumber(_Mychar):
_Mychar = _Mychar.lower()
equivalentNumber = ord(_Mychar) - 96
return equivalentNumber
def computeSumOfCharacters(myWord):
sum = 0
for i in myWord: # apple
sum += getEquivalentNumber(i)
return sum
print(computeSumOfCharacters(user_input))
You define functions with def.
You can get the value of the units digit of a number with number % 10.
You can remove the units digit with number = number // 10.
You can accumulate those digits by starting an accumulator at zero and adding each digit.
You can loop until the number becomes zero.
You can return a value from the function with return.
Apologies if some of that seems too basic but I'm not sure what skill level you're at. That's pretty much the process I'd follow, without giving you the actual code.
The only thing that concerns me is computeSumOfDigits(911) must return a SINGLE digit yet the text after that says 9 + 1 + 1 = 11.
If you are required to further process results that are not a single digit, you can check that before returning and call the same function on the result, something like (pseudo-code):
if accumulator > 9:
return computeSumOfDigits(accumulator)
That would calculate: 9 + 1 + 1 -> 11, 1 + 1 -> 2.

Can anybody tell me what d = d+1 and l = l+1 do in this code what its uses in this code? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
In this code first it take d=0 and l = 0 and then it write d=d+1 and l=l+1 do in this code what its uses in this code ? ]1
In this code first it take d=0 and l = 0 and then it write d=d+1 and l=l+1 do in this code what its uses in this code ?
Go through it line by line - first you run a loop where each character of the input is sequentially represented as i.
Now, for each i, if i is a digit, you increase the count of d - using d=d+1.Otherwise (elif) if i is an alphabet, you increase the count of l - using l=l+1.
This way you're storing the number of digits in the input as d, and the number of letters in the input as l.
Finally, after the loop runs on all character of the input, you print the number of letters and digits respectively using print("letter",l,"digit",d)

What is the most effiecient way to get Factorial Sum? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
The code is to find the factorial of each individual value in an array and then find the sum of them together .An example would be [1,2,3,4], which will then be 1!+2!++3!+4!=33.A single integer equal to the desired sum, reduced modulo . The issue is that when it comes on to large numbers(just my assumption) it results in "Terminated due to timeout" status
At first I used a for loop to go through each value in the array. Thinking that it may be a search issue I used for in range to ensure it has a set range. Sadly that still hasn't solved the problem. I now assume that it has to be a problem with factorial since multiplication is
def factModSum(arr):
sum=0
for i in range (0,len(arr)):
sum=sum+factorial(arr[i])
return sum%(10**9)
Example 1:
Input: 1 2 3 4
output: 33
Expected output: 33
Example 2:
Input:2 3 5 7
Output:5168
Expected output: 33
Example 3:
Input:12 13 14
Output:884313600
Expected output: 33
At the core of it at the function works. But Im getting timeout error for some of my Test case , therefore assuming that the code is not able to process large numbers in a given time
If you are modding by 10 ** 9 you can try this:
def factModSum(arr):
return sum(factorial(i) for i in arr if i < 40) % 10**9
This is because n! with n >= 40 is congruent to 0 mod 10**9.

Algorithm for generating an array with a subarray sum of zero [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am trying to randomly generate an array of integers of range between -10^7 to 10^7 such that there exists a sub-array with a sum of zero.
For example : 7 6 4 8 -4 -8
1<=Size of array<=10^5
I am able to do it using brute-force but it is taking a lot of time as I have to generate very big such arrays. Is there any efficient way of achieving this using python or c++?
Edit: Actually I want to generate a lot of such arrays with different scenarios. I am generating these arrays as testcases for a problem to determine whether any given array of positive and negative integers contain a sub-array with zero sum.
Tried brute force code:
import random
N = random.randint(10,100)
mylist = []
for i in xrange(1,N):
mylist.append(random.randint(-100,100))
list2 = [1,-1]
mylist = mylist[1:N-2] + list2 + mylist[N-2:N]
print mylist
So I have to manually tweak it a lot.
Thanks!
The answer depends on how random you want your array to be. Like some of the commenters mentioned, you can always include a zero and are thus guaranteed to have a subarray with sum of zero. I thought it would be helpful to your eventual solution, so I want to mention that you can check if an array has a subarray with sum of zero in O(N^2) time.
def array_has_zerosubarray( A ):
for _begin in xrange(0,len(A)-1):
for _end in xrange(_begin+1,len(A)):
sum = 0
for ai in range(_begin,_end):
sum = sum + A[ai]
if sum==0:
return True
return False

Categories