Why does this code print None? - python

The Ackermann's Function had been tried to implement through the following code
def A(m, n):
if m == 0:
return n + 1
elif m > 0 and n == 1:
A(m - 1, 1)
elif m > 0 and n > 0:
A(m - 1, A(m, n - 1))
print A(4, 5)

Your function doesn't return anything for 2 of the 3 branches of the if statements; only if m == 0 do you explicitly return a value.
You need to return the results of recursive calls too:
def A(m, n):
if m == 0:
return n + 1
elif m > 0 and n == 1:
return A(m - 1, 1)
elif m > 0 and n > 0:
return A(m - 1, A(m, n - 1))
Without an explicit return, the function ends with the default return value of None.

Related

How to use searching algorithm like jump search or fibonacci search on list that has nested list?

i have a problem with finding the solution to make searching algorithm on a list that have various type of item, especially with nested list.
def fib(n):
if n < 1:
return 1
elif n == 1 :
return 1
else:
return fib(n-1) + fib(n-2)
def fibonaccisearch(arr,x,q):
p = 0
p += q
n = 0
while p > 0:
while fib(n) < len(arr) and p != 0:
n = n + 1
offset = -1
while (fib(n) > 1) and p > 0:
i = min(offset + fib(n-2), len(arr) - 1)
if type(arr[i]) == list:
countingx(arr[i])
z = stringdata2.count(x)
print(f"{x} found1 at index:", i,"kolom ke -",fibonaccisearch(arr[i],x,z))
arr[i] = 'this is x'
p -= 1
elif (x > arr[i]):
n = n-1
offset = i
elif (x < arr[i]):
n = n-2
elif (x == arr[i]):
print(arr[i])
print(f"{x} found2 at index :", i)
p -= 1
arr[i] = 'this is x'
while p == 1:
z = 0
z += i
while z > -1:
if arr[z] != x:
z -= 1
else:
print(f"{x} found3 at index :", z)
arr[z] = 'this is X'
z = -1
p -= 1
else:
print()
if (fib(n-1) and arr[offset + 1] == x):
p -= 1
return offset + 1
return -1
def countingx(data):
global stringdata2
global list1
stringdata1 = []
stringdata2 = []
list1 = []
stringdata1.extend(data)
while True:
if len(stringdata1) == 0:
break
elif type(stringdata1[0]) == str:
stringdata2.append(stringdata1[0])
stringdata1.pop(0)
else:
list1.extend(stringdata1[0])
stringdata1.pop(0)
stringdata1.extend(list1)
list1.clear()
arr = ['b','a', ['c', 'a'], 'd', ['a', 'e', 'c'], 'a']
x = 'a'
countingx(arr)
print(stringdata2)
q = stringdata2.count(x)
print(arr)
fibonaccisearch(arr,x,q)
this is my code i dont know whats wrong with it i completely lost my mind trying to find the solution, i try to modified it the closes i find is, the code find the way to find the 'a' in the index 2 column 1, index 4 column 0, and index 5 but skips the 'a' in the index 1, i tried to fix it but it still dont works.

Number of subsets with a given sum . Recursion not tracing few branches of the tree

I have written this code in python and it is not yielding the right answer for the input wt[]=[2,3,5,6,8,10] in this order . It is giving right answer for few other combinations like wt[]=[3,2,6,10,8,5].I I have also tried tracing the recursive tree to debug accordingly but still cannot figure out why the code is not tracing some branches of the tree.
Kindly please help me figure out the problem.
Thank you!
n=6 #int(input())
m=10 #int(input())
wt=[2,3,5,6,8,10]
dp_table=[[-1 for i in range(n+1)]for j in range (m+1)]
total=[0]
def SS(m,n):
a=0
b=0
if m==0:
print(n-1)
total[0]=total[0]+1
return 0;
if n==0:
return 0;
else:
if wt[n-1]>m:
return (SS(m,n-1));
else:
if dp_table[m-wt[n-1]][n-1]==-1:
a=SS(m-wt[n-1],n-1) + wt[n-1]
if dp_table[m][n-1]==-1:
b=SS(m,n-1)
dp_table[m][n]=max(a,b)
return dp_table[m][n];
if m==0 or n==0:
print("Not Possible!")
if SS(m,n)==m:
print("Possible and the no of subsets with equal sum are: ",total[0])
else:
print("False")
You're storing results in dp_table but never using them (giving incorrect results). If the dp_table value of an entry isn't -1, you're ignoring the result (and assuming it's always 0).
Often it's better to do the cache-checks at the top of the function (or better yet, use functools.cache).
If you really want to keep the code structured as it is now, this will fix the issue:
def SS(m, n):
a = dp_table[m - wt[n - 1]][n - 1]
b = dp_table[m][n - 1]
if m == 0:
total[0] += 1
return 0
if n == 0:
return 0
else:
if wt[n - 1] > m:
dp_table[m][n] = b if b != -1 else SS(m, n - 1)
else:
if a == -1:
a = SS(m - wt[n - 1], n - 1)
a += wt[n - 1]
if b == -1:
b = SS(m, n - 1)
dp_table[m][n] = max(a, b)
return dp_table[m][n]
If you want to do the caching yourself, you can put cache checks at the top (a better approach), rather than putting a check (and an if-else statement) before every recursive call, like this:
def SS2(m, n):
if dp_table[m][n] != -1:
return dp_table[m][n]
if m == 0:
total[0] += 1
dp_table[m][n] = 0
elif n == 0:
dp_table[m][n] = 0
else:
if wt[n - 1] > m:
dp_table[m][n] = SS(m, n - 1)
else:
dp_table[m][n] = max(SS(m - wt[n - 1], n - 1) + wt[n - 1], SS(m, n - 1))
return dp_table[m][n]
But the most 'Pythonic' and least work alternative is to use the decorators built into the standard library. You can limit the total memory usage, and it might even be faster if your manual DP-table happens to have cache-unfriendly access patterns.
import functools
#functools.cache
def SS3(m, n):
if m == 0:
total[0] += 1
return 0
elif n == 0:
return 0
else:
if wt[n - 1] > m:
return SS(m, n - 1)
else:
return max(SS(m - wt[n - 1], n - 1) + wt[n - 1], SS(m, n - 1))

Fast Prime Generator besides Sieve

I recently made this bit of code, but wonder if there is a faster way to find primes (not the Sieve; I'm still trying to make that). Any advice? I'm using Python and I'm rather new to it.
def isPrime(input):
current = 0
while current < repetitions:
current = current + 2
if int(input) % current == 0:
if not current == input:
return "Not prime."
else:
return "Prime"
else:
print current
return "Prime"
i = 1
primes = []
while len(primes) < 10001:
repetitions = int(i)-1
val = isPrime(i)
if val == "Prime":
primes.append(i)
i = i + 2
print primes[10000]
here is a function that detect if x is prime or not
def is_prime(x):
if x == 1 or x==0:
return False
elif x == 2:
return True
if x%2 == 0:
return False
for i in range(3, int((x**0.5)+1), 2):
if x%i == 0:
return False
return True
and another implementation that print prime numbers < n
def prime_range(n):
print(2)
for x in range(3, n, 2):
for i in range(3, int((x**0.5)+1), 2):
if x%i == 0:
break
else:
print(x)
hope it helps !
If you are not using a sieve, then the next best are probably wheel methods. A 2-wheel checks for 2 and odd numbers thereafter. A 6-wheel checks for 2, 3 and numbers of the form (6n +/- 1), that is numbers with no factors of 2 or 3. The answer from taoufik A above is a 2-wheel.
I cannot write Python, so here is the pseudocode for a 6-wheel implementation:
function isPrime(x) returns boolean
if (x <= 1) then return false
// A 6-wheel needs separate checks for 2 and 3.
if (x MOD 2 == 0) then return x == 2
if (x MOD 3 == 0) then return x == 3
// Run the wheel for 5, 7, 11, 13, ...
step <- 4
limit <- sqrt(x)
for (i <- 5; i <= limit; i <- i + step) do
if (x MOD i == 0) then return false
step <- (6 - step) // Alternate steps of 2 and 4.
end for
return true
end function
I leave it to you to convert that into Python.
As in
n = 10000
for p in range(2, n+1):
for i in range(2, p):
if p % i == 0:
break
else:
print p
print 'Done'
?

Why does my boolean function sometimes return None?

Using Python 3.4. Have attempted to call function prime/2 that returns a boolean--always either True or False--from within an IF-statement. The function is expensive to run, so I want to call it only when I know it is needed, hence calling from within a decision point. The called function does not reliably return True/False. Sometimes the return is None, at which point the test fails. I use Python's IDLE and its debugger. I call primes(2, 5, []) and step through the code. When prime/2 reaches line elif n <= p while n = 5 and p = 5, the debugger shows that prime/2 returns True, as it should, but the line in primes/3 elif prime(m, 2) takes a value of None. And at that point my test fails. My code:
def primes(m, n, l): # the calling function
if m > n: # creates a list of primes from
print(l, end='\n') # m through n, inclusive
elif m < 2:
primes(2, n, l)
elif m == 2:
l.append(2)
primes(3, n, l)
elif m % 2 == 0:
primes(m + 1, n, l)
elif prime(m, 2): # calling the second function
l.append(m) # to test m for primality
primes(m + 2, n, l)
else:
primes(m + 2, n, l)
def prime(n, p): # the called function will return
if n < 2: # True if m is prime, False otherwise
return False
elif n < 4:
return True
elif n <= p:
return True
elif (n > 2) and (n % p == 0):
return False
elif p == 2:
prime(n, 3)
else:
prime(n, p + 2)
The error is in how you call prime() recursively. You need to explicitly return the value. Like this:
def prime(n, p): # the called function will return
if n < 2: # True if m is prime, False otherwise
return False
elif n < 4:
return True
elif n <= p:
return True
elif (n > 2) and (n % p == 0):
return False
elif p == 2:
return prime(n, 3) # <--- RETURN VALUE
return prime(n, p + 2) # <--- & RETURN VALUE

A bug in my simple python program of lcs

import numpy as np
def lcs(i, j):
global x, y, c
if i <= 0 or j <= 0:
return 0
else:
if c[i][j] < 0:
if x[i - 1] == y[j - 1]:
c[i][j] = lcs(i - 1, j - 1) + 1
else:
m = lcs(i - 1, j)
n = lcs(i, j - 1)
print m, n
c[i][j] = max(m, n)
else: return c[i][j]
c = np.zeros((8, 8), int)
c = c - 1
x = 'ABCBDAB'
y = 'BDCABA'
lcs(7, 6)
print c
the program has bugs so i lookup the 'm','n',
the print results come up with 'None'
ex:
0 0
0 None
0 None
0 None
None None
then the program occur an error:
TypeError: long() argument must be a string or a number, not 'NoneType'
i don't know where the 'None' comes
i'm a newer, thanks
i don't know where the 'None' comes
If you don't return anything, the return value of a python function is None.
In particular, you don't return anything in the if c[i][j] < 0: branch.

Categories