I was doing excercise no.3 from http://cscircles.cemc.uwaterloo.ca/15b-python-pushups/ , I made the code work but was wondering if it was possible to do it in fewer lines? Here is my solution:
los = [] # short for list of strings
while True:
s = input()
if s == '###': break
los += s.lower().split() # making a list of lower case words from the input sentences
test = []
for x in los:
test += str(los.count(x)) # made a new list of the frequency of each word
a = test.index(max(test)) # variable a provides the location of them most frequent word
print (los[a]) # we know the position of the most frequent string, so find it in los.
# a is not needed but it looks neater
So this part in particular is what i'm not happy with:
for x in los:
test += str(los.count(x))
I want to re write it like:
test += str(list.count(x)) for x in los
but it tells me invalid syntax..any tips?
I think the syntax you want is:
# No need for test = []
test = [str(list.count(x)) for x in los]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.