Im trying to write a recursive function that gets as an input a string and a char. the function return the first index appearance of the char in the string. If the char doesnt appear it returns None.
I have a problem only with returning None. In my case when the char isnt in the string the function throws an error, any advice?
def char_first_index(s,c):
if len_rec(s)==0:
return None
if s[0]==c:
return 0
return 1+ char_first_index(s[1:],c)
You are creating a new slice at each iteration, and you have to add 1 for each recursion. Instead, recurse on the index:
def char_first_index(s, c, index = 0):
if len(s) == index:
return None
if s[index] == c:
return index
return char_first_index(s, c, index + 1)
If the character is not in the input, your function tries to perform 1+None, hence the error. Try this instead:
def char_first_index(s,c):
if len_rec(s)==0:
return None
if s[0]==c:
return 0
answer = char_first_index(s[1:],c)
if answer is not None:
return 1+answer
else:
return answer
Firstly I'm assuming len_rec is a recursive function that gets the length of the string; you haven't written it so I've just changed it to len() for testing.
Secondly, I'm not sure how this function is supposed to handle the character not being in the string, as that will mean trying to add None to a number.
Here is an amended function that still uses your count idea, but handles the case of a None being returned:
def char_first_index(s,c):
if len(s)==0:
return None
elif s[0]==c:
return 0
else:
count = char_first_index(s[1:], c)
if count != None:
return count + 1
else:
return None
Related
In this Exercise, you will sum the value of a string. Complete the recursive function
def sumString(st):
This function accepts a string as a parameter and sums the ASCII value for each character whose ASCII value is an even number.
I know how to sum all the values but the even numbers part is challenging.
def sumString(st):
if not st:
return 0
else:
return ord(st[0]+sumString(st[1:])]
I tried something but i am just confused at this point.
def sumString(st):
if not st:
return 0
t=[ord(st[0]),sumString(st[1:])]
for item in t:
if item%2==0:
return item+t
Maybe something like this?
def sumString(st):
if not st:
return 0
else:
out = ord(st[0]) if ord(st[0]) % 2 == 0 else 0
return out + sumString(st[1:])
print(sumString("abcd"))
Output:
198
The ASCII value for b is 98 and the ASCII value for d is 100. So 100 + 98 gives you the output.
When posting code which causes an error, make sure to include that error
TypeError: unsupported operand type(s) for +: 'int' and 'list' in this case.
No offense, but the code you have written is a hot mess. You create a list with the ord of the first char, then the output of the function.
I think you then attempt to check if both values are even (not needed), and then return the sum (which you dont do since the return statement is inside the loop).
To do this you only need to check the first value of the string, then hand the rest to the same function
def sumString(st):
if not st:
return 0
out = sumString(st[1:]) # get output of the rest of the string
if ord(st[0]) % 2 == 0: # check if first char in str is even
out += ord(st[0])
return out
Here a method recursive and non:
def recursive_sum_even_ascii(s):
if s:
first, *other = s
value = 0
if not ord(first) % 2:
value = ord(first)
return value + recursive_sum_even_ascii(other)
return 0
def sum_even_ascii(s):
return sum(ord(char) for char in s if not ord(char) % 2)
# test
s = "23"
out_rec = recursive_sum_even_ascii(s)
out = sum_even_ascii(s)
print(out_rec == out)
Could you please help me why the second method does not work in the class even though it works separately?
the question is
Develop a SuperStr class that inherits the functionality of the standard str type and contains 2 new methods:
a. is_repeatance(s) method, which takes 1 argument s and returns True or False depending on whether the current row can be obtained by an integer number of repetitions of the string s. Return False if s is not a string. Assume that the empty string contains no repetitions.
b. is_palindrom() method, which returns True or False depending on whether the string is a palindrome. Ignore the case of characters. The empty string is considered a palindrome.
my code:
class SuperStr:
def __init__(self, main_str):
self.main_str= main_str
def is_repeatance(self, s):
string = self.main_str
count = 0
is_repeated = False
if string == '':
return False
else:
for i in range(0, len(string)):
if string[i] == s:
count = count + 1
if count == 2:
is_repeated = True
return is_repeated
break
return is_repeated
def isPalindrome(str):
if str == '':
return True
else:
for i in range(0, int(len(str) / 2)):
if str[i] != str[len(str) - i - 1]:
return False
return True
str = SuperStr("welcome to the world of python programming")
print(str.is_repeatance('s'))
print(str.isPalindrome('saas'))
the result is https://drive.google.com/file/d/1dHXK8RJs7vlRovULrUPS5uxRkX_oDNRO/view?usp=sharing
the second method does not work but the first does
even though it works this way if it is alone
https://drive.google.com/file/d/1SBFnQ6OeDGtoTvo98SHeSdIbks8BTXnT/view?usp=sharing
What Avinash said in the comments should fix your problem. You need to include self in the method definition. e.g.
def isPalindrome(self, s):
if s == '':
return True
else:
for i in range(0, int(len(s) / 2)):
if s[i] != s[len(s) - i - 1]:
return False
return True
The error you have is...
TypeError: isPalindrome() takes 1 positional argument but 2 were given
The error is saying that isPalindrome() has been defined with 1 positional argument. In your case this is the str in the def isPalindrome(str):. When you call it using the instance object str.isPalindrome('saas'), python adds the object itself as the first argument, so the method is called with 2 arguments. The object str and the value 'saas'.
Notice also that your def is_repeatance(self, s): method has self as an argument and works fine.
hey so i am trying to write a code that that tells me if a string is valid or not .
a valid string is a string that contains an equal number of "(" and ")" and each "(" must be closed by a ")"
for example
'((()()))' this is a valid string . this isn't ')( '
this is what i wrote so far :
def is_valid_paren(s, cnt=0):
if s == "":
return True
if "(" in s:
cnt += 1
if ")" in s:
cnt -= 1
return is_valid_paren(s[1:])
it doesn't give the correct output for
"(.(a)"
yet for
"p(()r((0)))"
it does
why does it sometimes work ?
oh one more thing this is to be solved only by recursion ( without the use of loops anywhere )
While I don't understand why you want to solve this problem with recursion (it's very unnatural in this case), here is a recursive solution:
def is_valid(s):
def _is_valid(s, idx):
if idx == len(s): return 0
if s[idx] == '(': return _is_valid(s, idx + 1) + 1
if s[idx] == ')': return _is_valid(s, idx + 1) - 1
return _is_valid(s, idx + 1)
return _is_valid(s, 0) == 0
You can pass down a count of pending apertures (i.e. number of unclosed parentheses) and check if the count goes below 0 (too many closures) as you go and if it ends back at zero at the end:
def validPar(s,count=0):
if count<0 : return False # too many closing
if not s: return count == 0 # must balance pending apertures
return validPar(s[1:],count+(-1,1)[s[0]=="("]) # pass down count +/- 1
print(validPar('((()()))')) # True
Recursion
Iteration is likely to be the best method of solving this, but recursion also works. To attack this problem recursively, we need a system of checking the count of each and if at any stage that count falls below zero, the parentheses will be invalid because there are more closing brackets than opening ones. This is where the tough section comes into play: we need some method of not only returning the count, but whether or not the past ones were valid, so we will have to return and save using variables like return count, valid and count, valid = is_valid_parentheses(s[1:]). The next thing we need is some over-arching function which looks at the end results and says: "is the count equal to zero, and were the parentheses valid to begin with". From there, it needs to return the result.
I need to write this iterative function to do the same thing but it must be recursive.
def task1(string: str):
for i in range(len(string)):
if string[i] != string[len(string) - i - 1]:
return False
return True
This is what i tried but it does not work.
def task1_recursion(string: str):
print(string)
if len(string) > 1:
if string[0] == task1_recursion(string[1::1]):
return True
else:
return False
else:
return string
My code seems to one the last recursion return string "" and that makes it to return False.
Just check the tip and the tail, continue with the string without them:
def task1_recursion(string: str):
# recursion base condition (exit condition)
if len(string) <= 1:
return True
# unpack values
first, *_, last = string
# check if they are different
if first != last:
return False
# if not continue checking the remaining string
return task1_recursion(string[1:-1])
If I understand correctly you want to check if a string is symmetric with the code in task1. My solution is below:
def fct(s: str, i: int):
if len(s) <= 1 or i == len(s):
return True
return s[i] == s[len(s) - 1 - i] and fct(s, i + 1)
I tested and fct produces the same result as task1. It needs an additional parameter for the index though. But you can wrap it inside another function if you want the parameter to include only the input string. i is always set to 0 when you call the function, e.g. fct("ABCCBA", 0).
I'm trying to figure out how to write a recursive function (with only one parameter) that returns the number of times the substring “ou” appears in the string. Where I'm confused at is that I'm not allowed to use any built-in string functions other than len, or the string operators [] and [:] for indexing and splicing. So I can't use the find built-in find function
I remember seeing something like this, but it uses two parameters and it also uses the find() method
def count_it(target, key):
index = target.find(key)
if index >= 0:
return 1 + count_it(target[index+len(key):], key)
else:
return 0
Very inefficient, but should work:
def count_it(target):
if len(target) < 2:
return 0
else:
return (target[:2] == 'ou') + count_it(target[1:])
See it working online: ideone
It's basically the same idea as the code you posted, except that it moves only one character at a time through the string instead of using find to jump ahead to the next match.
Try this, it works for the general case (any value of key, not only 'ou'):
def count_it(target, key):
if len(target) < len(key):
return 0
found = True
for i in xrange(len(key)):
if target[i] != key[i]:
found = False
break
if found:
return 1 + count_it(target[len(key):], key)
else:
return count_it(target[1:], key)