doing an exercise on CheckIO and I'm wondering as to why this won't work. Given a set of strings, I'm trying to return True if any of the strings are suffixes of any other string in the set. False otherwise. Using itertools I'm generating the necessary permutations in tuples first. Then for each tuple (each i), I wanted to see the hard way if the second tuple was in the end of the first tuple (option1). The otherway was using the .endwith function (option2), but neither will work for me. Why are these two options flawed?
import itertools
def checkio(words_set):
for i in itertools.permutations(words_set, 2):
#option1 ---- if i[1] in i[0][-len(i[1]):]:
#option2 ---- if i[0].endswith(i[1]):
return True
else:
return False
examples:
checkio({"hello", "lo", "he"}) == True
checkio({"hello", "la", "hellow", "cow"}) == False
I know this works as an answer. But just wondering why my original methods wouldn't take.
def checkio(words_set):
for w1 in words_set:
for w2 in words_set:
if w1.endswith(w2) and w1 != w2:
return True
return False
Your return False should be at the end of the for loop, otherwise the function will return True/False at every first comparison and will ignore all subsequent comparisons:
import itertools
def checkio(words_set):
for i in itertools.permutations(words_set, 2):
if i[0].endswith(i[1]):
return True
return False
Since it's an exercise, I won't give you the full answer, but are you sure that you really want to return False in the else clause?
Its because you return False right after the first check. and if it fails it will returns False you need to put it out of your for loop!
But as a more pythonic way you can use combinations and a generator expression within any function :
>>> from itertools import combinations
>>> s={"hello", "lo", "he"}
>>> any(i.endswith(j) or j.endswith(i) for i,j in (combinations(s,2)))
True
>>> s2={"hello", "la", "hellow", "cow"}
>>> any(i.endswith(j) or j.endswith(i) for i,j in (combinations(s2,2)))
False
Related
why does the output of these two functions give different outputs when the logic or idea is the same and they are working with the same string?
def solution(inputString):
a = ""
b = a[::-1]
if a == b:
return True
else:
return False
print(solution("az"))
def ans(something):
if something == reversed(something):
print(True)
else:
print(False)
ans('az')
This is I think because you are not using your inputString parameter in the function solution(). This may be closer to what you want:
def solution(inputString):
a = inputString
b = a[::-1]
if a == b:
return True
else:
return False
when the logic or idea is the same
No, the solution and ans functions have different logic.
solution uses the common way of reversing a string, thats fine
However, the second function uses reversed() function, which does:
reversed(seq)
Return a reverse iterator. seq must be an object which has a __reversed__() method or supports the sequence protocol ...
It does not return the reversed string as you'd probably expected.
To put that in perspective, the following code returns False:
print("oof" == reversed("foo"))
Because the return value of reversed("foo") is an <reversed object> and not the reversed String.
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
I want a function that will say if a subset is proper. So if they are identical it will return True, if they aren't then False. I have a very simple design but it doesn't account for the set's properties, which is if there are duplicates in the set it will delete them. It will also be identifical if one set is IN the other set.
Here's my code:
def proper_subset(S,T):
if S == T:
return True
else:
return False
Here's some test cases on what it does and what it SHOULD do:
#What it does
S = {1,2}
T = {1,2,3}
proper_subset(S,T)
>>> False
#What it should do
S = {1,2}
T = {1,2,3}
proper_subset(S,T)
>>> True
Please help!
In python the set entity supports addition and subtraction. So you can just check the lengths of the subtraction operations.
def properSubset(S,T):
return len(S-T)==0 and len(T-S)>0
Also as the comments mention you can just use '<'
def properSubset(S,T):
return S<T
I'm trying to compare two list-elements in python. If the two elements match exactly, true should be returned, otherwise false.
The elements look like this:
list1_element_1: ['GigabitEthernet0/6/4/1']
list2_element_1: ['GigabitEthernet0/6/4/1.100']
I tried multiple ways of comparing these two elements, including regex.
The following is the function I use to compare the elements:
def find_word(text,search):
result = re.findall('\\b'+search+'\\b', text)
if len(result)>0:
return True
else:
return False
Expected results:
find_word('GigabitEthernet0/6/4/1.100','GigabitEthernet0/6/4/1') FALSE
Actual results:
find_word('GigabitEthernet0/6/4/1.100','GigabitEthernet0/6/4/1') TRUE, because 'GigabitEthernet0/6/4/1' is existing in element 'GigabitEthernet0/6/4/1.100', I guess?
True should only be returned if both list elements are exactly the same!
Thanks!
I hate to tell you this, but you're overthinking it - you can just use the regular == operator for this:
list1_element_1: ['GigabitEthernet0/6/4/1']
list2_element_1: ['GigabitEthernet0/6/4/1.100']
list3_element_1: ['GigabitEthernet0/6/4/1']
print(list1_element_1 == list2_element_1) # False
print(list1_element_1 == list3_element_1) # True
For strings, the == operator returns True if they match exactly. For lists, it returns True if the lengths are the same and corresponding elements match exactly (the .__eq__() method is used for this comparison, if you're trying to compare custom classes - all built-in classes have their notions of equality implemented). So if you have a list of strings, you can test whether or not it's equal to another list of strings:
print(['str1', 'str2', 'str3'] == ['str1', 'str2', 'str3']) # True
print(['str1', 'str2', 'str3'] == ['str1', 'str3', 'str2']) # False
Just use:
def find_word(text, search):
return text == search
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.