Im trying to solve a specific leetcode problem and but a particular if else block never executes in my code and I cant figure why. Here is the code. I'm new to python and I think i'm making a noob mistake but I just figure what it is.
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
left, right = 1, len(nums) - 1
while left < right :
mid = left + (right-left)//2
count = 0
print("l,r -->" + str(left) + ',' + str(right))
print("mid -->" + str(mid))
for k in nums :
if mid < k <= right: # this block never executes.
print(k)
count += 1
print("count -->" + str(count))
if count > right -mid:
left = mid + 1
else :
right = mid
return right
For one thing, this
if mid < k <= right: # this block never executes.
is not doing what you think it is -- instead, you want
if mid < k and k <= right:
Related
Please help as this is getting on my nerves I can't figure out what I'm doing wrong and have tried trace code.
Link to problem: https://leetcode.com/problems/longest-substring-without-repeating-characters/
I created a solution using a sliding window. It works on most test cases, but fails for a few (such as "ad"). I can't figure out where the bug is. I basically keep track in a dictionary of characters I've seen and the last index I saw them at which gets updated periodically in a loop. I use two indices i and j; i gets updated when I find a repeat character. I return the max of current max and length of current substring which is i-j. Here is my code below:
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
if len(s) < 2:
return len(s)
m = 1
i = 0
j = 1
d = {}
d[s[0]] = 0
while j < len(s):
if s[j] in d and d[s[j]] >= i:
m = max(m, j -i)
i = j
d[s[j]] = j
j += 1
return max(m, j - i - 1)
Why does this fail for some cases? Example:
"au"
Output
1
Expected
2
Last line should be return max(m, j - i). Because i is the last index we see repeated character. So. We start this index to end of the string.So length is len(s) - i . And since j = len(s) (while loop ends when j = len(s)) so last substring length is j-i. not j-i-1
And also we are updating i wrong.let's say s = "abcadf". In while loop when we see second "a" ,so j = 3, we should update i = 1, not 3. Because in this case our longest substring will start with "b".So we should update i as i = d[s[j]] + 1. So final result:
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
if len(s) < 2:
return len(s)
m = 1
i = 0
j = 1
d = {}
d[s[0]] = 0
while j < len(s):
if s[j] in d and d[s[j]] >= i:
m = max(m, j -i)
i = d[s[j]] + 1
d[s[j]] = j
j += 1
return max(m, j - i)
How do I write this entire code in only one line?
for i in range(len(array)):
if array[i] - 1 > 0:
array[i] -= 1
else:
array[i] = 0
I have tried this but doesn't work:
(array[i] -= 1 if array[i] - 1 > 0 else array[i] = 0) for i in range(len(array))
Iterate over the elements instead of the numerator in your list comprehension, since i is only used for indexing into the array, not for anything else (thus i can be left out, and an iteration over the elements suffies):
array = [0 if item - 1 <= 0 else item - 1 for item in array]
Using VS2008 C++, console application (empty, made from scratch), placing this in the code :
printf("\n\n%d + %d = %d !!!\n\n",(unsigned __int32)(19L / 17L),((19L % 17L) == 0L)?0L:1L,(unsigned __int32)(19L / 17L) + ((19L % 17L) == 0L)?0L:1L);
And when I run the program, I get :
1 + 1 = 0 !!!
What am I missing?????? :'~(
You are missing 'precedence'. In the last argument to printf(), the addition is higher precedence than the conditional. The sum is evaluated as
(__int32)1 + (2L == 0) which is 1 + 0, or 1 (which is then promoted to long)
Therefore the conditional resolves to
1L ? 0L : 1L
which is 0L since the 'condition' is non-false (non-zero).
printf("\n\n%d + %d = %d !!!\n\n",(unsigned __int32)(19L / 17L),((19L % 17L) == 0L)?0L:1L,((unsigned __int32)(19L / 17L)) + (((19L % 17L) == 0L)?0L:1L));
it seems to be a simple issue of operator precedence. I definitely have been programming for too long today :)
Given a binary string s, we need to find the number of its substrings, containing exactly k characters that are '1'.
For example: s = "1010" and k = 1, answer = 6.
Now, I solved it using binary search technique over the cumulative sum array.
I also used another approach to solve it. The approach is as follows:
For each position i, find the total substrings that end at i containing
exactly k characters that are '1'.
To find the total substrings that end at i containing exactly k characters that are 1, it can be represented as the set of indices j such that substring j to i contains exactly k '1's. The answer would be the size of the set. Now, to find all such j for the given position i, we can rephrase the problem as finding all j such that
number of ones from [1] to [j - 1] = the total number of ones from 1 to i - [the total number of ones from j to i = k].
i.e. number of ones from [1] to [j - 1] = C[i] - k
which is equal to
C[j - 1] = C[i] - k,
where C is the cumulative sum array, where
C[i] = sum of characters of string from 1 to i.
Now, the problem is easy because, we can find all the possible values of j's using the equation by counting all the prefixes that sum to C[i] - k.
But I found this solution,
int main() {
cin >> k >> S;
C[0] = 1;
for (int i = 0; S[i]; ++i) {
s += S[i] == '1';
++C[s];
}
for (int i = k; i <= s; ++i) {
if (k == 0) {
a += (C[i] - 1) * C[i] / 2;
} else {
a += C[i] * C[i - k];
}
}
cout << a << endl;
return 0;
}
In the code, S is the given string and K as described above, C is the cumulative sum array and a is the answer.
What is the code exactly doing by using multiplication, I don't know.
Could anybody explain the algorithm?
If you see the way C[i] is calculated, C[i] represents the number of characters between ith 1 and i+1st 1.
If you take an example S = 1001000
C[0] = 1
C[1] = 3 // length of 100
C[2] = 4 // length of 1000
So coming to your doubt, Why multiplication
Say your K=1, then you want to find out the substring which have only one 1, now you know that after first 1 there are two zeros since C[1] = 3. So number of of substrings will be 3, because you have to include this 1.
{1,10,100}
But when you come to the second part: C[2] =4
now if you see 1000 and you know that you can make 4 substrings (which is equal to C[2])
{1,10,100,1000}
and also you should notice that there are C[1]-1 zeroes before this 1.
So by including those zeroes you can make more substring, in this case by including 0 once
0{1,10,100,1000}
=> {01,010,0100,01000}
and 00 once
00{1,10,100,1000}
=> {001,0010,00100,001000}
so essentially you are making C[i] substrings starting with 1 and you can append i number of zeroes before this one and make another C[i] * C[i-k]-1 substrings. i varies from 1 to C[i-k]-1 (-1 because we want to leave that last one).
((C[i-k]-1)* C[i]) +C[i]
=> C[i-k]*C[i]
writing code to test the Hailstone Sequence, also called Collatz conjecture. Code will print out the number of iterations of the Hailstone sequence.
def main():
start_num = eval (input ("Enter starting number of the range: "))
end_num = eval (input ("Enter ending number of the range: "))
The main problem is that my code returns an infinite loop. I want to check all of these conditions in one statement
while (start_num > 0 and end_num > 0 and end_num > start_num):
cycle_length = 0
max_length = 0
max_number = 0
my code seems inefficient, there is probably a better way to approach the problem
for i in range(start_num, (end_num + 1)):
cycle_length = 0
while (i != 1):
if (i % 2 == 0):
i = i // 2
cycle_length += 1
if (i % 2 == 1):
i = ((3 * i) + 1)
cycle_length += 1
print (cycle_length)
I just started coding, and I always know that there is a more efficient way to approach these problems. Any suggestions on methodology, problem solving, or stylistic advice would be greatly appreciated.
Here is an answer in java. I assume that we will not start with 1.
public static void main(String[] args) {
int counter =0;
Scanner sc = new Scanner(System.in);
System.out.println("Give us a number to start with:");
int start = sc.nextInt();
System.out.println("Give us a number to end with:");
int end = sc.nextInt();
if (end > start) {
for (int i = 0; i <= end - start; i++) {
counter = 0;
int num = start + i;
int temp = num;
while(temp != 1) {
if ( temp % 2 == 0 ) {
temp = temp / 2;
} else {
temp = 3* temp +1;
}
counter++;
}
System.out.println(num + " takes " + counter + "iterations.");
}
} else {
System.out.println("Your numbers do not make sense.");
}
}
Here's an answer in python in case you're staying up late trying to solve this problem. :P Have a good night.
start_num = 1
end_num = 10
for i in range(start_num, (end_num + 1)):
cycle_length=0
num = i
while (num != 1):
if (num % 2 == 0):
num = num // 2
cycle_length+=1
else:
num = ((3 * num) + 1)
cycle_length+=1
print(cycle_length)