Code is in Infinite Loop and I don't know Why - python

My code is stuck in an infinite loop on the following lines:
while i <= len(mylist):
if mylist[i][j] == number:
I've stepped through the code but still do not know how to fix it. The problem I'm trying to solve is as follows:
Define a procedure, check_sudoku,
that takes as input a square list
of lists representing an n x n
sudoku puzzle solution and returns the boolean
True if the input is a valid
sudoku square and returns the boolean False
otherwise.
A valid sudoku square satisfies these
two properties:
Each column of the square contains
each of the whole numbers from 1 to n exactly once.
Each row of the square contains each
of the whole numbers from 1 to n exactly once.
You may assume that the input is square and contains at
least one row and column.
The below code I've written should check for just the row, not the column. Any advice on how to fix it and what I've done wrong would be greatly appreciate, so I'll understand and not make the mistake again.
def check_sudoku(mylist):
i = 0
j = 0
number = len(mylist)
while i <= len(mylist):
if mylist[i][j] == number:
number = number - 1
j = 0
if number == 0:
i = i + 1
number = len(mylist)
else:
j = j + 1
if number not in list:
break
return False
return True
check_sudoku([[1, 2, 3, 4],
[1, 3, 1, 4],
[3, 1, 2, 3],
[4, 4, 4, 4]])

I'm going to explain the function with the list you supplied as an example.
What's happening is:
number = len(mylist)
number = 4
while 0 <= 4
if 1 == 4: // This condition will never be true and therefore doesn't run the code below it
The while will run again and the same will happen.

If you put this line
print("i: " + str(i) + " j: " + str(j))
Just under where the While Loop starts, you realise that i and j never increment and it stays on the first spot.
You have to increment i and j after your bigger if statement

Related

While loop keeps going back to end condition

I'm just going over some python basics, and wrote some code that I thought would print every even element inside of a list:
def print_evens(numbers):
"""Prints all even numbers in the list
"""
length = len(numbers)
i = 0
while i < length:
if numbers[i] % 2 == 0:
print (numbers[i])
i += 1
print_evens([1, 2, 3, 4, 5, 6])
I'm not sure why but the loop doesn't go past the end condition and just keeps cycling back and forth. I feel I'm missing something very simple.
If I had to guess where the problem lies, I'd say it's with the if statement, though I'm not sure what would be wrong about it.
The problem is that when you start with 1 the variable i never get updated, because it's not even. So the solution is to increment the i every time without a condition:
while i < length:
if numbers[i] % 2 == 0:
print (numbers[i])
i += 1
If you don't want to bother with indexes you can loop directly on the list items.
def print_evens(numbers):
"""Prints all even numbers in the list
"""
for n in numbers:
if n % 2 == 0:
print(n)

Python code to extend a list of prime numbers

I want to write code that extends a list of prime numbers using Python, but something does not work:
list = [2,3,5,7]
for num in range(15,30):
for i in range(0,len(list)-1):
if num%list[i] != 0:
if i + 1 == len(list):
list.append(num)
else:
continue
else:
break
print(list)
The incorrect output is: [2, 3, 5, 7]
Your issue is that
for i in range(0,len(list)-1):
should be
for i in range(0,len(list)):
The range function in python will stop on the number before the number you specify in the stop argument, so you don't need to minus 1 yourself. From the documentation:
For a positive step, the contents of a range r are determined by the formula r[i] = start + step*i where i >= 0 and r[i] < stop.
Because your code doesn´t work.
If you run your code, you will see that the program jumps in the else part of your first if condition and there you will break the for loop. So your program does nothing other than deklaring a list and print that list, because the true part of the if condition isn´t processed.
Another way to fix the issue #RobStreeting pointed out (+1) is to get rid of the range(len()) idiom and use enumerate(). We can fix the missing 11 & 13 that #ThierryLathuille points out by starting our loop just afer the last collected prime. Finally, you shouldn't have a variable named list as that's a reserved Python keyword. Putting this all together, your code looks something like:
primes = [2, 3, 5, 7]
for number in range(primes[-1] + 1, 50):
for i, prime in enumerate(primes, start=1):
if number % prime:
if i == len(primes):
primes.append(number)
else:
continue
else:
break
print(*primes, sep=", ")

Output going beyond specified maximum in range() function

I am trying to answer the following practice question:
"Write a loop (we suggest a for loop) that prints the numbers from minimum to maximum, including minimum and maximum themselves. If even is True, print only the even numbers. If even is False, print only the odd numbers. You may assume minimum will always be less than maximum."
For this I have written the following code, and it works for certain minimum and maximum values:
minimum = 5
maximum = 14
even = True
if even:
for numbers in range(minimum, maximum+1, 2):
if numbers%2 == 0:
print(numbers)
elif numbers%2 == 1:
numbers += 1
print(numbers)
else:
for numbers in range(minimum, maximum+1, 2):
if numbers%2 == 1:
print(numbers)
elif numbers%2 == 0:
numbers += 1
print(numbers)
This generated my desired output of 6, 8, 10, 12, 14.
However, once my minimum, maximum and even values are altered, to below for example:
minimum = 29
maximum = 33
even = True
The code somehow generates an output of 30, 32 and 34. 34 > 33 and therefore it shouldn't be there, yet it is. I was under the assumption that range() works such that it doesn't include the maximum number and thus I used maximum+1 to include maximum as the question asked, yet it included a number that is even beyond maximum+1!
To test further, I tried altering the variables as following and discovered something as interesting as it is puzzling too:
minimum = 1
maximum = 4
even = False
As expected, I got 1, 3 as my output. However, when I changed minimum = 2, I got 3, 5 as my output instead!
Could someone please explain to me why the code is acting this way? Thanks in advance!
Because when you are in the for loop you are incrementing number variable, wich is the loop index, and should be managed by the loop itself.
Specifically when number is 33 when you reach
elif numbers%2 == 1:
numbers += 1
print(numbers)
it gets incremented by 1 and being 34 even it gets printed.
May I suggest an implementation:
for number in range(minimum, maximum+1):
if (number%2 == 0 and even):
print number
elif (number%2 != 0 and not even):
print number
When maximum is 33 and you make a range object that goes to maximum+1, the largest value you're going to see from it is maximum, which is 33. However, when you add 1 to that value with numbers += 1, you change that to 34, which is where you get 34. You can clean up your code by changing minimum and maximum as necessary before you start, rather than shifting every number in the range.
def printer(low, hi, even):
for num in range(low + (even == low%2), hi+1, 2):
print(num)
mn, mx, even = 5, 14, True
for x in range(mn + int(bool(mn % 2) == even), mx + 1, 2):
print(x)
int() converts a bool value inside to either 0 or 1, which is the necessary offset for starting.
PS To understand why you ran out of range in your code, assume numbers = 33, plug it in your code, and see what happens:
if numbers%2 == 0:
print(numbers)
elif numbers%2 == 1:
numbers += 1
print(numbers)

Removing data structure

The goal here is to take an amount of int values indicated by the first int and create a list, in order of even numbers to odd numbers (value order of the numbers doesn't matter).
My code so far deals with most of the problem. However, how would I go about ignoring the first int value?
Example input:
example=[7,1, 0, 1, 0, 0, 1, 1]
example=[3,3, 3, 2]
example=[3,2, 2, 2]
My code:
even=[]
odd=[]
while True:
try:
n = int(input())
except:
break
if n % 2 ==0:
even.append(n)
else:
odd.append(n)
print(even+odd)
Before going in while loop, pop out first value. You can also save this as the total numbers.
Also, there is an error in your code. If try fails in while loop, for the first time loop running there will be an exception. And next on previous value will be used, so a single value will be repeated. I corrected it by adding n=0.
even=[]
odd=[]
n=0
NumCount= int(input())
while True:
try:
n = int(input())
except:
break
if n % 2 ==0:
even.append(n)
else:
odd.append(n)
print ("Total numbers (even+odd)", NumCount)
print(even+odd)

Finding all numbers that evenly divide a number

So I'm trying to make a program that when I input a number it will give me all the factors(12->1,2,3,4,6,12). I only started programming very recently so there may be some very obvious things. But here's my code
numbers = [1]
newnum = 1
chosen = int(input("Enter what you want the factors of: "))
def factors(numbers,newnum,chosen):
lastnum = numbers[-1]
if (chosen == lastnum):
for number in numbers:
if (number % 1 != 0):
numbers.remove(number)
print (numbers)
else:
factors(numbers,newnum,chosen)
else:
newnum = numbers[-1] + 1
numbers.append(newnum)
print (numbers)
factors(numbers,newnum,chosen)
factors(numbers,newnum,chosen)
Ok, so I don't really need the redundancies addressed but if you see something that would completely stop the program from working please point it out. Sorry I bothered you all with this but I don't know what else to do.
There are lots of problems:
Every integer number modulo 1 is zero because each integer is divisible by one without remainder.
You remove items from the list you're iterating over, that will definetly give wrong results if you don't do it carefully!
You try to do recursion but you don't return the result of the recursive call. That's possible because you operate on a mutable list but it's generally not really good style
You don't have any inline comments explaining what that line is supposed to do, so it's hard to give any reasonable guidance on how to improve the code.
If you want a code that finds all factors, consider something like this:
chosen = int(input("Enter what you want the factors of: "))
def factors(chosen, currentnum=None, numbers=None):
# Recursion start, always append 1 and start with 2
if numbers is None:
numbers = [1]
currentnum = 2
# We're at the last value, it's always divisible by itself so
# append it and return
if currentnum == chosen:
numbers.append(currentnum)
return numbers
else:
# Check if the chosen item is divisible by the current number
if chosen % currentnum == 0:
numbers.append(currentnum)
# Always continue with the next number:
currentnum += 1
return factors(chosen, currentnum, numbers)
>>> factors(chosen)
Enter what you want the factors of: 12
[1, 2, 3, 4, 6, 12]
That's not the optimal solution but it uses recursion and gives a proper result. Just don't enter negative values or catch that case in the function at the beginning!
# Two Pointer Approach
ans = []
def divisor(val):
result = []
for i in range(1, val + 1):
ans.append(i)
i = 0
j = len(ans) - 1
while i < j:
if ans[i] * ans[j] == ans[-1]:
result.append(ans[i])
result.append(ans[j])
i += 1
else:
j -= 1
return sorted(result)
print(divisor(12))
# Output
>>> [1, 2, 3, 4, 6, 12]

Categories