I have a specific question about the code in the problem and its solution at http://articles.leetcode.com/finding-minimum-window-in-s-which
In the code below the figure (NOT the figure above the figure), 5th line of code from for loop
if (hasFound[S[end]] <= needToFind[S[end]]) **// WHY this condition is required???**
count++;
Based on my understanding
1) this if condition is not needed and just (whenever found a char just increase count which represents the # of chars found so far)
count++;
2) OR could be < (instead of <=) and equal doesn't seem to make sense for me
if (hasFound[S[end]] < needToFind[S[end]])
count++;
I tested 1) and 2) but neither of them give me the correct answer for all cases.
only (if condition with <=) gives me the correct solution for all cases.
I really don't understand why
if (hasFound[S[end]] <= needToFind[S[end]])
should be required to make this code work correctly for all cases.
Imagine that pattern T contains 3 chars A and 2 chars B.
So needToFind['A'] = 3
And you have to increment count, when hasFound['A'] becomes 1, 2 and 3
When hasFound['A'] becomes 2 only (you proposition about '<'), window contains only two A chars, it is impossible to make T, and count never reaches tLen=5
If remove this condition at all, 5 chars A give count=5=tlen, while window still doesn't contain any B
Related
I read everyone uses enumerate, but I don't think I know how to use it in my code. I want to print the value of an alphabet in a string according to alphabet order and the next character will increment the value by 1 and I want to start it from the last character in the string.
I can solve the code, but how can I replace the counter i without using i = i+1 to make this code a bit shorter? Is there a way to implement something in the for loop?
This is my code:
def project(r):
i = 0
for char in range(len(r),0,-1):
print(ord(r[char-1])-96+i)
i=i+1
project(str(input()).lower())
For example, if I insert a string such as "sad", the output will be [4,2,21] because d = 4, a = 1, s = 19.
Is there a way to implement the counter without initializing i?
According to your question what I can understand is you want to use enumerate to get your result.
You can simply do as below:
def project(r):
for (i, char) in enumerate(r, 0):
print(ord(r[-i-1])-96+i)
project(str(input()).lower())
And the enumerate() method adds a counter to an iterable and returns it in a form of an enumerate object.
Syntax: enumerate(iterable, start)
Here 0 is the default value of start which you can give according to your requirement. For example, if you want your counter to start from 100, then you can do like enumerate(iterable, 100).
In the above code, I have used enumerate() function and initialized the counter from 0 and as you want to display from the last, I used -ve index to get the last item in a list.
And as I initialized the counter 0 so how can I get the items from last? For that, I subtract the index by -1 like r[-i-1]. So for the first iteration the i value becomes 0, so r[-i-1] becomes r[-0-1] which is r[-1] and on the second iteration, i becomes 1, so r[-i-1] becomes r[-1-1]which isr[-2]` which result second last item. Similarly it goes on.
For more information about enumeration, please check the below link so you can get a clear idea.
Python enumerate()
13. Enumerate
Dcoder14, actually I want to make my code a bit shorter. Even there is a way other than enumerate, but still thank you very much... I used your code, but I edited it a little bit to make it one line shorter...
This is my code:
def project(r):
for (i, char) in enumerate(r, 0):
print(str(ord(r[-i-1])-96+i))
project(str(input()).lower())
If you want to make it shorter, you can use the decrement char value since we can get an increment by subtracting the length of the string (input) with char in the for loop.
For example, this is my code:
def project(r):
for char in range(len(r),0,-1):
print(ord(r[char-1])-96+(len(r)-char))
project(str(input()).lower())
Original Problem:
A word was K-good if for every two letters in the word, if the first appears x times and the second appears y times, then |x - y| ≤ K.
Given some word w, how many letters does he have to remove to make it K-good?
Problem Link.
I have solved the above problem and i not asking solution for the above
problem
I just misread the statement for first time and just thought how can we solve this problem in linear line time , which just give rise to a new problem
Modification Problem
A word was K-good if for every two consecutive letters in the word, if the first appears x times and the second appears y times, then |x - y| ≤ K.
Given some word w, how many letters does he have to remove to make it K-good?
Is this problem is solvable in linear time , i thought about it but could not find any valid solution.
Solution
My Approach: I could not approach my crush but her is my approach to this problem , try everything( from movie Zooptopia)
i.e.
for i range(0,1<<n): // n length of string
for j in range(0,n):
if(i&(1<<j) is not zero): delete the character
Now check if String is K good
For N in Range 10^5. Time Complexity: Time does not exist in that dimension.
Is there any linear solution to this problem , simple and sweet like people of stackoverflow.
For Ex:
String S = AABCBBCB and K=1
If we delete 'B' at index 5 so String S = AABCBCB which is good string
F[A]-F[A]=0
F[B]-F[A]=1
F[C]-F[B]=1
and so on
I guess this is a simple example there can me more complex example as deleting an I element makens (I-1) and (I+1) as consecutive
Is there any linear solution to this problem?
Consider the word DDDAAABBDC. This word is 3-good, becauseDandCare consecutive and card(D)-card(C)=3, and removing the lastDmakes it 1-good by makingDandCnon-consecutive.
Inversely if I consider DABABABBDC which is 2-good, removing the lastDmakes CandBconsecutive and increases the K-value of the word to 3.
This means that in the modified problem, the K-value of a word is determined by both the cardinals of each letter and the cardinals of each couple of consecutive letters.
By removing a letter, I reduce its cardinal of the letter as well as the cardinals of the pairs to which it belongs, but I also increase the cardinal of other pair (potentially creating new ones).
It is also important to notice that if in the original problem, all letters are equivalent (I can remove any indifferently), while it is no longer the case in the modified problem.
As a conclusion, I think we can safely assume that the "consecutive letters" constrain makes the problem not solvable in linear time for any alphabet/word.
Instead of finding the linear time solution, which i think doesn't exist (among others because there seem to be a multitude of alternative solutions to each K request), i'd like to preset the totally geeky solution.
Namely, take the parallel array processing language Dyalog APL and create these two tiny dynamic functions:
good←{1≥⍴⍵:¯1 ⋄ b←(⌈/a←(∪⍵)⍳⍵)⍴0 ⋄ b[a]+←1 ⋄ ⌈/|2-/b[a]}
make←{⍵,(good ⍵),a,⍺,(l-⍴a←⊃b),⍴b←(⍺=good¨b/¨⊂⍵)⌿(b←↓⍉~(l⍴2)⊤0,⍳2⊥(l←⍴⍵)⍴1)/¨⊂⍵}
good tells us the K-goodness of a string. A few examples below:
// fn" means the fn executes on each of the right args
good" 'AABCBBCB' 'DDDAAABBDC' 'DDDAAABBC' 'DABABABBDC' 'DABABABBC' 'STACKOVERFLOW'
2 3 1 2 3 1
make takes as arguments
[desired K] make [any string]
and returns
- original string
- K for original string
- reduced string for desired K
- how many characters were removed to achieve deired K
- how many possible solutions there are to achieve desired K
For example:
3 make 'DABABABBDC'
┌──────────┬─┬─────────┬─┬─┬──┐
│DABABABBDC│2│DABABABBC│3│1│46│
└──────────┴─┴─────────┴─┴─┴──┘
A little longer string:
1 make 'ABCACDAAFABBC'
┌─────────────┬─┬────────┬─┬─┬────┐
│ABCACDAAFABBC│4│ABCACDFB│1│5│3031│
└─────────────┴─┴────────┴─┴─┴────┘
It is possible to both increase and decrease the K-goodness.
Unfortunately, this is brute force. We generate the 2-base of all integers between 2^[lenght of string] and 1, for example:
0 1 0 1 1
Then we test the goodness of the substring, for example of:
0 1 0 1 1 / 'STACK' // Substring is now 'TCK'
We pick only those results (substrings) that match the desired K-good. Finally, out of the multitude of possible results, we pick the first one, which is the one with most characters left.
At least this was fun to code :-).
I have a boolean function that evaluates a 1d array of characters. It has two parameters: a 1d array of characters , and a char c. I want the function to return true if the given char c appears at least four consecutive times within the given array, otherwise it will return false.
I don't know how to start or complete this function at all. Please help! Thanks.
I hope I'm not doing you're homework for you ;). So here's the sudo-code for this problem to help you get started
The first thing you would want is the method header that returns a boolean, and has a parameter for an array of characters and a char
The next step would be to create a counter and run a loop to sift threw every character in the array. Every time you encounter that specific character in the array you would add one to the counter, if the next character isn't the one you want then you would reset the counter to 0. Then add a conditional in the loop to check if the counter reaches 4, if so you would return true. If it never reaches 4 then you would want to return false. Go ahead and try to code that up and see if you get it.
Simple problem. If this is your homework then you shouldn't be doing this. Your question needs to be changed. Firstly give it a try before asking and then once you are done trying you can post the errors or the snippets of codes that you are unsure of and then ask for help. Else you are not going to learn anything. Got a simple solution to your problems. I'm not going to give you the complete solution but instead a guide to help you with your question.
In my opinion string is always a better choice to use instead of char because of the functions that come with that package. Char is just plain old annoying (again in my opinion) unless your question or whatever you are doing this program for requires you to use char.
First,
Create your main program -> create your array and initialize it if you want or you can prompt the user for their input. whichever works.
use the "bool" data type to create your Boolean variable.
Prompt the user to input the char value to check for.
Now call the function and provide the parameters. I'm guessing the function is where you are stuck with so i'm going to provide you the snippets from the code that i wrote for this question.
bool check(char* <array_name>, char* <array_name>) //for the array list and the
//value to check for
{
int size;
size = strlen(<array_name>); //to get the size of the array (array list)
int counter=0; //to keep count of the occurrence of the char to check
for(int x=0; x<size; x++) //ar = array list and token = char to check
{
if(ar[x]==token[0]) //check for each iteration if token is in ar[x]
counter++; //if it is then counter increases by 1
else
counter = 0; //To reset the value to 0 if its not consecutive.
if(counter == 4) //to stop the loop when 4 consecutive values has been found.
break;
}
if(counter >= 4) //as per your requirement 4 or above
return true;
else
return false;
}
EDIT: This is to check the values just until 4 consecutive values of what you are searching for is found and to end the loop. If you want it in a different way then please feel free to comment on this answer. You can always add another counter or anything at all to check how many consecutive times the value is found. For example 1,1,1,1,2,3,4,1,1,1,1,2,3,4,1,1,1,1,2,3,4.
The counter for that will be 3 since it happens 3 times with each time repeating the same value for 4 times consecutively.
If this is your homework then you better study properly because it's a really simple problem and your shouldn't be asking for a solution but instead ask for guidance and try first.
Good luck! If you need further clarification or help just comment on this.
So the program that I wanna write is about adding two strings S1 and S2 who are made of int.
example: S1='129782004977', S2='754022234930', SUM='883804239907'
So far I've done this but still it has a problem because it does not rive me the whole SUM.
def addS1S2(S1,S2):
N=abs(len(S2)-len(S1))
if len(S1)<len(S2):
S1=N*'0'+S1
if len(S2)<len(S1):
S2=N*'0'+S2
#the first part was to make the two strings with the same len.
S=''
r=0
for i in range(len(S1)-1,-1,-1):
s=int(S1[i])+int(S2[i])+r
if s>9:
r=1
S=str(10-s)+S
if s<9:
r=0
S=str(s)+S
print(S)
if r==1:
S=str(r)+S
return S
This appears to be homework, so I will not give full code but just a few pointers.
There are three problems with your algorithm. If you fix those, then it should work.
10-s will give you negative numbers, thus all those - signs in the sum. Change it to s-10
You are missing all the 9s. Change if s<9: to if s<=9:, or even better, just else:
You should not add r to the string in every iteration, but just at the very end, after the loop.
Also, instead of using those convoluted if statements to check r and substract 10 from s you can just use division and modulo instead: r = s/10 and s = s%10, or just r, s = divmod(s, 10).
If this is not homework: Just use int(S1) + int(S2).
Trying to solve the following problem:
Given a string of arbitrary length, find the longest substring that occurs more than one time within the string, with no overlaps.
For example, if the input string was ABCABCAB, the correct output would be ABC. You couldn't say ABCAB, because that only occurs twice where the two substrings overlap, which is not allowed.
Is there any way to solve this reasonably quickly for strings containing a few thousand characters?
(And before anyone asks, this is not homework. I'm looking at ways to optimize the rendering of Lindenmayer fractals, because they tend to take excessive amounts of time to draw at high iteration levels with a naive turtle graphics system.)
Here's an example for a string of length 11, which you can generalize
Set chunk length to floor(11/2) = 5
Scan the string in chunks of 5 characters left to looking for repeats. There will be 3 comparisons
Left Right
Offset Offset
0 5
0 6
1 5
If you found a duplicate you're done. Otherwise reduce the chunk length to 4 and repeat until chunk length goes to zero.
Here's some (obviously untested) pseudocode:
String s
int len = floor(s.length/2)
for int i=len; i>0; i--
for j=0; j<=len-(2*i); j++
for k=j+i; k<=len-i; k++
if s.substr(j,j+i) == s.substr(k,k+i)
return s.substr(j,j+i)
return null
There may be an off-by-one error in there, but the approach should be sound (and minimal).
it looks like a suffix tree problem. Create the suffix tree, then find the biggest compressed branch with more than one child (occurs more than once in the original string). The number of letters in that compressed branch should be the size of the biggest subsequence.
i found something similar here: http://www.coderanch.com/t/370396/java/java/Algorithm-wanted-longest-repeating-substring
Looks like it can be done in O(n).
First we need to define the start symbol of our substring and define the length. Iterate all possible start positions then figure out the length doing binary search for the length (if you can find substr with lenght a, you may find with the longer length, function looks monotonous so bin search should be fine). Then find equal substring is N, using KMP or Rabin-Karp any linear algo is fine. Total N*N*log(N). Is that too much complexity?
The code is something like:
for(int i=0;i<input.length();++i)
{
int l = i;
int r = input.length();
while(l <= r)
{
int middle = l + ((r - l) >> 1);
Check if string [i;middle] can be found in initial string. Should be done in O(n); You need to check parts of initial string [0,i-1], [middle+1;length()-1];
if (found)
l = middle + 1;
else
r = middle - 1;
}
}
Make sense?
This type of analysis is often done in genome sequences. have a look at this paper. it has an efficient implemention (c++) for solving repeats: http://www.complex-systems.com/pdf/17-4-4.pdf
might be what you are looking for