Sequence of legal pairs of parentheses using recursion - Python - python-3.x

I have some problem to solve using recursion in Python.
I'm simply bad in recursion and don't know how to start so please guide me.
We will say that a string contains 'n' legal pairs of parentheses if the string contains only the chars '(',')' and if this sequence of parentheses can be written so in a manner of mathematical formula (That is, every opening of parentheses is closed and parentheses are not closed before they are opened). More precise way to describe it is at the beginning of the string the number of '(' is greater or equal to ')' - and the number of any kind of char in the whole string is equal. Implement a function that recieves a positive integer n and returns a list which contains every legal string of n-combination of the parentheses.
I have tried to start at least, think of a base case, but what's my base case at all?
I tried to think of a base case when I am given the minimal n which is 1 and then I think I have to return a list ['(', ')']. But to do that I have also a difficulty...
def parentheses(n):
if n == 1:
return combine_parent(n)
def combine_parent(n):
parenth_lst = []
for i in range(n):
parenth_lst +=
Please explain me the way to solve problems recursively.
Thank you!

Maybe it's helpful to look in a simple case of the problem:
n = 2
(())
()()
So we start by n=2 and we produce a sequence of ( n times followed by a sequence of ) n times and we return a list of that. Then we recursively do that with n-1. When we reach n=1 it looks like we reached the base case which is that we need to return a string with () n times (not n=1 but n=2).
n = 3
((()))
(())()
()()()
Same pattern for n=3.
The above examples are helpful to understand how the problem can be solved recursively.
def legal_parentheses(n, nn=None):
if nn == 1:
return ["()" * n]
else:
if not nn:
nn = n
# This will produce n ( followed by n ) ( i.e n=2 -> (()) )
string = "".join(["(" * nn, ")" * nn])
if nn < n:
# Then here we want to produce () n-nn times.
string += "()" * (n-nn)
return [string] + legal_parentheses(n, nn-1)
print(legal_parentheses(3))
print(legal_parentheses(4))
print(legal_parentheses(5))
For n = 3:
['((()))', '(())()', '()()()']
For n = 4:
['(((())))', '((()))()', '(())()()', '()()()()']
For n = 5:
['((((()))))', '(((())))()', '((()))()()', '(())()()()', '()()()()()']
This is one way of solving the problem.
The way to think about solving a problem recursively, in my opinion, is to first pick the simplest example of your problem in your case, n=2 and then write down what do you expect as a result. In this case, you are expecting the following output:
"(())", "()()"
Now, you are trying to find a strategy to break down the problem such that you can produce each of the strings. I start by thinking of the base case. I say the trivial case is when the result is ()(), I know that an element of that result is just () n times. If n=2, I should expect ()() and when n=3 I should expect ()()() and there should be only one such element in the sequence (so it should be done only once) hence it becomes the base case. The question is how do we calculate the (()) part of the result. The patterns shows that we just have to put n ( followed by n ) -> (()) for n=2. This looks like a good strategy. Now you need to start thinking for a slightly harder problem and see if our strategy still holds.
So let's think of n=3. What do we expect as a result?
'((()))', '(())()', '()()()'
Ok, we see that the base case should still produce the ()()() part, all good, and should also produce the ((())) part. What about the (())() part? It looks like we need a slightly different approach. In this case, we need to somehow generate n ( followed by n ) and then produce n-1 ( followed by n-1 ) and then n-2 ( followed by n-2 ) and so on, until we reach the base case n=1 where we just going to produce () part n times. But, if we were to call the function each time with n-1 then when we reach the base case we have no clue what the original n value was and hence we cannot produce the () part as we don't know how many we want (if original n was 3 then we need ()()() but if we change n by calling the function with n-1 then by the time we reach the base case, we won't know the original n value). Hence, because of that, in my solution, I introduce a second variable called nn that is the one that is reduced each time, but still, we leave the n unmodified so we know what the original value was.

Related

DC3/Skew Suffix Array Algorithm doesn't work for specific cases

When applying the DC3/Skew algorithm to the string yabadabado, I can't quite get it to sort correctly. This issue happens in other cases, but this is a short example to show it.
This first table is for reference:
These are the triples of R12
We have a tie between i = 1, and i = 5 since both their triples are aba.
We now need to get the suffix array of the ranks R' through recursing, but we can quickly break this tie since i_1 = [1,3] > i_5 = [1,2] which implies that the suffix starting at i = 5 should come before i = 1. Recursing returns the same result with R'5 < R'1.
So applying these results puts the relative order of those two suffixes as:
S[5,] == abado // Comes first (smaller)
S[1,] == abadabado
But abadabado < abado. I've been looking at this for a while, and can't seem to figure out where I stray from the algorithm.
I'm hoping someone with more experience using the algorithm can point me in the right direction.

How To Understand THE Following Code Snippet?

i came up with understanding confusion , what will be the right explanation for this code?
a = [(0,1),(1,2),(2,3)]
result = sum(n for _,n in a)
print(result)
I guess that your confusion is coming from the , and the fact that sum also accepts a second argument.
In this case, only one argument is passed to sum because that line is evaluated as
result = sum(n for (_, n) in a)
This line simply sums all the second elements in the list of tuples, and it is equivalent to the following:
list_of_tuples = [(0,1),(1,2),(2,3)]
total = 0
for (first_element, second_element) in list_of_tuples:
total += second_element
print(total)
Technically _ is a normal, valid identifier name, but the convention is to use it for values that are disregarded in the next part of the code.
I think another way of thinking of it is:
result=0
for _,n in a:
result += n
You can substitute "_,n" for any other two variables like "x,y" for example.

Doesn't accept the list index?

I have this peice of code:
n = int (input ('Enter the Number of Players: '))
m = [[j] for j in range (0, n)]
all_names= []
i = 0
while n > 1:
m[i] = input('Player {0}: '.format (i+1))
all_names.extend ([m[i]])
if m[i][0] != m[i-1][-1]:
b= m.pop (i)
n = n-1
if all_names.count (m[i]) == 2:
n = n-1
b= m.pop (i)
i = i+1
It says the index is out of range (second if clause)
but I dont get it, why?
I hate to not answer your question directly, but what you're trying to do seems... really confusing. Python has a sort of rule that there's supposed to be a really clear, clean way of doing things, so if a piece of code looks really funky (especially for such a simple function), it's probably not using the right approach.
If you just want to create a container of names, there are numerous simpler ways of doing it:
players=int(input("How many players?\n"))
player_names=set()
while len(player_names)<players:
player_names.add(input("What is player {}'s name?\n".format(len(player_names)+1)))
... will give you a set of unique player names, although this won't be ordered. That might matter (your implementation kept order, so maybe it is), and in this case you could still use a list and add a small check to make sure you were adding a new name and not repeatedly adding names:
players=int(input("How many players?\n"))
player_names=list()
while len(player_names)<players:
playname=input("What is player {}'s name?\n".format(len(player_names)+1))
if playname not in player_names:
player_names.append(playname)
I'm open to someone haranguing me about dodging the question, particularly if there's a purpose/reason for the approach the questioner took.
Length of m decreases every time the code enters the first if clause. However, you increment the value of i in each iteration. So, at the midpoint of length of m (if the 1st clause is entered always) or a little later, the value of i will be bigger than the value of m and you will get an index out of range.

Haskell - Find the longest word in a text

I've got a problem about to write a function to find the longest word in a text.
Input: A string with a lot of word. Ex: "I am a young man, and I have a big house."
The result will be 5 because the longest words in the text have 5 letters (young and house).
I've just started to learn Haskell. I've tried:
import Char
import List
maxord' (str:strs) m n =
if isAlpha str == True
then maxord'(strs m+1 n)
else if m >= n
then maxord'(strs 0 m)
else maxord'(strs 0 n)
maxord (str:strs) = maxord' (str:strs) 0 0
I want to return n as the result but I don't know how to do it, and it seems there is also something wrong with the code.
Any help? Thanks
Try to split your task into several subtasks. I would suggest splitting it like this:
Turn the string into a list of words. For instance, your example string becomes
["I","am","a","young","man","and","I","have","a","big","house"]
map length over the list. This calculates the word lengths. For example, the list in step 1 becomes
[1,2,1,5,3,3,1,4,1,3,5]
Find the word with the highest number of characters. You could use maximum for this.
You can compose those steps using the operator (.) which pipes two functions together. For instance, if the function to perform step 1 is called toWords, you can perform the whole task in one line:
maxord = maximum . map length . toWords
The implementation of toWords is left as an excercise to the reader. If you need help, feel free to write a comment.
There are several issues here. Let's start with the syntax.
Your else parts should be indented the same or more as the if they belong to, for example like this:
if ...
then ...
else if ...
then ...
else ...
Next, your function applications. Unlike many other languages, in Haskell, parentheses are only used for grouping and tuples. Since function application is so common in Haskell, we use the most lightweight syntax possible for it, namely whitespace. So to apply the function maxord' to the arguments strs, m+1 and n, we write maxord' strs (m+1) n. Note that since function application has the highest precedence, we have to add parentheses around m+1, otherwise it would be interpreted as (maxord' strs m) + (1 n).
That's it for the syntax. The next problem is a semantic one, namely that you have recursion without a base case. Using the pattern (str:strs), you have specified what to do when you have some characters left, but you've not specified what to do when you reach the end of the string. In this case, we want to return n, so we add a case for that.
maxord' [] m n = n
The fixed maxord' is thus
maxord' [] m n = n
maxord' (str:strs) m n =
if isAlpha str == True
then maxord' strs (m+1) n
else if m >= n
then maxord' strs 0 m
else maxord' strs 0 n
However, note that this solution is not very idiomatic. It uses explicit recursion, if expressions instead of guards, comparing booleans to True and has a very imperative feel to it. A more idiomatic solution would be something like this.
maxord = maximum . map length . words
This is a simple function chain where words splits up the input into a list of words, map length replaces each word with its length, and maximum returns the maximum of those lengths.
Although, note that it's not the exact same as your code, since the words function uses slightly different criteria when splitting the input.
There are a couple of problems
There is no termination for you recursion. You want to return n when you processed the whole input.
maxord' [] _ n = n
Syntax:
maxord'(strs 0 m)
this means that call apply strs with parameters 0 and m, and then use that as an argument to maxord. What you wan't to do is this:
maxord' strs 0 m
m+1 should be (m+1).
You might want to process empty strings, but maxord doesn't allow it.
maxord s = maxord' s 0 0
That should do it. There are a couple of subtleties. maxord' shoudln't leak out to the namespace, use where. (max m n) is a lot more concise than the if-then-else you use. And check the other answers to see how you can build your solution by wiring builtin things together. Recursions are a lot harder to read.

Why doesn't my Haskell function accept negative numbers?

I am fairly new to Haskell but do get most of the basics. However there is one thing that I just cannot figure out. Consider my example below:
example :: Int -> Int
example (n+1) = .....
The (n+1) part of this example somehow prevents the input of negative numbers but I cannot understand how. For example.. If the input were (-5) I would expect n to just be (-6) since (-6 + 1) is (-5). The output when testing is as follows:
Program error: pattern match failure: example (-5)
Can anyone explain to me why this does not accept negative numbers?
That's just how n+k patterns are defined to work:
Matching an n+k pattern (where n is a variable and k is a positive integer literal) against a value v succeeds if x >= k, resulting in the binding of n to x - k, and fails otherwise.
The point of n+k patterns is to perform induction, so you need to complete the example with a base case (k-1, or 0 in this case), and decide whether a parameter less than that would be an error or not. Like this:
example (n+1) = ...
example 0 = ...
The semantics that you're essentially asking for would be fairly pointless and redundant — you could just say
example n = let n' = n-1 in ...
to achieve the same effect. The point of a pattern is to fail sometimes.

Resources