Im working on Advent of Code: Day 2, and Im having trouble working with lists. My code takes a string, for example 2x3x4, and splits it into a list. Then it checks for an 'x' in the list and removes them and feeds the value to a method that calculates the area needed. The problem is that before it removes the 'x's I need to find out if there are two numbers before the 'x' and combine them, to account for double digit numbers. I've looked into regular expressions but I don't think I've been using it right. Any ideas?
def CalcAreaBox(l, w, h):
totalArea = (2*(l*w)) + (2*(w*h))+ (2*(h*l))
extra = l * w
toOrder = totalArea + extra
print(toOrder)
def ProcessString(dimStr):
#seperate chars into a list
dimStrList = list(dimStr)
#How to deal with double digit nums?
#remove any x
for i in dimStrList:
if i == 'x':
dimStrList.remove(i)
#Feed the list to CalcAreaBox
CalcAreaBox(int(dimStrList[0]), int(dimStrList[1]), int(dimStrList[2]))
dimStr = "2x3x4"
ProcessString(dimStr)
You could use split on your string
#remove any x and put in list of ints
dims = [int(dim) for dim in dimStrList.split('x')]
#Feed the list to CalcAreaBox
CalcAreaBox(dims[0], dims[1], dims[2])
Of course you will want to consider handling the cases where there are not exactly two X's in the string
Your question is more likely to fit on Code Review and not Stack Overflow.
As your task is a little challenge, I would not tell you an exact solution, but give you a hint towards the split method of Python strings (see the documentation).
Additionally, you should check the style of your code against the recommendation in PEP8, e.g. Python usually has function/variable names in all lowercase letters, words separated by underscores (like calc_area_box).
Related
I am trying to create a function compare(lst1,lst2) which compares the each element in a list and returns every common element in a new list and shows percentage of how common it is. All the elements in the list are going to be strings. For example the function should return:
lst1 = AAAAABBBBBCCCCCDDDD
lst2 = ABCABCABCABCABCABCA
common strand = AxxAxxxBxxxCxxCxxxx
similarity = 25%
The parts of the list which are not similar will simply be returned as x.
I am having trouble in completing this function without the python set and zip method. I am not allowed to use them for this task and I have to achieve this using while and for loops. Kindly guide me as to how I can achieve this.
This is what I came up with.
lst1 = 'AAAAABBBBBCCCCCDDDD'
lst2 = 'ABCABCABCABCABCABCA'
common_strand = ''
score = 0
for i in range(len(lst1)):
if lst1[i] == lst2[i]:
common_strand = common_strand + str(lst1[i])
score += 1
else:
common_strand = common_strand + 'x'
print('Common Strand: ', common_strand)
print('Similarity Score: ', score/len(lst1))
Output:
Common Strand: AxxAxxxBxxxCxxCxxxx
Similarity Score: 0.2631578947368421
I am having trouble in completing this function without the python set and zip method. I am not allowed to use them for this task and I have to achieve this using while and for loops. Kindly guide me as to how I can achieve this.
You have two strings A and B. Strings are ordered sequences of characters.
Suppose both A and B have equal length (the same number of characters). Choose some position i < len(A), len(B) (remember Python sequences are 0-indexed). Your problem statement requires:
If character i in A is identical to character i in B, yield that character
Otherwise, yield some placeholder to denote the mismatch
How do you find the ith character in some string A? Take a look at Python's string methods. Remember: strings are sequences of characters, so Python strings also implement several sequence-specific operations.
If len(A) != len(B), you need to decide what to do if you're comparing the ith element in either string to a string smaller than i. You might think to represent these as the same placeholder in (2).
If you know how to iterate the result of zip, you know how to use for loops. All you need is a way to iterate over the sequence of indices. Check out the language built-in functions.
Finally, for your measure of similarity: if you've compared n characters and found that N <= n are mismatched, you can define 1 - (N / n) as your measure of similarity. This works well for equally-long strings (for two strings with different lengths, you're always going to be calculating the proportion relative to the longer string).
I'm looking to write a piece of code in Javascript or Python that generates a wordlist file out of a pre-defined combination of characters.
E.g.
input = abc
output =
ABC
abc
Abc
aBc
abC
AbC
ABc
aBC
I have very basic knowledge of either so all help is appreciated.
Thank you
I'll assume that you're able to import Python packages. Therefore, take a look at itertools.product:
This tool computes the cartesian product of input iterables.
For example, product(A, B) returns the same as ((x,y) for x in A for y in B).
It looks quite like what you're looking for, right? That's every possible combination from two different lists.
Since you're new to Python, I'll assume you don't know what a map is. Nothing too hard to understand:
Returns a list of the results after applying the given function to each item of a given iterable (list, tuple etc.)
That's easy! So the first parameter is the function you want to apply and the second one is your iterable.
The function I applied in the map is as follows:
''.join
This way you set '' as your separator (basically no separator at all) and put together every character with .join.
Why would you want to put together the characters? Well, you'll have a list (a lot of them in fact) and you want a string, so you better put those chars together in each list.
Now here comes the hard part, the iterable inside the map:
itertools.product(*((char.upper(), char.lower()) for char in string)
First of all notice that * is the so-called splat operator in this situation. It splits the sequence into separate arguments for the function call.
Now that you know that, let's dive into the code.
Your (A, B) for itertools.product(A, B) are now (char.upper(), char.lower()). That's both versions of char, upper and lowercase. And what's char? It's an auxiliar variable that will take the value of each and every character in the given string, one at a time.
Therefore for input 'abc' char will take values a, b and c while in the loop, but since you're asking for every possible combination of uppercase and lowercase char you'll get exactly what you asked for.
I hope I made everything clear enough. :)
Let me know if you need any further clarification in the comments. Here's a working function based on my previous explanation:
import itertools
def func():
string = input("Introduce some characters: ")
output = map(''.join, itertools.product(*((char.upper(), char.lower()) for char in string)))
print(list(output))
As an additional note, if you printed output you wouldn't get your desired output, you have to turn the map type into a list for it to be printable.
A simple approach using generators, and no library code. It returns a generator (iterator-like object), but can be converted to a list easily.
def lU(s):
if not s:
yield ''
else:
for sfx in lU(s[1:]):
yield s[0].upper() + sfx
yield s[0].lower() + sfx
print list(lU("abc"))
Note that all the sub-lists of suffixes are not fully expanded, but the number of generator objects (each a constant size) that get generated is proportional to the length of the string.
This question already has an answer here:
How can I replace multiple characters in a string using python?
(1 answer)
Closed 5 years ago.
I already asked a question exactly like this, but the answer I got still worked and it used the .translate method within the function, but I want to use "for loops" to get the output I am looking for. Here is the link to the questions I asked a while ago: How can I replace multiple characters in a string using python?
I am having some trouble figuring out how to replace multiple characters in a string using a for loop. I am trying to write a functions called replace(string) that takes in an input, and replaces certain letters in the input with another letter.
Lets say I have the string "WXYZ" and I want to replace all the W with Y, X with Z, Y with W, and Z with X. I want it to do the replacement no matter what the input is. So if I also do something like replace("WWZXWWXYYZWYYY") it should replace the letters like I said above.
This is what I have done so far with the for loops:
def replace(string):
for letters in string:
string = string.replace("W","Y").replace("X","Z").replace("Y","W").replace("Z","X")
print(string)
but when I run it with replace("WXYZ")
I get the output of the code as: WXWX
Instead of getting YZWX as the output. I also want to use the built in functions of python as well.
How can I achieve this?
The problem is that you have intersection in your replaces. Python calls the methods from the left to right. That's why the following code works:
In [6]: 'ax'.replace('a', 'b').replace('b', 'g')
Out[6]: 'gx'
For getting ride of that problem you should replace the characters at once. One way around this is using regex or even better (if you just want to replace the character) the str.translate method:
In [16]: d = {"W": "Y", "X": "Z", "Y": "W", "Z": "X"}
In [17]: "WXYZ".translate(str.maketrans(d))
Out[17]: 'YZWX'
Here is a solution to your problem. I hope this helps you :)
def replacer(string): #define the function with a parameter (which will be whatever string you want)
newlist = [] #create a new list which will be the output
strlist = list(string) #create a list of each character in the input string
for item in strlist: #iterate through the items in the list of string characters
if item == 'W': # this line and the next 7 lines check what the letter is and writes the letter you want to the new list
newlist.append('Y')
elif item == 'X':
newlist.append('Z')
elif item == 'Y':
newlist.append('W')
elif item == 'Z':
newlist.append('X')
return ''.join(newlist) #output the new list as a string
replacer('WWZXWWXYYZWYYY') #call the function with the string as a parameter
The problem is that the third replace replaces also the new Ys (that were originally Ws).
One way is to use RegEx, as in here.
Another way I can think of is to swap into temporary values. But for that you need to find temporary values that would never appear in the original string.
For example, if you know the original string would be only UPPERCASE letters, you can use string.replace("W","y").replace("X","z").replace("Y","w").replace("Z","x"), and then replace all the lowercase back into uppercase without worrying about rereplacing the letters.
If you can't be sure it'll be only uppercase, find another set of chars that will never be on the string, or use RegEx.
I am using CodingBat for practice exercises for the Python Language, I got to the "Warmup-1 > missing_char" exercise. The problem is as so:
Given a non-empty string and an int n, return a new string where the
char at index n has been removed. The value of n will be a valid index
of a char in the original string (i.e. n will be in the range
0..len(str)-1 inclusive).
The examples were:
missing_char('kitten', 1) → 'ktten'
missing_char('kitten', 0) → 'itten'
missing_char('kitten', 4) → 'kittn'
I wrote:
def missing_char(str, n):
return str.replace(str[n], "")
It returned all correct. As I usually do when I get my answers correct, I look and see how CodingBat answered it. They answered it in the following way:
def missing_char(str, n):
front = str[:n] # up to but not including n
back = str[n+1:] # n+1 through end of string
return front + back
Now, my question is the following: which answer is more viable? Is there setbacks to my method whereas CodingBat's method is more solid? Or is this just one of those "multiple approaches to things" kind of situation?
For the sake of posting a formal answer and as all previous comments suggest:
str.replace(char,"") will remove all occurences of the character regardless of their position.
str[:n]+str[n+1:] will only remove the n-th character.
So for that exercice str.replace(char,"") is not suitable.
You should be able to circumvent that problem by adding a count so that it only takes the first character:
def missing_char(str, n):
return str.replace(str[n], "",1)
I added a 1 so that it only takes the first occurrence of that character
For my assignment, I'm required to first come up with a function that reverses a string that is inputted (which I've already done using the code below)
def reverse(s):
if len(s) <= 1:
return s
return reverse(s[1:]) + s[0]
The next part is to construct a new string from a given one by breaking it at a certain index value, and concatenating the reverse of the second part (the suffix) to the beginning of the first part (the prefix)
For example, if the input string is 'laptop' and the chosen index value is, say, 3, the string is broken as 'lap' + 'top'. 'top' would then be reversed to 'pot' and would be concatenated with the prefix (in the order) as 'pot' + 'lap'
The assignment is somewhat confusing and since I'm a novice with little to no experience besides a couple of days working in Python, I'm a little confused as to what to do. I'm pretty sure I have to use the slice and concatenation operators but I'm not sure how I should go about constructing a function that suits the above criteria. Any pointers?
Combining the other two answers, and implementing your reverse function:
def concatreverse(s, i):
"""This function takes in a string, s, which
is split at an index, i, reverses the second of the split,
and concatenates it back on to the first part"""
#Takes your inputs and processes
part1,part2 = s[0:i], s[i:]
#Reverse part2 with the function you already created
#this assumes it is accessible (in the same file, for instance)
rev_part2 = reverse(part2)
#concatenate the result
result = part1 +rev_part2
#Give it back to the caller
return result
As a beginner, it helps to step through line by line, or doing tests using the interpreter to see exactly what's going on :)
Something like:
def concatreverse(s, i):
return s[:i] + reverse(s[i:])
You could do as follows:
s = 'laptop'
i = 3;
# split the string into two parts
part1,part2 = s[0:i], s[i:]
# make new string starting with reversed second part.
s2 = part2[::-1] + part1
print(s2)
# prints: potlap