Input : UserID/ContactNumber
Output: user-id/contact-number
I have tried the following code:
s ="UserID/ContactNumber"
list = [x for x in s]
for char in list:
if char != list[0] and char.isupper():
list[list.index(char)] = '-' + char
fin_list=''.join((list))
print(fin_list.lower())
but the output i got is:
user-i-d/-contact-number
You could use a regular expression with a positive lookbehind assertion:
>>> import re
>>> s ="UserID/ContactNumber"
>>> re.sub('(?<=[a-z])([A-Z])', r'-\1', s).lower()
'user-id/contact-number'
What about something like that:
s ="UserID/ContactNumber"
so = ''
for counter, char in enumerate(s):
if counter == 0:
so = char
elif char.isupper() and not (s[counter - 1].isupper() or s[counter - 1] == "/"):
so += '-' + char
else:
so += char
print(so.lower())
What did I change from your snippet?
You were checking if this is the first char and if it is a upper char.
I have add a check on the previous char, to not consider when the previous is upper (for the D of ID) or when the previous is \ for the C of Contact.
You are also editing the list list while iterating on it's element, that is dangerous.
I have instead create an output string to store the new values
I did something like this
s ="UserID/ContactNumber"
new = []
words = s.split("/")
for word in words:
new_word = ""
prev = None
for i in range(0, len(word)):
if prev is not None and word[i].isupper() and word[i-1].islower():
new_word = new_word + "-" + word[i]
prev = word[i]
continue
new_word = new_word + word[i]
prev = word[i]
new.append(new_word.lower())
print "/".join(new)
user-id/contact-number
Related
I'm trying to add the letter 'X' before each vowel in a string or sentence, however, when there is a repeated vowel, the letter 'X' should only be written once. For example, the word 'speeding' should look like this 'spXeedXing' but i'm getting 'spXeXedXing'.
I know why I'm getting this problem but don't know where to go from here to make it work.
Code below
def vowels(string):
newString = ""
for letter in string:
if letter in "aeiou":
newString += "X" + letter
else:
newString += letter
print(newString)
if __name__ == "__main__":
vowels("speeding")
>>> import re
>>> re.sub('([aeiou]+)','X\g<1>','speeding')
'spXeedXing'
>>>
You should create a new variable to track the previous letter in string. Check if the letters are continuous and only add X if the previous char is not the same as the current char.
def vowels(string):
newString = ""
i = 0 # Create a counter variable
for letter in string:
if (letter in "aeiou" and letter != string[i-1]) or (letter in "aeiou" and i == 0 and letter == string[i-1]): # Change this condition.
i += 1
newString += "X" + letter
else:
newString += letter
i += 1 # Increment counter variable
print(newString)
if __name__ == "__main__":
vowels("speeding")
Output:
spXeedXing
Other test cases:
vowels("oompaloompas")
XoompXalXoompXas
vowels("eerie")
XeerXiXe
You can let a regex do all the state-machine hard work...
To prepend 'X' to any number of consecutive vowels:
import re
s = 'speeding'
>>> re.sub(r'([aeiou]+)', r'X\1', s)
'spXeedXing'
To prepend 'X' only to the same repeating vowel:
s = 'speeding'
>>> re.sub(r'(([aeiou])\2*)', r'X\1', s)
'spXeedXing'
s = 'toaster'
>>> re.sub(r'(([aeiou])\2*)', r'X\1', s)
'tXoXastXer'
Here is a simple non-regex version:
def vowels(word):
new_word = ""
prev = "" # no previous letter at first
for letter in word:
if letter in "aeiou" and letter != prev:
new_word += "X" + letter
else:
new_word += letter
prev = letter # keep to avoid insertion for repeats
return new_word
if __name__ == "__main__":
print(vowels("speeding"))
print(vowels("eerie"))
print(vowels("aaaaaaaaaaaaaargh"))
producing
spXeedXing
XeerXiXe
Xaaaaaaaaaaaaaargh
you should try checking the previous letter in the string to see if it is the same letter as the current index
def vowels(string):
newString = ""
for i in range(len(string)):
if string[i] in "aeiou":
if string[i - 1] == string[i]:
newString += string[i]
else:
newString += "X" + string[i]
else:
newString += string[i]
print(newString)
I have written a program to find the duplicate character of a string, as below:
string = "India";
print("Duplicate characters in a given string: ");
#Counts each character present in the string
for i in range(0, len(string)):
count = 1;
for j in range(i+1, len(string)):
if(string[i] == string[j] and string[i] != ' '):
count = count + 1;
#Set string[j] to 0 to avoid printing visited character
string = string[:j] + '0' + string[j+1:];
#A character is considered as duplicate if count is greater than 1
if(count > 1 and string[i] != '0'):
print(string[i]);
But thats not it I just want to increase the duplicate character by putting one extra occurence of that character.
For Example:
input : "India"(Here Duplicate Character is 'i')
output : "IIndiia"(Increase one occurrence of the duplicate character)
Can any one help me in solving this?
Collect all counts in one go, and do so case-insensitively:
from collections import Counter
string = "India"
c = Counter(string.lower())
"".join(x * (1 + (c[x.lower()] > 1)) for x in string)
'IIndiia'
One easy way is to use standard python string methods:
line = "some string"
result = ""
for letter in line:
result = result + letter
if line.upper().count(letter.upper()) > 1:
result = result + letter
does anyone know how to translate robber's languge to English in python?
like this one but in reverse?
def translate(s):
consonants = 'bcdfghjklmnpqrstvwxz'
return ''.join(a + 'o' + a if a in consonants else a for a in s)
print(translate("hej"))
Maybe something like:
def translate(s):
consonants = 'bcdfghjklmnpqrstvwxz'
counter = 0
outputcounter = 0
output = s
while counter < len(s):
char = s[counter]
if char in consonants:
output = output[:outputcounter] + char + output[outputcounter + 3:]
counter += 3
outputcounter += 1
else:
counter += 1
outputcounter += 1
return output
Try it out! (I don't know if that's nice code style, but however)
Here is an alternative approach
Since this is an interesting problem, I decided to have a go myself. Here is an efficient way of writing your first function with O(1) set lookup:
def translate_english_robber(s):
consonants = 'bcdfghjklmnpqrstvwxz'
# using a set instead is more efficient
lookup = set(consonants + consonants.upper())
result = ""
for char in s:
if char in lookup:
# anonymous function for converting the case of the letter "o"
convert_case = lambda x: "o" if x.islower() else "O"
# add it to the result
result += char + convert_case(char) + char
else:
result += char
return result
Then for the reverse translation, all you need to do is find a consonant, and append it to the list, then somehow remove the next 2 characters, and continue the next iteration after the last removed character. Otherwise, if the current character is not a constant, add it normally.
For example, If my Robbers language was "hohey", I would first find "h", add it, and remove "o" and "h" after that, then start iterating from "e". In the end, we would have "hey" as the English translation.
Using an iterator would be useful here. You can also read up on iterators here, they are quite useful for problems like this.
Here is my attempt:
def translate_robber_english(s):
consonants = 'bcdfghjklmnpqrstvwxz'
lookup = set(consonants + consonants.upper())
# create the iterator
it = iter(list(s))
result = ""
# loop till we reach the end
while True:
try:
# get the current letter
current = next(it)
# add it regardless
result += current
# if consonant, skip the next to letters
if current in lookup:
next(it)
next(it)
# If this exception occurs, break out of the loop
except StopIteration:
break
return result
And now you can get the reverse translations with both the above functions:
>>> robber = translate_english_robber("black")
>>> print(robber)
boblolacockok
>>> english = translate_robber_english(robber)
>>> print(english)
black
You can try something like this:
def reverse_translate(s):
vowel = ['a', 'e', 'i', 'o', 'u']
final = []
for i in range(len(s)):
if s[i] in vowel:
final.append(s[i])
else:
try:
if s[i] == s[i + 2]:
final.append(s[i:i + 3])
except IndexError:
pass
for j, i in enumerate(final):
if i == 'o':
try:
if final[j] == final[j + 1]:
pass
else:
del final[j]
except IndexError:
del final[j]
return "".join(list(map(lambda x: x[0], final)))
Now test_cases:
Normal test_case:
print(reverse_translate('boblolacockok'))
output:
black
But if text also include 'o' as vowel now :
print(reverse_translate('boblolocockok'))
output:
block
I need to convert a string word where each character that appears only once should be appear as '(' in the new string. Any duplicate characters in the original string should be replaced with ')'.
My code below...
def duplicate_encode(word):
new_word = ''
for char in word:
if len(char) > 1:
new_word += ')'
else:
new_word += '('
return new_word
The test I'm not passing is as follows:
'((((((' should equal '()()()'
This would suggest that, if for example, the input is "recede," the output should read ()()().
Your Code is Good just need some alteration it will be great.
def duplicate_encode(word):
"""
To replace the duplicate letter with ")" in a string.
if given letter is unique it replaced with "("
"""
word_dict = {} # initialize a dictionary
new_word = ""
for i in set(word): # this loop is used to count duplicate words
word_count = word.count(i)
word_dict[i] = word_count # add letter and count of the letter to dictionary
for i in word:
if word_dict[i] > 1:
new_word += ")"
else:
new_word += "("
print new_word
duplicate_encode("recede")
I think you got the answer :)
Just because (it's late and) it's possible:
def duplicate_encode(word):
return (lambda w: ''.join(('(', ')')[c in w[:i] + w[i+1:]] for i, c in enumerate(w)))(word.lower())
print(duplicate_encode("rEcede"))
OUTPUT
> python3 test.py
()()()
>
Seems like your result is based on the number of occurrences of a character in the word, you can use Counter to keep track of that:
def duplicate_encode(word):
from collections import Counter
word = word.lower() # to disregard case
counter = Counter(word)
new_word = ''
for char in word:
if counter[char] > 1: # if the character appears more than once in the word
# translate it to )
new_word += ')'
else:
new_word += '('
return new_word
duplicate_encode('recede')
# '()()()'
How can I remove duplicate characters from a string using Python? For example, let's say I have a string:
foo = "SSYYNNOOPPSSIISS"
How can I make the string:
foo = SYNOPSIS
I'm new to python and What I have tired and it's working. I knew there is smart and best way to do this.. and only experience can show this..
def RemoveDupliChar(Word):
NewWord = " "
index = 0
for char in Word:
if char != NewWord[index]:
NewWord += char
index += 1
print(NewWord.strip())
NOTE: Order is important and this question is not similar to this one.
Using itertools.groupby:
>>> foo = "SSYYNNOOPPSSIISS"
>>> import itertools
>>> ''.join(ch for ch, _ in itertools.groupby(foo))
'SYNOPSIS'
This is a solution without importing itertools:
foo = "SSYYNNOOPPSSIISS"
''.join([foo[i] for i in range(len(foo)-1) if foo[i+1]!= foo[i]]+[foo[-1]])
Out[1]: 'SYNOPSIS'
But it is slower than the others method!
How about this:
oldstring = 'SSSYYYNNNOOOOOPPPSSSIIISSS'
newstring = oldstring[0]
for char in oldstring[1:]:
if char != newstring[-1]:
newstring += char
def remove_duplicates(astring):
if isinstance(astring,str) :
#the first approach will be to use set so we will convert string to set and then convert back set to string and compare the lenght of the 2
newstring = astring[0]
for char in astring[1:]:
if char not in newstring:
newstring += char
return newstring,len(astring)-len(newstring)
else:
raise TypeError("only deal with alpha strings")
I've discover that solution with itertools and with list comprehesion even the solution when we compare the char to the last element of the list doesn't works
def removeDuplicate(s):
if (len(s)) < 2:
return s
result = []
for i in s:
if i not in result:
result.append(i)
return ''.join(result)
How about
foo = "SSYYNNOOPPSSIISS"
def rm_dup(input_str):
newstring = foo[0]
for i in xrange(len(input_str)):
if newstring[(len(newstring) - 1 )] != input_str[i]:
newstring += input_str[i]
else:
pass
return newstring
print rm_dup(foo)
You can try this:
string1 = "example1122334455"
string2 = "hello there"
def duplicate(string):
temp = ''
for i in string:
if i not in temp:
temp += i
return temp;
print(duplicate(string1))
print(duplicate(string2))