debug they have same value but still get index out of range - python

When I debug my code, the value of the variables shows that they are equal to my limit condition but my while loop still works
I'm trying to stop my while loop by this limitation:
while (i + j) != len(fruits):
Even though (i+j) is equal to len(fruits), the loop still works, it doesn't break.
It should be broken when it meets my limitation.
My code is below:
from typing import List
class Solution:
def totalFruit(self, fruits: List[int]) -> int:
pointed = [0 for i in range(max(fruits) + 1)]
maX, count = 0, 0
count_type = 0
i, j = 0, 0
while (i + j) != len(fruits):
while count_type < 3:
if pointed[fruits[i + j]] == 0:
count_type += 1
if count_type < 3:
count += 1
pointed[fruits[i + j]] += 1
j += 1
elif count_type < 3 and pointed[fruits[i + j]] != 0:
pointed[fruits[i + j]] += 1
count += 1
j += 1
if count > maX: maX = count
if pointed[fruits[i]] == 1: count_type -= 2
pointed[fruits[i]] -= 1
count -= 1
i += 1
j-= 1
return maX
fruits = input()
fruits = [int(i) for i in fruits.split()]
obj = Solution()
print(obj.totalFruit(fruits))
when I debug:
enter image description here

Related

Writing a "Chessboard" function in Python that prints out requested length of binary

I have an assignment for my Python course that I'm struggling with.
We are supposed to make a function that prints out binary as follows:
If the input is:
chessboard(3)
It should print out:
101
010
101
And so forth..
Its a "simple" program but I'm really new to coding.
I can produce a while loop that writes out the correct length and amount of lines but I'm struggling to produce variation between the lines.
This is what I have come up with so far:
def chessboard(n):
height = n
length = n
while height > 0:
while length > 0:
print("1", end="")
length -= 1
if length > 0:
print("0", end="")
length -= 1
height -= 1
if length == 0:
break
else:
print()
length = n
With the input:
chessboard(3)
It prints out:
101
101
101
Could someone help me figure out how I could start every other line with zero instead of one?
As I understand it, it is simple :
print("stackoverflow")
def chessboard(n):
finalSentence1 = ""
finalSentence2 = ""
for i in range(n): #we add 0 and 1 as much as we have n
if i%2 == 0: #
finalSentence1 += "1"
finalSentence2 += "0"
else:
finalSentence1 += "0"
finalSentence2 += "1"
for i in range(n): #we print as much as we have n
if i%2 == 0:
print(finalSentence1)
else:
print(finalSentence2)
chessboard(3)
returns :
stackoverflow
101
010
101
I am working on the same kind of assignment, but as we have only covered conditional statements and while loops so far, following the same logic, here is my solution:
def chessboard(size):
output_1 = ''
output_2 = ''
i = 1
j = 1
while j <= size:
while i <= size:
if i % 2 == 0:
output_1 += '1'
output_2 += '0'
i += 1
else:
output_1 += '0'
output_2 += '1'
i += 1
if j % 2 == 0:
print(output_1)
j += 1
else:
print(output_2)
j += 1
chessboard(5)
returns:
10101
01010
10101
01010
10101
def chessboard(x):
i = 0
while i < x:
if i % 2 == 0:
row = "10"*x
else:
row = "01"*x
print(row[0:x])
i += 1

Using a while loop to iterate over a range of integers

How do I rewrite the first code to use a while loop instead of the given for loop? The output of the two programs should be the same.
num = 500
for j in range(30, 100):
if j > 70:
num = num – 5
else:
num = num + 2
print(num)
print("program output is", num)
I have tried this but it does not work correctly:
num = 500
while j > 30 and j < 100:
if j > 70:
num = num – 5
else:
num = num + 2
print(num)
A for loop automatically updates the loop variable (j) in every iteration.
In a while loop however, you have to assign a new value to the variable yourself, otherwise the loop will never end.
A for loop like
for j in range(a, b):
# do something ...
is equivalent to this while loop:
j = a
while j < b:
# do something ...
j += 1
(Note that j += 1 means the same as j = j + 1.)
In your case, you need to write:
num = 500
j = 30
while j < 100:
if j > 70:
num = num – 5
else:
num = num + 2
print(num)
j += 1
print("program output is", num)

how to turn this code into a function working code?

so i have some code that works perfectly without a function. But i want to change this inside a function, but it does not work properly.
For example, i have the end="". This doesn't work in a function, without using print.
I also have more than one print statements. When i turn these to return, they don't work. So could someone please help me change this code to work in a function?
Thanks!
My code
def underscore_hash_staircase(number):
if number > 0:
k = 2 * number - 2
for i in range(0, number):
for j in range(number-1, k):
print(end=" ".replace(" ", "_"))
k = k - 1
for j in range(0, i + 1):
print("#", end="")
print("")
else:
number = int(str(number).replace("-", ""))
i = number
while i >= 1:
j = number
while j > i:
print('', end=' '.replace(" ", "_"))
j -= 1
k = 1
while k <= i:
print('#', end='')
k += 1
print()
i -= 1
print(underscore_hash_staircase(8))
so the code above doesn't work properly in a function, without the print statements. Please let me know how to get this working in a function without the print statements. Using returns. It should be exact output as what is being returned in this not function-working code.
Thanks again!
Since a function can only return one value, instead of printing, you want to add to a variable to return instead of printing. Try:
def underscore_hash_staircase(number):
returnValue = "" # start as empty string
if number > 0:
k = 2 * number - 2
for i in range(0, number):
for j in range(number-1, k):
returnValue += "_"
k = k - 1
for j in range(0, i + 1):
returnValue += "#"
returnValue += "\n" # adding a new line
else:
number = int(str(number).replace("-", ""))
i = number
while i >= 1:
j = number
while j > i:
returnValue += "_"
j -= 1
k = 1
while k <= i:
returnValue += "#"
k += 1
returnValue += "\n"
i -= 1
print(underscore_hash_staircase(8))
Edit: missed a print when replacing
The function should append to a string instead of printing, and then return the string. Append \n to add a newline.
def underscore_hash_staircase(number):
result = ""
if number > 0:
k = 2 * number - 2
for i in range(0, number):
for j in range(number-1, k):
result += "_"
k = k - 1
for j in range(0, i + 1):
result += "#"
result += "\n"
else:
number = -number
i = number
while i >= 1:
j = number
while j > i:
result += "_"
j -= 1
k = 1
while k <= i:
result += "#"
k += 1
result += "\n"
i -= 1
return result
print(underscore_hash_staircase(8))
You also don't need all those inner loops. You can repeat a string by multiplying it.
def underscore_hash_staircase(number):
result = ""
if number > 0:
k = 2 * number - 2
for i in range(1, number + 1):
result += "_" * (number - i)
result += "#" * i
result += "\n"
else:
number = -number
for i in range(number, 0, -1):
result += "_" * (number - i)
result += "#" * i
result += "\n"
return result
print(underscore_hash_staircase(8))
print(underscore_hash_staircase(-8))

Very Beginner Problem in Python While Loop

Why this While loop is not breaking or stopping
I have added some output screenshot
term = 0
i = 13
while True:
print i > 1
print "i = ",i
if i == 1:
term += 1
break
if i%2 == 0:
i = i / 2
term += 1
if i%2 != 0:
i = i * 3 + 1
term += 1
Output
I also tried This way too
term = 1
i = 13
while i > 1:
print i > 1
if i%2 == 0:
i = i / 2
term += 1
if i%2 != 0:
i = i * 3 + 1
term += 1
Use elif to make the cases mutually exclusive. You don't want multiple if statements to execute in the same loop iteration.
if i%2 == 0:
i = i / 2
term += 1
elif i%2 != 0:
i = i * 3 + 1
term += 1
Or just make it else since the second condition is redundant.
if i%2 == 0:
i = i / 2
term += 1
else:
i = i * 3 + 1
term += 1
The reason it oscillates between 2 and 4 as written is because 2 causes both if statements to run. 2 is even so the first one runs and halves i, making it 1. Now it's odd and the second one triggers, turning 1 into 4.
if i%2 == 0:
i = i / 2 # 2 --> 1
term += 1
if i%2 != 0:
i = i * 3 + 1 # 1 --> 4
term += 1
The next iteration 4 becomes 2.
if i%2 == 0:
i = i / 2 # 4 --> 2
term += 1
These two iterations repeat over and over in an endless cycle.
Let's say your i is 2. It is divisible by 2, so if i % 2 == 0 fires, and i becomes 1. And the code continues to execute, so now we are at if i % 2 != 0 line, and this condition is also true, because you just modified i and it's now 1. So i becomes 4.
Your modified second attempt, which prevents the second condition from being checked if the first one succeeds, is below:
term = 1
i = 13
while i > 1:
print(i > 1)
if i % 2 == 0:
i = i / 2
term += 1
elif i % 2 != 0:
i = i * 3 + 1
term += 1
Also notice that you actually don't need to check the second condition, as it is definitely true if the first one is not, so elif ... line can be replaced just with else:
You can also use continue keyword to stop the rest of the loop from executing if the first condition is true:
term = 1
i = 13
while i > 1:
print(i > 1)
if i % 2 == 0:
i = i / 2
term += 1
continue
if i % 2 != 0:
i = i * 3 + 1
term += 1
Your first attempt has exactly the same problem; fixing it I leave as an exercise for the reader :)
P.S. do not learn Python 2
The problem is:
if i%2 == 0:
i = i / 2
term += 1
if i%2 != 0:
i = i * 3 + 1
term += 1
The problem is that, if i % 2 == 0 is true, it will remain true until i = 1. Once i = 1, i % 2 != 0 executes and makes i = 4.

Working with recursion but not with for loop

I have written a code using recursion, but later realized that the depth is too high and does not work for higher level input values. It works completely fine without any issue.
def checkCount(first_window, index=0,reference_list=None):
reference_list = []
count = 0
while index<=len(first_window)-2:
if first_window[index] < first_window[index+1]:
index += 1
count += 1
else: break
if count != 0:
reference_list.append(int((count*(count+1))/2))
count = 0
while index <= len(first_window)-2:
if first_window[index] > first_window[index+1]:
index += 1
count += 1
else: break
if count != 0:
reference_list.append(-int((count*(count+1))/2))
if index > len(first_window)-2: return reference_list
elif first_window[index] == first_window[index+1] and index<len(first_window)-2: index += 1
reference_list = reference_list + checkCount(first_window, index, reference_list)
return reference_list
import random
import time
start = time.clock()
input_array = list(map(int,"188930 194123 201345 154243 154243".split(" ")))
input_array = random.sample(range(1,100),10)
def main():
N = len(input_array)
K = 8
if K == 1: return None
print("Input array: ",input_array)
print("First Window",input_array[:K])
print("Real Output", checkCount(input_array[:K]))
if __name__ == "__main__":main()
Now no matter how I try without recursion, it ends with an infinite loop. I have tried different ways but no progress.
One way I have tried is taking out the recursion statement and returning the referencelist + index:
def checkCount(..):
....
....
return referencelist,index
while index <= K-2:
print("While",index)
reference_list, index = checkCount(new_input, index=0, reference_list=[])
referencelist += reference_list
The application is similar to the here. But we have to deal with tons of data where recursion cannot help. Assume that the input array is greater than 100,000. I am really struck here, I do not understand what logic am I missing. Any help will be grateful.
The first_window variable is only read, and the index variable is only incremented. There is no need for recursion, a simple loop can work.
def check_count(first_window):
reference_list = []
index = 0
while index < len(first_window) - 2:
count = 0
while index <= len(first_window) - 2:
if first_window[index] < first_window[index + 1]:
index += 1
count += 1
else:
break
if count != 0:
reference_list.append(int((count * (count + 1)) / 2))
count = 0
while index <= len(first_window) - 2:
if first_window[index] > first_window[index + 1]:
index += 1
count += 1
else:
break
if count != 0:
reference_list.append(-int((count * (count + 1)) / 2))
if index < len(first_window) - 2 and first_window[index] == first_window[index + 1]:
index += 1
return reference_list
Of course, this algorithm can be optimised, for instance, we can avoid repetitions like: len(first_window) - 2.

Categories