How to ignore printing "None Object" in python - python-3.x

n = int(input())
def reverse(num):
while num > 0:
return f"{num}{reverse(num - 1)}"
result = reverse(n)
print(result)
I have some code lines as above. (Incase Input n = 5)It prints "54321None" instead of "54321" as I expected.
Please help me

The last iteration will always be a 0. If you just call reverse(0) it will return None, so that is the problem.
Without rewriting too much code the 'simple' solution could be:
return f"{num}{reverse(num-1)if num-1 != 0 else ''}"
This only executes the reverse function if the variable you pass into reverse is not 0. Otherwise it will return Nothing.

Related

canConstruct a memorization dynamic programming problem

I am stating to solve some dynamical programming problem, I came across the problem to solve if a string can be constructed from a list of string.
I have use this following method in python 3.8.
def canConstruct(target,workbank,memo={}):
if (target in memo):
return(memo[target])
if len(target)==0:
return(True)
for i in range (len(workbank)):
pos=target.find(workbank[i])
if (pos != -1):
suffix=target[pos:pos+len(workbank[i])]
out=canConstruct(suffix,workbank,memo)
if (out==True):
memo[target]=True
return(True)
memo[target]=False
return(False)
print(canConstruct('aabbc',['aa','b','c']))
instead of getting true I am getting the error maximum recursion depth exceeded in comparison.
I have checked my recursion limit it is 1000.
Can anyone tell me if I am doing anything wrong.
Thank you in advance.
Ok, there are few pitfalls in your code.
The main issue was, the for loop, because every time it calls the function, it started a new loop, hence the index of i was always one, this was creating the maximum recursion depth error.
The memo parameter, was been redundant to make it as a Dictionary,better in this case as a List.
This suffix=target[pos:pos+len(workbank[i])] had wrong position, it is supposed to be:
suffix = target[len(workbank[idx]):]]
Becase you need to leave behind was is already call and move forward right?
You were doing [0:2] which is 'aa' again. Insted you should do [2:] which is bbc
Solution
Note: I create as I understood the issue, if you expect a different output, please let me know in a comment below.
def canConstruct(target,workbank,memo=[], idx=0):
pos = target.find(workbank[idx])
if pos != -1:
memo.append(True)
idx += 1
try:
suffix = target[len(workbank[idx]):]
canConstruct(suffix,workbank,memo, idx)
except IndexError: # Here we exit the recursive call
pass
else: # In case it did not find string, append False
memo.append(False)
return all(memo) # in order to be True, all item in memo must be True
print(canConstruct('aabbc',['aa','bb','c']))
Output
# True
def canConstruct(target, wordbank, memo=None):
if memo is None:memo={}
if target in memo:return memo[target]
if target == '':return True
for word in wordbank:
if target.startswith(word):
suffix = target.replace(word, '', 1)
if canConstruct(suffix, wordbank, memo) == True:
memo[target] = True
return True
memo[target] = False
return False

generating a list but only the first index showed

i want to generate a list, in which only odd number get factorial application. However only the first number will be execute, can you help me? Thanks.
def factorial(x):
if x<=0:
return 1
else:
return x*factorial(x-1)
def odd(x):
if x%2 ==0:
return x
else:
return factorial(x)
def apply_if(factorial,odd,xs):
#xs is a list
i=0
mlst=[]
for x in xs:
if i<len(xs):
return odd(xs[i])
i+=1
mlst=mlst.append(odd(x))
return mlst
You should change apply_if function.
def apply_if(factorial,odd,xs):
mlst=[]
for x in xs:
mlst.append(odd(x))
return mlst
Because at first iteration of loop i will always be smaller than lenght of ws list (if it's not empty). Also append method doesn't return anything so you shouldn't use a = a.append() as it just appends element to given list.

I am getting ZeroDivisionError while dividing by squared argument

I'm writing a recursive function in python that keeps giving me a division by zero error, why am I getting this?
I've tried several rearrangements of if statements to eliminate all operations when n==0 but somehow it still occurs. I've added a print(n) to the else portion to see when the error occurs and it prints fine all the way to n=2, but then when n=1 it seems I get the error. This is strange because when I do kleinfeldt(1) it works fine...
def kleinfeldt(n):
if n == 1:
return 1
else:
return ((1/(n^2)) + kleinfeldt(n-1))
If I type in kleinfeldt(3) for example, I should get a result of 1 + 1/4 + 1/9, but instead it just says that there's a division by zero error.
It seems that you confused the XOR operator (^) with power operator (**). The code works fine if change it:
def kleinfeldt(n):
if n == 1:
return 1
else:
return ((1/(n**2)) + kleinfeldt(n-1))
If you care about precise result you may want to read about fractions module.
Yes, indeed you will get an ZeroDivisionError: integer division or modulo by zero error because you are using an xor(^) operator in the below line of else condition :
return ((1/(n^2)) + kleinfeldt(n-1))
When it comes to the input 3, 2^2 will give you the 0 output so if you divide 1/(2^2) you will get an error.
To avoid this, you can use ** which will act as a power function or you can do like below :
import math
int(math.pow(2, 2))
Try the below modified codes :
def kleinfeldt(n):
if n == 1:
return 1
else:
return ((1/(n**2)) + kleinfeldt(n-1))
Or
import math
def kleinfeldt(n):
if n == 1:
return 1
else:
return ((1/(int(math.pow(n, 2)))) + kleinfeldt(n-1))
I hope it helps...

Value-Returning Function Not Returning Any Value

Am I doing something wrong? There was no errors running the program. This should output a boolean value, but when I run it there is no return value. The program lets the user to enter a number, but then the program doesn't return anything.
def main():
num = int(input("Enter a number:"))
isPrime(num)
def isPrime(num):
if num < 2:
return False
elif num == 2:
return True
else:
for counter in range(2, num):
if num % counter == 0:
return True
return False
main()
Do you mean to print isPrime (num)?
No, the return statement itself will not print to the console. The print statement does that.
"return" only returns that value from the function, it does not display anything to the screen. You could assign the value that is being returned to a variable, but if it is not assigned or used, it is lost. If you wanted it to actually be displayed, you could do
print(isPrime(num))
which will then print out the resulting boolean to the console, or assign the returned value to a variable for later use.
You may do like this
result = isPrime(num)
print(result)

Why does this code return none

why does the following code returns none:
j = 22
def test(j):
if j > 0:
print('j>0')
else:
print('j<0')
Output:
j>0
None
A function in Python always has a return value, even if you do not use a return statement, defaulting to None
Because the test function doesn't return a value, it ends up returning the object None. that's why it ended up printing None Since you do not have a return value specified
you may not use print in your function, but return a string instead
def test(j):
if j > 0:
return 'j>0'
else:
return 'j<0'
then call it like this: print it when calling the function
print(test(22))
see answer's here for more detail

Resources