Program ignores all the numbers after the 1st one - python-3.x

Why the program takes just the first number in the list and ignores others, making an empty list.
This happens in every function with for loop.
cars=[23.11,1531,'volvo','BMW']
def price(CAR):
num=[]
strings=[]
for i in CAR:
if isinstance(i,float)or isinstance(i,int):
num.append(i)
elif isinstance(i,str):
strings.append(i)
else:
pass
return num,strings
print(price(cars))
([23.11], [])

The only reason I can think of is, your return statement is aligned with your for loop, so it exists after the first iteration. (Though it looks aligned correctly right now, maybe the editor corrected it instinctively.)

Related

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

I'm not getting expected result , I want to know what's wrong with the code

I want to know whether I can use Input function under for loops and Lists?
I'm using the latest version of python 3.7.4.
List=['apple','Pomegranate','orange']
K=print(input('Enter the Value:'))
if (K in List):
print("yes it's in the list")
else:
print("It's not in the list")
If I entered apple I'm getting the result as it's not on the list. I want to know whether we can use Input function under for loops and lists with if-else conditions.
Your issue is with the line
K=print(input('Enter the Value:'))
You do not need print here. Print is a function that takes a value, prints it to your screen and returns None. You passed the input to print, but you want to store the value in K, not print it to the screen (the user is entering the value so they probably do not need to see it again). So change this to:
K=input('Enter the Value:')
Here you can check your error with print function.
List=['apple','Pomegranate','orange']
K=print(input('Enter the Value:'))
print(K)
.....
K is None in this case.

Improve execution time of code so that it does not time out

I have a piece of code that works is some of case ,but some case this take more time and give time out issue.can someone please help to improve this?
[Edit]:let me explain the how it is working
function accepts a list as input
function returns a list as output as follows:
1.The smallest number of list should be in middle
2.Next smallest number should be append at the end of list
3.Next smallest number should be appended at the start of list
4.Next smallest number should be append at the end of list
5.Next smallest number should be appended at the start of list
4.it continues ......unless we scan all input list
def pendulum(values):
result=[]
while(len(values)):
min_num=min(values)
result.insert(0,min_num)
values.remove(min_num)
if len(values)>0:
min_num=min(values)
result.insert(len(result),min_num)
values.remove(min_num)
return result
The biggest problem is that your code searches for the minimum once per element. Pre-sorting the list will make it much faster. You are also inserting at the front of the list, which forces every element of the list to be moved, for every other element. To combat this, I just use append, and then reverse the front half of the list.
def pendulum(values):
front = []
back = []
next_goes_to_front = True
for value in sorted(values):
if next_goes_to_front:
front.append(value)
else:
back.append(value)
next_goes_to_front = not next_goes_to_front
return list(reversed(front)) + back

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