I have a function isvowel that returns either True or False, depending on whether a character ch is a vowel.
def isvowel(ch):
if "aeiou".count(ch) >= 1:
return True
else:
return False
I want to know how to use that to get the index of the first occurrence of any vowel in a string. I want to be able to take the characters before the first vowel and add them end of the string. Of course, I can't do s.find(isvowel) because isvowel gives a boolean response. I need a way to look at each character, find the first vowel, and give the index of that vowel.
How should I go about doing this?
You can always try something like this:
import re
def first_vowel(s):
i = re.search("[aeiou]", s, re.IGNORECASE)
return -1 if i == None else i.start()
s = "hello world"
print first_vowel(s)
Or, if you don't want to use regular expressions:
def first_vowel(s):
for i in range(len(s)):
if isvowel(s[i].lower()):
return i
return -1
s = "hello world"
print first_vowel(s)
[isvowel(ch) for ch in string].index(True)
(ch for ch in string if isvowel(ch)).next()
or for just the index (as asked):
(index for ch, index in itertools.izip(string, itertools.count()) if isvowel(ch)).next()
This will create an iterator and only return the first vowel element. Warning: a string with no vowels will throw StopIteration, recommend handling that.
Here is my take:
>>> vowel_str = "aeiou"
>>> def isVowel(ch,string):
... if ch in vowel_str and ch in string:
... print string.index(ch)
... else:
... print "notfound"
...
>>> isVowel("a","hello")
not found
>>> isVowel("e","hello")
1
>>> isVowel("l","hello")
not found
>>> isVowel("o","hello")
4
Using next for a generator is quite efficient, it means you don't iterate though the entire string (once you have found a string).
first_vowel(word):
"index of first vowel in word, if no vowels in word return None"
return next( (i for i, ch in enumerate(word) if is_vowel(ch), None)
is_vowel(ch):
return ch in 'aeiou'
my_string = 'Bla bla'
vowels = 'aeyuioa'
def find(my_string):
for i in range(len(my_string)):
if my_string[i].lower() in vowels:
return i
break
print(find(my_string))
Related
I've been having problems with this simple hackerrank question. My code works in the compiler but hackerrank test is failing 6 test cases. One of which my output is correct for (I didn't pay premium). Is there something wrong here?
Prompt:
Steve has a string of lowercase characters in range ascii[‘a’..’z’]. He wants to reduce the string to its shortest length by doing a series of operations in which he selects a pair of adjacent lowercase letters that match, and then he deletes them. For instance, the string aab could be shortened to b in one operation.
Steve’s task is to delete as many characters as possible using this method and print the resulting string. If the final string is empty, print Empty String
Ex.
aaabccddd → abccddd → abddd → abd
baab → bb → Empty String
Here is my code:
def super_reduced_string(s):
count_dict = {}
for i in s:
if (i in count_dict.keys()):
count_dict[i] += 1
else:
count_dict[i] = 1
new_string = ''
for char in count_dict.keys():
if (count_dict[char] % 2 == 1):
new_string += char
if (new_string is ''):
return 'Empty String'
else:
return new_string
Here is an example of output for which it does not work.
print(super_reduced_string('abab'))
It outputs 'Empty String' but should output 'abab'.
By using a counter, your program loses track of the order in which it saw characters. By example with input 'abab', you program sees two a's and two b's and deletes them even though they are not adjacent. It then outputs 'Empty String' but should output 'abab'.
O(n) stack-based solution
This problem is equivalent to finding unmatched parentheses, but where an opening character is its own closing character.
What this means is that it can be solved in a single traversal using a stack.
Since Python can return an actual empty string, we are going to output that instead of 'Empty String' which could be ambiguous if given an input such as 'EEEmpty String'.
Code
def super_reduced_string(s):
stack = []
for c in s:
if stack and c == stack[-1]:
stack.pop()
else:
stack.append(c)
return ''.join(stack)
Tests
print(super_reduced_string('aaabab')) # 'abab'
print(super_reduced_string('aabab')) # 'bab'
print(super_reduced_string('abab')) # 'abab'
print(super_reduced_string('aaabccddd ')) # 'abd'
print(super_reduced_string('baab ')) # ''
I solved it with recursion:
def superReducedString(s):
if not s:
return "Empty String"
for i in range(0,len(s)):
if i < len(s)-1:
if s[i] == s[i+1]:
return superReducedString(s[:i]+s[i+2:])
return s
This code loops over the string and checks if the current and next letter/position in the string are the same. If so, these two letters/positions I get sliced from the string and the newly created reduced string gets passed to the function.
This occurs until there are no pairs in the string.
TESTS:
print(super_reduced_string('aaabccddd')) # 'abd'
print(super_reduced_string('aa')) # 'Empty String'
print(super_reduced_string('baab')) # 'Empty String'
I solved it by creating a list and then add only unique letters and remove the last letter that found on the main string. Finally all the tests passed!
def superReducedString(self, s):
stack = []
for i in range(len(s)):
if len(stack) == 0 or s[i] != stack[-1]:
stack.append(s[i])
else:
stack.pop()
return 'Empty String' if len(stack) == 0 else ''.join(stack)
I used a while loop to keep cutting down the string until there's no change:
def superReducedString(s):
repeat = set()
dups = set()
for char in s:
if char in repeat:
dups.add(char + char)
else:
repeat.add(char)
s_old = ''
while s_old != s:
s_old = s
for char in dups:
if char in s:
s = s.replace(char, '')
if len(s) == 0:
return 'Empty String'
else:
return s
I'm trying to write a function which given a string returns another string that flips its lowercase characters to uppercase and viceversa.
My current aproach is as follows:
def swap_case(s):
word = []
for char in s:
word.append(char)
for char in word:
if char.islower():
char.upper()
else:
char.lower()
str1 = ''.join(word)
However the string doesn't actually change, how should I alter the characters inside the loop to do so?
PS: I know s.swapcase() would easily solve this, but I want to alter the characters inside the string during a for loop.
def swap_case(s):
swapped = []
for char in s:
if char.islower():
swapped.append(char.upper())
elif char.isupper():
swapped.append(char.lower())
else:
swapped.append(char)
return ''.join(swapped)
you can use swapcase.
string.swapcase(s)
Return a copy of s, but with lower case letters converted to upper case and vice versa.
Source : Python docs
>>> name = 'Mr.Ed' or name= ["M","r",".","E","d"]
>>> ''.join(c.lower() if c.isupper() else c.upper() for c in name)
'mR.eD'
Your code is not working because you are not storing the chars after transforming them. You created a list with all chars and then, you access the values without actually saving them. Also, you should make your function return str1 or you will never get a result. Here's a workaround:
def swap_case(s):
word = []
for char in s:
if char.islower():
word.append(char.upper())
else:
word.append(char.lower())
str1 = ''.join(word)
return str1
By the way, I know you want to do it with a for loop, but you should know there are better ways to perform this which would be more pythonic.
You can use this code:
s = "yourString"
res = s.swapcase()
print(res)
Which will output:
YOURsTRING
def swap_case(s):
x = ''
for i in s:
if i.isupper():
i = i.lower()
else:
i = i.upper()
x += ''.join(i)
return x
I wrote a function that replace the letter if the letter is the same as the next letter in the string:
word = 'abcdeefghiijkl'
def replace_letter(word):
for i in range(len(word)-1):
if word[i] == word[i+1]:
word = word.replace(word[i],'7')
return word
replace_letter(word)
This should give me 'abcd7efgh7ijkl', but I got 'abcd77fgh77jkl'. Once the letter is the same with the next one both are replaced with '7'.
Why?
You should use:
word = word.replace(word[i],'7', 1)
to indicate that you want to make one character replacement. Calling replace() without indicating how many replacements you wish to make will replace any occurrence of the character "e" (as found at word[i]) by "7".
the answer above has a little bug
for example:
when your word = 'ebcdeefghiijkl'
the result of replace_letter(word) will be '7abcdeefgh7ijkl'
you can try this:
def replace_letter(word):
result=[]
for i in range(len(word)):
if i!=len(word)-1 and word[i] == word[i+1]:
result.append('7')
else:
result.append(word[i])
return ''.join(result)
I am trying to write a python program that checks if a given string is a pangram - contains all letters of the alphabet.
Therefore, "We promptly judged antique ivory buckles for the next prize" should return True while any string that does not contain every letter of the alphabet at least once should return False.
I believe I should be using RegEx for this one, but I'm not sure how. It should look similar to this:
import sys
import re
input_string_array = sys.stdin.readlines()
input_string = input_string_array[0]
if (re.search('string contains every letter of the alphabet',input_string):
return True
else:
return False
This is not something I'd solve with a regular expression, no. Create a set of the lowercased string and check if it is a superset of the letters of the alphabet:
import string
alphabet = set(string.ascii_lowercase)
def ispangram(input_string):
return set(input_string.lower()) >= alphabet
Only if every letter of the alphabet is in the set created from the input text will it be a superset; by using a superset and not equality, you allow for punctuation, digits and whitespace, in addition to the (ASCII) letters.
Demo:
>>> import string
>>> alphabet = set(string.ascii_lowercase)
>>> input_string = 'We promptly judged antique ivory buckles for the next prize'
>>> set(input_string.lower()) >= alphabet
True
>>> set(input_string[:15].lower()) >= alphabet
False
This is my solution in python:
alphabet = "abcdefghijklmnopqrstuvwxyz"
sentence = input()
sentence = sentence.lower()
missing = ''
for letter in alphabet:
if letter not in sentence:
missing = missing+letter
if (len(missing) != 0):
print("missing", missing)
else:
print("pangram")
You dont need regex. What you want can be done in two lines with good space efficiency.
ms = itertools.chain(range(ord("a"),ord("z")),range(ord("A"),ord("Z")))
flag = all(chr(o) in string for o in ms)
That's it. string is the string you want to check. flag will be either True or False depending on if all chars are in string or not.
A pangram is a function that contains at least each letter of the alphabet.
I have tried in this way:
def pangram():
n = str(input('give me a word to check if it is a pangram:\n'))
n = n.lower()
n = n.replace(' ','')
if not isinstance(n, str):
return n, False
elif set(n) >= set('abcdefghijklmnopqrstuvxywz'):
return n, True
else:
return n, False
The function isinstance(n, str) checks if n is a string. The function set() gives us a set. For example set('penny') returns {'y', 'e', 'p', 'n'}... as you see it is a set without the repeated letters.
I was doing the same exercise today, maybe it's not the best aproach, but I think it's easy to understand.
def ispangram(s):
stringy = ''
flag = True
validLetters = "abcdefghijklmnopqrstuvwxyz"
#transform the given string in simple string with no symbols only letters
for char in s.lower():
if(char in validLetters):
stringy += char
#check if all the letters of the alphabet exist on the string
for char in validLetters:
if(char in stringy):
pass
else:
flag = False
break
return flag
if(ispangram("We promptly judged antique ivory buckles for the next prize")):
print("It's PANGRAM!")
else:
print("It's not Pangram :(")
import string
def ispangram(str1, alphabet=string.ascii_lowercase):
return ''.join(sorted(set(str1.lower().replace(" ","")))) == alphabet
First changed all alphabets to lowercase and then removed all spaces using replace. Then Converted into set to have unique chars and then used sorted function to sort alphabetically. As sorted function gives a list, so join func to join it without spaces and then compared it to all lowercase chars.
Here is my solution:
def isaPangrams(s):
alph = list(string.ascii_lowercase)
s = s.lower()
s = list(s)
for letter in alph:
if letter not in s:
print('not pangram')
present='false'
break
if letter in s:
present = 'true'
if present == 'true':
print('pangram')
if __name__ == '__main__':
s = input()
answer = isaPangrams(s)
I am trying to make an up language translator. Simple task for me in python. Or so i thought. If you are unaware, up language is when you take a word and say it while adding up before every vowel. for example, Andrew would be Upandrupew. I am trying to find out how find all of the vowels in a user submitted word, and put up before them. Is there a way to cut up a word before all vowels. so excellent would be exc ell ent? thanks.
maybe
VOWELS = 'aeiou'
def up_it(word):
letters = []
for letter in word:
if letter.lower() in VOWELS:
letters.append('Up')
letters.append(letter)
return ''.join(letters)
can be simplified to
def up_it(word):
return ''.join('up'+c if c.lower() in 'aeiou' else c for c in word)
You could do that with a regex:
import re
a = "Hello World."
b = re.sub("(?i)([aeiou])", "up\\1", a)
The (?i) makes it case-insensitive. \\1 refers to the character that was matched inside ([aeiou]).
''.join(['up' + v if v.lower() in 'aeiou' else v for v in phrase])
for vowel in [“a“,“e“,“i“,“o“,“u“]:
Word = Word.replace(vowel,“up“+vowel)
print(Word)
import re
sentence = "whatever"
q = re.sub(r"([aieou])", r"up\1", sentence, flags=re.I)
vowels = ['a', 'e', 'i', 'o', 'u']
def upped_word(word):
output = ''
for character in word:
if character.lower() in vowels:
output += "up"
output += character
return output
Here is a one-liner for the entire problem
>>> "".join(('up' + x if x.upper() in 'AEIOU' else x for x in 'andrew'))
'upandrupew'
Here's one way of doing it.
wordList = list(string.lower())
wordList2 = []
for letter in wordList:
if letter in 'aeiou':
upLetter = "up" + letter
wordList2.append(upLetter)
else:
wordList2.append(letter)
"".join(wordList2)
Create a list of letters (wordList), iterate through those letters and append it to a second list, which is joined at the end.
Returns:
10: 'upandrupew'
In one line:
"".join(list("up"+letter if letter in "aeiou" else letter for letter in list(string.lower())))
I'd probably go with RegExp but there are already many answers using it. My second choice is the map function, witch is better then iterate through every letter.
>>> vowels = 'aeiou'
>>> text = 'this is a test'
>>> ''.join(map(lambda x: 'up%s'%x if x in vowels else x, text))
'thupis upis upa tupest'
>>>
def is_vowel(word):
''' Check if `word` is vowel, returns bool. '''
# Split word in two equals parts
if len(word) % 2 == 0:
parts = [word[0:len(word)/2], word[len(word)/2:]]
else:
parts = [word[0:len(word)/2], word[(len(word)/2)+1:]]
# Check if first part and reverse second part are same.
if parts[0] == parts[1][::-1]:
return True
else:
return False
This is a smart solution which helps you to count and find vowels in input string:
name = input("Name:- ")
counter = []
list(name)
for i in name: #It will check every alphabet in your string
if i in ['a','e','i','o','u']: # Math vowels to your string
print(i," This is a vowel")
counter.append(i) # If he finds vowels then he adds that vowel in empty counter
else:
print(i)
print("\n")
print("Total no of words in your name ")
print(len(name))
print("Total no of vowels in your name ")
print(len(counter))