I'm looking for a "for loop" that finds the length of each item and choose the largest number.
>>>T=[chicken, soda, candy]
>>>Highest = 0
>>>"for loop goes here"
>>>print (highest)
7
You need quotes around your strings (e.g. "chicken"), and the case of variables matters so Highest and highest are different. Also use round parentheses () for a tuple and square [] for a list.
A simple way to do this in Python is be to use max() to find the longest string, and len() to find the lengths, with the for keyword creating a generator expression:
T=("chicken", "soda", "candy")
Highest = max(len(x) for x in T)
print(Highest)
Slightly older versions of Python would use a list comprehension:
Highest = max([len(x) for x in T])
erip's answer showed how to use a for loop instead.
T is not a tuple, but a list. You can find out by doing print(type(T)). Try to read up on lists and Python programming in general, there are quite a few good resources available. If you want T to be a Tuple, simply change the brackets [] to regular () parenthesis like this T = ("chicken", "soda", "candy"), looping through it works the same way as mentioned below, so no need to change any of that.
The elements in your list T needs to be some kind of type or variable. What you are looking for is probably a String. To create the words as the String type, put it in double quotes like this "chicken".
Heres what I suspect that you are looking for:
T = ["chicken", "soda" ,"candy"]
Highest = 0
for word in T:
lengthOfWord = len(word)
if lengthOfWord > Highest:
Highest = lengthOfWord
print(Highest)
You can also check out a live version here.
You can create list of lengths with the following:
[len(i) for i in T]
You can then call max on an iterable, which will return the maximum element.
Putting this together you have:
print(max([len(i) for i in T]))
If you want a for-loop explicitly, you can use this:
max_length = 0
for i in T:
max_length = max(len(i), max_length))
print(max_length)
Note these both work for lists and tuples.
The question is not clear.
But I hope this will help you.
T = ('chicken', 'soda', 'candy')
Highest = 0
for i in range(0, len(T)):
if len(T[i]) > int(Highest):
Highest = len(T[i])
print ("Highest is %d" % Highest)
Related
I have this exercise that I fail to understand
Suppose we are given a list X of integers. We need to construct a sequence of indices (positions) of the elements in this list equal to the maximal element. The indicies in the sequence are in the ascending order.
Hint use the enumerator function
from typing import Iterator
X = [1,10,3,4,10,5]
S : Iterator[int] = YOUR_EXPRESSION
assert list(S)==[1,4]
This is the only thing I could come up with, but for sure it does not return [1,4]
If you wondering what I don't understand, it is not clear from reading the description how it could return [1,4].
Maybe you want to try to explain that to me first...
This is my (wrong) solution
my_enumerate=enumerate (X)
my_enumerate=(list(my_enumerate))
my_enumerate.sort(reverse=True)
So you have the list X containing [1,10,3,4,10,5]. The maximal, or largest, element is 10. Which means we should return a list of all the indices where we find 10. There are two 10s at index 1 and 4 respectively.
Using enumerate you get at each iteration the index and element. You can use that to filter out the elements you don't need. List comprehensions are useful in this case, allowing for filtering with the if syntax i.e. [val for val in items if some_condition]
you can use a generator like this
max_val=max(X)
s = (i for i, v in enumerate(X) if v==max_val)
This is my solution
( x[0] for x in enumerate (X) if x[1] == max(X) )
this is the book solution
(i for (i, n) in enumerate(X) if n == max(X))
This requires two steps:
Determine the maximum value with max
Iterate the indices of your list and retain those that have this maximum value
To avoid a bad time complexity, it is necessary to not repeat the first step:
S : Iterator[int] = (lambda mx:
(i for i, x in enumerate(X) if x == mx)
)(max(X))
The reason for presenting the code in such ugly expression, is that in the question it seems a requirement to follow the template, and only alter the part that is marked with "YOUR_EXPRESSION".
This is not how you would write it without such artificial constraints. You would just do mx = max(X) and then assign the iterator to S in the next statement without the need for this inline lambda.
I would like print a result without duplicate with my multiplication
Here an example :
5*3*2=30
2*3*5=30
5*2*3=30
3*2*5=30
.....
All these element are from my list that I browse and you can see it's always =30
So I would like display only the first element (5*3*2) and not others because they are the same.
To be more accurate, here an example what I have :
list = ['5*3*2','5*2*3','2*3*5','2*5*3']
for i in list:
if eval(i) == eval(i)+1 ??? (I dont know how to say the next element)
print(eval(i))
Thanks for reading
Something like this with not in will help you.
#python 3.5.2
list = ['5*3*2','5*2*3','6*9','2*3*5','2*5*3','8*3','9*6']
elm = []
for i in list:
elm_value = eval(i)
if elm_value not in elm:
elm.append(elm_value)
print(elm)
DEMO: https://rextester.com/QKV22875
The comparison:
eval(i) == eval(i)+1
Will compare if the the number i is equal to i + 1, which will always return False. I'm sure you mean to use i as an index and simply wanted to compare if the current element is equal to the next element in the list. However, doing this doesn't really keep track of duplicates, since you have to consider everything else in the list.
Its also not a good idea to use list as a variable name, since it shadows the builtin function list. Plenty of other suitable names you can use.
One way is to use a set to keep track of what items you have seen, and only print items that you have seen for the first time:
lst = ["5*3*2","5*2*3","2*3*5","2*5*3"]
seen = set()
for exp in lst:
calc = eval(exp)
if calc not in seen:
print(calc)
seen.add(calc)
If you are always dealing with simple multiplying expressions with the * operator(no brackets), you could also use functools.reduce and operator.mul instead to multiply the numbers instead of eval here. This will first split the numbers by *, map each number string to an integer, then multiply every element with each other.
from operator import mul
from functools import reduce
lst = ["5*3*2","5*2*3","2*3*5","2*5*3"]
seen = set()
for exp in lst:
numbers = map(int, exp.split("*"))
calc = reduce(mul, numbers)
if calc not in seen:
print(calc)
seen.add(calc)
Output:
30
With the following list:
l = ['5*3*2','5*2*3','2*3*5','2*5*3', '2*2']
(Note that list is already something in python so I wouldn't recommend using that as a variable name)
I would first create a list of unique values:
unique_vals = set(map(eval, list))
set([4, 30])
Then for each unique values get the first match in l:
[next(x for x in l if eval(x) == i) for i in unique_vals]
I get:
['2*2', '5*3*2']
Is that what you want?
I am building a function to extract all negatives from a list called xs and I need it to add those extracted numbers into another list called new_home. I have come up with a code that I believe should work, however; it is only showing an empty list.
Example input/output:
xs=[1,2,3,4,0,-1,-2,-3,-4] ---> new_home=[1,2,3,4,0]
Here is my code that returns an empty list:
def extract_negatives(xs):
new_home=[]
for num in range(len(xs)):
if num <0:
new_home= new_home+ xs.pop(num)
return
return new_home
Why not use
[v for v in xs if v >= 0]
def extract_negatives(xs):
new_home=[]
for num in range(len(xs)):
if xs[num] < 0:
new_home.append(xs[num])
return new_home
for your code
But the Chuancong Gao solution is better:
def extract_negative(xs):
return [v for v in xs if v >= 0]
helper function filter could also help. Your function actually is
new_home = filter(lambda x: x>=0, xs)
Inside the loop of your code, the num variable doesn't really store the value of the list as you expect. The loop just iterates for len(xs) times and passes the current iteration number to num variable.
To access the list elements using loop, you should construct loop in a different fashion like this:
for element in list_name:
print element #prints all element.
To achieve your goal, you should do something like this:
another_list=[]
for element in list_name:
if(element<0): #only works for elements less than zero
another_list.append(element) #appends all negative element to another_list
Fortunately (or unfortunately, depending on how you look at it) you aren't examining the numbers in the list (xs[num]), you are examining the indexes (num). This in turn is because as a Python beginner you probably nobody haven't yet learned that there are typically easier ways to iterate over lists in Python.
This is a good (or bad, depending on how you look at it) thing, because had your code taken that branch you would have seen an exception occurring when you attempted to add a number to a list - though I agree the way you attempt it seems natural in English. Lists have an append method to put new elements o the end, and + is reserved for adding two lists together.
Fortunately ignorance is curable. I've recast your code a bit to show you how you might have written it:
def extract_negatives(xs):
out_list = []
for elmt in xs:
if elmt < 0:
out_list.append(elmt)
return out_list
As #ChuangongGoa suggests with his rather terse but correct answer, a list comprehension such as he uses is a much better way to perform simple operations of this type.
I'm trying to find the longest word in Python but I'm getting the wrong result. The code below was done in interactive mode. I should've received 'merchandise' (10 characters) as the longest word/string but I got 'welcome' (7 characters) instead.
str = 'welcome to the merchandise store' #string of words
longest = [] #empty list
longest = str.split() #put strings into list
max(longest) #find the longest string
'welcome' #Should've been 'merchandise?'
It's sorting the strings alphabetically not by length, what you need is:
max(longest, key=len)
Let me clarify a little bit further. In Python the default comparison for strings is alphabetical. This means "aa" will be less than "abc" for all intents and purposes (cmp in python2 and < in python2/3). If you call max on the list without a key then it will compare using the default comparison. If you put in a key function then it will compare the key instead of the value. Another options (python2 only) is the cmp argument to max, which takes a function like cmp. I don't suggest this method because it's going to end up being something like cmp=lambda x,y: len(x)-len(y) which seems much less readable then just key=len and isn't supported in python3.
If you have any more questions about using key, I'd suggest reading this specifically note (7) which covers cmp and key for list.sort which uses them in the same manner.
You can also so do this:
str = 'welcome to the merchandise store'
sorted(str.split(), key=len)[-1]
Split it, sort them by length, then take the longest (last one).
Change your str.split() to str.split(" ")
Then,
max = []
for x in str.split(" "):
if len(x) > len(max[0]):
max = []
max.append(x)
elif len(x) == len(max[0]):
max.append(x)
This is one way to do it without the lambda or key=len just using a for loop and list comprehension:
str = 'welcome to the merchandise store'
longest = []
longest = str.split()
lst = []
for i in longest:
x = len(i)
lst.append(x)
y = [a for a in longest if max(lst)== len(a)]
print y[0]
Output:
merchandise
This is in Python 2, in Python 3 print (y[0])
I have to alphabetically sort a text file where each new word is on a new line. I currently have the whitespace stripped and my program prints the first letter attaching it to a integer with the ord function. I cannot use sort and I know I have to put it into a list just not sure how. This is what i wrote for the lists.
lists = [ [] for _ in range( 26 ) ]
If you can't use the sort() method, the sorted() function is your next bet.
words = [...]
sorted_words = sorted(words)
Unlike words.sort(), using sorted() won't modify its input, and it works on arbitrary iterables.
You could use the following function to sort your list of words:
def qsort(array):
if len(array) < 2:
return array
head, *tail = array
less = qsort([item for item in tail if item < head])
more = qsort([item for item in tail if item >= head])
return less + [head] + more
For the range command you have to put two exclusive integers as parameters for example range(0,11) will pick a number between 1 and 10. This is probably why you can use range(). Also you need to use a column to follow range():.