When i change True to False in the first code my output stays same.Why is that? - python-3.x

My code:
liste = ["345","sadas","324a","14","zxc"]
for i in liste:
try:
int(i) == True #(make it false for example)
print(i)
except:
pass
for i in liste:
try:
i = int(i)
print(i)
except:
pass
output:
345
14
Here as you can see there are two different codes and the question is only write the numbers not letters.(By using try-except). But my question is when i change True to False in the first code my output stays same.Why is that?

This:
int(i) == True #(make it false for example)
first try to make an int of i, and if the operation succeeds, compares it with True, then discard the result of the test. IOW, the whole comparison ends up being a no-op ((functionally speaking - the code is still executed), and could as well be replaced with just
`int(i)`
Of course since the result of the comparison is discarded, you could test against just any value that's comparable with an int (another int, a float, a bool etc), this would make absolutely no difference.
As a side note: this:
try:
something()
except:
pass
is pure evil - it catches absolutely everything (including a SystemExit) and ignore it. I understand this is just a quick test code snippet, but do yourself a favour and never do this in real code - always specify the exact exception(s) you expect and can handle at this point in the code, and if you want to ignore them, at least log them somewhere so you know what really happens in your code.

when i change True to False in the first code my output stays same
Because you're not doing anything with that result, as compared to
if int(i) == True:
print(i)
Or simply
if int(i):
print(i)
But, more appropriate would be
if i.isdigit():
print(i)

Related

Why along with output it is showing NONE each time? [duplicate]

What does the return statement do? How should it be used in Python?
How does return differ from print?
See also
Often, people try to use print in a loop inside a function in order to see multiple values, and want to be able to use the results from outside. They need to be returned, but return exits the function the first time. See How can I use `return` to get back multiple values from a loop? Can I put them in a list?.
Often, beginners will write a function that ultimately prints something rather than returning it, and then also try to print the result, resulting in an unexpected None. See Why is "None" printed after my function's output?.
Occasionally in 3.x, people try to assign the result of print to a name, or use it in another expression, like input(print('prompt:')). In 3.x, print is a function, so this is not a syntax error, but it returns None rather than what was displayed. See Why does the print function return None?.
Occasionally, people write code that tries to print the result from a recursive call, rather than returning it properly. Just as if the function were merely called, this does not work to propagate the value back through the recursion. See Why does my recursive function return None?.
Consider How do I get a result (output) from a function? How can I use the result later? for questions that are simply about how to use return, without considering print.
The print() function writes, i.e., "prints", a string in the console. The return statement causes your function to exit and hand back a value to its caller. The point of functions in general is to take in inputs and return something. The return statement is used when a function is ready to return a value to its caller.
For example, here's a function utilizing both print() and return:
def foo():
print("hello from inside of foo")
return 1
Now you can run code that calls foo, like so:
if __name__ == '__main__':
print("going to call foo")
x = foo()
print("called foo")
print("foo returned " + str(x))
If you run this as a script (e.g. a .py file) as opposed to in the Python interpreter, you will get the following output:
going to call foo
hello from inside foo
called foo
foo returned 1
I hope this makes it clearer. The interpreter writes return values to the console so I can see why somebody could be confused.
Here's another example from the interpreter that demonstrates that:
>>> def foo():
... print("hello within foo")
... return 1
...
>>> foo()
hello within foo
1
>>> def bar():
... return 10 * foo()
...
>>> bar()
hello within foo
10
You can see that when foo() is called from bar(), 1 isn't written to the console. Instead it is used to calculate the value returned from bar().
print() is a function that causes a side effect (it writes a string in the console), but execution resumes with the next statement. return causes the function to stop executing and hand a value back to whatever called it.
Think of the print statement as causing a side-effect, it makes your function write some text out to the user, but it can't be used by another function.
I'll attempt to explain this better with some examples, and a couple definitions from Wikipedia.
Here is the definition of a function from Wikipedia
A function, in mathematics, associates one quantity, the argument of the function, also known as the input, with another quantity, the value of the function, also known as the output..
Think about that for a second. What does it mean when you say the function has a value?
What it means is that you can actually substitute the value of a function with a normal value! (Assuming the two values are the same type of value)
Why would you want that you ask?
What about other functions that may accept the same type of value as an input?
def square(n):
return n * n
def add_one(n):
return n + 1
print square(12)
# square(12) is the same as writing 144
print add_one(square(12))
print add_one(144)
#These both have the same output
There is a fancy mathematical term for functions that only depend on their inputs to produce their outputs: Referential Transparency. Again, a definition from Wikipedia.
Referential transparency and referential opaqueness are properties of parts of computer programs. An expression is said to be referentially transparent if it can be replaced with its value without changing the behavior of a program
It might be a bit hard to grasp what this means if you're just new to programming, but I think you will get it after some experimentation.
In general though, you can do things like print in a function, and you can also have a return statement at the end.
Just remember that when you use return you are basically saying "A call to this function is the same as writing the value that gets returned"
Python will actually insert a return value for you if you decline to put in your own, it's called "None", and it's a special type that simply means nothing, or null.
I think the dictionary is your best reference here
Return and Print
In short:
return gives something back or replies to the caller of the function while print produces text
In python, we start defining a function with def, and generally - but not necessarily - end the function with return.
Suppose we want a function that adds 2 to the input value x. In mathematics, we might write something like f(x) = x + 2, describing that relationship: the value of the function, evaluated at x, is equal to x + 2.
In Python, it looks like this instead:
def f(x):
return x + 2
That is: we define a function named f, which will be given an x value. When the code runs we figure out x + 2, and return that value. Instead of describing a relationship, we lay out steps that must be taken to calculate the result.
After defining the function, it can be called with whatever argument you like. It doesn't have to be named x in the calling code, and it doesn't even have to be a variable:
print f(2)
>>> 4
We could write the code for the function in some other ways. For example:
def f(x):
y = x + 2
return y
or even
def f(x):
x = x + 2
return x
Again, we are following steps in order - x = x + 2 changes what x refers to (now it means the result from the sum), and that is what gets returned by return x (because that's the value *at the time that the return happens).
return means "output this value from this function".
print means "send this value to (generally) stdout"
In the Python REPL, a function's return value will be output to the screen by default (this isn't the same as printing it). This output only happens at the REPL, not when running code from a .py file. It is the same as the output from any other expression at the REPL.
This is an example of print:
>>> n = "foo\nbar" #just assigning a variable. No output
>>> n #the value is output, but it is in a "raw form"
'foo\nbar'
>>> print(n) #the \n is now a newline
foo
bar
>>>
This is an example of return:
>>> def getN():
... return "foo\nbar"
...
>>> getN() #When this isn't assigned to something, it is just output
'foo\nbar'
>>> n = getN() # assigning a variable to the return value. No output
>>> n #the value is output, but it is in a "raw form"
'foo\nbar'
>>> print(n) #the \n is now a newline
foo
bar
>>>
This answer goes over some of the cases that have not been discussed above.
The return statement allows you to terminate the execution of a function before you reach the end. This causes the flow of execution to immediately return to the caller.
In line number 4:
def ret(n):
if n > 9:
temp = "two digits"
return temp #Line 4
else:
temp = "one digit"
return temp #Line 8
print("return statement")
ret(10)
After the conditional statement gets executed the ret() function gets terminated due to return temp (line 4).
Thus the print("return statement") does not get executed.
Output:
two digits
This code that appears after the conditional statements, or the place the flow of control cannot reach, is the dead code.
Returning Values
In lines number 4 and 8, the return statement is being used to return the value of a temporary variable after the condition has been executed.
To bring out the difference between print and return:
def ret(n):
if n > 9:
print("two digits")
return "two digits"
else :
print("one digit")
return "one digit"
ret(25)
Output:
two digits
'two digits'
Note that return can also be used for control flow. By putting one or more return statements in the middle of a function, we can say: "stop executing this function. We've either got what we wanted or something's gone wrong!"
For example, imagine trying to implement str.find(sub) if we only had str.index(sub) available (index raises a ValueError if the substring isn't found, whereas find returns -1).
We could use a try/except block:
def find(s: str, sub: str) -> int:
try:
return s.index(sub)
except ValueError:
return -1
This is fine, and it works, but it's not very expressive. It's not immediately clear what would cause str.index to raise a ValueError: a reader of this code must understand the workings of str.index in order to understand the logic of find.
Rather than add a doc-string, saying "...unless sub isn't found, in which case return -1", we could make the code document itself, like this:
def find(s: str, sub: str) -> int:
if sub not in s:
return -1
return s.index(sub)
This makes the logic very clear.
The other nice thing about this is that once we get to return s.index(sub) we don't need to wrap it in a try/except because we already know that the substring is present!
See the Code Style section of the Python Guide for more advice on this way of using return.
To put it as simply as possible:
return makes the value (a variable, often) available for use by the caller (for example, to be stored by a function that the function using return is within). Without return, your value or variable wouldn't be available for the caller to store/re-use.
print, by contrast, prints to the screen - but does not make the value or variable available for use by the caller.
Difference between "return" and "print" can also be found in the following example:
RETURN:
def bigger(a, b):
if a > b:
return a
elif a <b:
return b
else:
return a
The above code will give correct results for all inputs.
PRINT:
def bigger(a, b):
if a > b:
print a
elif a <b:
print b
else:
print a
NOTE: This will fail for many test cases.
ERROR:
----
FAILURE: Test case input: 3, 8.
Expected result: 8
FAILURE: Test case input: 4, 3.
Expected result: 4
FAILURE: Test case input: 3, 3.
Expected result: 3
You passed 0 out of 3 test cases
Here is my understanding. (hope it will help someone and it's correct).
def count_number_of(x):
count = 0
for item in x:
if item == "what_you_look_for":
count = count + 1
return count
So this simple piece of code counts number of occurrences of something. The placement of return is significant. It tells your program where do you need the value. So when you print, you send output to the screen. When you return you tell the value to go somewhere. In this case you can see that count = 0 is indented with return - we want the value (count + 1) to replace 0.
If you try to follow logic of the code when you indent the return command further the output will always be 1, because we would never tell the initial count to change.
I hope I got it right.
Oh, and return is always inside a function.
return should be used for recursive functions/methods or you want to use the returned value for later applications in your algorithm.
print should be used when you want to display a meaningful and desired output to the user and you don't want to clutter the screen with intermediate results that the user is not interested in, although they are helpful for debugging your code.
The following code shows how to use return and print properly:
def fact(x):
if x < 2:
return 1
return x * fact(x - 1)
print(fact(5))
This explanation is true for all of the programming languages not just python.
return is part of a function definition, while print outputs text to the standard output (usually the console).
A function is a procedure accepting parameters and returning a value. return is for the latter, while the former is done with def.
Example:
def timestwo(x):
return x*2
Best thing about return function is you can return a value from function but you can do same with print so whats the difference ?
Basically return not about just returning it gives output in object form so that we can save that return value from function to any variable but we can't do with print because its same like stdout/cout in C Programming.
Follow below code for better understanding
CODE
def add(a, b):
print "ADDING %d + %d" % (a, b)
return a + b
def subtract(a, b):
print "SUBTRACTING %d - %d" % (a, b)
return a - b
def multiply(a, b):
print "MULTIPLYING %d * %d" % (a, b)
return a * b
def divide(a, b):
print "DIVIDING %d / %d" % (a, b)
return a / b
print "Let's do some math with just functions!"
age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)
print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq)
# A puzzle for the extra credit, type it in anyway.
print "Here is a puzzle."
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
print "That becomes: ", what, "Can you do it by hand?"
We are now doing our own math functions for add, subtract, multiply, and divide. The important thing to notice is the last line where we say return a + b (in add). What this does is the following:
Our function is called with two arguments: a and b.
We print out what our function is doing, in this case "ADDING."
Then we tell Python to do something kind of backward: we return the addition of a + b. You might say this as, "I add a and b then return them."
Python adds the two numbers. Then when the function ends, any line that runs it will be able to assign this a + b result to a variable.
The simple truth is that print and return have nothing to do with each other. print is used to display things in the terminal (for command-line programs).1 return is used to get a result back when you call a function, so that you can use it in the next step of the program's logic.
Many beginners are confused when they try out code at Python's interpreter prompt2, like
>>> def example():
... return 1
...
>>> example()
1
The value was displayed; doesn't this mean that return displays things? No. If you try the same code in a .py file, you can see for yourself that running the script doesn't cause the 1 to display.
This shouldn't actually be confusing, because it works the same way as any other expression:
>>> 1 + 1
2
This displays at the interactive prompt, but not if we make a script that just says 1 + 1 and try running it.
Again: if you need something to display as part of your script, print it. If you need to use it in the next step of the calculation, return it.
The secret is that the interactive prompt is causing the result to be displayed, not the code. It's a separate step that the prompt does for you, so that you can see how the code works a step at a time, for testing purposes.
Now, let's see what happens with print:
>>> def example():
... return 'test'
...
>>> print(example())
test
The result will display, whether we have this in an interactive prompt or in a script. print is explicitly used to display the value - and as we can see, it displays differently. The interactive prompt uses what is called the repr of the value that was returned from example, while print uses the str of the value.
In practical terms: print shows us what the value looks like, in text form (for a string, that just means the contents of the string as-is). The interactive prompt shows us what the value is - typically, by writing something that looks like the source code we would use to create it.3
But wait - print is a function, right? (In 3.x, anyway). So it returned a value, right? Isn't the interpreter prompt supposed to display that in its separate step? What happened?
There is one more trick: print returns the special value None, which the interpreter prompt will ignore. We can test this by using some expressions that evaluate to None:
>>> None
>>> [None][0]
>>> def example():
... pass # see footnote 4
...
>>> example()
>>>
In each case, there is no separate line at all for output, not even a blank line - the interpreter prompt just goes back to the prompt.
1 It can also be used to write into files, although this is a less common idea and normally it will be clearer to use the .write method.
2 This is sometimes called the REPL, which stands for "read-eval-print loop".
3 This isn't always practical, or even possible - especially once we start defining our own classes. The firm rule is that repr will lean on the .__repr__ method of the object to do the dirty work; similarly, str leans on .__str__.
4 Functions in Python implicitly return None if they don't explicitly return a value.
Return statement -- will return some values according your function.
def example(n):
if n == 5:
return true
else:
return false
if you call above function and you pass number 5 then it will return true else it will return false.
Printing function -- it will print content that you have given to the print function or with in print function bracket.
def example(n):
if n == 5:
print("number is equal")
else:
print("number is not equal")

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.

How do I give an option to the user to skip the first calculation part and proceed to the second part?(Python 3.X)

How do you write an if statement (or anything else), that let the user have a choice to do the first calculation or not. For example,
Do you want to do Calculation A?
If yes then show the calculation A, else skip to Calculation B.
How do you write this in code?
The code itself is trivial. Assuming you have a boolean called
doA
where it is true if you want to do the first calc, false otherwise, if looks like:
if(doA) :
# do the A calc
else:
# do the B calc
# rest of code goes here...
But I assume you are asking something slightly different?
For cleaner code, define each calculation in a separate function. Use input() to retrieve the user's input and use if/else to check the input and determine which function to call.
def calcA():
print("Calculation A")
def calcB():
print("Calculation B")
inp = input("Enter yes to do Calculation A: ")
calcA() if inp == "yes" else calcB()

recursion not stopping with 'if'

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.

Resources