I need to code a function that takes as input a list of tuples, the number of tuples, and two numbers. This function should return True if the two given numbers exist in one of the tuples in our list.
For example : ma_fonction(l,n,i,j)
l: list of tuples
i and j two numbers between 0 and n-1 and i != j
I tried this code:
def ma_fonction(l,n,i,j):
checker = False
for item in l :
if ( i in item and j in item ):
cheker = True
return True
else:
return False
ma_fonction([(0,1), (5,2), (4,3)], 6, 2, 5)
But it doesn't work. What should I add or change?
I tried this ( somehow i didnt copy all my work in my question )
This is my work:
def ma_fonction(l,n,i,j):
checker = False
if((i!=j )and (0<=i<=n-1 )and( 0<=j<=n-1) ):
for item in l :
if ( i in item and j in item ):
cheker=True
return True
else:
return False
change your function to this:
def foo(l,n,i,j):
for item in l:
if (i in item and j in item):
return True
return False
You go over all tuples, and if i and j are in the tuple, you return True.
If it went over all tuples and didn't find a match, we can be sure that we can return False.
And this implementation really doesn't need the parameter n
The logic is that for each tuple in this list, check whether it contains the number i and j. If yes, then return True; if no, continue check the next tuple. Once you finish checking every tuple, and it turns out that there is no satisfied tuple, then return False.
def ma_fonction(l,n,i,j):
for item in l :
if ( i in item and j in item ):
return True
return False
This should work:
def ma_fonction(l,n,i,j):
for item in l :
if ( i in item and j in item ):
return True
return False
The reason your solution is not working is because you are returning False at the first element of the list that doesn't match with i and j. What you need to do is return False if and only if you looked in all the elements of the list and you couldn't find a match.
Related
How to write python code that let the computer know if the list is a right sequence and the position doesn't matter, it will return true, otherwise it return false.
below are some of my example, I really don't know how to start
b=[1,2,3,4,5] #return true
b=[1,2,2,1,3] # return false
b=[2,3,1,5,4] #return true
b=[2,4,6,4,3] # return false
sort function is O(nlogn), we can use for loop which is O(n):
def check_seq(in_list):
now_ele = set()
min_ele = max_ele = in_list[0]
for i in in_list:
if i in now_ele:
return False
min_ele = min(i, min_ele)
max_ele = max(i, max_ele)
now_ele.add(i)
if max_ele-min_ele+1 == len(in_list):
return True
return False
Create a set and one to compare with -- based on minimum and maximum:
isRightSequence = set(range(min(b), max(b)+1)) == set(b)
This question is quite simple and can be solved a few ways.
The conditional approach - if there is a number that is bigger than the length of the list, it automatically cannot be a sequence because there can only be numbers from 1-n where n is the size of the list. Also, you have to check if there are any duplicates in the list as this cannot be possible either. If none of these conditions occur, it should return true
Using dictionary - go through the entire list and add it as a key to a dictionary. Afterwards, simply loop through numbers 1-n where n is the length of the list and check if they are keys in the dictionary, if one of them isn't, return false. If all of them are, return true.
Both of these are quite simply approaches and you should be able to implement them yourselves. However, this is one implementation for both.
1.
def solve(list1):
seen = {}
for i in list1:
if i > len(list1):
return False
if i in seen:
return False
seen[i] = True
return False
def solve(list1):
seen = {}
for i in list1:
seen[i] = True
for i in range (1, len(list1)+1):
if i not in seen:
return False
return True
This solution needs O(n) runtime and O(n) space
def is_consecutive(l: list[int]):
if not l:
return False
low = min(l)
high = max(l)
# Bounds Check
if high - low != len(l) - 1:
return False
# Test all indices exist
test_vec = [False] * len(l) # O(n)
for i in range(len(l)):
test_vec[l[i] - low] = True
return all(test_vec)
assert is_consecutive(range(10))
assert is_consecutive([-1, 1,0])
assert not is_consecutive([1,1])
assert not is_consecutive([1,2,4,6,5])
Given a list of ints, return True if the array contains a 3 next to a 3 somewhere.
has_33([1, 3, 3]) → True
has_33([1, 3, 1, 3]) → False
has_33([3, 1, 3]) → False
First Approch:
def has_33(nums):
for i in range(0,len(nums)):
return nums[i] == nums[i+1] ==3
Could someone explain me what's wrong with this approach, I see that this code is returning True only if all the elements in a list are true.
Second Approach:
def has_33(nums):
for i in range(0,len(nums)):
if(nums[i] == nums[i+1] ==3):
return True
The second approach satisfies my question.
What is the difference between these two approaches?
Well, the difference is rather obvious. In the first case, you inconditionnaly return the result of expression nums[i] == nums[i+1] ==3, whatever the value of this expression is. This actually means that you always return on the very first iteration, so your code could as well be written as
def has_33(nums):
if len(nums):
return nums[0] == nums[1] ==3
In the second case, you only return if the expression is true, so the iteration goes on until either you explicitely return (found a match) or the iteration naturally terminates and you've found nothing (in which case the function will implicitely return None).
Unrelated, but your code (second version) can be improved in quite a few ways. First point: Python "for" loop are of the "foreach" kind - you iterate on the sequence elements, not indices. If you don't need the indice, the proper way is
for item in iterable:
do_something_with(item)
no need for range(len(xxx)) and indexed access here.
If you do need both the item and the index, then enumerate() is your friend - it yields (index, item) tuples:
for index, item in enumerate(sequence):
print("item at {} is {}".format(index, item))
Now for your current need - geting (item, nextitem) pairs -, there's still another solution: zip(seq1, seq2) + slicing:
for item, nextitem in zip(sequence, sequence[1:]):
print("item: {} - nextitem : {}".format(item, nextitem))
and finally, if what you want is to check if at least one item in a sequence satisfies a condition, you can use any() with a predicate:
def has_33(nums):
return any((item == nextitem == 3) for item, nextitem in zip(nums, nums[1:]))
Another solution could be to turn nums into a string and look for the literal string "33" in it:
def has_33(nums):
return "33" in "".join(str(x) for x in nums)
but I'm not sure this will be more efficient (you can use timeit to find out by yourself).
In your first approach, you will return the value of
return nums[i] == nums[i+1] == 3 #Where i = 0 since it returns
first iteration.
return nums[0]==nums[1] == 3 #If nums = [0,3,3]
return false # would be your result. But it would never check the next pair of values.
In your second approach, you will return the value
return true #If the if-statement is satisfied
The return function, will end the function call when called. Therefore, if being called in a for-loop without an if-statement, it will be called for the first iteration. If there is an if-statement and the iteration passes through the if-statement, it will return and end the loop at that iteration. Basically, the return function ends the function call and returns the value given.
how to check if this list is empty?
l = ['',['']]
I tried solutions from how to find if nested lists are empty. but none of them worked.
def isListEmpty(inList):
if isinstance(inList, list): # Is a list
return all( map(isListEmpty, inList) )
return False # Not a list
You should check if the list is falsy/empty first before recursively checking the list items. You can also avoid explicitly returning True or False by using the and and or operators:
def isListEmpty(inList):
return inList == '' or isinstance(inList, list) and (not inList or all(map(isListEmpty, inList)))
Demo: https://repl.it/repls/AccurateSmallOutcome
For lists that actually are empty, the function should simply return True.
def isListEmpty(inList):
if isinstance(inList, list): # Is a list
if len(inList) == 0:
return True
else:
return all(map(isListEmpty, inList))
return False # Not a list
l is not empty in fact. But in this case this code should work:
l = ['',['']]
def isListEmpty(inList):
for char in inList:
if char == '' or ['']:
return True
else:
return False
break
print(isListEmpty(l))
You can use a simple recursive approach with any. Using any would make sure that the recursively search ends as soon as a non empty item is found
>>> def is_non_empty_list (l):
... return any(is_non_empty_list(e) if isinstance(e, list) else e for e in l)
...
>>> def is_empty_list (l):
... return not is_non_empty_list(l)
...
>>> is_empty_list(['', ['']])
True
>>> is_empty_list(['', ['a']])
False
>>>
Try This
l = [' ',[ ]]
def isListEmpty(thisList):
for el in thisList:
if (len(el)==0 and type(el)==list):
print('empty') # Or whatever you want to do if you encounter an empty list
isListEmpty(l)
If you face any problems comment below
I am trying to make a function that is able to find a element in a nested list.
That is what if got so far:
def in_list(ele, lst, place):
if ele == lst[place]:
return True
else:
for i in range(len(lst)):
in_list(ele, lst[i], place)
This is what i input:
a=[[1,2],[3,4]]
if in_list(2,a,1)==True:
print("True")
the variable "place" is the place in the list where the element should be found...
Now somehow it doesn't understand this line if ele == lst[place]
this is the error message: TypeError: 'int' object is not subscriptable
Thanks in advance
There are two issues in the last line
def in_list(ele, lst, place):
if ele == lst[place]:
return True
else:
for i in range(len(lst)):
in_list(ele, lst[i], place)
lst[i] is an integer (assuming lst is a list of integers), which is why you get your error.
The other issue is that you're not returning anything from the else branch.
Something like this might work better in case of arbitrary, but uniform, nesting:
def recursive_contains(item, lst):
if len(lst) == 0:
return False
elif isinstance(lst[0], collections.Iterable):
return any(recursive_contains(item, sublist) for sublist in lst)
else:
return item in lst
for arbitrary non-uniform nesting, perhaps something like this:
def recursive_contains(item, lst):
if not isinstance(lst, collections.Iterable):
return item == lst
for val in lst:
if item == val:
return True
elif isinstance(val, collections.Iterable):
if recursive_contains(item, val):
return True
return False
of course if you only have 2 levels (all elements of lst are lists of int), you could simply say:
if ele in sum(lst, []):
...
which uses sum to flatten the list first.
The other answers well define the mistake in your code.
Just to reiterate that you were assuming each element in the list as a nested list and subscripting it like - elem[place].
You can't subscript a primitive type such as integer and hence the error.
Refer the below code to handle nesting.
Note - You Don't require the 3rd parameter of place, more appropriately you wouldn't the place if you are searching.*
def fetch(data, l):
for element in l:
if type(element) == list:
if fetch(data, element):
return True
else:
if element == data:
return True
return False
On further thought you are looking for an element that should be only at "place" index of any of the nested lists.
Refer to the snippet below for that-
def fetch(data, l,place):
if data == l[place]:
return True
else:
for element in l:
if type(element) == list and fetch(data,element,place):
return True
return False
Note- Only call fetch again if the element is a list.
a = [[1, 2], [3, 4]]
def inlist(e, l, p):
for lists in range(len(l)):
print("array:", l[lists])
print("Looking for", e)
print("In position", p)
print(l[lists][p])
if l[lists][p] == e:
print(True, ": The element ", e, " is in the list n.", lists, " at the place ", p)
return True
inlist(2, a, 1)
Output
array: [1, 2]
Looking for 2
In position 1
2
True : The element 2 is in the list n. 0 at the place 1
I'm working with this exercise:
Write a function is_member() that takes a value (i.e. a number, string, etc) x and a list of values a, and returns True if x is a member of a, False otherwise. (Note that this is exactly what the in operator does, but for the sake of the exercise you should pretend Python did not have this operator.)
I wrote this function:
def isMember(value, list):
for element in list:
if(element == value):
return True
else:
return False
myList = ["a","b","c",1,2,3]
print(isMember("a",myList)) #Returns True; correct
print(isMember(3,myList)) #Returns False; why the heck?
You need to take the return False out of the loop:
def isMember(value, list):
for element in list:
if(element == value):
return True
return False
The way you have it currently, isMember will return False if the value is not the first item in the list. Also, you should change the name of your list variable to something other than list, which is a built-in function in Python.
The problem is that your return False is within the loop, directly as the else case of your membership test. So as you loop through the list, you get to the first element and check if it is in the list or not. If it is in the list, you return true—that’s fine. If it’s not in the list, you return false, aborting the loop process and ending the function. So you never look at the other values inside the loop.
So to fix this, move the return False outside of the loop, at the end of the function. That way, only when all elements have been looked at, you return false.
def isMember (value, list):
for element in list:
if element == value:
return True
return False
Another way would be to simplify this using the any function to perform the check for every element in the list. any takes an iterable and looks at the values. As soon as it finds a true value, it returns true. Otherwise it keeps iterating until it finds a false value or hits the end of the iterator, both cases yielding a false. So you could rewrite it like this:
def isMember (value, list):
return any(value == element for element in list)