Coding bat( Python > List-1 > same_first_last - python

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

Related

Linear reverse search python

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)

Loop through int array, return True if following int is equal to current

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 fix this function please?

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.

palindrome error with 8 or 9 letters

I have the following code, when going through the python, the options aaabaaaa, zzzazzazz gave me the false test.Here is the code, I am not too sure on how to fix it.
def checkPalindrome(inputString):
n=len(inputString)
#if string is one letter
if n==1:
return True
#if string has more than one letter
for i in range (0, math.floor(n/2)) :
if inputString[i]!=inputString[n-1-i]:
return False
else:
return True
You have a few issues. The main issue here is that your else clause has a return True inside the loop. What you'd want to do is finish iterating over the string before returning True. If you are familiar with boolean logic, this is the equivalent of short circuiting with AND.
The other issue (not really an issue, more a nitpick) is that you can just use integer division //, instead of having to import math's floor function.
So,
def isPalindrome(string):
for i in range(0, len(string) // 2):
if string[i] != string[-(i + 1)]:
return False
return True
Another way of handling this would be using all:
def isPalindrome(string):
return all(x == y for x, y in zip(string, reversed(string)))
Or, taking advantage of python's convenient slice notation for the most concise solution possible, we have:
def isPalindrome(string):
return string == string[::-1]
Try this which uses array slicing (reversing an array of chars)
def checkPalindrome(inputString):
n=len(inputString)
#if string is one letter
if n==1:
return True
#if string has more than one letter
return inputString==inputString[::-1]
Another approach could be using slicing. Strings can be accessed by index like arrays/lists and also be inverted like this.
def isPalindrom(string)
return string == string[::-1]
the [::-1] slicing returns the reversed string, the comparision with the original string is True if it's the same otherwise false.

Python Recursively check for repeats

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:])

Categories