The instructions are to replace certain characters within a string to the corresponding value in the dictionary.
Here is my code:
word = input()
password = ''
wordDict = {
'i': '!',
'a': '#',
'm': 'M',
'B': '8',
'o': '.',
}
for i in range(len(word)):
if word[i] in wordDict.keys():
word.replace(word[i], wordDict.get(word[i]))
i += 1
else:
i += 1
print(word)
The problem with my code is that nothing about the given password is changing nor does it seem to be iterating through the for loop.
Your problem is with this line:
word.replace(word[i], wordDict.get(word[i]))
Strings in Python, as well as many other languages, are immutable, meaning you can't edit the string.
The function you're calling (str.replace) doesn't replace the character in the string, it returns a new str with the character replaced.
The easiest, though naive if you want this to work efficiently, solution is to replace it with this line:
word = word.replace(word[i], wordDict.get(word[i]))
Related
I want to create a list given a string such as 'b123+xyz=1+z1$' so that the list equals ['b123', '+', 'xyz', '=', '1', '+', 'z1', '$']
Without spaces or a single repeating pattern, I do not know how to split the string into a list.
I tried creating if statements in a for loop to append the string when it reaches a character that is not a digit or letter through isdigit and isalpha but could not differentiate between variables and digits.
You can use a regular expression to split your string. This works by using positive lookaheads and look behinds for none word chars.
import re
sample = "b123+xyz=1+z1$"
split_sample = re.split("(?=\W)|(?:(?<=\W)(?!$))", sample)
print(split_sample)
OUTPUT
['b123', '+', 'xyz', '=', '1', '+', 'z1', '$']
REGEX EXPLAIN
Another regex approach giving the same result is:
split_sample = re.split(r"(\+|=|\$)", sample)[:-1]
The [:-1] is to remove the final empty string.
"""
Given the equation b123+xyz=1+z1$, break it down
into a list of variables and operators
"""
operators = ['+', '-', '/', '*', '=']
equation = 'b123+xyz=1+z1$'
equation_by_variable_and_operator = []
text = ''
for character in equation:
if character not in operators:
text = text + character
elif character in operators and len(text):
equation_by_variable_and_operator.append(text)
equation_by_variable_and_operator.append(character)
text = ''
# For the final variable
equation_by_variable_and_operator.append(text)
print(equation_by_variable_and_operator)
Output
['b123', '+', 'xyz', '=', '1', '+', 'z1$']
A straight-forward regex solution is;
equation = "b123+xyz=1+z1$"
equation_list = re.findall(r'\W+|\w+', equation)
print(equation_list)
This would also work with strings such as -b**10.
Using re.split() returns empty strings at the start and end of the string from the delimiters at the start and end of the string (see this question). To remove them, they can be filtered out, or otherwise look-behind or look-ahead conditions can be used which add to the pattern's complexity, as earlier answers to this question demonstrate.
Well my answer seems to not be the easiest among them all but i hope it helps you.
data: str = "b123+xyz=1+z1$"
symbols: str = "+=$"
merge_text: str = ""
for char in data:
if char not in symbols:
merge_text += char
else:
# insert a unique character for splitting
merge_text += ","
merge_text += char
merge_text += ","
final_result: list = merge_text.split(",")
So in the following program I have comes up with something that isn't working the way I want, and I need help figuring this out.
The first input takes a string
"Joe,123-5432 Linda,983-4123 Frank,867-5309"
It first replaces commas with white space, and converts it into list.
['Joe', '123-5432', 'Linda', '983-4123', 'Frank', '867-5309']
However, I want to convert this list into a dictionary using the first entry as the key, and the second entry as the value. So it would look like this:
{'Joe':'123-5432', 'Linda':'983-4123', 'Frank':'867-5309'}
This is where I find my problem (within the function). When I call it into the function it broke it up by individual characters, rather than seeing the .splits as a whole string, which looks like this...
{'J': 'o', 'e': ' ', '1': '2', '3': ' ', '5': '3', ' ': '9', 'i': 'n', 'd': 'a', '8': '6', '-': '4', 'F': 'r', 'a': 'n', 'k': ' ', '7': '-', '0': '9'}
Which ya know is funny, but not my target here.
Later in the program, when Ecall gets an input, it cross references the list and pulls the phone number from the dictionary. Can you help me build a better comprehension for Pdict in the function that does this and not whatever I did?
def Convert(FormatInput):
Pdict = {FormatInput[i]: FormatInput[i + 1] for i in range(0, len(FormatInput), 2)}
return Pdict
user_input = input()
FormatInput=user_input.replace(",", " ")
Pdict=Convert(FormatInput)
Ecall = (input())
print(Pdict.get(Ecall, 'N/A'))
Use two different split operations instead of doing the replace to try to do it in a single split (which just makes things more difficult because now you've lost the information of which separator was which).
First split the original string (on whitespace) to produce a list of comma-separated entries:
>>> user_input = "Joe,123-5432 Linda,983-4123 Frank,867-5309"
>>> user_input.split()
['Joe,123-5432', 'Linda,983-4123', 'Frank,867-5309']
and then split on the commas within each entry so you have a sequence of pairs that you can pass to dict(). You can do the whole thing in one easy line:
>>> dict(entry.split(",") for entry in user_input.split())
{'Joe': '123-5432', 'Linda': '983-4123', 'Frank': '867-5309'}
Hi working on a sort of morse-code problem where a user would input a string in a format like this
pattern = ['.', '.', '_', '.', '_', '.']
and the code would print out the resulting word for each like so:
"dot-dot-dash-dot-dash-dot"
I've tried this:
def ss(pattern):
dotdash = ""
for s in pattern:
if s == ".":
dotdash+=("dot")
elif s == "_":
dotdash+=("dash")
x = "-".join(dotdash)
print(x)
ss(['.', '.', '_', '.', '_', '.'])
but that's just giving me output like this:
d-o-t-d-o-t-d-a-s-h-d-o-t-d-a-s-h-d-o-t
looking for a solution to separate those dots and dashes with a hyphen--just a bit stumped. thinking maybe to split--based on the words--but just unsure how to accomplish that. any help is hugely appreciated.
You could add the hyphens first with join, which gives you a string, and then apply two replacements to get the final string:
def ss(pattern):
return '-'.join(pattern).replace('.', 'dot').replace('_', 'dash')
print(ss(['.', '.', '_', '.', '_', '.'])) // dot-dot-dash-dot-dash-dot
What you are passing to the join() function is a string, so it will iterate through every letter in the string, that's why you are getting this output. What you really want to do is use a list, so that join() iterates through every word in the list:
...
dotdash = []
for s in pattern:
if s == ".":
dotdash.append("dot")
elif s == "_":
dotdash.append("dash")
x = "-".join(dotdash)
...
well, i'll just go ahead and respond to my own answer--woops. Easy solution here--i just changed dotdash to a list, and that took care of all my problems.
Change ("dot") to ("dot",) with a trailing comma, and do the same for ("dash").
The trailing comma forces it to be a list type.
Edit: Also, change dotdash to be initialised like dotdash = []
I am passing a function a list populated with strings. I want this function to take each of those strings and iterate through them, executing two different actions depending on the letters found in each string, then displaying them as the separate and now changed strings in a new list.
Specifically, when the program iterates through each string and finds a consonant, it should write that consonant in the order that it was found, into the new list. If the program finds a vowel in the current string, it should append 'xy' before the vowel, then the vowel itself.
As an example:
If the user input: "how now brown cow", the output of the function should be: "hxyow nxyow brxyown cxyow". I've tried nested for loops, nested while loops, and variations between. What's the best way to accomplish this? Cheers!
For every character in old string check if it is vowel or consonant and create new string accordingly.
old = "how now brown cow"
new = ""
for character in old:
if character in ('a', 'e', 'i', 'o', 'u'):
new = new + "xy" + character
else:
new = new + character
print(new)
I gave you the idea and now I leave it as exercise to make it work for list of strings. Also make appropriate changes if you are using python2.
>>> def xy(st):
... my_list,st1 =[],''
... for x in st:
... if x in 'aeiou':
... st1 += 'xy'+x
... elif x in 'cbdgfhkjmlnqpsrtwvyxz':
... my_list.append(x)
... st1 += x
... return my_list,st1
...
>>> my_string="how now brown cow"
>>> xy(my_string)
(['h', 'w', 'n', 'w', 'b', 'r', 'w', 'n', 'c', 'w'], 'hxyow nxyow brxyown cxyow')
In above function for iterates through string when it find vowel concatenate xy+vowel else it append consonant to list, at last returns list and string
A simple way to do this using a list comprehension:
old_str = "how now brown cow"
new_str = ''.join(["xy" + c if c in "aeiou" else c for c in old_str])
print new_str
But if you're processing a lot of data it'd be more efficient to use a set of vowels, eg
vowels = set("aeiou")
old_str = "how now brown cow"
new_str = ''.join(["xy" + c if c in vowels else c for c in old_str])
print new_str
Note that these programs simply copy all characters that aren't vowels, i.e., spaces, numbers and punctuation get treated as if they were consonants.
string1="abc"
string2="abdabcdfg"
I want to find if string1 is substring of string2. However, there are wildcard characters like "." can be any letter, y can be "a" or "d", x can be "b" or "c".
as a result, ".yx" will be substring of string2.
How can I code it using only one loop? I want to loop through string2 and make comparisons at each index. i tried dictionary but I wand to use loop
my code:
def wildcard(string,substring):
sum=""
table={'A': '.', 'C': '.', 'G': '.', 'T': '.','A': 'x', 'T': 'x', 'C': 'y', 'G': 'y'}
for c in strand:
if (c in table) and table[c] not in sum:
sum+=table[c]
elif c not in table:
sum+=c
if sum==substring:
return True
else:
return False
print wildcard("TTAGTTA","xyT.")#should be true
I know you are specifically asking for a solution using a loop. However, I would suppose a different approach: You can easily translate your pattern to a regular expression. This is a similar language for string patterns, just much more powerful. You can then use the re module to check whether that regular expression (and thus your substring pattern) can be found in the string.
def to_regex(pattern, table):
# join substitutions from table, using c itself as default
return ''.join(table.get(c, c) for c in pattern)
import re
symbols = {'.': '[a-z]', '#': '[ad]', '+': '[bc]'}
print re.findall(to_regex('.+#', symbols), 'abdabcdfg')
If you prefer a more "hands-on" solution, you can use this, using loops.
def find_matches(pattern, table, string):
for i in range(len(string) - len(pattern) + 1):
# for each possible starting position, check the pattern
for j, c in enumerate(pattern):
if string[i+j] not in table.get(c, c):
break # character does not match
else:
# loop completed without triggering the break
yield string[i : i + len(pattern)]
symbols = {'.': 'abcdefghijklmnopqrstuvwxyz', '#': 'ad', '+': 'bc'}
print list(find_matches('.+#', symbols, 'abdabcdfg'))
Output in both cases is ['abd', 'bcd'], i.e. it can be found two times, using these substitutions.