Create a new string out of the old string with python (1) - python

My function has three string parameters i.e. string, search, and replace. If the search parameter is an empty string, then the function is supposed to insert the replaceable parameter before the first parameter, in between each character of the old string, and after the last character of the old string. Here is what I have done so far:
def main():
s='I am going go'
x=""
y='aa'
print(rep_str(s,x,y))
def rep_str(s, x, y):
if x in s:
result = ''
i = 0
while i < len(s):
if s[i : i + len(x)] == x:
result += y
i += len(x)
else:
result += s[i]
i += 1
elif x not in s:
result= s
else:
if x=="":
result=y
for ch in s:
result+=(ch+y)
return result
main()
I developed each condition separately and put them altogether in the function when I got satisfactory result from them. My last else condition was working fine in a separate run but it is not working in the function module. I don't know what is the problem with the code.
I would appreciate, if someone could give me some pointers. Thanks
My output for the last else condition should be:
aaIaa aaaaamaa aagaaoaaiaanaagaa aagaaoaa

restructure you code:
if x=='':
pass
elif x in s:
pass
elif x not in s:
pass

Related

What's the role of string = "" in a program Python

i know the title may not be the best, as i'm not exactly how to explain my problem in short words. However i recently was looking at some codes online and i didn't get the reason why some code was used i tried looking on the internet but as i dont know what that part of the code is called ive no idea what to search up so you guys are my last hope.
In this function
def NumIntoChar(LineLis):
for n in LineLis:
string = "" # Here is what im not sure. why is this used here ?
for i in range(n):
string += '-'
print(string)
Im unsure why string = "" is used between the 2 for looks
another example is:
message = """SAHH""" # Add Code
message = message.upper()
keyShift = 1
encryptedMsg = ""
result = {}
while keyShift <= 26:
encryptedMsg = ""
for character in message:
if character.isalpha() is True:
x = ord(character) - 65
x += keyShift
x = x % 26
encryptedMsg += chr(x + 65)
else:
encryptedMsg += character
result[keyShift] = encryptedMsg
keyShift += 1
for r in result.keys():
print(r,result[r])
Here we see ' encryptedMsg = "" ' being used just like in the previous code.
Just below that line of code, you have this for loop:
for i in range(n):
string += '-'
The x += y operator is syntactic sugar for x = x + y. In order to use this operator, x must have a defined value first.
For the first iteration of the loop, string will essentially be assigned like this:
string = string + '-'
In order to avoid NameError being thrown, string first needs to be declared and assigned some value, which is what string = "" does. The expression in the first iteration of the loop then essentially becomes:
string = '' + '-'
Here you initialize a variable with empty string using var = ''.
It is commonly followed in scenarios where you have to iteratively concatenate content to form a bigger string. Your code starts with initializing the empty string and within the loop, content of the string is concatenated. For example:
my_str = ""
while repeat:
my_str += some_str
# Do some stuff
Other scenario in which you might need it is: when you have to set default value of string as empty, but based on some condition reset the content of string. For example:
my_name = ''
if user.is_logged_in():
my_name = user.name
Also read: Initialize a string variable in Python: “” or None?

Code is not validating: TypeError cannot concatenate 'str' and 'int' objects

While loops are new to me and I'm having trouble getting my code to validate.
Description
In this exercise your function will receive two parameters: a
string(long_word) and a character(char). Use a while loop to go
through all the letters in the string and build a new string made up
from those letters until you find the char. You may assume that each
string will contain the passed in character(char).
This is my code.
def letters_up_to_char(long_word, char):
new = ""
i = 0
while i != char:
for letter in long_word:
new += letter
i += 1
return new
Example output
letters_up_to_char('coderoxthesox', 'x') -> 'codero'
letters_up_to_char('abcdefghijklmnop', 'f') -> 'abcde'
When I go to run my code I get:
TypeError: cannot concatenate 'str' and 'int' objects
To get rid of TypeError: cannot concatenate 'str' and 'xyz' objects, just
cast the object being concatenated to a string. If your code was
string + num or string += num just cast num to string like so:
str(num)
BUT, your code won't return the desired output. See why below:
If I'm not mistaken, the code shouldn't compile because when new is defined, you don't close the double quotes. Or if you are using single quotes, change your code and your question to reflect your change.
When I ran your code and executed it, it went in an infinite loop, the beginner's worst enemy! In your code, the
for letter in long_word:
new += letter
Is the same as saying new += long_word, because you are just adding the individual characters instead of the whole string at one go.
Your code can then be rewritten as follows:
def letters_up_to_char(long_word, char):
new = ""
i = 0
while i != char:
new += long_word
i += 1
return new
Now it is clear what your code is doing. It's just adding the whole word to new each time the while loop is executed. And the while loop is executed till i != char. Since i is an int and char is a str, i != char is always true. Infinite loop in the making!
Your function should look like this:
def letters_up_to_char(long_word, char):
new = ""
i = 0
while i < len(long_word) and long_word[i] != char:
new += long_word[i]
i += 1
return new
Explanation:
Go through each character in long_word from the start (this can be more easily accomplished using a for...in loop, but I'm using a while loop as per your request) and till the current character != char, add that character to new.
This code returns the desired output for both your test cases.
Considering
You may assume that each string will contain the passed in
character(char).
not including the char:
def letters_up_to_char(long_word, char):
i=0
while long_word[i] != char:
i+=1
return long_word[:i]
including the char:
def letters_up_to_char(long_word, char):
i=0
while long_word[i] != char:
i+=1
return long_word[:i+1]
Though a more pythonic way is, i.e.:
def letters_up_to_char(long_word, char):
return long_word.partition(char)[0]
Suggest you to use http://docs.python.org/3/tutorial/index.html as a reference, when completing your assignments.
The "i" is int type which cannot be compared with a str type "char".
while i < len(long_word) and long_word[i] != char
There are a couple of ways similar to this to write this code. In your example, the while i != char line is going to result in a very long loop because it will loop until i == int(char), or possibly infinitely. I would write it with either a for or a while, as below:
def letters_while(long_word, char):
new = ""
i = 0
# A second condition is needed to prevent an infinite loop
# in the case that char is not in long_word
while long_word[i] != char and i < len(long_word):
new += letter
i += 1
return new
def letters_for(long_word, char):
new = ""
for letter in long_word:
if letter != char:
new += letter
return new
As a note, these are easy to understand examples, and a better way to do this would be
long_word.split(char)[0]

Replace a substring in a string with python

I am trying to replace every instance of a substring in a string using python. The following is the code that I have done and it is giving me some weird result.
def main():
s='IN GOING GO'
x='IN'
y='aa'
print(rep_str(s,x,y))
def rep_str(s,x,y):
result=""
if x in s:
for i in range(len(s)):
if s[i:i+len(x)] == x:
result=result+y
else:
result=result+s[i+1:i+len(x)]
return result
main()
I am not allowed to use the replace method. In fact, my function is supposed to do what replace function does in python. The following is the output that I am getting.
aa GOIaaG GO
I would appreciate if someone could give me some input about how to change the logic to get the right out put i.e.
aa GOaaG GO.
As I mentioned in comments, the mistake is that you are not skipping len(x) characters after match. Also in keyword is quite high-level routine (it does not less than search part of search & replace), so here is fixed version without in:
def rep_str(string, search, replacement):
result = ''
i = 0
while i < len(string):
if string[i : i + len(search)] == search:
result += replacement
i += len(search)
else:
result += string[i]
i += 1
return result
If you just want to have the result try with:
import re
re.sub(r'IN','aa','IN GOING GO')
but if you need some logic then you should compare for blocks of same length as the pattern, not char by char
#Zag asnwer is better, because can compare longer patterns and has return when it does not match nothing but if you want to get your code running you need to skip for when you have a match like this :
def rep_str(s,x,y):
result=""
skip = False
if x in s:
for i in range(len(s)):
if skip:
skip = False
continue
if s[i:i+2] == x:
result+=y
skip = True
else:
result+=s[i:i+1]
return result
else:
return s
but your code won't work when you will call the function with rep_str("A example test","test", "function") for example.
If you are allow to use the index() function, you can try this:
def main():
s='IN GOING GO'
x='IN'
y='aa'
print(rep_str(s,x,y))
def rep_str(s,x,y):
while x in s:
s = s[:s.index(x)] + y + s[s.index(x) + len(x):]
return s
main()

What did I do wrong with this function?

I don't know what I did - it's wrong .
Can someone help me?
def insert_sequence(dna1, dna2, number):
'''(str, str, int) -> str
Return the DNA sequence obtained by inserting the second DNA sequence
at the given index. (You can assume that the index is valid.)
>>> insert_sequence('CCGG', 'AT', 2)
'CCATGG'
>>> insert_sequence('TTGC', 'GG', 2)
'TTGGGC'
'''
index = 0
result = '';
for string in dna1:
if index == number:
result = result + dna2
result = result + string
index += 1
print(result)
Here's a solution:
def insert_sequence(dna1, dna2, number):
'''(str, str, int) -> str
Return the DNA sequence obtained by inserting the second DNA sequence
at the given index. (You can assume that the index is valid.)
>>> insert_sequence('CCGG', 'AT', 2)
'CCATGG'
>>> insert_sequence('TTGC', 'GG', 2)
'TTGGGC'
'''
return dna1[:number] + dna2 + dna1[number:]
you needed an if-else loop here :
def insert_sequence(dna1, dna2, number):
result = '';
#you can use enumerate() to keep track of index you're on
for ind,x in enumerate(dna1):
if ind == number: #if index is equal to number then do this
result = result + dna2 +x
else: #otherwise do this
result = result + x
print(result)
insert_sequence('CCGG', 'AT', 2)
insert_sequence('TTGC', 'GG', 2)
output:
CCATGG
TTGGGC
There are already right working functions in other answers (specially the comment from Rakesh Pandit and the answer from JeffS), but your actual question is "why my original function doesn't work".
I copied a working version of your function, comments below:
def insert_sequence(dna1, dna2, number):
index = 0
result = ''
for character in dna1:
if index == number:
result = result + dna2
result = result + character
index += 1
print(result)
Python considers indentation, so you should print only at the end of things, outside loops and ifs.
When you "increase" your result, you do this only inside the "if" on your function, when actually you should increase "for every character in dna1", and only when/"if index == number" you should put the middle string inside.
I believe you are very new to Python or to programming in general, being probably from a biological background, but you really shouldn't iterate to get this type of string operation done, as others have shown.
Hope this helps!
You're never splitting the string apart, so you'll always prepend dna2 to dna1.
You probably want to return dna1[:number] + dna2 + dna1[number:]
You do nothing if the index is not at the insertion point, including incrementing the index. Your code needs an else and you are also printing prematurely:
def insert_sequence(dna1, dna2, number):
index = 0
result = '';
for char in dna1:
if index == number:
result = result + dna2
result = result + char
index += len(dna2) + 1
else:
result = result + char
index += 1
print(result)
mistakes made: a) parameter index is initialised to 0. b) "for sting in dia1:" should have been "for dia1_position in range(len(dia1)):" c) print result indentation is wrong and function isn't just supposed to print. It should return result. d) index need not be incremented now.
Answers are already there. Above briefly lists the mistakes made. I guess you didn't see any error because you never called the function. First error should be "number" not defined (not any more as question has been updated and parameter has number defined).

Exercise 7.9 in "How to Think Like a Computer Scientist (python)" measuring occurrences of a character in a string

The question is how to write a program that measures how many times a character appears in a string in a generalizable way in python.
The code that I wrote:
def countLetters(str, ch):
count=0
index=0
for ch in str:
if ch==str[index]:
count=count+1
index=index+1
print count
when I use this function, it measures the length of the string instead of how many times the character occurs in the string. What did I do wrong? What is the right way to write this code?
You are over-writing your 'ch' variable:
def countLetters(str, ch):
# ^ the character you are looking for
count=0
index=0
for ch in str:
# ^ the string character you are trying to check
if ch==str[index]: # ???
count=count+1
index=index+1
print count
(also, it is usually more useful to return the value than to just print it).
The built-in method is str.count:
"aaabb".count("a") -> 3
How you could rewrite your code:
def countLetters(search_in, search_for):
count = 0
for s in search_in: # iterate by string char, not by index
if s==search_for:
count += 1
return count
and a quick pythonic replacement:
def countLetters(search_in, search_for):
return sum(1 for s in search_in if s==search_for)
Think logically about what happens when you run your code: since the test in the loop succeeds on the first iteration, it is guaranteed to succeed every time! You are simply checking that iteration in Python works.
The correct formulation is
def count(s, input):
count = 0
for c in s:
if c == input:
count += 1
Or, equivalently,
def count(input):
return sum(c == input for c in s)
But you could just as well do:
s.count(c)
Your loop is wrong.
This should work:
for s in str:
if ch == s:
...
this way index variable will not be used and you can remove it. If you want to use index then change for into:
for index in range(len(str)):
... (rest is OK but ...)
... (do not increase index in loop body)
You can also increment variable by += operator like:
cnt += 1
So finished code will look like:
def countLetters(str, ch):
count = 0
for s in str:
if ch == s:
count += 1
print count
Completely untested:
def count_letters(s, c):
return sum(1 for x in s if x == c)

Categories

Resources