Finding an item not in list : Python - python-3.x

What happens when you search for 35 in the list [10,20,30,40,50]?
To simplify this i'll just post the options,
1.The program would handle the case by printing a suitable message that the element is not found
2.The value 30 is returned as it is the closest number less than 35 that is present in the list
3.The value 40 is returned as it is the closest number greater than 35 that is present in the list
4.The program will abruptly come to an end without intimating anything to the user.

Alright, so this statement will return False.
35 in [10,20,30,40,50]
What you can then do is expand on this however you want, if you want it to print whether or not it is in the list as such:
if 35 in [10,20,30,40,50]:
print("Element found in list")
else:
print("Element not found in list")
In python, when you search for an item in a list in this way, it will return a Boolean (True or False), it will not return anything else unless you want it to by programming it to do so.
If you do want to implement something like finding the closest item in a list to your search query, you could do it like this (Stolen from https://stackoverflow.com/a/12141207/8593865):
def findClosest(myNumber, myList):
return min(myList, key=lambda x:abs(x-myNumber))
If you just want to do something if an item is not in a list:
if 35 not in [10,20,30,40,50]:
#Do something

Related

Removing multiple elements from a list

In this program I have entered the elements of a list and have to find the second highest element,to achieve that I have created a separate list with the same values of original list,removed the highest element,sort in descending order and print the first element. However,the highest element is 95 and occurs twice in the list but by using the following code, only one 95 gets removed from the list
marks_list2 = marks_list
high = float(max(marks_list))
for j in marks_list:
if j==high:
marks_list2.remove(j)
marks_list2.sort(reverse=True)
print('The second highest element is:',marks_list2[0])
Can anyone help me rectify the code and also tell me where I went wrong with my logic. Thanks in advance!
The python built in set() method removes all the repetitions.
marks_list = set(marks_list)
marks_list.remove(max(marks_list))
print('The second highest element is: %s' % max(marks_list))

Defining a function to find the unique palindromes in a given string

I'm kinda new to python.I'm trying to define a function when asked would give an output of only unique words which are palindromes in a string.
I used casefold() to make it case-insensitive and set() to print only uniques.
Here's my code:
def uniquePalindromes(string):
x=string.split()
for i in x:
k=[]
rev= ''.join(reversed(i))
if i.casefold() == rev.casefold():
k.append(i.casefold())
print(set(k))
else:
return
I've tried to run this line
print( uniquePalindromes('Hanah asked Sarah but Sarah refused') )
The expected output should be ['hanah','sarah'] but its returning only {'hanah'} as the output. Please help.
Your logic is sound, and your function is mostly doing what you want it to. Part of the issue is how you're returning things - all you're doing is printing the set of each individual word. For example, when I take your existing code and do this:
>>> print(uniquePalindromes('Hannah Hannah Alomomola Girafarig Yes Nah, Chansey Goldeen Need log'))
{'hannah'}
{'alomomola'}
{'girafarig'}
None
hannah, alomomola, and girafarig are the palindromes I would expect to see, but they're not given in the format I expect. For one, they're being printed, instead of returned, and for two, that's happening one-by-one.
And the function is returning None, and you're trying to print that. This is not what we want.
Here's a fixed version of your function:
def uniquePalindromes(string):
x=string.split()
k = [] # note how we put it *outside* the loop, so it persists across each iteration without being reset
for i in x:
rev= ''.join(reversed(i))
if i.casefold() == rev.casefold():
k.append(i.casefold())
# the print statement isn't what we want
# no need for an else statement - the loop will continue anyway
# now, once all elements have been visited, return the set of unique elements from k
return set(k)
now it returns roughly what you'd expect - a single set with multiple words, instead of printing multiple sets with one word each. Then, we can print that set.
>>> print(uniquePalindromes("Hannah asked Sarah but Sarah refused"))
{'hannah'}
>>> print(uniquePalindromes("Hannah and her friend Anna caught a Girafarig and named it hannaH"))
{'anna', 'hannah', 'girafarig', 'a'}
they are not gonna like me on here if I give you some tips. But try to divide the amount of characters (that aren't whitespace) into 2. If the amount on each side is not equivalent then you must be dealing with an odd amount of letters. That means that you should be able to traverse the palindrome going downwards from the middle and upwards from the middle, comparing those letters together and using the middle point as a "jump off" point. Hope this helps

How do i fix the 'element not found' in binary search?

I have been trying to implement this code whose work is to find a particular element using Binary search.Now the code works fine if element is present in the list but it is unable to display the intended block if the search element is not present.I have assumed that the list is sorted in ascending order.Help on this would be appreciated
I have tried giving an else part with the while: but it doesn't help.Its unable to show the error for element not found
def binarysearch(l,item):
low=0
u=len(l)-1
while low<=u:
mid=int((low+u)/2)
if item==l[mid]:
return mid
elif item<l[mid]:
high=mid-1
else:
low=mid+1
l=eval(input("Enter the list of elements"))
item=int(input("Enter search item:"))
index=binarysearch(l,item)
if index>=0:
print(item,"found at index",index)
else:
print("Element not found") #i am unable to reach this part
If input is:
Enter the list of elements[8,12,19,23]
Enter search item:10
I expect the result to be "Element not found" .but the program does nothing in this situation
I will give you a tip and later on I will test better this code and try to explain why it is happening.
The tip is to use in to check if the items exist in a list or not. In is more performatic than use a loop.
Exemplo working:
def binarysearch(elem, item):
if item in elem:
return elem.index(item)
else:
return -1 # because your if verifying if the return is equal or greater than 0.
Update 1
When I tried to run your code I got in one infinite loop, it's happening because of the expression mid=int((low+u)/2) - I couldn't understand why you did it. If we run this code happens this:
list [8,12,19,23] and Item 10
u=len(l)-1 u = 3 because 4 - 1
Get in the while because the condition is True
mid=int((low+u)/2) here mid will be (0+3)/2 as you force it to be int the result will be 1
if item==l[mid]: 10 == 12 -- l[mid] - l[1] - False
elif item<l[mid]: 10<12 True
high=mid-1 high will be 1 - 1 = 0
You go to the next iteration starting on the number 3, and that is why you get in an infinite loop
To go through all positions in a list, you could use the low that starts in 0 and increase if the item is not == the value in that position. So you could use the while but in that way:
def binarysearch(l,item):
low=0
u=len(l)-1
while low<=u:
if item==l[low]:
return low
else:
low+=1
return -1
l=eval(input("Enter the list of elements"))
item=int(input("Enter search item:"))
index=binarysearch(l,item)
if index>=0:
print(item,"found at index",index)
else:
print("Element not found")
To debug your code you can use [1]: https://docs.python.org/3/library/pdb.html

Entering a word and then searching through and array of words to find the word

I am trying to create a program which checks to see if words entered (when run) are in an array. I would like to use a loop for this.
I have created a list of words and tried a for loop however the code is proving to be erroneous.
def Mylist():
Mylist= [Toyota,BMW,Pontiac,Cadillac,Ford,Opel]
Search=input("Enter a word")
Mylist[1]="Toyota"
for loop in range (1,6):
if Mylist[loop]==Search:
print("found")
break
I have repeated line 4 for the other car manufacturers.
TypeError: 'function' object does not support item assignment
First, here some recommendations to start:
Indentation in Python is IMPORTANT, be careful to have the right indentation. You must take special care when posting code here in SO so your code does not look like complete gibberish.
You should read Naming conventions. TL;DR we use snake_case for naming functions and variables.
If you are not using an IDE (such as PyCharm) to program, or something intelligent that shows the information on functions, you should always check out the documentation (it is beautiful).
Check out the difference between "Toyota" and Toyota. The first one has quotes, it is a string (i.e. chain of characters), it is a primitive type such as integer and boolean; the second is a token that is to be evaluated, it has to be defined before, such as variables, functions and classes.
Search in the docs if there is an in-built function that already does the job you want.
Check out return values in functions. Functions evaluate to None when you do not explicit a return value.
Now to your question. As some people pointed out, there is the in keyword that does exactly what you want.
CAR_BRANDS= ["Toyota", "BMW", "Pontiac", "Cadillac", "Ford","Opel"]
def check_car():
word = input("Enter a word: ")
if word in CAR_BRANDS:
print("found")
return True
print("not found")
return False
If you don't care about the print you can just do return word in CAR_BRANDS
If you actually want to challenge yourself to write the logic, you were right in choosing a for-loop to iterate over the list.
Index in Python starts from 0, and that range does not give you all the indexes to iterate over your list, you are missing the 0 index. Also, we don't like magic numbers, instead of hard-coding the length of your list of car brands, better compute the length!
for i in range(len(CAR_BRANDS)):
if CAR_BRANDS[i] == word:
print("found")
But even better you can directly iterate over the items in your list, no need to do the range, which will give you something like:
CAR_BRANDS= ["Toyota", "BMW", "Pontiac", "Cadillac", "Ford","Opel"]
def check_car():
word = input("Enter a word: ")
for brand in CAR_BRANDS:
if brand == word:
print("found")
return True
print("not found")
return False
If you have any more questions, do not hesitate! Happy coding.

Creating a function that creates two lists in Python 3

I am trying to create a function, getStocks, that gets from the user two lists, one containing the list of stock names and the second containing the list of stock prices. This should be done in a loop such that it keeps on getting a stock name and price until the user enters the string 'done' as a stock name. The function should return both lists. My main issues are figuring out what my parameters are, how to continuously take in the name and price, and what type of loop I should be using. I am very new to programming so any help would be appreciated. I believe I'm close but I am unsure where my errors are.
def getStocks(name,price):
stockNames = []
stockPrices = []
i = 0
name = str(input("What is the name of the stock?"))
price = int(input("what is the price of that stock?"))
while i < len(stockNames):
stockNames.append(name)
stockPrices.append(price)
i += 1
else:
if name = done
return stockNames
return stockPrices
Your question is a bit unclear but some things off the bat, you cant have two return lines, once you hit the first, it leaves the function. Instead you'do write something like
return (stockNames, stockPrices)
Secondly while loops dont have an else, so you'd actually set up your while loop, then setup an if statement at the beginning to check if the string is 'done', then act accordingly. Break will get you out of your last while loop, even though it looks like it's associated with the if. So something like this:
while i < len(stockNames):
if name.upper() == 'DONE':
break
else:
stockNames.append(name)
stockPrices.append(price)
i += 1
Also you have to use == (comparison) instead of = (assignment) when you check your name = done. And dont forget done is a string, so it needs to be in quotations, and I used .upper() to make the input all caps to cover if its lower case or uppercase.
If you can clear up your question a little bit, I can update this answer to include everything put together. I'm not quite understanding why you want to input a list and then also take user input, unless you're appending to that list, at which point you'd want to put the whole thing in a while loop maybe.
Update:
Based on your comment, you could do something like this and enclose the whole thing in a while loop. This takes the incoming two lists (assuming you made a master list somewhere) and sends them both into the getStocks function, where someone can keep appending to the pre-existing list, and then when they type done or DONE or DoNe (doesn't matter since you use .upper() to make the input capitalized) you break out of your while loop and return the updated lists:
def getStocks(name, price):
stockNames = name
stockPrices = price
while 1:
inputName = str(input("What is the name of the stock?"))
inputPrice = int(input("what is the price of that stock?"))
if name.upper() != 'DONE':
stockNames.append(inputName)
stockPrices.append(inputPrice)
else:
break
return (stockNames, stockPrices)
But really, depending on the rest of the structure, you might want to make a dictionary instead of having 2 separate lists, that way everything stays in key:value pairs, so instead of having to check index 0 on both and hoping they didn't get shifted by some rogue function, you'd have the key:value pair of "stock_x":48 always together.

Resources