Need to divide string inside list comprehension - python

Asked of me: By filtering the lowers list, create and print a list of the words for which the first half of the word matches the second half of the word. Examples include "bonbon", "froufrou", "gaga", and "murmur".
What i have so far:
[word for word in lowers if list.(word)(1:len(word)/2:)==list.(word)(len(word)/2::)]
Im not sure how to make word a list so I can only use certain characters for this filter. I know this will not work but its my logic so far.

Logical Error: You're slicing from index 1 instead of 0 in list.(word)(1:len(word)/2:)
Syntax Errors: list.(word) is incorrect syntax, and list slicing uses [ ] not ( ). Simply use word[start:stop] to break it up
Use:
[word for word in lowers if word[:len(word)//2]==word[len(word)//2:]]
Edit: Thanks to Ignacio Vazquez-Abrams' comment - Use integer division ( // operator ) for Python 3 compatibility

Try this:
[word for word in lowers if word[len(word)//2:] == word[:len(word)//2]]

Related

How to remove the first character of a string that's in a list? [PYTHON]

I would like to remove the ["flow", "flappy", "flirtify"] first character from every single index in this array, but I don't know how. I tried almost everything but it still doesn't work. Any suggestions?
first_char_removed = [word[1:] for word in original_list]
In the future, I would recommend posting your code attempts
to remove the first character of a string you can just use string[1:] who return you the same string without the first character.
see code example below :
for myword in myWordsArray:
print(myword[1:])
The simplest way would probably be list comprehension
l = [e[1:] for e in ["flow", "flappy", "flirtify"]]
[word[1:] for word in ["flow", "flappy", "flirtify"]]
you can see how to do it for a single string, and then use list comprehension

Python - Capture string with or without specific character

I am trying to capture the sentence after a specific word. Each sentences are different in my code and those sentence doesn't necessarily have to have this specific word to split by. If the word doesn't appear, I just need like blank string or list.
Example 1: working
my_string="Python is a amazing programming language"
print(my_string.split("amazing",1)[1])
programming language
Example 2:
my_string="Java is also a programming language."
print(my_string.split("amazing",1)[1]) # amazing word doesn't appear in the sentence.
Error: IndexError: list index out of range
Output needed :empty string or list ..etc.
I tried something like this, but it still fails.
my_string.split("amazing",1)[1] if my_string.split("amazing",1)[1] == None else my_string.split("amazing",1)[1]
When you use the .split() argument you can specify what part of the list you want to use with either integers or slices. If you want to check a specific word in your string you can do is something like this:
my_str = "Python is cool"
my_str_list = my_str.split()
if 'cool' in my_str_list:
print(my_str)`
output:
"Python is cool"
Otherwise, you can run a for loop in a list of strings to check if it finds the word in multiple strings.
You have some options here. You can split and check the result:
tmp = my_string.split("amazing", 1)
result = tmp[1] if len(tmp) > 1 else ''
Or you can check for containment up front:
result = my_string.split("amazing", 1)[1] if 'amazing' in my_string else ''
The first option is more efficient if most of the sentences have matches, the second one if most don't.
Another option similar to the first is
result = my_string.split("amazing", 1)[-1]
if result == my_string:
result = ''
In all cases, consider doing something equivalent to
result = result.lstrip()
Instead of calling index 1, call index -1. This calls the last item in the list.
my_string="Java is also a programming language."
print(my_string.split("amazing",1)[1])
returns ' programming language.'

How can I delete comma at the end of the output in Python?

I am trying to order a word's letters by alphabetically in Python. But there is a comma at the end of the output.(I tried ''.sort() command, it worked well but there is square brackets at the beginning and at the end of the output). The input and the output must be like this:
word
'd','o','r','w'
This is my code:
alphabet='AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
word=str(input())
for i in alphabet:
for j in word:
if i==j:
print("'{}',".format(i),end='')
And this is my output:
word
'd','o','r','w',
Python strings have a join() function:
ls = ['a','b','c']
print(",".join(ls)) # prints "a,b,c"
Python also has what is called a 'list comprehension', that you can use like so:
alphabet='AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
word=str(input())
matches = [l for l in word if l in alphabet]
print(",".join(sorted(matches)))
All the list comprehension does is put l in the list if it is in alphabet. All the candidate ls are taken from the word variable.
sorted is a function that will do a simple sort (though more complex sorts are possible).
Finally; here are a few other fun options that all result in "a,b,c,d":
"a,b,c,d,"[:-1] . # list-slice
"a,b,c,d,".strip(",") . # String strip
you store it in an array and then print it at the end
alphabet='AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
word=str(input())
matches = []
for i in alphabet:
for j in word:
if i==j:
matches.append("'{i}',".format(i=i))
#now that matches has all our matches
print(",".join(arrayX) # join it
or as others have mentioned
print(",".join(sorted(word)))
You want to use the string.join() function.
alphabet='AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
','.join(alphabet)
There's really no need to anything to make the string into a list, join will iterate over it quite happily. Tried on python 2.7 and 3.6
Doing it your self
The trick is in the algorithm you use.
You want to add a comma and a space, after each field, except the last. But it is hard to know which is the last, until it is too late.
It would be much easier if you could make the first field the special case, as this is mach easier to predict.
Therefore transform the algorithm to: Add a comma and a space, before each field, except the first. This produces the same output, but is a much simpler algorithm.
Use a library
Using a library is always preferable (unless doing it just for the practice).
python has the join method. See other answers.

Trying to make sure certain symbols aren't in a word

I currently have the following to filter words with square and normal brackets and can't help but think there must be a tidier way to do this..
words = [word for word in random.choice(headlines).split(" ")[1:-1] if "[" not in word and "]" not in word and "(" not in word and ")" not in word]
I tried creating a list or tuple of symbols and doing
if symbol not in word
But it dies because I'm comparing a list with a string. I appreciate I could explode this out and do a compare like:
for word in random.choice(headlines).split(" ")[1:-1]:
popIn = 1
for symbol in symbols:
if symbol in word:
popIn = 0
if popIn = 1:
words.append(word)
But it seems like overkill in my head. I appreciate I'm a novice programmer so anything I can do to tidy either method up would be very helpful.
Use set intersection.
brackets = set("[]()")
words = [word for word in random.choice(headlines).split(" ")[1:-1] if not brackets.intersection(word)]
The intersection is empty if word does not contain any of the characters in brackets.
You might also consider using itertools instead of a list comprehension.
words = list(itertools.ifilterfalse(brackets.intersection,
random.choice(headlines).split(" "))[1:-1]))
I'm not sure of what you want to filter but I advise you to use the Regular expression module of python.
import re
r = re.compile("\w*[\[\]\(\)]+\w*")
test = ['foo', '[bar]', 'f(o)o']
result = [word for word in test if not r.match(word)]
print result
output is ['foo']

Using list comprehension and sets

Create and print a list of words for which both the following criteria are all met:
the word is at least 8 characters long;
the word formed from the odd-numbered letter is in the set of lower-case words; and
the word formed from the even-numbered letters is in the set of lower-case words.
For example, the word "ballooned" should be included in your list because the word formed from the odd-numbered letters, "blond", and the word formed from the even-numbered letters, "aloe", are both in the set of lower-case words. Similarly, "triennially" splits into "tinily" and "renal", both of which are in the word list.
My teacher told us we should use a set: s=set(lowers) because this would be faster.
what i have so far:
s=set(lowers)
[word for word in lowers if len(word)>=8
and list(word)(::2) in s
and list(word)(::-2) in s]
I do not think I am using the set right. can someone help me get this to work
The problem is that you cast word to a list (unnecessary), your slices are not in brackets (you used parenthesis), and your second slice uses the wrong indices (should be 1::2, not ::-2).
Here are the slices done correctly:
>>> word = "ballooned"
>>> word[::2]
'blond'
>>> word[1::2]
'aloe'
Note that s is an odd name for a collection of lowercase words. A better name would be words.
Your use of set is correct. The reason your teacher wants you to use a set is it is much faster to test membership of a set than it is for a list.
Putting it together:
words = set(lowers)
[word for word in words if len(word) >= 8
and word[::2] in words
and word[1::2] in words]
Here is a quick example of how to structure your condition check inside of the list comprehension:
>>> word = 'ballooned'
>>> lowers = ['blond', 'aloe']
>>> s = set(lowers)
>>> len(word) >= 8 and word[::2] in s and word[1::2] in s
True
edit: Just realized that lowers contains both the valid words and the "search" words like 'ballooned' and 'triennially', in any case you should be able to use the above condition inside of your list comprehension to get the correct result.
list(word)(::2)
First, the syntax to access index ranges is using squared parentheses, also, you don’t need to cast word to a list first, you can directly do that on the string:
>>> 'ballooned'[::2]
'blond'
Also, [::-2] won’t give you the uneven word, but a reversed version of the other one. You need to use [1::2] (i.e. skip the first, and then every second character):
>>> 'ballooned'[::-2]
'dnolb'
>>> 'ballooned'[1::2]
'aloe'
In general it is always a good idea to test certain parts separately to see if they really do what you think they do.
this should do it:
s=set(lowers)
[word for word in lowers if len(word)>=8 and word[::2] in s and word[1::2] in s]
or using all():
In [166]: [word for word in lowers if all((len(word)>=8,
word[::2] in s,
word[1::2] in s))]
use [::] not (::) and there's no need of list() here, plus to get the word formed by letters placed at odd position use [1::2].
In [151]: "ballooned"[::2]
Out[151]: 'blond'
In [152]: "ballooned"[1::2]
Out[152]: 'aloe'

Categories

Resources