While loop testing equality with 0 will not break [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
This while loop won't end. Any suggestions for this Python program?
[Edit: Upon request I quoted the entire program. It's supposed to find the largest palindrome produced by two n digit decimals.]
def palindrome(n):
first = 1
second = 1
largestPalindrome = 1
palindrome = True
while(first < 10**n):
while(second < 10**n):
number = []
candidate = 1
while candidate!=0:
number.append(candidate%10)
candidate = candidate // 10
print("in")
i = 0
ub = len(number)//2
while(i<ub):
if(number[i]!=number[len(number)-1-i]):
palindrome = False
i += 1
if palindrome == True:
largestPalindrome = first*second
print(largestPalindrome)

Your external while loops
while(first < 10**n):
while(second < 10**n):
...
are checking if the variables first and second are under a certain value (10**n). The problem is that, inside these loops, you never increment either first or second, so the condition is always satisfied and your loops keep going on forever.

Related

Function to find a continuous sub-array which adds up to a given number in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
Improve this question
I want to know what's wrong in the below code. Will it consume more time to in some certain scenarios?
Expected time complexity: O(n)
def subArraySum(self,arr, n, s):
if sum(arr[0:n]) == s:
return [1, n]
if sum(arr[0:n]) < s:
return [-1]
start = 0
i =1
sum_elements = 0
while i < n:
sum_elements = sum(arr[start:i+1])
if sum_elements == s:
return [start+1, i+1]
if sum_elements < s:
i += 1
continue
if sum_elements > s:
start += 1
continue
if sum_elements < s:
return [-1]
Instead of running sum(arr[start:i+1]) in each iteration of the while loop, you should use a variable and add or subtract the respective value that is included or excluded from the subarray in each iteration. That way you can avoid the O(n^2) complexity and stay within O(n).
Currently there is a lot of overhead for calculating the sum of a (potentially large) subarray that has only changed by one single value at the beginning or the end during each iteration.

Problems with nested loops in Python [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am new to Python and wanted to use it for a university project. I read data from a .csv file, and apply the SVD algorithm on them. Afterwards I want to resize the arrays I get as an output into new arrays as per the project's instructions. The problem arises when I try to sopy the data from one array to the other. Here's some code that produces the same behaviour.
import numpy as np
import pandas as pd
test = np.ones((4,5))
test2 = np.zeros((4,3))
i=0
j=0
while i < 4:
while j < 3:
test2[i][j] = test[i][j]
j += 1
i += 1
After the nested loops I expect to see the same data on arrays test and test2 but what actually happens is that only the first row gets copied while the rest don't and I have no idea why.
The crux of your problem is using the wrong loop type. You made a very common mistake with using a while to do the job of a for.
i = 0
j = 0
while i < 6036:
while j < 50:
u_50[i][j] = u[i][j]
j += 1
i += 1
After you're done with the first iteration of the i loop, you increment i from 0 to 1, and hit the while j statement. However, j is still 50, because you failed to reset it. You need the j controls totally within the i loop:
i = 0
while i < 6036:
j = 0
while j < 50:
u_50[i][j] = u[i][j]
j += 1
i += 1
Please revisit your tutorial materials and learn to use for, so you don't repeat this mistake.
for i in range(6036):
for j in range(50):
u_50[i][j] = u[i][j]

I'm returning a defaultdict(list), but randomly choosing between the two, why does it return nothing sometimes? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
output = ""
numberList = [0, 1]
print(random.choice(numberList))
if(random.choice(numberList) == 0):
if len(slots) > 0:
output = templates[state][0].replace("<num_classes>", str(slots[0][1]))
else:
output = templates[state][0]
elif(random.choice(numberList) == 1):
if len(slots) > 0:
output = templates2[state][0].replace("<num_classes>", str(slots[0][1]))
else:
output = templates2[state][0]
return output
expected answer
sometimes get this
Sometimes it returns nothing or no dictionary... Why?
With
elif(random.choice(numberList) == 1)
you will again choose a brand new random number. And if that isn't 1 then there's no else that will set output.
Instead of elif you should have a plain else.

Why is there a None in output? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Help, I'm trying to create a function that uses modulus to print numbers that are divisible by an integer, in this case, multiples of 17:
def nextDivisible(n):
if n % 17 == 0:
print n
else:
nextDivisible(n+1)
But the output is for example:
n: 93 next divisible: 102
None
n: 59 next divisible: 68
None
Why is there a None?! and how do I remove it, thanks!
I think your problem is that you are printing out the result instead of returning it from the function.
If you change your code to be like this it should fix it:
def nextDivisible(n):
if n % 17 == 0:
return n
return nextDivisible(n + 1)
How this works with recursion is that your function nextDivisible is going to be repeatedly called until it reaches its base case of n being divisible by 17. When that case occurs it will return n all the way back up the recursive stack to where the original first call to the function was done.
You also don't need an else statement because return statements break out of the function code. But sometimes else's are good for readability.
You don't need to:
print(nextDivisible(n))
I think you get None printed because your function doesn't return anything. It is also redundant to print the return of the function because you print the numbers inside the loop.
All you need is:
nextDivisible(n)
And it will print the divisible numbers.
If you are use nextDivisible() in other functions, it may be worth nothing that a return statement may be required depending on the nature of how you are using it.
For all intents and purposes this should work just fine.
And python 3.x:
x = [x for x in range(1000)]
def nextDivisible(x, mod=17):
c = 0
for n in x:
if n % mod == 0:
print(n)
c += 1
else:
#nextDivisible(n+1)
pass
print('{} numbers divisible by {} in {}'.format(c, mod, len(x)))
nextDivisible(x)
Expected output:
59 total numbers divisible by 17 in 1000

How does this for loop on consecutive integers work? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
This seems like an embarrassingly easy concept but I can't understand why this for loop is working the way it is. The question is simply asking "Given a binary array, find the maximum number of consecutive 1s in this array."
def main(nums):
count = 0
for num in nums:
if num == 1:
count+=1
else:
count = 0
main([1,1,0,1,1,1,0,0,1,1,1,1,1])
My question is, why does this for loop work? I expected the loop to print out the total count of 1's.
It just doesn't work.
You can't expect to have the sum of all the 1s because when the loop find a zero it reset the counter (the "else" part).
However, your code doesn't do what it was expected to do, add a zero at the end of the list and you will easily see that the code fails.
To do what you asked, without changing your code too much, try this
def main(nums):
count = maxcount = 0
for num in nums:
if num == 1:
count+=1
else:
maxcount=max(maxcount, count)
count = 0
return maxcount
print(main([1,1,0,1,1,1,1,1,1,0,0,1,1,1,1,0,1]))
Dave
The difference is that once it sees a zero, it sets the value of count back down to zero, saying that it's seen 0 consecutive ones. This code actually doesn't work—it only gets lucky on this input because the longest sequence is at the very end of the list.
A better practice would be to store both the lengths of the current_group of ones and the highest_total count.
It's probably hard to believe, but could it be that the reason you are wondering why this loop works at all is that you are not familiar with Python ability to iterate over all elements of a list, not needing any counter variable increasing its value?
[1,1,0,1,1,1,0,0,1,1,1,1,1]
is in Python a kind of array storing multiple number of values.
Here some "pseudo-code" for explanatory purpose only demonstrating that "for num in nums" means in Python (in terms of programming in other
languages which don't support iteration over elements of a list/array):
noOfValuesIn_nums = lengthOf/sizeOf(nums)
for i = 0 to noOfValuesIn_nums do:
# get i=th value from 'nums' and put it to a variable named 'num':
num = nums[i]
...
By the way: the loop provided in the question gives the desired result for the provided example:
main([1,1,0,1,1,1,0,0,1,1,1,1,1])
but won't work on another one as demonstrated here:
def main(nums):
count = 0
for num in nums:
if num == 1:
count+=1
else:
count = 0
return count
print( main([1,1,1,1,1,1,0,0,1,1,1,0,1]) )
# it prints 1 instead of 6
The task of finding the longest consecutive sequence of ones
solves following code:
def main1(nums):
count = 0
maxOnes = 0
for num in nums:
if num == 1:
count+=1
else:
if count > maxOnes:
maxOnes = count
count = 0
return maxOnes
print( main1([1,1,1,1,1,1,0,0,1,1,1,0,1]) )
# gives 6

Categories