Hi i am new to Python programming . I am writing a python code which uses stack.
There are two function in my python code isdesc() and poisonplant()
When i have called the function poisonplant in there is another function but that function is not get called
Code is indented properly
Here is my code:
def isdesc(arr):
if len(arr) == 0:
return False
for i in range(0,len(arr)):
if arr[i+1] < arr[i]:
return True
else:
return False
def poisonplant(expr):
count=0
pdb.set_trace()
while not isdesc(expr):
s.push(expr[0])
for i in range(0,len(expr)):
if expr[i+1] < expr[i]:
s.push(expr[i+1])
count+=1
del expr[:]
for each_item in s.items:
a=s.pop()
expr.insert(0,a)
return count
input1=[6,5,8,4,7,10,9]
print(poisonplant(input1))
I have only called poisonplant and i think isdec is automatically get called inside poison function.
Can someone help me in this why isdesc is not get called here
isdesc is returning too soon, without looking at all the adjacent elements. It should read
def isdesc(arr):
for i in range(len(arr)-1):
if arr[i] < arr[i+1]:
return False
return True
(I've slightly modified the definition to treat empty lists as descending. If you treat an empty list as non-descending, you'll enter the loop, where you are assuming the list is not empty.)
Your main problem is that you're using return as if it will return each iteration, but you're actually just going to return on the very first one. You could instead return False if any of the sorts are wrong, but a better way to check if the lists are sorting in descending order is to check if the list is equal to a reverse sort of itself.
def isdesc(arr):
if len(arr) == 0:
return False
return arr == sorted(arr, reverse=True)
Related
The problem is my code keeps reflecting a variable as zero and this is caused by the fact that the variable is assigned at the start of my function, so each time I call the function the value evaluates to zero. However I need this variable assignment for the code to work and placing it within the elif statements still evaluates to zero and placing the the variable outside the function causes the function not work.
The aim of the program is to count pairs of consecutive letters in a string using recursion with no for/while loops in the code.
def countpairs(s):
pairs=0
if len(s)<2:
return 0 #base case
elif s[0].lower() == s[1].lower(): #recursion
pairs=+1
return countpairs(s[1:])
else: #recursion
pairs=+0
return countpairs(s[1:])
print(countpairs('Hello Salaam'))
This code is supposed to evaluate to 2 because of "ll" and "aa".
You need to wrap your head a little around what the recursion will do: it will call the function recursively to count the pairs from that point on, then (it should) add the pair, if any, found by this instance.
So your function needs to do something with the result of the recursive call, not just return it unchanged. For example, instead of this
elif s[0].lower() == s[1].lower():
pairs = +1
return countpairs(s[1:])
you might write this:
elif s[0].lower() == s[1].lower():
return countpairs(s[1:]) + 1
Something along these lines. You'll need to do a bit more work to get it just right, but I hope you get the idea.
The problems is that the variable pairs resets every recursive call...
When using counting recursive algorithms you don't need a variable that counts, that's the beauty
Instead, try to think how to recursive call can help you count.
def countpairs(s):
if len(s)<2:
return 0
elif s[0].lower() == s[1].lower():
return countpairs(s[1:])+1
else:
return countpairs(s[1:])
print(countpairs('Hello Salaam'))
There you go, in the recursive call the "counter" gets bigger every time it should be, think of the counter as a part of the function stack (or something like that).
You need to fix the syntax: pairs=+1 should be pairs+=1, same for pairs=+0. And you can pass the total into the next level.
def countpairs(s, pairs=0):
if len(s)<2:
return pairs #base case
elif s[0].lower() == s[1].lower(): #recursion
pairs+=1
return countpairs(s[1:], pairs)
else: #recursion
pairs+=0
return countpairs(s[1:], pairs)
print(countpairs('Hello Salaam')) # 2
You can do it by creating a recursive nested function and defining pairs in the outer function. Here's what I mean (with fixes for other issues encountered):
def countpairs(s):
pairs = 0
def _countpairs(s):
nonlocal pairs # Since it's not local nor global.
if len(s) < 2: # base case
return pairs
elif s[0].lower() == s[1].lower():
pairs += 1
return _countpairs(s[1:]) # recursion
else:
return _countpairs(s[1:]) # recursion
return _countpairs(s)
print(countpairs('Hello Salaam')) # -> 2
The code will always evaluate to zero because the last recursion will always have the length of s being less than 2. Instead use the global keyword to be able to grab the value of pairs.
numberOfPairs = 0
pairsList = []
def countpairs(s):
global numberOfPairs
if len(s)<2:
print("doing nothing")
return 0 #base case
elif s[0].lower() == s[1].lower(): #recursion
numberOfPairs+=1
newString = f"{s[0]} is equal to {s[1]}"
print(newString)
pairsList.append(newString)
return countpairs(s[1:])
else:
print(f"nothing happened: {s[0]}") #recursion
return countpairs(s[1:])
print(f"\nThe returned value of countpairs is: {countpairs('Hello Salaam')}")
print(f"Number of pairs: {numberOfPairs}")
print(pairsList)
def sudoku_solver(sudoku):
l = [0, 0]
if not find_empty_location(sudoku, l):
return True
row = l[0]
col = l[1]
for num in range(1, 10):
if check_location_is_safe(sudoku, row, col, num):
sudoku[row][col] = num
if sudoku_solver(sudoku):
return True,sudoku
sudoku[row][col] = 0
return False
def P():
a = np.zeros((9,9))
if sudoku_solver(sudoku):
a = sudoku_solver(sudoku)[1]
else:
a = 1
return a
There are two returns, True and sudoku. How can I call sudoku only in function P? When I run the function P(), it will show
'bool' object is not subscriptable.
You could make your function return a single value that would be either None or the sudoku data.
Python treats None as false so your condition could then be:
...
if sudoku_solver(sudoku):
a = sudoku_solver(sudoku)
...
Note that if sudoku_solver() is a complex and time consuming function, you will want to place its result in a variable BEFORE testing the condition so that it is not executed twice (as would be the case in the above condition)
...
a = sudoku_solver(sudoku)
if a:
...
Another option would be to systematically return a tuple with the boolean and the sudoku data (or None).
Your return statements would have to be changed to return True,sudoku and return False,None
Then your condition could use indexing directly:
...
if sudoku_solver(sudoku)[0]:
a = sudoku_solver(sudoku)[1]
...
but again, you probably don't want to execute the function twice so :
...
ok,a = sudoku_solver(sudoku)
if ok :
...
Another thing is that, if you're passing sudoku as a parameter, you have to realize that your function will modify the content of the calling variable even when it returns False. That may not be what you want but if it is, then there is no point in returning a second value because the caller's instance of the sudoku variable will already be modified and available.
When you see
return True,sudoku
you can catch the returned values like so
result, sudoku = my_function()
or if you've no interest in result
_, sudoku = my_function()
---Edit---
It seems your question centers around the two returns. Namely
return True,sudoku
versus
return False
That's adds unnecessary complexity. Can I suggest you simplify by instead using
return sudoku
and then later
return None
That means you can check the returned value like so
sudoku = my_function()
if (sudoku):
// Do something here
else:
// Do something else
You can't return multiple objects from a function, but you can return a container object, such as a list or tuple, that contains multiple member objects. Try using
return [ True, sudoku ]
I'm attempting to generate all n choose k combinations of a list (not checking for uniqueness) recursively by following the strategy of either include or not include an element for each recursive call. I can definitely print out the combinations but I for the life of me cannot figure out how to return the correct list in Python. Here are some attempts below:
class getCombinationsClass:
def __init__(self,array,k):
#initialize empty array
self.new_array = []
for i in xrange(k):
self.new_array.append(0)
self.final = []
self.combinationUtil(array,0,self.new_array,0,k)
def combinationUtil(self,array,array_index,current_combo, current_combo_index,k):
if current_combo_index == k:
self.final.append(current_combo)
return
if array_index >= len(array):
return
current_combo[current_combo_index] = array[array_index]
#if current item included
self.combinationUtil(array,array_index+1,current_combo,current_combo_index+1,k)
#if current item not included
self.combinationUtil(array,array_index+1,current_combo,current_combo_index,k)
In the above example I tried to append the result to an external list which didn't seem to work. I also tried implementing this by recursively constructing a list which is finally returned:
def getCombinations(array,k):
#initialize empty array
new_array = []
for i in xrange(k):
new_array.append(0)
return getCombinationsUtil(array,0,new_array,0,k)
def getCombinationsUtil(array,array_index,current_combo, current_combo_index,k):
if current_combo_index == k:
return [current_combo]
if array_index >= len(array):
return []
current_combo[current_combo_index] = array[array_index]
#if current item included & not included
return getCombinationsUtil(array,array_index+1,current_combo,current_combo_index+1,k) + getCombinationsUtil(array,array_index+1,current_combo,current_combo_index,k)
When I tested this out for the list [1,2,3] and k = 2, for both implementations, I kept getting back the result [[3,3],[3,3],[3,3]]. However, if I actually print out the 'current_combo' variable within the inner (current_combo_index == k) if statement, the correct combinations print out. What gives? I am misunderstanding something to do with variable scope or Python lists?
The second method goes wrong because the line
return [current_combo]
returns a reference to current_combo. At the end of the program, all the combinations returned are references to the same current_combo.
You can fix this by making a copy of the current_combo by changing the line to:
return [current_combo[:]]
The first method fails for the same reason, you need to change:
self.final.append(current_combo)
to
self.final.append(current_combo[:])
Check this out: itertools.combinations. You can take a look at the implementation as well.
I have an assignment I've been stuck on for a couple days now. I have to recursively figure out if a list has repeats but I cannot use any loops or built in functions besides len(). I'm also not allowed to use the 'in' function. Returns True if list L has repeats, False otherwise. This is what I've been able to figure out:
def has_repeats(L):
if len(L) <= 1:
return False
elif L[0] == L[1]:
return True
else: return has_repeats(L[0] + L[2:])
But the problem with that is it's only comparing the first element to the rest, instead of each element to the rest. I can't figure out how to do that without a running counter or something. Any suggestions?
You almost have it. Along with checking the first element with the rest of the list, you also need to check the second the same way:
def has_repeats(L):
if len(L) <= 1:
return False
if L[0] == L[1]:
return True
if has_repeats([L[0]] + L[2:]):
return True
if has_repeats(L[1:]):
return True
return False
You can also compact this into the following representation:
def has_repeats(L):
return len(L)>1 and L[0]==L[1] or has_repeats([L[0]]+L[2:]) or has_repeats(L[1:])
Use a helper function:
def helper(ele, rest):
if not rest:
return False
return ele == rest[0] or helper(ele, l[1:])
def has_repeats(l):
if not l:
return False
return helper(l[0], l[1:]) or has_repeats(l[1:])
I am trying to write a function which is supposed to compare list structures (the values are indifferent). The problem is that I have two lists which are unequal but the function still returns True even though it actually goes into the else part. I don't understand why and what I did wrong. Here is my code:
def islist(p): #is p a list
return type(p)==type(list())
def ListeIsomorf(a,b):
if len(a)==len(b):
for i,j in zip(a,b):
if islist(i) and islist(j):
ListeIsomorf(i,j)
elif islist(i) or islist(j):
return(False)
return(True)
else:
print(a,"length from the list isn't equal",b)
return(False)
#example lists
ListeE = [[],[],[[]]]
ListeD = [[],[],[[]]]
ListeF = [[[],[],[[]]]]
ListeG = [[],[[]],[[]]]
ListeH = [1,[3]]
ListeI = [1,3]
#tests
print(ListeIsomorf(ListeD,ListeE)) # True
print(ListeIsomorf(ListeD,ListeF)) # False
print(ListeIsomorf(ListeD,ListeG)) # False
print(ListeIsomorf(ListeH,ListeI)) # False
So the problem only occurs with the third print(ListeIsomorf(ListeD,ListeG)) # False. It actually goes into the else part and does print the "length from the list isn't equal" but it doesn't stop and it doesn't give out the return(False). Am I missing something?
The problem is that when your function calls itself recursively:
ListeIsomorf(i,j)
it ignores the returned value.
Thus the comparisons that take place at the second level of recursion have no effect on what the top level returns.
Changing the above to:
if not ListeIsomorf(i,j):
return(False)
fixes the problem.