recursion not stopping with 'if' - string

I am trying to write a code which prints True if given string has at max 2 consecutive c, and at max 1 b. I am using recursion to reduce the string and check that at max 'c' is present in the same index twice.But my recursion is not stopping till it empties the whole list. Can you please suggest what's wrong with my code. Thanks!
def stringcond(N,count=0,k=0):
N=list(N)
if(N.count('b')>1):
return False
if len(N)<2:
return True
else:
for i,j in enumerate(N):
if(j=='c'):
del N[i]
count+=1
if(k==i and count>2):
return False
stringcond(N,count=count,k=i)
return True

You have several mistakes. First, why are you splitting the characters into a list? There is a perfectly good count method for strings.
Your recursion fails because you ignore the return value. You would want something like
if not stringcond(N,count=count,k=i):
return False
# I make no claim that this logic is correct.
In any case, there is no need to recur. Use count to check the quantity of "b" and many-'c' substrings:
def stringcond(s, c_max=0):
return s.count('b') <= 1 and \
s.count("c" * (c_max+1)) == 0

You have to use the result of the stringcond call. Now your function will only return whatever was determined on the top level call.

Related

How can I convert this code into one liner or reduce the number of lines using list comprehension?

def consecutive_zeros(input_binary):
count = 0
count_list = list()
for x in input_binary:
if x == "0":
count += 1
else:
count_list.append(count)
count = 0
return max(count_list)
I tried different ways to implement the same but was getting syntax error or wrong output.
Is there a more efficient way in which I can implement the same? How to make it one liner?
It looks like you want to find the longest sequence of zeros following a one. If this is correct zeros in the end should not be counted. I have a solution that is based on string operations as I assume your input is a string. If not please consider adding an example input to your question.
def consecutive_zeros(input_binary):
return max(map(len, input_binary.rstrip('0').split('1')))
print(consecutive_zeros('0000111110001000000')) # 4
print(consecutive_zeros('00001111100010000001')) # 6
EDIT: As your function is named consecutive_zeros it could be that you also want a sequence in the end, which would not be counted in your code. If you want to count it you can use this code:
def consecutive_zeros(input_binary):
return max(map(len, input_binary.split('1')))
print(consecutive_zeros('0000111110001000000')) # 6
print(consecutive_zeros('00001111100010000001')) # 6
Per the function in your question, which returns the number of leading 0s, you can use this:
def consecutive_zeros(input_binary):
return len(input_binary) - len(input_binary.lstrip('0'))

Palindrome problem - Trying to check 2 lists for equality python3.9

I'm writing a program to check if a given user input is a palindrome or not. if it is the program should print "Yes", if not "no". I realize that this program is entirely too complex since I actually only needed to check the whole word using the reversed() function, but I ended up making it quite complex by splitting the word into two lists and then checking the lists against each other.
Despite that, I'm not clear why the last conditional isn't returning the expected "Yes" when I pass it "racecar" as an input. When I print the lists in line 23 and 24, I get two lists that are identical, but then when I compare them in the conditional, I always get "No" meaning they are not equal to each other. can anyone explain why this is? I've tried to convert the lists to strings but no luck.
def odd_or_even(a): # function for determining if odd or even
if len(a) % 2 == 0:
return True
else:
return False
the_string = input("How about a word?\n")
x = int(len(the_string))
odd_or_even(the_string) # find out if the word has an odd or an even number of characters
if odd_or_even(the_string) == True: # if even
for i in range(x):
first_half = the_string[0:int((x/2))] #create a list with part 1
second_half = the_string[(x-(int((x/2)))):x] #create a list with part 2
else: #if odd
for i in range(x):
first_half = the_string[:(int((x-1)/2))] #create a list with part 1 without the middle index
second_half = the_string[int(int(x-1)/2)+1:] #create a list with part 2 without the middle index
print(list(reversed(second_half)))
print(list(first_half))
if first_half == reversed(second_half): ##### NOT WORKING BUT DONT KNOW WHY #####
print("Yes")
else:
print("No")
Despite your comments first_half and second_half are substrings of your input, not lists. When you print them out, you're converting them to lists, but in the comparison, you do not convert first_half or reversed(second_half). Thus you are comparing a string to an iterator (returned by reversed), which will always be false.
So a basic fix is to do the conversion for the if, just like you did when printing the lists out:
if list(first_half) == list(reversed(second_half)):
A better fix might be to compare as strings, by making one of the slices use a step of -1, so you don't need to use reversed. Try second_half = the_string[-1:x//2:-1] (or similar, you probably need to tweak either the even or odd case by one). Or you could use the "alien smiley" slice to reverse the string after you slice it out of the input: second_half = second_half[::-1].
There are a few other oddities in your code, like your for i in range(x) loop that overwrites all of its results except the last one. Just use x - 1 in the slicing code and you don't need that loop at all. You're also calling int a lot more often than you need to (if you used // instead of /, you could get rid of literally all of the int calls).

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

How to convert a conditional statement to a simple expression? Is compounding a return this way Acceptable practice?

The exercise I am doing was given by a book that takes a dictionary argument and asks for me to give a return value of True or False. I am new to Python 3 and as a personal exercise for learning I want to convert all the conditions of a "valid dictionary as a chessboard into" a single return value. I haven't actually tested this code for errors as it isn't finished, but I did run it through an online validator I found https://extendsclass.com/python-tester.html.
I want to know how I can convert the following 2 code blocks into simple expressions to be used in the return statement in my function below, You can see below that I've converted most expressions into the return value already with "and" because "ALL expressions must == True"
for pieces in dictionary.values():
if all(pieces.startswith('b')) or \
all(pieces.startswith('w')):
return True
else:
return False
The above code block loops through the dictionary keys passed to function as "pieces",
and compares each key individually to determine if it starts with a value of 'b' or 'w'. So if any key does not start with 'b' or 'w' the dictionary "chessboard" is false as it contains an improper piece. Ok I think I see an error in this I'm going to look into it and try to figure it out. Ok I noticed some errors in the above code that need to be addressed I am currently researching how to properly execute the above code.
for square in dictionary:
try:
if int(square[:0]) <= 8 and \
square[-1] <= 'h':
return True
else:
return False
except ValueError:
return False
I worked on the above code block a very long time and am still not sure that's the "best" implementation of what I want it to do. But I am still new and did my best.
Anyway it slices the dictionary key and compares the first char in the key to make sure it isn't over 8 which is the maximum "valid range" if over valid range it returns false and anything not int is obviously automatically False and returned as such by the "exception".
Then it slices the dictionary key to get the last char of the dictionary key and compares it to <= 'h' as that is the valid range and anything over 'h' or not a valid type value will return as False.
And then it compares the results of True/False "and" True/False with "and" because both conditions must be True.
Here is the function as it currently is with a test dictionary at the end:
def cBV(dic): # (c)hess(B)oard(V)alidator
Err = 'Error: Invalid Board -'
if not isinstance(dic, type({})):
raise TypeError('Object passed to cBV is not of type <class dict>')
chess_pieces = {'bk pieces': 0, 'wh pieces': 0,
'bk pawns': 0, 'wh pawns': 0}
# converts dictionary values into keys and assigns those keys "counn of values"
for squares, pieces in dic.items:
if pieces.startswith('b'): # alt if pieces[:0] == 'b':
if pieces.startswith('bpawn'): # alt if pieces == 'bpawn':
chess_pieces['bk pawns'] += 1
chess_pieces['bk pieces'] += 1
elif pieces.startswith('w'):
if pieces.startswith('wpawn'):
chess_pieces['wh pawns'] += 1
chess_pieces['wh pieces'] += 1
return 'wking' in dic.values() and \
'bking' in dic.values() and \
chess_pieces['bk pieces'] <= 16 and \
chess_pieces['wh pieces'] <= 16 and \
chess_pieces['bk pawns'] <= 8 and \
chess_pieces['wh pawns'] <= 8 and \
dict = {'8h': 'wking', '2c': 'bking', '3a': 'wpawn', '3b': 'wpawn', '3c': 'wpawn',
'3d': 'wpawn', '3e': 'wpawn', '3f': 'wpawn', '3g': 'wpawn', '3h': 'wpawn', '4b': 'wpawn'}
test = cBV(dict)
print('Is this a valid chessboard? ' + str(test))
What you have now is good, and you should feel proud - there are more fancy techniques for making things more concise, and you'll get more used to them as you wrap your head around how the various data structures work.
for pieces in dictionary.values()
if pieces.startswith('b') or \
pieces.startswith('w'):
return True
else:
return False
can be converted to the one-liner
return all(
piece.startswith('b') or piece.startswith('w')
for piece in dictionary.values()
)
which does a few things.
The all() function takes any iterable object, and returns True if all of the values in that iterable are truthy. If even one of them is not, then it 'short-circuits' and returns False instead.
As our argument to all(), we give a "comprehension". A comprehension is essentially a one-line for loop, of the form f(element) for element in iterable: it performs whatever f(element) is, for every element in the iterable.
In our case, the iterable is dictionary.values(), which returns all of the values (but not the keys) in dictionary (which, here, is 'wking', 'wpawn', ...). In this case, these are strings.
piece is what we assign each element of, for each 'iteration' of the comprehension. It'll run for piece = 'wking', then for piece = 'wpawn', etc.
piece.startswith('b') or piece.startswith('w') is the function that we perform for each piece. This outputs either True or False, depending on whether the conditions are met.
You can wrap a comprehension in square-brackets [] to have it output as a regular list. However, if you give a comprehension as an argument to a function like all(), which is what we're doing here, then it will end up as a "generator", a slightly more efficient object that only calculates one object at a time. For our purposes, this isn't important.
The comprehension, overall, produces a series containing either True or False, that all() will consume.
Similarly with your second code snippet. You have the basics down, but can be more concise. Your code:
def allSquaresAreInRange(dictionary):
for square in dictionary:
try:
if int(square[:0]) <= 8 and \
pieces[-1] <= 'h':
return True
else:
return False
except ValueError:
return False
can be turned into
def allSquaresAreInRange(dictionary):
try:
return all(
(1 <= int(row) <= 8) and ('a' <= col <= 'h')
for (row, col) in dictionary
)
except ValueError:
return False
Here we make use of a few things:
As before, we use all(), and as before, we use a comprehension. But this time, we iterate through dictionary directly
Iterating through a dict is functionally identical to iterating through dict.keys(). So, we're iterating through the keys '8h', '2c', ...
Each key is a two-character string. Strings are iterable, just like lists are, and most iterables have an interesting property called "multiple assignment": if we assign exactly as many variables as the iterable has elements, then those elements get split up.
(row, col) = '8h', for example, is functionally identical to row = '8h'[0] and col = '8h'[1]. In both cases, we're left with row = '8' and col = 'h'.
This produces a ValueError if the number of elements on either side is mismatched - for example, if the key has only one character, or only three characters. A byproduct of this is that row and col are guaranteed to be exactly one-character long strings, if that error doesn't happen.
Our condition checks if the row is between 1 and 8, and whether the col is between A and H, using greater than/less than signs. This returns True or False, once again.
As you seemed to discover, using int() on something that doesn't represent an integer will also throw a ValueError.
This new snippet keeps the try/except blocks you came up with in yours, because they work just fine.
Python has a bit of a culture surrounding it that prides 'efficiently-written' code. Which is to say, code that looks as fancy as possible, and follows Functional Programming paradigms. Comprehensions, as well as all() and any(), are a big part of that, and so they're probably the 'correct' solution for any problem which they are a solution for (if they can be written concisely).
Similarly, the snippet
if condition:
return True
else:
return False
can almost always be condensed to
return condition
(or return bool(condition), in the case that condition deals with a value that has truthiness but isn't a boolean, such as None or an empty list or string). If this is applicable, it's good practice (but again, it's not always applicable).
The most important thing, though, is that your code works the way you want it to, and that it's clear enough for you to come back to it a few months down the line and figure out what you were doing, and why you were doing it that way. There are some cases where things can be written as comprehensions but that makes them extremely complicated and unreadable - and in those cases, it's sometimes a good idea to not write them as comprehensions, and do it the more verbose way. Just keep that in mind as you're continuing to develop, and you'll do fine.

Error: maximum recursion depth exceeded in comparison

I am trying to find a character in an alphabetized string... Here is the code
def isIn(char, aStr):
middleChar = len(aStr)//2
if char == aStr[middleChar]:
return True
elif char < aStr[middleChar]:
LowerHalf = aStr[:middleChar]
return isIn(char, LowerHalf)
elif char > aStr[middleChar]:
UpperHalf = aStr[middleChar:]
return isIn(char, UpperHalf)
else:
return False
print(isIn('a', 'abc'))
It returns True. But When I put
print(isIn('d', 'abc'))
it returns this error: maximum recursion depth exceeded in comparison; instead of False.
I don't understand whats wrong. Please tell me where is the logical mistake I am doing.
With d, The program splits the string from abc and picks out UpperHalf bc. Then it searches the new string bc. It then returns 'c' from 'bc' as expected. Since d > c, the program goes chooses that condition and once again returns the upper half of string 'c', which is c. Hence the recursion. To fix this, you need a separate way of handling length 1 strings.
The last else is useless - it will never be executed.
The end of binary search is when the array becomes of one item - if this item isn't the searched one, the searched item isn't in the array.

Resources