I am going through popular interview questions, and came up with the following solution to "Compute all permutations of a string."
def perm(s):
if len(s) == 0:
return ['']
else:
l = []
prev = perm(s[1:])
for old_str in prev:
for i in range(len(old_str)):
new_str = old_str[0:i] + s[0] + old_str[i:]
l.append(new_str)
return l
However, this solution returns [] on all input. If I make the string in the base case any string other than the empty string, the computation runs as expected. For example, with 'hi' in the base case, perm('abc') returns
['abchi', 'bachi', 'bcahi', 'bchai', 'acbhi', 'cabhi', 'cbahi', 'cbhai', 'achbi', 'cahbi', 'chabi', 'chbai', 'abhci', 'bahci', 'bhaci', 'bhcai', 'ahbci', 'habci', 'hbaci', 'hbcai', 'ahcbi', 'hacbi', 'hcabi', 'hcbai']
As far as I can tell the algorithm for this code is correct. I am unsure of why the empty string isn't behaving as I anticipate, while other strings do. I have referenced this thread for better solutions, but I am still puzzled by why this one doesn't work.
You should probably add a special case for len(s)==1.
As written, the recursion will go down to the base case with an empty string, and then prev will be []. The for loop that follows this will never run, because prev is empty, so the final result will be empty too.
Related
I have this exercise:
Write a recursive function that takes a string and returns all the characters that are not repeated in said string.
The characters in the output don't need to have the same order as in the input string.
First I tried this, but given the condition for the function to stop, it never evaluates the last character:
i=0
lst = []
def list_of_letters_rec(str=""):
if str[i] not in lst and i < len(str) - 1:
lst.append(str[i])
list_of_letters_rec(str[i+1:])
elif str[i] in lst and i < len(str) - 1:
list_of_letters_rec(str[i+1:])
elif i > len(str) - 1:
return lst
return lst
word = input(str("Word?"))
print(list_of_letters_rec(word))
The main issue with this function is that it never evaluates the last character.
An example of an output:
['a', 'r', 'd', 'v'] for input 'aardvark'.
Since the characters don't need to be ordered, I suppose a better approach would be to do the recursion backwards, and I also tried another approach (below), but no luck:
lst = []
def list_of_letters_rec(str=""):
n = len(str) - 1
if str[n] not in lst and n >= 0:
lst.append(str[n])
list_of_letters_rec(str[:n-1])
elif str[n] in lst and n >= 0:
list_of_letters_rec(str[:n-1])
return lst
word = input(str("Word?"))
print(list_of_letters_rec(word))
Apparently, the stop conditions are not well defined, especially in the last one, as the output I get is
IndexError: string index out of range
Could you give me any hints to help me correct the stop condition, either in the 1st or 2nd try?
You can try:
word = input("> ")
result = [l for l in word if word.count(l) < 2]
> aabc
['b', 'c']
Demo
One improvement I would offer on #trincot's answer is the use of a set, which has better look-up time, O(1), compared to lists, O(n).
if the input string, s, is empty, return the empty result
(inductive) s has at least one character. if the first character, s[0] is in the memo, mem, the character has already been seen. Return the result of the sub-problem, s[1:]
(inductive) The first character is not in the memo. Add the first character to the memo and prepend the first character to the result of the sub-problem, s[1:]
def list_of_letters(s, mem = set()):
if not s:
return "" #1
elif s[0] in mem:
return list_of_letters(s[1:], mem) #2
else:
return s[0] + list_of_letters(s[1:], {*mem, s[0]}) #3
print(list_of_letters("aardvark"))
ardvk
Per your comment, the exercise asks only for a string as input. We can easily modify our program to privatize mem -
def list_of_letters(s): # public api
def loop(s, mem): # private api
if not s:
return ""
elif s[0] in mem:
return loop(s[1:], mem)
else:
return s[0] + loop(s[1:], {*mem, s[0]})
return loop(s, set()) # run private func
print(list_of_letters("aardvark")) # mem is invisible to caller
ardvk
Python's native set data type accepts an iterable which solves this problem instantly. However this doesn't teach you anything about recursion :D
print("".join(set("aardvark")))
akdrv
Some issues:
You miss the last character because of i < len(str) - 1 in the conditionals. That should be i < len(str) (but read the next points, as this still needs change)
The test for if i > len(str) - 1 should come first, before doing anything else, otherwise you'll get an invalid index reference. This also makes the other conditions on the length unnecessary.
Don't name your variable str, as that is already a used name for the string type.
Don't populate a list that is global. By doing this, you can only call the function once reliably. Any next time the list will still have the result of the previous call, and you'll be adding to that. Instead use the list that you get from the recursive call. In the base case, return an empty list.
The global i has no use, since you never change its value; it is always 0. So you should just reference index [0] and check that the string is not empty.
Here is your code with those corrections:
def list_of_letters_rec(s=""):
if not s:
return []
result = list_of_letters_rec(s[1:])
if s[0] not in result:
result.append(s[0])
return result
print(list_of_letters_rec("aardvark"))
NB: This is not the most optimal way to do it. But I guess this is what you are asked to do.
A possible solution would be to just use an index instead of splicing the string:
def list_of_letters_rec(string="", index = 0, lst = []):
if(len(string) == index):
return lst
char = string[index]
if string.count(char) == 1:
lst.append(char)
return list_of_letters_rec(string, index+1, lst)
word = input(str("Word?"))
print(list_of_letters_rec(word))
I'm trying to write a function to return the longest common prefix from a series of strings. Using a debugger, saw that my function reaches the longest common prefix correctly, but then when it reaches the statement to return, it begins reverting to earlier stages of the algorithm.
For test case strs = ["flower","flow","flight"]
The output variable holds the following values:-
f > fl > f
instead of returning fl.
Any help would be appreciated, because I don't really know how to Google for this one. Thank you.
class Solution(object):
def longestCommonPrefix(self, strs, output = ''):
#return true if all chars in string are the same
def same(s):
return s == len(s) * s[0]
#return new list of strings with first char removed from each string
def slicer(list_, list_2 = []):
for string in list_:
string1 = string[1:]
list_2.append(string1)
return list_2
#return string containing first char from each string
def puller(list_):
s = ''
for string in list_:
s += string[0]
return s
#pull first character from each string
s = puller(strs)
#if they are the same
#add one char to output
#run again on sliced list
if same(s):
output += s[0]
self.longestCommonPrefix(slicer(strs), output)
return output
This can be handled with os.path.commonprefix.
>>> import os
>>> strs = ["flower","flow","flight"]
>>> os.path.commonprefix(strs)
'fl'
It doesn't "revert". longestCommonPrefix potentially calls itself - what you're seeing is simply the call-stack unwinding, and flow of execution is returning to the calling code (the line that invoked the call to longestCommonPrefix from which you are returning).
That being said, there's really no need to implement a recursive solution in the first place. I would suggest something like:
def get_common_prefix(strings):
def get_next_prefix_char():
for chars in zip(*strings):
if len(set(chars)) != 1:
break
yield chars[0]
return "".join(get_next_prefix_char())
print(get_common_prefix(["hello", "hey"]))
You are looking at the behavior...the final result...of recursive calls to your method. However, the recursive calls don't do anything to affect the result of the initial execution of the method. If we look at the few lines that matter at the end of your method:
if same(s):
output += s[0]
self.longestCommonPrefix(slicer(strs), output)
return output
The problem here is that since output is immutable, its value won't be changed by calling longestCommonPrefix recursively. So from the standpoint of the outermost call to longestCommonPrefix, the result it will return is determined only by if same(s) is true or false. If it is true it will return s[0], otherwise it will return ''.
The easiest way to fix this behavior and have your recursive call affect the result of the prior call to the method would be to have its return value become the value of output, like this:
if same(s):
output += s[0]
output = self.longestCommonPrefix(slicer(strs), output)
return output
This is a common code pattern when using recursion. Just this change does seem to give you the result you expect! I haven't analyzed your whole algorithm, so I don't know if it becomes "correct" with just this change.
Can you try this? I
class Solution(object):
def longestCommonPrefix(self, strs, output = ''):
#return true if all chars in string are the same
def same(s):
return s == len(s) * s[0]
#return new list of strings with first char removed from each string
def slicer(list_, list_2 = []):
for string in list_:
string1 = string[1:]
list_2.append(string1)
return list_2
#return string containing first char from each string
def puller(list_):
s = ''
for string in list_:
s += string[0]
return s
#pull first character from each string
s = puller(strs)
# Can you Try this revision?
# I think the problem is that your new version of output is being lost when the fourth called function returns to the third and the third returns to the second, etc...
# You need to calculate a new output value before you call recursively, that is true, but you also need a way to 'store' that output when that recursively called function 'returns'. Right now it disappears, I believe.
if same(s):
output += s[0]
output = self.longestCommonPrefix(slicer(strs), output)
return output
I am a beginning in Python.
I have a function that checks if it is a vowel.
def vowel(x):
if(x=='a' or x=='e' or x=='i' or x=='o' or x=='u'):
return True;
else:
return False;
And a function that tries to convert the string to a robber's language by using the vowel function above. (The algorithm for conversion is to double every consonant and place an "o" in between).
def robber(text):
s=""
for i,c in enumerate(text):
if vowel(c)==False:
s=s.join([c,'o',c])
return s;
When I try to run it by passing robber("asdf") into the function, I get a blank line and "Process finished with exit code 0"
I suspect that there might be multiple errors, but the program is syntactically correct. Could you help me with this?
You should append to s instead of assigning and also appending the c in case it is no vowel:
def robber(text):
s=""
for i,c in enumerate(text):
if vowel(c)==False:
s += ''.join([c,'o',c])
else:
s += c
return s
Furthermore some additional remarks:
it is more Pythonic to use not instead of == False;
you do not need to use enumerate(..) since i is never used;
you do not need to return True and return False if the test succeeds/fails, simply return the condition; and
you can rewrite both the vowel(..) and robber(..) function more elegantly.
So putting it together:
def vowel(x):
return x.lower() in ('a','e','i','o','u')
and:
def robber(text):
return ''.join([c if vowel(c) else ''.join((c,'o',c)) for c in text])
If you want to avoid all those append/overwrite errors (and get a much better performance/avoid string concatenation), better start writing those using list comprehension:
text = "asdf"
new_text = "".join([c if c in "aeiou" else "{0}o{0}".format(c) for c in text])
print(new_text)
result:
asosdodfof
the new text is a joined list (creates a string) of a list comprehension built using a ternary expression: leave the letter alone if vowel, else create the pattern.
Firstly, your problem
On the line s=s.join([c,'o',c]), you are actually replacing the contents of s every time. I think what you do want to do is to append it to s, so I would use s += "".join([c, 'o', c])
Also the use of join is wrong - the string before the join comes between every two elements in the given list, not before the first.
So, as I said, the correct form to do that should be:
s += "".join([c, 'o', c])
Disclaimer : Not tested.
Code readability
As you stated that you are a beginner, let me give you some tips about your coding style (Python's coding style is very unique).
1
Instead of doing x=='a' or x=='e' or x=='i' or x=='o' or x=='u', you do:
`if x in 'aeiou':`
Much more understandable and reads better.
2
Doing:
if ...:
return True
else
Return False
Is very clumsy. Try:
return ...
And in your case:
return x in 'aeiuo'
The condition is already a boolean value (True or False) - no need to reevaluate it ;)
The purpose of this code is to find the longest string in alphabetical order that occurs first and return that subset.
I can execute the code once, but when I try to loop it I get 'NoneType' object is not iterable (points to last line). I have made sure that what I return and input are all not of NoneType, so I feel like I'm missing a fundamental.
This is my first project in the class, so the code doesn't need to be the "best" or most efficient way - it's just about learning the basics at this point.
s = 'efghiabcdefg'
best = ''
comp = ''
temp = ''
def prog(comp, temp, best, s):
for char in s:
if comp <= char: #Begins COMParison of first CHARacter to <null>
comp = char #If the following character is larger (alphabetical), stores that as the next value to compare to.
temp = temp + comp #Creates a TEMPorary string of characters in alpha order.
if len(temp) > len(best): #Accepts first string as longest string, then compares subsequent strings to the "best" length string, replacing if longer.
best = temp
if len(best) == len(s): #This is the code that was added...
return(s, best) #...to fix the problem.
else:
s = s.lstrip(temp) #Removes those characters considered in this pass
return (str(s), str(best)) #Provides new input for subsequent passes
while len(s) != 0:
(s, best) = prog(comp, temp, best, s)
prog is returning None. The error you get is when you try to unpack the result into the tuple (s, best)
You need to fix your logic so that prog is guaranteed to not return None. It will return None if your code never executes the else clause in the loop.
You don't return in all cases. In Python, if a function ends without an explicit return statement, it will return None.
Consider returning something if, for example, the input string is empty.
def count_vowels(s):
if not s:
return 0
elif s[0] in VOWELS:
return 1 + count_vowels(s[1:])
else:
return 0 + count_vowels(s[1:])
I see that this code works perfectly fine for finding the number of vowels in a string. I also understand recursion always calls for a base case. I guess my main problem with this code is what does the first if statement actually mean? What is it checking?
if not s:
return 0
if what not s? Is there any way to write the code without that portion?
This is your exit from recursion. Your recursion has to stop at some point of time (otherwise it will run forever).
It means that if the string is empty - return 0 (there are no vowels in empty string) and stop.
if not s checks if the string is empty. Empty strings are "false-y" objects in Python. If the string is empty, it must not have any vowels.
I realize you are probably required to use recursion here, but this would be a better way to do it in practice:
>>> VOWELS = set('aeiou')
>>> def count_vowels(s):
... return sum(x in VOWELS for x in s)
...
>>> count_vowels('hello world')
3