How do I get my code to only print one output? - python

Essentially, I am trying to make a function which reads an array, and a number. If the number is within the array, it should return True, and False otherwise. However, I find that for each element in the array there is a True or False - the code checks everything individually, when I only need one True or False; is the number in the array or not ?
def is_it_there(arr, k):
for x in arr:
if x == k:
print(True)
else:
print(False)
is_it_there([8,5,2,234,426,7,11],11)
Like I said before, only one True was expected, but each item was checked and so it was False, False, False, False, False, False, True

It's just
if k in arr:
print(True)
else:
print(False)
or, simpler
print(k in arr)

The problem rises from the fact because you are checking it constantly while looping through the elements. So the code is going to check through constantly whether or not the element is present or not. So you are going to end up printing a statement everytime. Python gives a neat way to do achieve this
def is_it_there(arr, k):
if k in arr:
print(True)
else:
print(False)
is_it_there([8,5,2,234,426,7,11],11)

You can refactor your code like this:
def is_it_there(arr, k):
for x in arr:
if x == k
return True
return False
print(is_it_there([8,5,2,234,426,7,11],11))

If you find the item anywhere in the list, print True and exit the function immediately.
If you make it all the way to the end of the list without finding it, only then print False.
def is_it_there(arr, k):
for x in arr:
if x == k:
# print True and terminate the function
print(True)
return
# if we made it all the way through the loop, we didn't find it
print(False)
However, the 'in' operator already does what you want:
if value in mylist:
print 'True'
else:
print 'False'

You are printing a result each time you do a test in your loop. Try to record the result of each round of your test in a list, and test if there is any "True" value in your result list.
Code Example:
def is_it_there(arr, k):
result = list()
for x in arr:
if x == k:
result.append(True)
else:
result.append(False)
if True in result:
print(True)
else:
print(False)
is_it_there([8,5,2,234,426,7,11],11)

Related

How to find if there are 2 elements of same value consecutively in a list?

For example,
[1,3,3,5] should return True while [1,3,1,3] should return False.
I am looking for a simple solution using loops.
I tried the following:
def conseq(nums):
for i in range (len(nums)):
if nums[i]==nums[i+1]:
return True
break
else:
return False
The first time your function encounters 2 consecutive numbers which are different, it returns False. Returning from a function ends that function immediately, the function does not continue after that. This is also why the break is not necessary.
Another issue with your code is that once you reach the final number, nums[i + 1] will access out of the bounds of the array. That's why you should iterate over len(nums) - 1 rather than len(nums) - there's no reason to check the final number because there's nothing after it.
def conseq(nums):
for i in range(len(nums) - 1):
if nums[i]==nums[i+1]:
return True
# Only return False once we've exhausted all numbers.
# Since we didn't return True so far - it means there are
# no consecutive equal numbers, so we can safely return False
return False
the return ends the function, so here it will stop the processing as well
your true statement mostly works, and the break is unnecessary
you don't want the else statement until after the for loop ends (it returns False only if everything else has been parsed)
Also the way you parse through the code, nums can't access nums[i+1] when you're at the final nums so you need the range len(nums) - 1
If you feel like putting an else that does nothing, you can with a single semicolon or pass I believe, but the else is unnecessary here
def conseq(nums):
for i in range (len(nums)-1):
if nums[i]==nums[i+1]:
return True
else:
;
return False
You can't return False until the loop is done (since the match may be in the part of the list you haven't checked yet). And the break after return will never happen (since return ends the function and everything in it).
Enumerate list without last (to avoid try catch for i+1 being out of range) then compare each item with next one and return True if they are same. After loop return False because none are similar consequtively (returns break functions)
def function(number_list):
for i, item in enumerate(number_list[:-1]):
if item == number_list[i+1]:
return True
return False
def conseq(nums):
for i in range (len(nums)):
if nums[i]==nums[i-1]:
return True
return False
I modified your Code. Please check and let know if useful
def conseq(nums):
flag=True
for i in range (len(nums)-1):
if nums[i]==nums[i+1]:
print(True)
flag=False
break
else:
continue
if(flag):
print(False)
nums=[1,3,3,5]
nums1=[1,3,1,3]
conseq(nums)
conseq(nums1)
We have many solutions here already. I have tried out using numpy without a loop:
>>> import numpy as np
>>> f = np.array([1,3,3,5])
>>> (np.where(np.diff(f) == 0)[0]).astype('bool')[0] #check if we have any difference of two elements 0?
True

How do I check whether squares of certain numbers in one list are in the second

So, I've stumbled upon a problem during my codewars practise and i'm currently stuck on how to actually check for squares in another list.
I passed some tests, but when I actually try to submit it, it raises certain errors, and tests come back False.
import math
def comp(array1, array2):
**if array1 == []:
return False
if array2 == []:
return False
for i in range(len(array1)):
promenljiva = array1[i * i]
if promenljiva in array2:
return True
break
for j in range(len(array2) - 1):
promenljiva_1 = math.sqrt(array2[j])
if promenljiva_1 not in array1:
return False
elif promenljiva_1 != array1[0]:
return False
break
This is my code, so if someone can please assist me on this, I would be very happy! :)
P.S. Promenljiva is actually just a serbian term for variable :)
This will return True if all of the items**2 in array1 are in array 2. Otherwise, it will return False. However, it will still return True if there are additional values in array2.
def comp(array1, array2):
results = []
for i in array1:
if i*i in array2:
results.append(True)
else:
results.append(False)
if False in results: #if any squares are not in array2, return False
return False
else:
return True

if...else.. compare character list and string by python

I am writing an for loop comparing the character in list and string, then return False if the character is not same. But I keep receiving True. Can someone explain what is wrong with my code?
def compare (sofar, orig):
if len(sofar) == len(orig):
for i in range(len(orig)+1):
if orig[i] == sofar[i]:
return True
else:
return False
return False
here is the result i got:
In [29]: compare (['a','v','c','c','s'], 'abccs')
Out[29]: True
But it suppose to be False
You could just join the characters back into a string
def compare (sofar, orig):
return ''.join(sofar) == orig
Otherwise, if you wanted a loop, you need to compare all characters before you return True. You can return False when the first does not match
Here's another one liner using all() over a loop of zipped characters.
You will need the length check before this statement
return all(x == y for x, y in zip(sofar, orig))
Or going back to the original code, invert your logic
def compare (sofar, orig):
if len(sofar) != len(orig):
return False
for i in range(len(orig)):
if orig[i] != sofar[i]:
return False
return True
If your function reaches a return statement, that's it. Your function has returned a value and it will not continue running.
You can use a generator to implement your logic. The below solution allows you to iterate lazily; retrieve a Boolean list with a letterwise comparison via list; or check if all letters align via all.
def compare(sofar, orig):
if len(sofar) == len(orig):
for i in range(len(orig)):
if orig[i] == sofar[i]:
yield True
else:
yield False
res = list(compare(['a','v','c','c','s'], 'abccs'))
# [True, False, True, True, True]
res = all(compare(['a','v','c','c','s'], 'abccs'))
# False
Another way of writing your logic without explicit iteration:
lst = ['a','v','c','c','s']
mystr = 'abccs'
res = ''.join(lst) == mystr
The statement return is exit from your function.
So your prog only compares the first element.
if orig[i] != sofar[i]:
return False
would do it

Looping with Consecutive Elements

I'm a beginner in Python programming and I'm having some trouble with some list stuff.
So I want to write a function that returns a boolean value. The function will inform the user whether there is a duplicate consecutive pair of elements in the list he or she entered. By the way, I want to do this using only len(), range(), loops, if-statements, variables and arithmetic (no built in functions).
For example:
contains_consecutive_duplicates([1,3,3]) should return True
contains_consecutive_duplicates([3,2,3]) should return False
My code:
def contains_consecutive_duplicates(xs):
for i in xs:
if xs[i] == xs[i-1] or xs[i] == xs[i+1]:
return True
else:
return False
My logic to this was as follows: Each time the for loop would run, i would refer to some element in the list. If that element was such that the element before it or after it was equal to it, then the for loop would return true. If not, keep searching. If there are none, it would return false.
Now, I actually understand where the error is (I think). The problem is that I don't know how to solve it. I think the for loop is running into a problem at the beginning (when i is reffering to the 0th element). There is no element before the 0th element, hence the error:
"index out of range"
P.S: Is that how you return a boolean value?
Is there a better way to do this?
I would appreciate any help given! Thanks in advance!
#roeland pointed out the problem with assuming iterating the list directly would get you indices (if you want index and value, use enumerate). But in this case you don't actually need the index.
For the simple case (where it's known to be a container you can slice), you can just iterate with zip over offset slices:
def contains_consecutive_duplicates(xs):
return any(x == y for x, y in zip(xs, xs[1:]))
More general solutions can be made with itertools.groupby to handle the case where you can't slice, but this is simple and involves no imports.
Use of any in this case is just a short hand to slurp the generator expression and return True if any values are truthy. The long equivalent form is:
def contains_consecutive_duplicates(xs):
for x1, x2 in zip(xs, xs[1:]):
if x1 == x2:
return True
return False
Since your teacher apparently thinks built-ins are bad, but len and range aren't built-ins (they are), you can do this the dumb way:
def contains_consecutive_duplicates(xs):
for i in range(len(xs) - 1):
if xs[i] == xs[i+1]:
return True
return False
Which does the same work as ziping, just less efficiently (generating index integers and explicitly indexing is surprisingly expensive in Python relative to native iteration).
This should do:
>>> def contains_consecutive_duplicates(xs):
... for i, v in enumerate(xs[:-1]):
... if v == xs[i+1]:
... return True
... else:
... pass
... return False
>>> l1 = [1,3,3]
>>> l2 = [1,3,2]
>>> l3 = []
>>> l4 = [2]
>>> contains_consecutive_duplicates(l1)
True
>>> contains_consecutive_duplicates(l2)
False
>>> contains_consecutive_duplicates(l3)
False
>>> contains_consecutive_duplicates(l4)
False
>>>
By using only range, for and if statements, this can be done with:
def contains_consequtive_duplicates(xs):
for i in range(len(xs)-1):
if xs[i] == xs[i+1]: return True
return False
You access lists with their index and not by their value (which you are by using for i in list). Additionally, if you perform the check xs[i] == xs[i-1] this will not yield the result you want since x[-1] will check the end of the list so [3, 2, 3] will return True.
As a small demonstration:
if contains_consequtive_duplicates([1,3,3]): print "consecutive"
# Prints Consequtive
if contains_consequtive_duplicates([3, 2, 3]): print "consecutive"
# Prints nothing
Try this:
def contains_consecutive_duplicates(xs):
for i in xs:
if xs.indexOf(i)==len(xs):
break
if xs[i] == xs[i-1] or xs[i] == xs[i+1]:
return True
else:
return False
What you are doing is trying to do is evaluate xs[i+1], but that does not exist.
This should do the trick:
def contains_consecutive_duplicates(xs):
for i in range(1, len(xs) - 1):
if xs[i] == xs[i-1] or xs[i] == xs[i+1]:
return True
return False
It iterates through all values bar the first and last (created by the range function), returning (which ends the loop) if it finds a duplicate.
If it reaches the end and hasn't found a duplicate one must not exist, so it returns False.

Check if item in list

I have a function like this:
def checks(a,b):
for item in a:
if b[1] == item[1]:
return True
else:
return False
I want to check if the second value of b is in the second value of item in a such as:
checks(['5v','7y'],'6y')
>>> True
But the code I have right now will return False because I believe it's comparing '6y' with '5v'. How do I solve this?
You’re returning True at the right spot, but if the first item doesn‘t match, the function returns False immediately instead of continuing with the loop. Just move the return False to the end of the function, outside of the loop:
def checks(a,b):
for item in a:
if b[1] == item[1]:
return True
return False
True will be returned if an item is matched and False will be returned if the loop finishes without a match.
Anyways, that explains why your code wasn’t working, but use any as suggested by others to be Pythonic. =)
This can be expressed in a simpler way:
def checks(a, b):
return any(b[1] == item[1] for item in a)
You could use any() here:
def checks(a,b):
return any (b[1] == item[1] for item in a)
>>> checks(['5v','7y'],'6y')
True
>>> checks(['5v','7z'],'6y')
False
Help on any:
>>> print any.__doc__
any(iterable) -> bool
Return True if bool(x) is True for any x in the iterable.
If the iterable is empty, return False.

Categories

Resources