I have a list lets say:
DIRECTION_LETTERS=['u', 'd' ,'r' , 'l', 'w', 'x', 'y', 'z']
Now the other parameter of mine is like arguement, I write in
udl and it returns ['udl']
so lets say another list arg_list = ['udl']
I want to check if u and d and l is in this list or i want to check if none of the letters in my direction letters list in the arg list
to make it print error msg I have tried this:
for letter in DIRECTION_LETTERS:
for char in arg_list[4]:
if letter in arg_list[4][0]:
continue
else:
print (ERROR_MESSAGE_DIRECTIONS)
return False
return True
There's a handy function in Python called all() which returns true if all arguments are true. Feel free to find a nice way of using it, but in general:
>>> DIRECTION_LETTERS=['u', 'd' ,'r' , 'l', 'w', 'x', 'y', 'z']
>>>
>>> s="udl"
>>> print(all(c in DIRECTION_LETTERS for c in s))
True
>>> s="udlxa"
>>> print(all(c in DIRECTION_LETTERS for c in s))
False
This line
if letter in arg_list[4][0]:
needs to be
if char in DIRECTION_LETTERS:
and you need to delete the line for letter in DIRECTION_LETTERS:.
Related
My purpose is to get an input as a string and return a list of lower case letters of that string, without repeats, without punctuations, in alphabetical order. For example, the input "happy!" would get ['a','h','p','y']. I try to use the join function to get rid of my punctuations but somehow it doesn't work. Does anybody know why? Also, can sort.() sort alphabets? Am I using it in the right way? Thanks!
def split(a):
a.lower()
return [char for char in a]
def f(a):
i=split(a)
s=set(i)
l=list(s)
v=l.join(u for u in l if u not in ("?", ".", ";", ":", "!"))
v.sort()
return v
.join() is a string method, but being used on a list, so the code raises an exception, but join and isn't really needed here.
You're on the right track with set(). It only stores unique items, so create a set of your input and compute the intersection(&) with lower case letters. Sort the result:
>>> import string
>>> s = 'Happy!'
>>> sorted(set(s.lower()) & set(string.ascii_lowercase))
['a', 'h', 'p', 'y']
You could use:
def f(a):
return sorted(set(a.lower().strip('?.;:!')))
>>> f('Happy!')
['a', 'h', 'p', 'y']
You could also use regex for this:
pattern = re.compile(r'[^a-z]')
string = 'Hello# W0rld!!##'
print(sorted(set(pattern.sub('', string))))
Output:
['d', 'e', 'l', 'o', 'r']
I have a string as follows:
f = 'ATCTGTCGTYCACGT'
I want to check whether the string contains any characters except: A, C, G or T, and if so, print them.
for i in f:
if i != 'A' and i != 'C' and i != 'G' and i != 'T':
print(i)
Is there a way to achieve this without looping through the string?
You can use set to achieve the desired output.
f = 'ATCTGTCGTYCACGTXYZ'
not_valid={'A', 'C', 'G' , 'T'}
unique=set(f)
print(unique-not_valid)
output
{'Y','X','Z'} #characters in f which are not equal to 'A','C','G','T'
Depending on the size of your input string, the for loop might be the most efficient solution.
However, since you explicitly ask for a solution without an explicit loop, this can be done with a regex.
import re
f = 'ABCDEFG'
print(*re.findall('[^ABC]', f), sep='\n')
Outputs
D
E
F
G
Just do
l = ['A', 'C', 'G', 'T']
for i in f:
if i not in l:
print(i)
It checks whether the list contains a char of the list
If you don't want to loop through the list you can do:
import re
l = ['A', 'C', 'G', 'T']
contains = bool(re.search("%s" % "[" + "".join(l) + "]", f))
Technically this loops but we convert your input string to a set which removes duplicate values
accepted_values = ['a','t','c','g']
input = 'ATCTGTCGTYCACGT'
print([i for i in set(input.lower()) if i not in accepted_values])
So I'm trying to make a program that allows you to decode messages in python. Here's what I got so far...
def decode():
print("Let's see what she wanted to tell you.")
time.sleep(2)
messageOne= raw_input('Please paste the message: ')
print("Decoding message now...")
message= list(messageOne)
and I was wondering how I would take the individual letters in the list and change them based on the code I want. Aka I need to know how to change a specific value in the list. Thanks!
Your question isn't very clear, based on what I see you can have different ways of replacing letters. For example let's use string s:
>>> s = 'Hello'
>>> s.replace('l','h')
Hehho
If you only want to replace one occurrence of a given letter use this:
>>> s = 'Hello'
>>> s.replace('l','h', 1) #will only replace the first occurrence
Hehlo
You can also convert your string into a list
>>> s = 'Hello'
>>> s = [x for x in s]
>>> s
['H', 'e', 'l', 'l', 'o']
In here you can replace anything by anything, like so:
>>> s[3] = 'h'
>>> s
['H', 'e', 'l', 'h', 'o']
When you're done with replacing whatever you want, you can use the .join() method to make your list a string again like so:
>>> s = ''.join(s) #separator goes in between the quotes
>>> s
Helho
I want to check if a string the user inputted contains one of the strings in a list.
I know how to check if the string contains one string but I want to know how to check if a string contains either this string, or that string, or another string.
For example, if I am checking the user's input to see if it contains a vowel.. there can be 5 different choices when we're talking about vowels (a, e, i, o, or u). How can I check to see if the string the user inputted has one of those?
Using any:
>>> vowels = 'a', 'e', 'i', 'o', 'u'
>>> s = 'cat'
>>> any(ch in vowels for ch in s)
True
>>> s = 'pyth-n'
>>> any(ch in vowels for ch in s)
False
>>> vowels = set(['a', 'e', 'i', 'o', 'u'])
>>> inp = "foobar"
>>> bool(vowels.intersection(inp))
True
>>> bool(vowels.intersection('qwty'))
False
This is the basic logic you want:
def string_checker(user_input_string, vowels):
for i in vowels:
if i in user_input_string:
return 'Found it'
return 'Sorry grashooper :('
print string_checker('Hello',('a','e','i','o','u'))
The short cut way to do this is by using the built-in any() method; which will return true if any of the items in it returns a truth value.
Here is how it would work:
any(i in user_input_string for i in vowels)
The difference is that instead of returning a custom string, this method will return True or False; we can use it the same way in our loop:
if any(i in user_input_string for i in vowels):
print('Found it!')
else:
print('Oh noes! No vowels for you!')
Checking the strings sequentially works, but if it's too inefficient for your case, you can use Aho-Corasick algorithm.
You can use this syntax
if myItem in list:
# do something
also look at the functions:
http://docs.python.org/2/library/functions.html
Is there an easy way to sort the letters in a string alphabetically in Python?
So for:
a = 'ZENOVW'
I would like to return:
'ENOVWZ'
You can do:
>>> a = 'ZENOVW'
>>> ''.join(sorted(a))
'ENOVWZ'
>>> a = 'ZENOVW'
>>> b = sorted(a)
>>> print b
['E', 'N', 'O', 'V', 'W', 'Z']
sorted returns a list, so you can make it a string again using join:
>>> c = ''.join(b)
which joins the items of b together with an empty string '' in between each item.
>>> print c
'ENOVWZ'
Sorted() solution can give you some unexpected results with other strings.
List of other solutions:
Sort letters and make them distinct:
>>> s = "Bubble Bobble"
>>> ''.join(sorted(set(s.lower())))
' belou'
Sort letters and make them distinct while keeping caps:
>>> s = "Bubble Bobble"
>>> ''.join(sorted(set(s)))
' Bbelou'
Sort letters and keep duplicates:
>>> s = "Bubble Bobble"
>>> ''.join(sorted(s))
' BBbbbbeellou'
If you want to get rid of the space in the result, add strip() function in any of those mentioned cases:
>>> s = "Bubble Bobble"
>>> ''.join(sorted(set(s.lower()))).strip()
'belou'
Python functionsorted returns ASCII based result for string.
INCORRECT: In the example below, e and d is behind H and W due it's to ASCII value.
>>>a = "Hello World!"
>>>"".join(sorted(a))
' !!HWdellloor'
CORRECT: In order to write the sorted string without changing the case of letter. Use the code:
>>> a = "Hello World!"
>>> "".join(sorted(a,key=lambda x:x.lower()))
' !deHllloorW'
OR (Ref: https://docs.python.org/3/library/functions.html#sorted)
>>> a = "Hello World!"
>>> "".join(sorted(a,key=str.lower))
' !deHllloorW'
If you want to remove all punctuation and numbers.
Use the code:
>>> a = "Hello World!"
>>> "".join(filter(lambda x:x.isalpha(), sorted(a,key=lambda x:x.lower())))
'deHllloorW'
You can use reduce
>>> a = 'ZENOVW'
>>> reduce(lambda x,y: x+y, sorted(a))
'ENOVWZ'
the code can be used to sort string in alphabetical order without using any inbuilt function of python
k = input("Enter any string again ")
li = []
x = len(k)
for i in range (0,x):
li.append(k[i])
print("List is : ",li)
for i in range(0,x):
for j in range(0,x):
if li[i]<li[j]:
temp = li[i]
li[i]=li[j]
li[j]=temp
j=""
for i in range(0,x):
j = j+li[i]
print("After sorting String is : ",j)
Really liked the answer with the reduce() function. Here's another way to sort the string using accumulate().
from itertools import accumulate
s = 'mississippi'
print(tuple(accumulate(sorted(s)))[-1])
sorted(s) -> ['i', 'i', 'i', 'i', 'm', 'p', 'p', 's', 's', 's', 's']
tuple(accumulate(sorted(s)) -> ('i', 'ii', 'iii', 'iiii', 'iiiim', 'iiiimp', 'iiiimpp', 'iiiimpps', 'iiiimppss', 'iiiimppsss', 'iiiimppssss')
We are selecting the last index (-1) of the tuple