Python3 String Manipulation Using Replacement - python-3.x

I want to create a list of vowels from a string that contains letters and still have the consonants in that string. I have something that worked for a particular string, with one occurrence in that string but when I have multiple occurrences, it does not work.
PRINCELY worked well,
EMEKA did not work.
I need help!
alphabets = {"A":1,"B":2,"C":3, "D":4,"E":5,"F":6,"G":7,"H":8,"I":9,"J":1,"K":2,"L":3,"M":4,"N":5,"O":6,"P":7,"Q":8,"R":9,"S":1,
"T":2,"U":3,"V":4,"W":5, "X":6,"Y":7,"Z":8}
def digit_sum(num):
return sum( [ int(char) for char in str(num) ] )
def numerology(word):
total = 0
for letter in word:
total += alphabets[letter]
total = digit_sum(total)
return total
fan = 'PRINCELY'
def vowels(fan):
vowels=[]
if 'I' in fan:
vowels.append(9)
fan1=fan[:fan.index('I')]+fan[fan.index('I')+1:]
consonant = fan1
if 'E' in fan:
vowels.append(5)
fan2=fan1[:fan1.index('E')]+fan1[fan1.index('E')+1:]
consonant = fan2
if 'A' in fan:
vowels.append(1)
fan3=fan2[:fan2.index('A')]+fan2[fan2.index('A')+1:]
consonant = fan3
if 'O' in fan:
vowels.append(6)
fan4=fan3[:fan3.index('O')]+fan3[fan3.index('O')+1:]
consonant = fan4
if 'U' in fan:
vowels.append(3)
fan5=fan4[:fan4.index('U')]+fan4[fan4.index('U')+1:]
consonant = fan5
print(vowels)
print(consonant)
print(digit_sum(sum(vowels)))
cons = numerology(consonant)
print(cons)
vowels(fan)
#outputs
#[9, 5]
#PRNCLY
#5
#7

The easiest way is to use str.translate with an appropriate translation table. First we'll make a function that takes a character and returns the appropriate number as a string. We'll use that to build a translation table. Then we just use that translation table on the string
def get_number(char):
return str(ord(char.lower())-96) # lowercase ascii letters start at 97
vowels = (vowel for letter in 'aeiou' for vowel in (letter, letter.upper()))
table = str.maketrans({vowel: get_number(vowel) for vowel in vowels})
print('PRINCELYPRINCELY'.translate(table))
# PR9NC5LYPR9NC5LY
To sort the string into vowels and consonants, and then turn the vowels into numbers you could do
s = 'PRINCELYPRINCELY'
vowels = [ord(char.lower())-96 for char in s if char.lower() in 'aeiou']
# [9, 5, 9, 5]
consonants = s.translate(str.maketrans('','','aeiouAEIOU'))
# 'PRNCLYPRNCLY'

Related

How do I replace vowels for another value?(a to e, e to i, etc.)

I need to be able to have a user input a string, and my code is supposed to look at the string and change the vowels. So all the a's become e's, all the e's become i's, and so on. This is what I have, but I don't know how to make it work correctly.
def askForString():
userString=str(input("Enter a string: "))
userString=userString.lower()
return userString
def changeVowels(theString,vowels):
newString=[]
#newVowels=['e','i','o','u','a']
for i in range(len(theString)):
if theString[i] in vowels:
i+=newString
newString.append(i)
return newString
def main():
theString=askForString()
vowels=["a","e","i","o","u"]
NewString=changeVowels(theString,vowels)
print(NewString)
main()
I think I need to somehow have the vowels change into new vowels, but I cannot figure out how. That's why I have it as a comment.
The line i+=newString is erraneous.
i is an integer while newString is a list. You cannot add an integer to a list.
From the question I gather that you need to replace the vowels in your string as follows:
a -> e
e -> i
i -> o
o -> u
u -> a
You have multiple ways to achieve that:
Method 1:
inputString = input() # input returns string by default, no need to call with with str()
outputString = ""
vowels = ['a','e','i','o','u']
for character in inputString:
if character in vowels:
vowelIndex = vowels.index(character) # get the index of the vowel
if vowelIndex == len(vowels)-1: # if its 'u', then we need to cycle back to 'a'
vowelIndex = 0
else:
vowelIndex += 1 # if its not 'u', then just add 1 to go to next index which gives us the next vowel
outputString += vowels[vowelIndex] # put that character into the outputString
else:
outputString += character # if not vowel, then just put that character into the string.
print(outputString)
Method 2: Using dictionary to directly map the vowel to next vowel
vowels = {
"a" : "e",
"e" : "i",
"i" : "o",
"o" : "u",
"u" : "a"
}
inputString = input()
outputString = ""
for character in inputString:
if character in vowels: # checks the a key named "character" exists in the dictionary "vowels
outputString += vowels[character]
else:
outputString += character
print(outputString)
def changeVowels(theString, vowels):
newString=[]
repls = dict(zip(vowels, vowels[1:]+[vowels[0]]))
for theLetter in theString:
if theLetter in vowels:
theLetter = repls[theLetter]
newString.append(theLetter)
return newString

hello friends i cant execute my else condition

The program must accept a string S as the input. The program must replace every vowel in the string S by the next consonant (alphabetical order) and replace every consonant in the string S by the next vowel (alphabetical order). Finally, the program must print the modified string as the output.
s=input()
z=[let for let in s]
alpa="abcdefghijklmnopqrstuvwxyz"
a=[let for let in alpa]
v="aeiou"
vow=[let for let in v]
for let in z:
if(let=="a"or let=="e" or let=="i" or let=="o" or let=="u"):
index=a.index(let)+1
if index!="a"or index!="e"or index!="i"or index!="o"or index!="u":
print(a[index],end="")
else:
for let in alpa:
ind=alpa.index(let)
i=ind+1
if(i=="a"or i=="e" or i=="i"or i=="o"or i=="u"):
print(i,end="")
the output is :
i/p orange
pbf
the required output is:
i/p orange
puboif
I would do it like this:
import string
def dumb_encrypt(text, vowels='aeiou'):
result = ''
for char in text:
i = string.ascii_letters.index(char)
if char.lower() in vowels:
result += string.ascii_letters[(i + 1) % len(string.ascii_letters)]
else:
c = 'a'
for c in vowels:
if string.ascii_letters.index(c) > i:
break
result += c
return result
print(dumb_encrypt('orange'))
# puboif
Basically, I would use string.ascii_letters, instead of defining that anew. Also, I would not convert all to list as it is not necessary for looping through. The consonants you got right. The vowels, I would just do an uncertain search for the next valid consonant. If the search, fails it sticks back to default a value.
Here I use groupby to split the alphabet into runs of vowels and consonants. I then create a mapping of letters to the next letter of the other type (ignoring the final consonants in the alphabet). I then use str.maketrans to build a translation table I can pass to str.translate to convert the string.
from itertools import groupby
from string import ascii_lowercase as letters
vowels = "aeiou"
is_vowel = vowels.__contains__
partitions = [list(g) for k, g in groupby(letters, is_vowel)]
mapping = {}
for curr_letters, next_letters in zip(partitions, partitions[1:]):
for letter in curr_letters:
mapping[letter] = next_letters[0]
table = str.maketrans(mapping)
"orange".translate(table)
# 'puboif'

Lexicographically smallest palindrome in python

I found this question to be interesting and I would like to share this here and find reasonably good codes, specific to py :
Given a string S having characters from English alphabets ['a' - 'z'] and '.' as the special character (without quotes).
Write a program to construct the lexicographically smallest palindrome by filling each of the faded character ('.') with a lower case alphabet.
Definition:
The smallest lexicographical order is an order relation where string s is smaller than t, given the first character of s (s1 ) is smaller than the first character of t (t1 ), or in case they
are equivalent, the second character, etc.
For example : "aaabbb" is smaller than "aaac" because although the first three characters
are equal, the fourth character b is smaller than the fourth character c.
Input Format:
String S
Output Format:
Print lexicographically smallest palindrome after filling each '.' character, if it
possible to construct one. Print -1 otherwise.
Example-1
Input:
a.ba
Output:
abba
Example-2:
Input:
a.b
Output:
-1
Explanation:
In example 1, you can create a palindrome by filling the '.' character by 'b'.
In example 2, it is not possible to make the string s a palindrome.
You can't just copy paste questions from NPTEL assignments and ask them here without even trying!
Anyways,since the "code" is your only concern,try copy pasting the lines below:
word = input()
length = len(word)
def SmallestPalindrome(word, length):
i = 0
j = length - 1
word = list(word) #creating a list from the input word
while (i <= j):
if (word[i] == word[j] == '.'):
word[i] = word[j] = 'a'
elif word[i] != word[j]:
if (word[i] == '.'):
word[i] = word[j]
elif (word[j] == '.'):
word[j] = word[i]
else: # worst case situation when palindrome condition is not met
return -1
i = i + 1
j = j - 1
return "".join(word) # to turn the list back to a string
print(SmallestPalindrome(word, length)) #Print the output of your function
s=input()
s=list(s)
n=len(s)
j=n
c=0
for i in range(n):
j=j-1
if((s[i]==s[j]) and (i==j) and (s[i]=='.' and s[j]=='.')):
s[i]='a'
s[j]='a'
elif(s[i]==s[j]):
continue
elif((s[i]!=s[j]) and (i!=j) and (s[i]=='.' or s[j]=='.')):
if(s[i]!='.'):
s[j]=s[i]
else:
s[i]=s[j]
elif((i==j) and (s[i]=='.')):
s[i]=a
else:
c=c+1
break
if(c<1):
for k in s:
print(k,end="")
else:print("-1")

How to keep the vowel at the beginning of all the words in a string, but remove in the rest of the string

def shortenPlus(s) -> "s without some vowels":
for char in s:
if char in "AEIOUaeiou":
return(s.replace(char,""))
I have the taken it out of the entire string. But I can't figure out how to restrict the replace function to everything but the first letter of each word in a string.
Not sure exactly what you're looking for, can you clarify, perhaps give a simple example? None of the words you have in your example start with vowels!
But here you could remove all the vowels in a word except the first vowel of the first word. Hard coded but gives you an idea:
s="without some vowels"
for char in s[2:]:
if char in "AEIOUaeiou":
s=s.replace(char,"")
print(s)
Outputs
witht sm vwls
Alternatively, to get the first char of every word, you could use a sentinel value that flags each time a non-alpha char such as punctuation or a space is present, then keeps the next char but not the others.
s="without some vowels"
sent=2
for char in s:
if sent>0:
sent-=1
print(char)
continue
if not char.isalpha():
sent=2
continue
s=s.replace(char,"")
print(output)
Outputs
w s v
def shortenPlus(s):
counter = 0 # accepted character count
add_the_vowel = True # check if vowel came for the first time for the word
temp = " " # temp string to store the output
for letter in s:
if letter == " ":
add_the_vowel= True
if add_the_vowel == True and letter in "AEIOUaeiou":
temp += s[counter] # first vowel of the word
if letter in "AEIOUaeiou":
add_the_vowel = False # restrict second vowel appeared
else:
temp += s[counter]
counter += 1
print(temp)
s = "without some vowels frienis"
shortenPlus(s)
How to keep the vowel at the beginning of all the words in a string, but remove in the rest of the string
output :
witht som vowls frins

python3 sum in stings each letter value

i need sum in string letters value ex.
a = 1
b = 2
c = 3
d = 4
alphabet = 'abcdefghijklmnopqrstuvwxyz'
v1
string = "abcd"
# #result = sum(string) so
if string[0] and string[1] and string[2] and string[3] in alphabet:
if string[0] is alphabet[0] and string[1] is alphabet[1] and string[2] is alphabet[2] and string[3] is alphabet[3]:
print(a+b+c+d)
v2
string = ("ab","aa","dc",)
if string[0][0] and string[0][1] and string[1][0] and string[1][1] and string[2][0] and string[2][1] in alphabet:
if string[0] is alphabet[0] and string[1] is alphabet[1] and string[2] is alphabet[2] and string[3] is alphabet[3]:
print(a+b+c+d)
what is the solution? can you help me
Use the sum() function and a generator expression; a dictionary built from string.ascii_lowercase can serve as a means to getting an integer value per letter:
from string import ascii_lowercase
letter_value = {c: i for i, c in enumerate(ascii_lowercase, 1)}
wordsum = sum(letter_value.get(c, 0) for c in word if c)
The enumerate(ascii_lowercase, 1) produces (index, letter) pairs when iterated over, starting at 1. That gives you (1, 'a'), (2, 'b'), etc. That can be converted to c: i letter pairs in a dictionary, mapping letter to integer number.
Next, using the dict.get() method lets you pick a default value; for any character in the input string, you get to look up the numeric value and map it to an integer, but if the character is not a lowercase letter, 0 is returned instead. The sum(...) part with the loop then simply adds those values up.
If you need to support sequences with words, just use sum() again. Put the above sum() call in a function, and apply that function to each word in a sequence:
from string import ascii_lowercase
letter_value = {c: i for i, c in enumerate(ascii_lowercase, 1)}
def sum_word(word):
return sum(letter_value.get(c, 0) for c in word if c)
def sum_words(words):
return sum(sum_word(word) for word in words)
The old-fashioned way is to take advantage of the fact that lowercase letters are contiguous, so that ord(b) - ord(a) == 1:
data = "abcd"
print("Sum:", sum(ord(c)-ord("a")+1 for c in data))
Of course you could "optimize" it to reduce the number of computations, though it seems silly in this case:
ord_a = ord("a")
print("Sum:", sum(ord(c)-ord_a for c in data)+len(data))

Resources