I am trying to write a program to change character if ch is found inside the string called st i will replace it with '!'
I wrote a program but for some reason this code can't replace one letter for example if i enter:
st = a
ch = a
I dont get an output of '!' instead i get 'a' but i dont want that i want it to be '!'
my code is
st = raw_input("String: ")
ch = raw_input("character: ")
def replace_char(st,ch):
if st.find(ch):
new = st.replace(ch,'!')
print new
return new
elif len(st)==len(ch):
if ch==st:
print"!"
else:
print st
else:
print st
return st
replace_char(st,ch)
Please help i dont get what i'm doing wrong or missing from my code
From the Python documentation:
find(s, sub[, start[, end]])¶
Return the lowest index in s where the substring sub is found such
that sub is wholly contained in s[start:end]. Return -1 on failure.
Defaults for start and end and interpretation of negative values is
the same as for slices.
It does not say anything about find() returning True or False. This is your problem.
For a substring search better use
if some_string in some_otherstring:
do_something()
st.find(ch) returns position where ch is in st not True/False. Because if == True is True in Python your program works in some cases... :)
Consider str == 'a' and ch == 'a', first condition fails, but second condition works only if str and ch has same length. I guess u have something else in your st or ch.
In my PC your program works except the case if searching ch is first in st, like following: st = 'afsdf' ch = 'a'.
Better solution is like follows:
st.replace(ch, '!')
It will work in all cases.
Related
I am trying to emulate a circumstance where i send information and only get a true or false as a return. So i can check each character and if it is true, that means that character is in the string. I would know there would be a position 0 to some number x. I would receive a true result and eventually only receive false result and then I would know the string has been solved. In my circumstance i would not know the target string.
I am trying to iterate through all characters and see if it matches the string character. if it does, I add the character to a list until the list contains all the characters of the string. but for some reason, this isn't working.
import string
hi = list()
swoll = "dkjfksjdfksjdkfjksdjfsjkdfjsjreuvnslei"
characters = string.ascii_lowercase + string.ascii_uppercase + string.digits
for ch in characters:
print(''.join(hi) + ch)
for i in swoll:
if i == ch:
hi.append(ch)
print(''.join(hi))
break
else:
continue
results:
a
b
c
d
d
de
de
def
def
defg
defh
defi
defi
defij
defij
defijk
defijk
defijkl
defijkl
defijklm
defijkln
defijkln
defijklno
defijklnp
defijklnq
defijklnr
defijklnr
defijklnrs
defijklnrs
defijklnrst
defijklnrsu
defijklnrsu
defijklnrsuv
defijklnrsuv
defijklnrsuvw
defijklnrsuvx
defijklnrsuvy
defijklnrsuvz
defijklnrsuvA
defijklnrsuvB
defijklnrsuvC
defijklnrsuvD
defijklnrsuvE
defijklnrsuvF
defijklnrsuvG
defijklnrsuvH
defijklnrsuvI
defijklnrsuvJ
defijklnrsuvK
defijklnrsuvL
defijklnrsuvM`
As you can see, it does not match the string
When I tried the code above, I was expecting the string to come out the same as the other string.
Based on my understanding of the question, I've implemented a function which I believe emulates the interface you are talking to:
spos = 0
def in_swoll(ch):
global spos
if spos == len(swoll) or ch != swoll[spos]:
return False
spos += 1
return True
This will return True and increment the counter into swoll when a character matches, otherwise it will return False.
You can then use this function in a loop which iterates until False is returned for all characters in characters. Inside the loop characters is iterated until a match is found, at which point it is added to hi:
hi = []
while True:
for ch in characters:
if in_swoll(ch):
hi.append(ch)
print(''.join(hi))
break
else:
# no matches, we're done
break
Output for your sample data:
d
dk
dkj
dkjf
dkjfk
dkjfks
dkjfksj
dkjfksjd
dkjfksjdf
dkjfksjdfk
dkjfksjdfks
dkjfksjdfksj
dkjfksjdfksjd
dkjfksjdfksjdk
dkjfksjdfksjdkf
dkjfksjdfksjdkfj
dkjfksjdfksjdkfjk
dkjfksjdfksjdkfjks
dkjfksjdfksjdkfjksd
dkjfksjdfksjdkfjksdj
dkjfksjdfksjdkfjksdjf
dkjfksjdfksjdkfjksdjfs
dkjfksjdfksjdkfjksdjfsj
dkjfksjdfksjdkfjksdjfsjk
dkjfksjdfksjdkfjksdjfsjkd
dkjfksjdfksjdkfjksdjfsjkdf
dkjfksjdfksjdkfjksdjfsjkdfj
dkjfksjdfksjdkfjksdjfsjkdfjs
dkjfksjdfksjdkfjksdjfsjkdfjsj
dkjfksjdfksjdkfjksdjfsjkdfjsjr
dkjfksjdfksjdkfjksdjfsjkdfjsjre
dkjfksjdfksjdkfjksdjfsjkdfjsjreu
dkjfksjdfksjdkfjksdjfsjkdfjsjreuv
dkjfksjdfksjdkfjksdjfsjkdfjsjreuvn
dkjfksjdfksjdkfjksdjfsjkdfjsjreuvns
dkjfksjdfksjdkfjksdjfsjkdfjsjreuvnsl
dkjfksjdfksjdkfjksdjfsjkdfjsjreuvnsle
dkjfksjdfksjdkfjksdjfsjkdfjsjreuvnslei
I am trying to create a function in Python which allows me to know if a string contains a letter "y" which appears in the beginning of a word and before a consonant. For example, the sentence "The word yes is correct but the word yntelligent is incorrect" contains the "y" of the word "yncorrect", so the function has to return True. In addition, it has to return true if the "y" is in capital letters and verifies those same conditions.
I have done it in the following way and it appears as if the program works but I was asked to use the method for strings in Python find and I havent't been able to include it. Any hint about how to do it using the method find? Thank you very much.
def function(string):
resultado=False
consonants1="bcdfghjklmnñpqrstvwxyz"
consonants2="BCDFGHJKLMNÑPQRSTVWXYZ"
for i in range(0,len(string)):
if string[i]=="y" and string[i-1]==" " and string[i+1] in consonants1:
resultado=True
break
if string[i]=="Y" and string[i-1]==" " and string[i+1] in consonants2:
resultado=True
break
return resultado
print(function("The word yes is correct but the word yntelligent is incorrect"))
Basically it is better to use re
consonants1="BCDFGHJKLMNÑPQRSTVWXYZ"
for i in consonants1:
if (a:= string.upper().find(f' Y{i}')) != -1:
print(...)
break
I think the function you want isn't find, but finditer from the package 're' (find will only give you the first instance of y, while finditer will return all instances of y)
import re
import string
consonants = string.ascii_lowercase
vowels = ['a', 'e', 'i', 'o', 'u']
for vowel in vowels:
consonants.remove(vowel)
def func(string):
for x in re.finditer('y', string.lower()):
if string[x.start() + 1] in consonants:
return True
return False
The function find returns the index at which the string first begins or is found. So, it returns the first index, else -1. This won't work for your use cases, unless you make it a bit more complicated.
Method One: Check every combination with find.
You have to two results, one to check if its the first word, or if its in any other word. Then return True if they hit. Otherwise return false
def function(string):
consonants1="bcdfghjklmnñpqrstvwxyz"
string = string.lower()
for c in consonants1:
result1 = string.find(" y" + c)
result2 = string.find("y" + c)
if result1 != 1 or result2 == 0:
return True
return False
Method Two: loop through find results.
You can use .find but it will be counter-intuitive. You can use .find and loop through each new substring excluding the past "y/Y", and do a check each time you find one. I would also convert the string to .lower() (convert to lowercase) so that you don't have to worry about case sensitivity.
def function(string):
consonants1="bcdfghjklmnñpqrstvwxyz"
string = string.lower()
start_index = 0
while start_index < len(string):
temp_string = string[start_index+1:end] ## add the 1 so that you don't include the past y
found_index = temp_string.find("y")
if found_index == -1: return False
og_index = start_index + found_index
## check to see if theres a " yConsonants1" combo or its the first word without space
if (string[og_index - 1] == " " and string[og_index+1] in consonants1) or (string[og_index+1] in consonants1 and og_index == 0):
return True
else:
start_index = og_index
return False
Here's how I would go about solving it:
Look up what the find function does. I found this resource online which says that find will return the index of the first occurrence of value (what's passed into the function. If one doesn't exist, it returns -1.
Since we're looking for combinations of y and any consonant, I'd just change the arrays of your consonants to be a list of all the combinations that I'm looking for:
# Note that each one of the strings has a space in the beginning so that
# it always appears in the start of the word
incorrect_strings = [" yb", " yc", ...]
But this won't quite work because it doesn't take into account all the permutations of lowercase and uppercase letters. However, there is a handy trick for handling lowercase vs. uppercase (making the entire string lowercase).
string = string.lower()
Now we just have to see if any of the incorrect strings appear in the string:
string = string.lower()
incorrect_strings = [" yb", " yc", ...]
for incorrect_string in incorrect_strings:
if string.find(incorrect_string) >= 0:
# We can early return here since it contains at least one incorrect string
return True
return False
To be honest, since you're only returning a True/False value, I'm not too sure why you need to use the find function. Doing if incorrect_string in string: would work better in this case.
EDIT
#Barmar mentioned that this wouldn't correctly check for the first word in the string. One way to get around this is to remove the " " from all the incorrect_strings. And then have the if case check for both incorrrect_string and f" {incorrect_string}"
string = string.lower()
incorrect_strings = ["yb", "yc", ...]
for incorrect_string in incorrect_strings:
if string.find(incorrect_string) >= 0 or string.find(f" {incorrect_string}"):
# We can early return here since it contains at least one incorrect string
return True
return False
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 work on a basic python program that is to find a substring of a string in python but the challenge was I can't use built functions or slicing.
MAINSTRING = raw_input('Enter a string : ')
print 'You entered %s' %MAINSTRING
isSubString = raw_input('Enter the substring : ')
print 'You entered %s' %isSubString
if isSubString in MAINSTRING:
print isSubString + " is a substring of " + MAINSTRING
It works but I can't use in syntax which is the frustrating part. I also know to use the slicing method in python but my challenge was to break it to the basics.
Sorry for being so vague, but I just got a hint.
The complete code consist of two 'for' loops, one for the string and one for the substring
To avoid anything other than for loops and a function you could do it like this although I have no idea why. Also you will have to use in which is pointed out in the comments. If a letter in the mainstring matches the first letter in the substring then add it to the temp string t, then go to the next letters in each and see if they match. If the temp string equals the substring then it exists and it will return.
def substring(ss, s):
x = 0
t = ""
for i in range(len(s)):
if s[i] == ss[x]:
t += ss[x]
if t == ss:
return s
x+=1
else:
x = 0
t = ""
I wrote the following program to determine whether a string s a palindrome using recursion. My problem is that I am not sure how to add a print statement that tells me whether the string is a palindrome or not. I realize that there are other codes which do the same thing, but I am trying to understand if my reasoning is correct.
import re
s= raw_input( " Enter a string to check if it is a palindrome ")
newstring = re.sub('\W', '', s)
newstring =newstring.lower()
def Palind(newstring):
if newstring[0] != newstring[-1]:
#print 'The given string is not a palindrome'
return False
else:
s_remain = newstring[1:-1]
if s_remain == '':
return True
elif len(s_remain) == 1 :
return True
else:
return Palind(s_remain)
if Palind(newstring):
print 'Yes'
else:
print 'No'
First, correctly indent your code, and properly lowercase the input:
import re
s= raw_input( " Enter a string to check if it is a palindrome ")
newstring = re.sub('\W', '', s)
newstring = newstring.lower()
def Palind(newstring):
if newstring[1] != newstring[-1]:
#print 'The given string is not a palindrome'
return False
else:
s_remain = newstring[1:-1]
return Palind(s_remain)
Then actually call your function and deal with the result:
if Palind(newstring):
print ('Yes')
else:
print ('No')
That's how you print the result of your function..
You will have problems when you enter a palindrome though, because you never actually return true. You'll need to fix that by checking if you've gotten to the end of the string without returning false.
Your logic is roughly right, but you are missing some things.
The first character in a string is string[0] not string[1], so you are comparing the wrong characters.
You need to call Palind() as well as defining it.
If you correct those problems, you are taking one letter off each side of the string each time, it gets shorter and shorter - the next interesting thing that happens is you either get down to a single character or you run out of characters. You should be looking for that state.