I'm supposed to be writing a function that find the amount of shoes a given number of dogs would need. It can easily be done with multiplication, but we're required to use recursion, so i have
def dogShoes(n):
total = 0
if n>0:
shoes = n + dogShoes(n)
total = total + 1
if total == 4:
return shoes
But I now realize that line 4 will go towards infinity and the bottom part that I though would stop it won't even be implemented. Is there a way to say when total is 4, stop and return the answer without shoes going towards infinity?
You can simplify your function a lot:
def dogShoes(n):
if n == 0:
return 0
else:
return 4 + dogShoes(n-1)
Since you have to use recursion instead of just returning n * 4 you can simply rewrite multiplication as addition (recursively).
What a weird task...
You're calling your function recursively, but never changing the parameter, thus giving infinite recursion. Try:
>>> def dog_shoes(n):
... if n > 0:
... return 4 + dog_shoes(n-1)
... else:
... return 0
...
>>> dog_shoes(1)
4
>>> dog_shoes(2)
8
>>> dog_shoes(3)
12
def Mul(n, x):
if n==1:
return x
else:
return x+ Mul(n-1,x)
Here's a simple multiplication function using Python recursion using two arguments.
Mul(3,3)
>>>9
Related
I tried to solve this Kata problem
Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number. You can guarantee that input is non-negative.
Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case.
But the problem is my code gives the correct answers right for the first time around but when
it is run for 2nd time onward it gives wrong answers only. I think it has to do sth with how my code is recursive. Please help me figure it out.
for example when i run count_bits(24) it gives the output 2 which is correct but when i run the same function again it would give 4 and then 6 and so on . I dont know what's wrong with this
My code.
dec_num = []
def count_bits(n):
def DecimalToBinary(n):
if n >= 1:
DecimalToBinary(n // 2)
dec_num.append( n % 2)
return dec_num
dec = DecimalToBinary(n)
return dec.count(1)
There is no need to create a list of digits if all you need is their sum. When possible, avoid creating mutable state in a recursive solution:
def count_bits(n):
if n > 0:
return n % 2 + count_bits(n // 2)
else:
return 0
That's a pretty natural translation of the obvious algorithm:
The sum of the bits in a number is the last bit plus the sum of the bits in the rest of the number.
Sometimes it's convenient to accumulate a result, which is best done by adding an accumulator argument. In some languages, that can limit stack usage, although not in Python which doesn't condense tail calls. All the same, some might find this more readable:
def count_bits(n, accum = 0):
if n > 0:
return count_bits(n // 2, accum + n % 2)
else:
return accum
In Python, a generator is a more natural control structure:
def each_bit(n):
while n > 0:
yield n % 2
n //= 2
def count_bits(n):
return sum(each_bit(n))
Of course, there are lots more ways to solve this problem.
That is because dec_num is outside the method, so it's reused at every call, put it inside
def count_bits(n):
dec_num = []
def DecimalToBinary(n):
if n >= 1:
DecimalToBinary(n // 2)
dec_num.append(n % 2)
return dec_num
dec = DecimalToBinary(n)
return dec.count(1)
Undertaking a task to Write a function power that accepts two arguments, a and b and calculates a raised to the power b.
Example
power(2, 3) => 8
Note: Don't use
2 ** 3
and don't use
Math.pow(2, 3)
I have tried this
def power(a,b):
return eval(((str(a)+"*")*b)[:-1])
And it works but seems to fail one test which is to return_1_when_exp_is_0
and i also get the error
Unhandled Exception: unexpected EOF while parsing (, line 0)
Please how do i solve this issue considering that i am new to python
This worked fine
def power(a,b):
if b == 0:
return 1
else:
return eval(((str(a)+"*")*b)[:-1])
Using eval is a terrible idea, but if you really wanted to then using join() would be a better way to create the string:
def power(a, b):
return eval('*'.join([str(a)]*b))
>>> power(2, 3)
8
If you add ['1'] to the front then the 0 exponent behaves properly:
def power(a, b):
return eval('*'.join(['1']+[str(a)]*b))
>>> power(2, 0)
1
However, this is simple to implement for integer exponents with a for loop:
def power(n, e):
t = 1
for _ in range(e):
t *= n
return t
>>> power(2, 3)
8
>>> power(2, 0)
1
You could also use functools.reduce() to do the same thing:
import functools as ft
import operator as op
def power(n, e):
return ft.reduce(op.mul, [n]*e, 1)
You can use a for loop
x=1
for i in range(b):
x=x*a
print(x)
def power(theNumber, thePower):
#basically, multiply the number for power times
try:
theNumber=int(theNumber)
thePower=int(thePower)
if theNumber == 0:
return 0
elif thePower == 0:
return 1
else:
return theNumber * power(theNumber,thePower-1)
except exception as err:
return 'Only digits are allowed as input'
You should avoid eval by all costs, especially when it's very simple to implement pure algorithmic efficient solution. Classic efficient algorithm is Exponentiation_by_squaring. Instead of computing and multiplying numbers n times, you can always divide it to squares to archive logarithmic* complexity.
For example, for calculating x^15:
x^15 = (x^7)*(x^7)*x
x^7 = (x^3)*(x^3)*x
x^3 = x*x*x
Thus taking 6 multiplications instead of 14.
def pow3(x, n):
r = 1
while n:
if n % 2 == 1:
r *= x
n -= 1
x *= x
n /= 2
return r
Source: https://helloacm.com/exponentiation-by-squaring/
Note: it was not mentioned in the question, but everything above considers N to be positive integer. If your question was also covering fractional or negative exponent, suggested approach will not work "as is".
* Of course depends on length of x and complexity of multiplying, see Wikipedia for detailed complexity analysis.
Also may be interesting to check out following questions: C solution or Python implementing pow() for exponentiation by squaring for very large integers
def power(a, b):
if b == 0:
return 1
else:
return a ** b
I'm writing a basic recursion function that takes an integer, n, and returns the sum of the first n reciprocals. Inputting 2 should result in 1.5, and inputting 0 should return 0.
sum_to(2) = (1 + 1/2) = 1.5
Here's what I have:
def sum_to(n):
if n>0:
return sum_to(1+1/n) # Not sure if this is correct
return 0
But all I'm getting is a Maximum recursion depth exceeded. I know I could lists to solve this, but recursion is really intriguing and I want to find a solution using it.
From the question, it seems that you want to compute
\sum_{i=1}^{n} 1/i
If the input is 0, then returns 0.
Remember that in a recursive function, you need to define a base case and an inductive clause.
In your question, the inductive clause is:
1.0 / i + sum_of_reciprocals(i-1)
while the base case can be set to 0 when i=0.
Given this formulation, the function with an example looks like:
def sum_to(n):
if n > 0:
return sum_to(n-1) + 1.0 / n
else:
return 0
if __name__ == '__main__':
print(sum_to(3))
and the result is 1.83333333333.
For more information about recursive functions, you can start from the related wikipedia page.
Trace through it to see if you ever reach your end condition:
(PS: at the time I wrote this the question's code was return 1 + sum_to(1/n))
sum_to(2):
n is 2, which is > 0
call sum_to(1/2)
n is .5, which is > 0
call sum_to(1/.5)
n is 2, which is > 0
call sum_to(1/2)
...
Your function never returns. The result would be infinite if you had infinite time and space to finish the calculation, since there is no end to the algorithm.
For your example, just write it this way:
def sum_to(n):
return 1 + 1/n
What is the expected result when n > 2? That will determine how to approach organizing working code.
I'm trying to return the count of digits in a number using recursion like this:
DigitCount(3456) → 4.
The code that I have without using recursion works fine, which is:
def DigitCount(n)
return len(str(n))
But when I try using recursion in this way:
def DigitCount(n):
return len(str(DigitCount(n)))
I get an error message saying 'RecursionError: maximum recursion depth exceeded'
The problem with your recursive function is that you didn't specify a base case to end the recursion, producing an infinite loop that ends with a stack overflow.
When writing recursive procedures, you have to think how to make the problem smaller at each call (in this case, dividing by 10 does the trick) until you reach a point where the problem is so simple, that you already know the answer - for instance, a number less than 10 has a single digit. Try this:
def DigitCount(n):
if n < 10:
return 1
else:
return 1 + DigitCount(n / 10) # use n // 10 in Python 3.x
It works as expected, as long as n is greater than or equal to zero:
DigitCount(0)
=> 1
DigitCount(234)
=> 3
What about something like:
def DigitCount(n):
if n<10: return 1
return 1 + DigitCount(n//10)
The idea is:
a number smaller than 10 has length 1
a number greater than 10 has length 1 + length(n//10); for instance 456 has length 1 + length(45).
It can be done using strings also.
def digitCount(n):
if len(str(n)) == 1:
return 1
else:
return 1 + digitCount(str(n)[1:])
It's a bit dirty, and very inefficient but works.
This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 4 months ago.
Write a simple procedure, myLog(x, b), that computes the logarithm of a number x relative to a base b.n other words, myLog should return the largest power of b such that b to that power is still less than or equal to x.
x and b are both positive integers; b is an integer greater than or equal to 2. Your function should return an integer answer.
Do not use Python's log functions; instead, please use an iterative or recursive solution to this problem that uses simple arithmatic operators and conditional testing.
What is wrong in the below code? As they have not mentioned what to return when the condition fails, so had kept false
def myLog(x, b):
count = 1
while x > 0 and b >= 2:
ans = b ** count
if (ans == x):
print str(count)
break
elif (ans > x):
print str(count-1)
break
count += 1
else:
return False
Since you haven't explained what problem you're trying to solve, all I can do is guess. But…
Your function never returns a number. If it succeeds, it prints out a number, then falls off the end of the function and returns None. If it fails, it returns False. And there's no other return anywhere in the code.
That's easy to fix: just return the value instead of print-ing it:
def myLog(x, b):
count = 1
while x > 0 and b >= 2:
ans = b ** count
if (ans == x):
return count
elif (ans > x):
return count-1
count += 1
else:
return False
You can improve performance by doing ans *= b each time through the loop instead of ans = b ** count. If the numbers are huge, dividing x by b might be better—division is usually slower than multiplication, but getting out of the huge-number domain early might help more than avoiding division.
It's also got some style problems, like the unnecessary parentheses some (but not all) of your conditions.
And finally, you may want to consider writing a "test driver". For example:
repcount = 100
errcount = 0
for _ in range(repcount):
x = generate_nice_random_x()
b = generate_random_base()
log1, log2 = myLog(x, b), int(math.log(x, b))
if log1 != log2:
print('log({}, {}): {} != {}'.format(x, b, log1, log2))
errcount += 1
print('{}/{} errors'.format(errcount, repcount))
Start with a small repcount to make sure you don't spam the screen; when you're happier with it, use a much larger one. Meanwhile, I'll leave it to you to figure out a good domain to choose from for testing log functions.
This is a question on an exam, that is currently ongoing.MITx: 6.00.1x Introduction to Computer Science and Programming