Consider a text file and 2 lists. In list_A there are some letters and in list_B some other letters. I want an algorithm to find the letters in the text which exist in list_A, and replaces them with letters with the same index from list_B. It finds and replaces them, but, each time it replaces it the previous result disappears.
I mean at last, I have the result of the last replacement in the print. How can I solve this problem? I mean I want a print in which all the letters are replaced, not just the last one.
what could be the problem with this loop:
for i in text:
if i in list_A:
p=text.replace(i, list_B[list_A.index(i)])
print(p)
With this line:
p=text.replace(i, list_B[list_A.index(i)])
Each time through the loop you're taking text and assigning a new version of it to p, but you're never updating text to contain the new copy (Which you probably shouldn't do, as you're iterating over it).
I'd start by making p a copy of text outside the loop, and inside, doing p = p.replace(...
Bear in mind that with the method you've chosen, you also have to worry about multiple replacements and the order in which you're checking. For example, if you are replacing all a with b, and also wanting to replace all b with c, then using your method if you start with aaaa you will end up with cccc (because it replaces them all with b, then checks for b...) , when you might have only wanted to replace the a if it was in the original string. If you're worried about that, I'd look at maketrans and translate as mentioned by bereal in a comment.
This should work.
temp = text
for i in temp:
if i in list_A:
temp=temp.replace(i, list_B[list_A.index(i)])
print "Original:",text
print "Modified: ",temp
Related
Challenge: Take 2 strings s1 and s2 including only letters from a to z. Return a new sorted string, the longest possible, containing distinct letters - each taken only once - coming from s1 or s2.
# Examples
a = "xyaabbbccccdefww"
b = "xxxxyyyyabklmopq"
assert longest(a, b) == "abcdefklmopqwxy"
a = "abcdefghijklmnopqrstuvwxyz"
assert longest(a, a) == "abcdefghijklmnopqrstuvwxyz"
So I am just starting to learn, but so far I have this:
def longest(a1, a2):
for letter in max(a1, a2):
return ''.join(sorted(a1+a2))
which returns all the letters but I am trying to filter out the duplicates.
This is my first time on stack overflow so please forgive anything I did wrong. I am trying to figure all this out.
I also do not know how to indent in the code section if anyone could help with that.
You have two options here. The first is the answer you want and the second is an alternative method
To filter out duplicates, you can make a blank string, and then go through the returned string. For each character, if the character is already in the string, move onto the next otherwise add it
out = ""
for i in returned_string:
if i not in out:
out += i
return out
This would be empedded inside a function
The second option you have is to use Pythons sets. For what you want to do you can consider them as lists with no dulicate elements in them. You could simplify your function to
def longest(a: str, b: str):
return "".join(set(a).union(set(b)))
This makes a set from all the characters in a, and then another one with all the characters in b. It then "joins" them together (union) and you get another set. You can them join all the characters together in this final set to get your string. Hope this helps
I was working on one problem while I encountered this problem. Let me explain through a simple example:
a = ['hello', 'world']
print(a.count('hello')) #prints 1 correctly
But...
a = "hello world"
for i in a.split():
print(a.count(i))
#prints
#2 -> for 'hello' which is wrong, one more than actual value
#1 -> counts of elements from 2nd onwards are correct
If I split it before, it works perfectly:
a = 'hello world'
a = a.split()
for i in a:
print(a.count(i))
#correctly prints
1
1
So I think the issue only happens when I use the split method directly in the for loop, but I'm not sure why.
Edit:
I rechecked it, and its printing wrong values for long statements, specifically for this one. Please check using this statement below:
"how many times does each word show up in this sentence word times each each word"
Edit 2:
Even though I was splitting the string in for loop directly, it did't change the original string and I was using count method on original string inside the for loop, which caused the error and the 'how' to show up two times.
Thanks to the user Bobby, for correctly pointing out.
It's works fine on my machine with Python 3.10.0.
I get 1s in every example.
Please provide more info like Python version, maybe we'll get the reason why it works like that on your machine.
In your first example a has never been updated. Even in the for loop, you split a but that didn't update a. You can verify this directly:
a = "hello world"
for i in a.split():
print(a)
print(a.count(i))
If you want the split string you need to save that to a variable like you did in the first example. You can do this within the for loop if you want:
a = "hello world"
for i in b:=a.split():
print(b.count(i))
count counts how many times the argument is found in a list. So for your first example:
a = ['hello', 'world']
print(a.count('hello'))
Hello is only in the list once.
a = ['hello', 'hello', 'world', 'hello', 'world']
print(a.count('hello')
Would return 3.
The function count when used on a string iterates the entire string for any match. It doesn't care about "words".
"abc".count("ab") # 1
From the docs:
str.count(sub[, start[, end]])
Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.
In your first example you use count on the string.
When used on lists however, it does not do partial matchign between the items:
["a", "b", "c"].count("ab") # 0
From the docs:
list.count(x)
Return the number of times x appears in the list.
This is what you do in your second example. You use count on a list. This happens because str.split returns a list.
So these are two different count methods you're using. One for strings (first example - a is a string) and one for lists (second example - a is a list returned from str.split).
Is there a function that replaces element in a list in python
like
given_list=['_','_','_','_',]
now i want to replace the '_' with a letter.
does such function exist. if not, how can i do it
I am pretty sure there so no function for doing this with a list/array but you can use the following code (I am not good with python so my code might not be that good):
given_list = ['_','_','_']
for item in given_list:
if item=='_':
given_list[given_list.index(item)] = 'a'
print(given_list)
output:
['a','a','a']
You can do this task using for loop. Iterate the list, check for every element if it is "_". If yes, repace it with the letter. Your code:
given_list=['_','_','_','_',]
letter="some_letter"
for i in range(0,len(given_list)):
if given_list[i]=="_":
given_list[i]=letter
print(given_list)
Replace the "some_letter" with the actual letter you want
Write a function that takes, as an argument, a list, identified by the variable aList. If the list only contains elements containing digits (either as strings as integers), return the string formed by concatenating all of the elements in the list (see the example that follows). Otherwise, return a string indicating the length of the list, as specified in the examples that follow.
I am just starting to learn how to code and this is my first CS class.
def amIDigits(aList):
for element in range(aList):
if element in aList.isdigit():
bList=[]
bList.append(aList)
return str(bList)
amIDigits([“hello”, 23]) should return the string “The length of the input is 2.”
amIDigits ([“10”, “111”]) should return the string “10111”
If I understand it right the output will be the joined digits even if they are not of the string format. So the best way is to use the all function (returns true if all elements of an iteration are true) and check if the string elements of the list are digits. If so, then return the join of all elements of the list converted to a string. Else, we return the length of the list using the new string formatting syntax (f represents string formatting and the {} return the result of an operation).
code:
def amIDigits(aList):
if all([str(i).isdigit() for i in aList]):
return ''.join(map(str,aList))
else:
return f'The length of the input is {len(aList)}.'
print(amIDigits(['hello', 23]))
print(amIDigits(['10', '111']))
print(amIDigits([55, 33]))
output:
The length of the input is 2.
10111
5533
First, I highly recommend having someone literally sit down and have you walk them through your thought process. It is more useful as a learner to debug your thought process than to have someone give you the answer.
One thing I noticed is that you created your empty list, bList, inside the for block. This will not work. You need to create an empty list to store things into before you begin for looping through the old list, otherwise you will be over-writing your new list every time it loops. So right now, your bList.append() statement is appending an element onto an empty list every time it runs. (You will get only the very last element in the aList stored into your bList.)
Another problem is that you use the range() function, but you don't need to. You want to look at each element inside the list. Range creates a sequence of numbers from 0 to whatever number is inside the parentheses: range() documentation. Your code tries to pass a list into range(), so it is invalid.
The "for blank in blank" statement breaks up whatever list is in the second blank and goes through each of its elements one at a time. For the duration of the for statement, the first blank is the name of the variable that refers to the element being looked at. so for example:
apples = ["Granny Smith","Red Delicious","Green"]
for apple in apples:
eat(apple) #yum!
The for in statement is more naturally spoken as "for each blank in blank:"
I just want to ask if how should I pop certain elements inside the list.
Let's say I have this list:
c = ['123','456','789']
When I type this:
print c[0][0]
It prints a value '1',
And somehow I want to delete the first element of the first value.
So that the output will be:
c = ['23','456','789']
But I have a problem in using pop().
I tried this but no luck:
c.pop(0, 0) # takes only one argument
Or
c[0].pop(0) # string doesn't have an attribute pop
Is there a way to solve my dilemma?
If this problem has a duplicate, please let me know.
Strings are immutable. As such, they can't be modified once created.
If all you want to do is "remove" the first character of the first string in the list c you can use slicing (that returns a new string):
c[0] = c[0][1:]
Read more on slicing here: Explain Python's slice notation