Upper bound equal to lower in Python range - python

Can someone please explain to me why this code works for 2 as well:
def is_prime_v1(n):
'''Return True if 'n' is prime. False otherwise.'''
if n == 1:
return False
for d in range(2,n):
if n % d == 0:
return False
return True
when the code gets to
for d in range(2,n):
if n % d == 0:
return False
return True
Would it not see this as start at 2 but go up to and do not include 2?
This does not make complete sense to me.
The formula works but if you try and create a list on that range like so:
x = list(range(2,2))
You get an empty list.
Please could anyone explain this to me? Does it work for two as well because it would not be able to do the below on range(2,2) and then moves down to return True?
if n % d == 0:
return False
return True
Thanks

because for loop is never executed , list(range(2,2)) == [], so the program didn't iterate over range and directly proced to return True statement

Your assumption is correct. The upper value of the range function is not put through the for loop. To overcome this, you could just add or n == 2 to the third line of your program.

Related

Given a list of ints, return True if the array contains a 3 next to a 3 somewhere

I want to creates a function that returns True if a list contains two consecutive 3 and false if not.
when using this code it doesn't work:
def has_33(x):
for i in range(len(x)-1):
if x[i:i+2] == [3,3]:
return True
else:
return False
But with this it works:
def has_33(x):
for i in range(len(x)-1):
if x[i:i+2] == [3,3]:
return True
return False
For me it's the same thing can you explain to me why plz
In the top code you only check the first 2 indices. In the bottom code you're checking the whole array. Here's why:
In the top code you have an else condition, which means that on the first iteration either the if-condition is true (i.e. the first and the second element of the list are 3) or you will go into the else condition. In either case, you're hitting a return statement after checking just the first 2 elements.
In the bottom code, you only return if you find something, or once you've finished the whole loop
I've added some print statements to both your functions. You can run this code and see the output to help you understand what's happening:
def has_33_incorrect(x):
print("\nRunning the incorrect function")
for i in range(len(x)-1):
print("Checking indices {} and {}".format(i, i+1))
if x[i:i+2] == [3,3]:
print("indices contain 2 consecutive 3's. Returning true")
return True
else:
print("indices don't contain 2 consecutive 3's. Returning false")
return False
def has_33_correct(x):
print("\nRunning the correct function")
for i in range(len(x)-1):
print("Checking indices {} and {}".format(i, i+1))
if x[i:i+2] == [3,3]:
print("indices contain 2 consecutive 3's. Returning true")
return True
print("Did not find consecutive 3's. Returning false")
return False
list = [1, 2, 4, 5, 6, 3, 3, 2, 5]
has_33_incorrect(list)
has_33_correct(list)
One more solution with any python builtin:
def has_33(l):
return any(l[i+1] == l[i] == 3 for i in range(len(l) - 1))
This code works since if the if condition is false it doesn't return anything, yet in the first function you showed it returns false and exits the function. You shouldn't return anything until you find that its true somewhere, only after you've iterate over the entire list then and only then should you return False
def has_33(x):
for i in range(len(x)-1):
if x[i:i+2] == [3,3]:
return True
return False
You can iterate over the list directly.
def has_33(x):
current = None
for item in x:
if current == item == 3:
return True
current = item
return False
If you ever find both current and item are equal to 3, you can return True immediately. Otherwise, you will return False when the loop exits naturally.
If you loop through adjacent entries at the same time, you can compare:
def adjacent_threes(x):
for a, b, in zip(x[:-1], x[1:]):
if a == b == 3:
return True
return False
Try this ,it's simple:
def has_33(nums):
for i,num in enumerate(nums):
if nums[i]==3 and nums[i+1]==3:
return True
return False
python code as follows :
def has_33(nums):
my_list = []
y =len(nums)-1
for x in range(0,y) :
if nums[x] == 3 and nums[x+1] == 3:
my_list.append(1)
else :
my_list.append(0)
print(my_list)
if 1 in my_list:
return True
else :
return False

Prime number calculator functions, why is one correct and the other incorrect?

I've seen some similar codes here on stack overflow but none had my same question.
basically, my question is why when I tried to check the inequality (!=) in the for loop it didn't work. But when I tried using the equality (==) it worked fine?
so this code returns True always:
def is_prime(x):
if x == 2:
return True
else:
for i in range(2, x):
if x > 2:
if x % i != 0:
return True
return False
while this code is works fine:
def is_prime(x):
if x < 2:
return False
if x == 2:
return True
else:
for i in range(2, x):
if x > 2:
if x % i == 0:
return False
return True
Your second function is correct because it returns False if in any loop x % i == 0. Otherwise, it returns True. This is the definition of a prime number.
Your first function is incorrect because it returns True if in any loop x % i != 0. Otherwise, it returns False. The problem with this is that for all integers k > 2 there exists an integer i in range [2, k) such that k % i does not equal 0. Trivially, you can set i = k - 1. So the function will always return True.

Recursive function seems to be fine, but won't return False

So the function should check if a list is symmetric; if the list is empty or has one integer, it is symmetric.
Otherwise the function should check if the first and last integers are the same and go on recursively. If not, return False.
The code seems right, but I can't figure out what's wrong and why it won't return False.
def symm(lst):
t = len(lst)
if t == 0 or 1:
return True
if t>1:
if lst[0] == lst[-1]:
return symm(lst[1:-2])
else:
return False
print symm([6,6,6,6,7])
if t == 0 or 1: is always true since this is read as if (t == 0) or (1): and 1 is always going to be true.
Change to: if t in [0,1]: or simply if len(lst) < 2:

Python prime number check

guys!
I have a codecademy Python course excercise in which I have to check if parameter passed is prime. My code looks like this:
def is_prime(x):
for n in range(2, x-1):
if (x < 2):
return False
elif(x % n == 0):
return True
else:
return False
It seems to me that I have covered all possibilities, but it constatnly displays this error:
Your function fails on is_prime(0). It returns None when it should return False.
This falls in the first if-condition as far as I can see. Can someone explain how this is possible?
Hint, what numbers are inside range(2, x-1) when x is 0?
This version may works.
def is_prime(x):
if (x < 2):
return False
for n in range(2, x-1):
if(x % n == 0):
return False
return True

How can I return false if more than one number while ignoring "0"'s?

This is a function in a greater a program that solves a sudoku puzzle. At this point, I would like the function to return false if there is more then 1 occurrence of a number unless the number is zero. What do am I missing to achieve this?
L is a list of numbers
l =[1,0,0,2,3,0,0,8,0]
def alldifferent1D(l):
for i in range(len(l)):
if l.count(l[i])>1 and l[i] != 0: #does this do it?
return False
return True
Assuming the list is length 9, you can ignore the inefficiency of using count here (Using a helper datastructure - Counter etc probably takes longer than running .count() a few times). You can write the expression to say they are all different more naturally as:
def alldifferent1D(L):
return all(L.count(x) <= 1 for x in L if x != 0)
This also saves calling count() for all the 0's
>>> from collections import counter
>>> def all_different(xs):
... return len(set(Counter(filter(None, xs)).values()) - set([1])) == 0
Tests:
>>> all_different([])
True
>>> all_different([0,0,0])
True
>>> all_different([0,0,1,2,3])
True
>>> all_different([1])
True
>>> all_different([1,2])
True
>>> all_different([0,2,0,1,2,3])
False
>>> all_different([2,2])
False
>>> all_different([1,2,3,2,2,3])
False
So we can break this down into two problems:
Getting rid of the zeros, since we don't care about them.
Checking if there are any duplicate numbers.
Striping the zeros is easy enough:
filter(lambda a: a != 0, x)
And we can check for differences in a set (which has only one of each element) and a list
if len(x) == len(set(x)):
return True
return False
Making these into functions we have:
def remove_zeros(x):
return filter(lambda a: a != 0, x)
def duplicates(x):
if len(x) == len(set(x)):
return True
return False
def alldifferent1D(x):
return duplicates(remove_zeros(x))
One way to avoid searching for every entry in every position is to:
flags = (len(l)+1)*[False];
for cell in l:
if cell>0:
if flags[cell]:
return False
flags[cell] = True
return True
The flags list has a True at index k if the value k has been seen before in the list.
I'm sure you could speed this up with list comprehension and an all() or any() test, but this worked well enough for me.
PS: The first intro didn't survive my edit, but this is from a Sudoku solver I wrote years ago. (Python 2.4 or 2.5 iirc)

Categories