How can I rewrite the function below to search from the end of the list?
def search(list,n):
for i in range(len(list)):
if list[i] == n:
return True
return False
You could iterate backwards through the list. For that you need to specify your range with three parameters. The first would be the starting point, the second the endpoint, and the third would be the increment. That's better than reversing it in runtime matters. Try this:
def search(list, n):
for i in range(len(list)-1, 0, -1):
print(list)
if list[i]=n:
return True
return False
Use list.reverse() to reverse your list so that you are starting from the end:
list= [1,2,3,4,5,6,7,8,9]
n=(3)
list.reverse()
def search(list,n):
for i in reversed(range(len(list))):
print(list)
if list[i] == n:
return True
return False
search(list,n)
Related
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.
The function is given a list and must return True if the 1st and last digit of the list are same.
def same_first_last(nums):
if nums[0] == nums[len(nums) - 1]:
return True
else:
return False
The function returns " index value out of range". Please help
The question is what to do with the case where you give an empty list. It depends on how you see it: if you see an empty list as a number with no digits, you can argue that the first and last digit are the same. In that case you can write:
def same_first_last(nums):
return not nums or nums[0] == nums[-1]
If you consider an empty list not to have the same first and last digit, you can use:
def same_first_last(nums):
return bool(nums) and nums[0] == nums[-1]
you can modify:
if nums[0] == nums[-1]:
return True
return False
but I think the error " index value out of range" ,may the nums post in this function may empty list
First, check whether the list is empty or not. Assuming the list is not empty. The method looks like as below.
def same_first_last(nums)
return True if a[0]==a[-1] else False
nums[-1] is the shortcut to get the last element from a list. The nums[-n] syntax gets the nth-to-last element. Example:
nums = [1,2,3,1,3]
nums[-2] #returns 1
nums[-3] #returns 3
I'm a programming semi-noob and am working through Torbjoern Lager's 46 Simple Python Exercises. This is number 10: Define a function overlapping() that takes two lists and returns True if they have at least one member in common, False otherwise. You may use your is_member() function, or the in operator, but for the sake of the exercise, you should (also) write it using two nested for-loops.
def over(list1,list2):
for i in list1:
for j in list2:
return i==j
I thought I had a nice, simple solution, but it can't recognize that the lists overlap, unless the overlapping elements are the first ones.
over(["a","b","c","d"],["e","f","a","h"])
returns False
over(["a","b","c","d"],["a","f","g","h"])
returns True
For some reason, it's not searching through all of the combinations. Any help would be appreciated.
It's not searching through all the combinations because you're returning on the first iteration of the nested loop. You could do this:
def over(list1,list2):
for i in list1:
for j in list2:
if i == j:
return True
return False
This returns True as soon as any overlap is found. If no overlap is ever found, it'll get to the last line and return False.
The problem is that you return i==j on the first iteration. Your function will justs compare list1[0] and list2[0]. The solution is to add if.
Here is an example:
def over(list1,list2):
for i in list1:
for j in list2:
if i == j:
return True
return False
You should be testing with an if as suggested in the other answers as you are returning after the very first iteration but using any would be a nicer approach:
def over(list1,list2):
return any(i ==j for i in list1 for j in list2)
Which is equivalent to:
def over(list1,list2):
for i in list1:
for j in list2:
if i == j:
return True
return False
short circuiting on a match and returning True if there is any match or returning False if there are none.
Or using sets for larger input would be the fastest approach:
def over(list1, list2):
return not set(list1).isdisjoint(list2)
if not set(list1).isdisjoint(list2) is True we have at least one common element.
When you execute the "return" stament de execution stops there, like it happens in Java. It returns true because you have 'a' in the first position in both arrays.
You can try this:
result = False;
for i in list1:
for j in list2:
if i == j:
result=True;
return result
If you want it more efficient:
for i in list1:
for j in list2:
if i == j:
return True;
return False;
I have an assignment I've been stuck on for a couple days now. I have to recursively figure out if a list has repeats but I cannot use any loops or built in functions besides len(). I'm also not allowed to use the 'in' function. Returns True if list L has repeats, False otherwise. This is what I've been able to figure out:
def has_repeats(L):
if len(L) <= 1:
return False
elif L[0] == L[1]:
return True
else: return has_repeats(L[0] + L[2:])
But the problem with that is it's only comparing the first element to the rest, instead of each element to the rest. I can't figure out how to do that without a running counter or something. Any suggestions?
You almost have it. Along with checking the first element with the rest of the list, you also need to check the second the same way:
def has_repeats(L):
if len(L) <= 1:
return False
if L[0] == L[1]:
return True
if has_repeats([L[0]] + L[2:]):
return True
if has_repeats(L[1:]):
return True
return False
You can also compact this into the following representation:
def has_repeats(L):
return len(L)>1 and L[0]==L[1] or has_repeats([L[0]]+L[2:]) or has_repeats(L[1:])
Use a helper function:
def helper(ele, rest):
if not rest:
return False
return ele == rest[0] or helper(ele, l[1:])
def has_repeats(l):
if not l:
return False
return helper(l[0], l[1:]) or has_repeats(l[1:])
I'm trying to define a method to check whether or not every element of a list is a factor of the parameter.
Here's what I have:
def factorall(x):
if all(x % num for num in nums) == 0:
return True
else:
return False
(In this case nums is a list of the integers from 1 to 10)
However, this returns true for any number. I'm assuming this happens because it is only checking 1 and then returning True, but shouldn't all() be checking for every element of the list before returning True?
I'm a bit unfamiliar with all() so I probably implemented it incorrectly. Can someone point me in the right direction?
Thanks!
you should use not any instead of all
def factorall(x):
return not any(x%num for num in nums) #if any of these is a value other than 0
or if you want it like you currently have it
def factorall(x):
return all(x%num==0 for num in nums)
You should do the comparison inside the all function, or simply remove it, and use negation of the result x % num:
def factorall(x):
return all(not x % num for num in nums)
The return statement works same as:
return all(x % num == 0 for num in nums)
I agree that the 2nd one seems clearer.
def factorall(x):
if all(x % num == 0 for num in nums):
return True
else:
return False