Encoding duplicate characters of a string in Python - python-3.x

I am trying to encode a string to replace a character with '(' if it occurs only once and with ')' if it occurs more than once. So "hello" becomes "(())(". I am using dictionary to solve this. I am saving the number of occurrences of each character in the string . Then I check if that character comes up more than once then I use .replace() to replace it with ')' else with '('. The problem happens when the string contains ')'.
So for example if I have the string "abca)". I should get ")(())" as the result but I get "(((((" cause when the program gets to ')' it sees it has occurred only once and then changes every occurrence of ')' with '('. It works fine rest of the time. Here's my code:
def duplicate_encode(word):
count = {}
word = word.lower()
for ch in word:
if ch in count:
count[ch] += 1
else:
count[ch] = 1
for k in count:
if count[k] > 1:
word = word.replace(k, ')')
else:
word = word.replace(k, '(')
print(word)
duplicate_encode("abca)")

Use the following code it will work
A=input()
b=list(A)
c=list(set(A))
for i in c:
if b.count(i)>1:
A=A.replace(i,")")
elif b.count(i)==1:
A=A.replace(i,"(")
print(A)

There are two mistakes in your code:
the only (and trailing) ( in word causes final word = replace(word, '(', ')') so that all (s are replaced with )s; therefore, I build the outword string from scratch;
len(count) < len(word) if there is any duplicate character in word; therefore, the k must iterate over word rather than over count.
Fixed code:
def duplicate_encode(word):
count = {}
outword = ''
word = word.lower()
for ch in word:
if ch in count:
count[ch] += 1
else:
count[ch] = 1
for k in word:
if count[k] > 1:
outword += ')'
else:
outword += '('
print( word, '=>', outword )
duplicate_encode("abca)")
duplicate_encode("hello")
Output: .\SO\67089558.py
abca) => )(()(
hello => (())(

Related

Concatenating string outputs of a for loop in Python 3

I have a code which, after a nested for loop, provides me with a unique string in each iteration. I want to find a way to concatenate those outputs so that my final line is a single string of those unique strings. Ignoring how ugly and inefficient this code is, what steps can I take to achieve the desired result?
VOWELS = ('a','e','i','o','u','A','E','I','O','U')
ad = "Desirable unfurnished flat in quiet residential area"
# remove all vowels, unless the word starts with a vowel
def is_vowel(c):
return c in VOWELS
def mod3(ad):
testAd =ad.split()
for word in testAd:
modAd = ""
i = 0
for char in word:
if i == 0:
modAd += char
elif not is_vowel(char):
modAd += char
i+=1
print(modAd)
mod3(ad)
my output for this code:
Otherwise, when I modify my code to look like this:
But my output is:
I don't believe a .join() would work here as it's not a list type. And I can't figure out where to put a string concat + anywhere without my for loop going bonkers. Any advice?
You can create a string result where you can concatenate your each iteration result and print that. You need to add spaces after each addition of words. So, append + " " to your result variable as well.
def mod3(ad):
result = ""
testAd =ad.split()
for word in testAd:
modAd = ""
i = 0
for char in word:
if i == 0:
modAd += char
elif not is_vowel(char):
modAd += char
i+=1
result += modAd + " "
print(result)
Second option: This is my take on it:
def mod4(ad):
result = ""
testAd =ad.split()
for word in testAd:
for i, char in enumerate(word):
if i == 0:
result += char
if i > 0 and char not in VOWELS:
result += char
result += " "
print(result)

Problem with Python Code and the Functions in it

I have a Problem, I have to solve a task in Python and I dont know how to do it. The task is to define a function number_of_vowels, where the output should be the Number of vowels in a Word. With this function I have to write anotherone, many_vowels thats working with a list an a Number and where the number says how many vowels have to be at least in a word to be appended to the result list and then I have to append this Word. Thanks to everybody helping me ;D.
here is the code:
Wort = "parameter"
def number_of_vowels(Word):
result = 0
counter0 = 0
while result < 20:
if Word[counter0] == 'a' or 'e' or 'i' or 'o' or 'u':
result = result + 1
counter0 = counter0 + 1
else:
counter0 = counter0 + 1
return result
Words = []
counter1 = 0
def many_vowels(List , number):
if number_of_vowels(List[counter1]) < number:
counter1 + 1
else:
Words.append(List[counter1])
counter1 + 1
return Words
This code just gives me the answer to the letter a and not to the other vowels. For
print(number_of_vowels(Wort))
the output is: 1
but there are 4 vowels in this word
it also says: line 21, in many_vowels
IndexError: string index out of range
You're trying to call a function with wrong brackets. Function call should use round ones.
Try changing number_of_vowels[List[counter1]] with number_of_vowels(List[counter1])
This code contains some errors:
Calling for function should be using round brackets: number_of_vowels(List[counter1]) instead of number_of_vowels[List[counter1]]
doing result + 1 won't change value of the variable result, since you did not put the calculation result in the variable. use result = result + 1 (same for counters)
in number_of_vowels function, you want to scan the whole word? cause you did not use any loop, so it currently looking only at the first letter. Secondly, you put the compression in result and then add 1 to it. I'm not really sure why
edit:
Word = "parameter"
def number_of_vowels(Word):
result = 0
counter0 = 0
for index, letter in enumerate(Word):
if letter == 'a' or letter == 'e' or letter == 'i' or letter == 'o' or letter == 'u':
result = result + 1
return result
Words = []
counter1 = 0
def many_vowels(List_name , number):
for index, item in enumerate (List_name):
if number_of_vowels(item) >= number:
Words.append(item)
return Words

Statement has no effect(Python)

program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itself.
Sample String : 'restart'
Expected Result : 'resta$t'
here's my code
def change(string):
string_len = len(string)
t = string[0]
for each in range(1, string_len):
if each is t:
each == '$'
else:
continue
return string
print(change("restart"))
output
restart
i'using Pycharm. Line no 6 (each == '$')says this statement has no effect. i don't want to use replace method. just want to know what is the problem.
Your code commented:
def change(string):
string_len = len(string)
t = string[0]
for each in range(1, string_len):
if each is t: # To compara strings you should use the == operator not the 'is' operator.
each == '$' # This will not have any effect because is a temporal variable visible just inside the 'for' loop and you are not using it.
else:
continue
return string
print(change("restart"))
A solution could be:
def change(s):
result = ''
for character in s:
result += '$' if character == s[0] else character
return result
print(change('restart'))
Python strings are immutable objects, so you can't do 'aaa'[1] = 'b' to get aba.
each is set to an integer and you are comparing it to a string.

I tried to check if index was out of range, but the code I used is giving index out of range?

I built this function to change a string input into pig latin. I was trying to check if the index was out of range but my method of checking is yielding index out of range.
See as follows:
def simple_pig_latin(input, sep=' ', end='.'):
words=input.replace(" ", " ").split(sep)
new_sentence=""
Vowels= ('a','e','i','o','u')
Digit= (0,1,2,3,4,5,6,7,8,9)
cons=('b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z')
characters= ('!','#','#','$','%','^','&','*','.')
for word in words:
if word[0] == " ":
new_word=word
else:
if word[0] in Vowels:
new_word= word+"way"
if word[0] in Digit:
new_word= word
if word[0] in cons:
first_letter=word[0] #saves the first letter
change= str(word) #change to string
rem= change.replace(first_letter,'')
put_last= rem+first_letter #add letter to end
new_word= put_last+"ay"
if word[0] in characters:
new_word= word
new_sentence= new_sentence+new_word+sep
new_sentence= new_sentence.strip(sep)+end
return new_sentence
You can see the first if statement is checking if it is empty, but I'm getting this exact error:
"line 9 IndexError: string index out of range"
How else can I check for the empty sequence? I can't use for word in range(len(words)) because then none of my if statements work. It will tell me object is not subscriptable.
in your loop you assume that word is not empty, which is not guaranteed at all, because you're splitting according to space, and empty fields can be issued when there are more than 1 space.
>>> "a b".split(" ")
['a', '', 'b']
So you could use split() without any argument (works only for space-like chars) or if you're using some other separator, filter out empty fields before your loop, for instance in a list comprehension:
words= [ w for w in input.split(sep) if w ]
Now you're sure that each item of words has at least 1 character.
EDIT: so much for the nice explanation about split and filtering out empty strings, but that doesn't seem to cut it since you can use l as a separator for hello world, so back to basics:
def simple_pig_latin(input, sep=' ', end='.'):
words=input.split(sep)
new_sentence=""
Vowels= ('a','e','i','o','u')
Digit= (0,1,2,3,4,5,6,7,8,9)
cons=set(('b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z'))
characters= ('!','#','#','$','%','^','&','*','.')
new_sentence = []
for word in words:
if word:
if word[0] == " ":
new_word=word
else:
if word[0] in Vowels:
new_word= word+"way"
elif word[0] in Digit:
new_word= word
elif word[0] in cons:
first_letter=word[0] #saves the first letter
change= str(word) #change to string
rem= change.replace(first_letter,'')
put_last= rem+first_letter #add letter to end
new_word= put_last+"ay"
elif word[0] in characters:
new_word= word
new_sentence.append(new_word)
else:
new_sentence.append(word)
return sep.join(new_sentence)+end
changes to your code:
use a list, and join back using join in the end
just filters out empty word, but puts it in the list anyway
a lot of elif instead of if
using a set for consomns for faster lookup
now:
print(simple_pig_latin("hello world",sep='l'))
yields:
ehayllo worwaylday.

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

Resources