debug of an function - python

The "Faculty " function, should return the faculty of the number it receives as a parameter. The faculty of a number n is 1 * 2 * 3 * 4 * ... * n. For example, faculty (5) should be 1 * 2 * 3 * 4 * 5 = 120. The function as it is written now always returns 0, no matter what number it receives as a parameter.
So, how do I fix the problem? (I'm just trying to learn, I'm new)
def faculty(integer):
result = 1
for i in range(integer):
result *= i
return result

The range statement takes a 0 as starting point. Therefore, the result is directly set to 0. You could change it to:
def faculty(integer):
result = 1
for i in range(1, integer+1):
result *= i
return result

The method range(stop) generates the values [0;stop[ so you have the 0 which kill everything, and not stop.
What you need is range(start, stop) with range(1, integer+1) to generates [1;value+1[
def faculty(integer):
result = 1
for i in range(1, integer+1):
result *= i
return result
When debugging, a nice way is in most time to use print to see what values are used to understand the behaviour of the code

Consider what values your loop is looping over.
for i in range(integer):
print(i)

Related

Is ther any other way to get sum 1 to 100 with recursion?

I'm studing recursive function and i faced question of
"Print sum of 1 to n with no 'for' or 'while' "
ex ) n = 10
answer =
55
n = 100
answer = 5050
so i coded
import sys
sys.setrecursionlimit(1000000)
sum = 0
def count(n):
global sum
sum += n
if n!=0:
count(n-1)
count(n = int(input()))
print(sum)
I know it's not good way to get right answer, but there was a solution
n=int(input())
def f(x) :
if x==1 :
return 1
else :
return ((x+1)//2)*((x+1)//2)+f(x//2)*2
print(f(n))
and it works super well , but i really don't know how can human think that logic and i have no idea how it works.
Can you guys explain how does it works?
Even if i'm looking that formula but i don't know why he(or she) used like that
And i wonder there is another solution too (I think it's reall important to me)
I'm really noob of python and code so i need you guys help, thank you for watching this
Here is a recursive solution.
def rsum(n):
if n == 1: # BASE CASE
return 1
else: # RECURSIVE CASE
return n + rsum(n-1)
You can also use range and sum to do so.
n = 100
sum_1_to_n = sum(range(n+1))
you can try this:
def f(n):
if n == 1:
return 1
return n + f(n - 1)
print(f(10))
this function basically goes from n to 1 and each time it adds the current n, in the end, it returns the sum of n + n - 1 + ... + 1
In order to get at a recursive solution, you have to (re)define your problems in terms of finding the answer based on the result of a smaller version of the same problem.
In this case you can think of the result sumUpTo(n) as adding n to the result of sumUpTo(n-1). In other words: sumUpTo(n) = n + sumUpTo(n-1).
This only leaves the problem of finding a value of n for which you know the answer without relying on your sumUpTo function. For example sumUpTo(0) = 0. That is called your base condition.
Translating this to Python code, you get:
def sumUpTo(n): return 0 if n==0 else n + sumUpTo(n-1)
Recursive solutions are often very elegant but require a different way of approaching problems. All recursive solutions can be converted to non-recursive (aka iterative) and are generally slower than their iterative counterpart.
The second solution is based on the formula ∑1..n = n*(n+1)/2. To understand this formula, take a number (let's say 7) and pair up the sequence up to that number in increasing order with the same sequence in decreasing order, then add up each pair:
1 2 3 4 5 6 7 = 28
7 6 5 4 3 2 1  = 28
-- -- -- -- -- -- -- --
8 8 8 8 8 8 8 = 56
Every pair will add up to n+1 (8 in this case) and you have n (7) of those pairs. If you add them all up you get n*(n+1) = 56 which correspond to adding the sequence twice. So the sum of the sequence is half of that total n*(n+1)/2 = 28.
The recursion in the second solution reduces the number of iterations but is a bit artificial as it serves only to compensate for the error introduced by propagating the integer division by 2 to each term instead of doing it on the result of n*(n+1). Obviously n//2 * (n+1)//2 isn't the same as n*(n+1)//2 since one of the terms will lose its remainder before the multiplication takes place. But given that the formula to obtain the result mathematically is part of the solution doing more than 1 iteration is pointless.
There are 2 ways to find the answer
1. Recursion
def sum(n):
if n == 1:
return 1
if n <= 0:
return 0
else:
return n + sum(n-1)
print(sum(100))
This is a simple recursion code snippet when you try to apply the recurrent function
F_n = n + F_(n-1) to find the answer
2. Formula
Let S = 1 + 2 + 3 + ... + n
Then let's do something like this
S = 1 + 2 + 3 + ... + n
S = n + (n - 1) + (n - 2) + ... + 1
Let's combine them and we get
2S = (n + 1) + (n + 1) + ... + (n + 1) - n times
From that you get
S = ((n + 1) * n) / 2
So for n = 100, you get
S = 101 * 100 / 2 = 5050
So in python, you will get something like
sum = lambda n: ( (n + 1) * n) / 2
print(sum(100))

How return works in recursion?

def sum_it(n,y):
if n ==0:
return y
else:
return sum_it(n-1,n+y)
required output for sum_it(3,4)i.e. (3+2+1)+4 must be 10
but obtained output is 5
Please how the return really works ?
Altough unclear, it seems like what you need when calling sum_it(n,y) is the sum of natural numbers from 1 to n plus y.
This initial sum is also known as "nth" triangular number.
If that's the case, you actually don't need recursion:
def sum_it(n,y):
return (n*(n+1))//2 + y
If recursion is a must:
def sum_it(n,y):
if (n > 1):
return n + sum_it(n-1,y)
return n + y
Feel free to ask if any doubt remains.
If you intended to sum like (3+2+1) + 4, this code will works.
def sum_it(n,y):
if( n == 1):
return y + 1
else:
return(n + sum_it(n-1,y))
For example, sum_it(3,4) works like below
sum_it(3,4) returns 3 + sum_it(2,4)
sum_it(2,4) returns 2 + sum_it(1,4)
sum_it(1,4) returns 1 + 4
It means
sum_it(3,4) returns 3 + 2 + 1 + 4

Find the number of digits after the decimal point [duplicate]

This question already has answers here:
Easy way of finding decimal places
(16 answers)
Closed 4 months ago.
I'm trying to write a Python 2.5.4 code to write a function that takes a floating-point number x as input and returns the number of digits after the decimal point in x.
Here's my code:
def number_of_digits_post_decimal(x):
count = 0
residue = x -int(x)
if residue != 0:
multiplier = 1
while int(multiplier * residue) != (multiplier * residue):
count += 1
multiplier = 10 * multiplier
print count
print multiplier
print multiplier * residue
print int(multiplier * residue)
return count
print number_of_digits_post_decimal(3.14159)
The print statements within the while loop are only for debugging purposes.
Now when I run this code, I get the following as output.
1
10
1.4159
1
2
100
14.159
14
3
1000
141.59
141
4
10000
1415.9
1415
5
100000
14159.0
14158
6
1000000
141590.0
141589
7
10000000
1415900.0
1415899
8
100000000
14159000.0
14158999
9
1000000000
....
The final value of count as returned by this function is 17.
How to modify this code in order to achieve our desired result?
Here's a shortcut that you might like:
def num_after_point(x):
s = str(x)
if not '.' in s:
return 0
return len(s) - s.index('.') - 1
This was interesting! So if you run the following:
x = 3.14159
residue = x - int(x)
print residue
You will get the following result:
0.14158999999999988
This decimal does in fact have 17 digits. The only way that I found to override this was to avoid doing the subtraction (which is the root cause of the error, as you can see from the inaccuracy here). So this code should work as you expect:
def number_of_digits_post_decimal(x):
count = 0
residue = x -int(x)
if residue != 0:
multiplier = 1
while not (x*multiplier).is_integer():
count += 1
multiplier = 10 * multiplier
return count
This will just shift the decimal to the right until python identifies it as an integer (it will do a rightward shift exactly the number of times you want too). Your code actually worked as you intended for it to, something unintended just happened during the subtraction process. Hope this helps!
def decimal_places(f):
exp = -1
remainder = True
while remainder:
exp += 1
a = f * 10**exp
remainder = int(a) - a
return(exp)
def precision(f):
integer, remainder = str(f).split('.')
return len(remainder)

create recursive power of 2 '*' in python

In pyschools, I am stuck in the power of 2 recursive function
>>> createStars(0) # 2 to power of 0 = 1
'*'
>>> createStars(1) # 2 to power of 1 = 2
'**'
>>> createStars(2) # 2 to power of 2 = 4
'****'
>>> createStars(3) # 2 to power of 3 = 8
'********'
What I am trying to do is as following:
def createStars(x):
if x == 0:
return '*'
else:
return '*' * x + createStars(x-1)
However, this seems to be a summation of 'x' not power of 2.
Meaning, this will break when the x is higher than 2
I know how to do the power of 2 recursively but no idea where to change to make createStars() work.
def power(x, n):
if n == 0:
return 1
else:
return x * power(x, n-1)
PS. I know it is easy to use non-recursive method to solve it.
But would like to seek advice how to do it in recursive way.
Thanks.
def createStars(x):
if x == 0:
return '*'
else:
return createStars(x-1) * 2
(Each step back in the recursion doubles the number of stars in the output string).
You're very close!
I would suggest comparing the two pieces of code you gave us. (I'm going to rename it a bit to make the analogy more clear):
def createStars(n):
if n == 0:
return '*'
else:
return '*' * n + createStars(n-1)
def power(x, n):
if n == 0:
return 1
else:
return x * power(x, n-1)
They have almost exactly the same structure. In particular, the last line of each has a slightly different structure.
In the (working) power, you multiply the result for n-1 by x. So, when computing the power(2, 6), you increase power(2, 5) by 2. (i.e. you multiply 32 by 2 to get 64).
In the (not working) createStars, you're not multiplying the result for the n-1 case by anything; you're just adding stuff to the start of it. What if you change it to make the structures match?
Also, you should check what the result is for createStars(1).

Sum of all numbers within a range without numbers divisible by x in python

I am trying to make a code (in python) where I can input a range and it will find the sum off all the numbers besides the ones that are divisible by x (which i also choose).
For example:
if the range is 0<N<10 and x = 3 then I want the code to sum the numbers
1 + 2 + 4 + 5 + 7 + 8
and output 27.
or if the range is 0<N<5 and x = 2 I want the code to sum the numbers
1 + 3
and output 4
But, the problem is I have no idea how to do it. Can anyone help me?
For your second example: (0<N<5, x=2):
sum(i for i in range(1, 5) if i%2)
def fn(N, x):
total = 0
for i in range(N):
if i%x:
total += i
return total
Read up on loops and ranges in python if you are new.
You could do something like this:
>>> div = 3
>>> n = 10
>>> num_div = filter(lambda x: x%div, range(n))
>>> sum(num_div)
27
or as a function
def func(n,div):
return sum(filter(lambda x: x%div, range(n))
The other answers implicitly assume the range will always start from 0. If you want to be able to set both the start and end points of your range, you could use:
def sumrange(start, stop, n):
return sum(i for i in range(start, stop) if i%n)

Categories