Newb programmer here, I'm most familiar with Python but also learning C and Java, so either of 3 would be fine.
What I have is a string of letters, say:
ABXDEYGH
However say,
X is possible to be M and N.
Y is possible to be P and Q.
In this example, I would like basically to print all possible variations of this string of letters.
Like:
ABMDEPGH
ABNDEPGH
ABMDEQGH
ABNDEQGH
Any help would be appreciated. Thanks in advance
This boils down to a simple problem of permutations. What you care about is the part of the text that can change; the variables. The rest can be ignored, until you want to display it.
So your question can be more simply stated: What are all the possible permutations of 1 item from set X and another item from set Y? This is known as a cross-product, sometimes also simply called a product.
Here's a possible Python solution:
import itertools
x = set(['M', 'N'])
y = set(['P', 'Q'])
for items in itertools.product(x, y)
print 'AB{0}DE{1}GH'.format(*items)
Note that the print ''.format() command uses the "unpack arguments" notation described here.
why dont you write two loops. one to replace all possible characters with X and one for Y.
foreach(char c in charSet1){
// replaces X
foreach(char ch in charSet2){
// replace Y
}
}
Related
I started coding in Python 4 days ago, so I'm a complete newbie. I have a dataset that comprises an undefined number of dictionaries. Each dictionary is the x and y of a point in the coordinates.
I'm trying to compute the summatory of xy by nesting the loop that multiplies xy within the loop that sums the products.
However I haven't been able to figure out how to multiply the values for the two keys in each dictionary (so far I only got to multiply all the x*y)
So far I've got this:
If my data set were to be d= [{'x':0, 'y':0}, {'x':1, 'y':1}, {'x':2, 'y':3}]
I've got the code for the function that calculates the product of each pair of x and y:
def product_xy (product_x_per_y):
prod_xy =[]
n = 0
for i in range (len(d)):
result = d[n]['x']*d[n]['y']
prod_xy.append(result)
n+1
return prod_xy
I also have the function to add up the elements of a list (like prod_xy):
def total_xy_prod (sum_prod):
all = 0
for s in sum_prod:
all+= s
return all
I've been trying to find a way to nest this two functions so that I can iterate through the multiplication of each x*y and then add up all the products.
Make sure your code works as expected
First, your functions have a few mistakes. For example, in product_xy, you assign n=0, and later do n + 1; you probably meant to do n += 1 instead of n + 1. But n is also completely unnecessary; you can simply use the i from the range iteration to replace n like so: result = d[i]['x']*d[i]['y']
Nesting these two functions: part 1
To answer your question, it's fairly straightforward to get the sum of the products of the elements from your current code:
coord_sum = total_xy_prod(product_xy(d))
Nesting these two functions: part 2
However, there is a much shorter and more efficient way to tackle this problem. For one, Python provides the built-in function sum() to sum the elements of a list (and other iterables), so there's no need create total_xy_prod. Our code could at this point read as follows:
coord_sum = sum(product_xy(d))
But product_xy is also unnecessarily long and inefficient, and we could also replace it entirely with a shorter expression. In this case, the shortening comes from generator expressions, which are basically compact for-loops. The Python docs give some of the basic details of how the syntax works at list comprehensions, which are distinct, but closely related to generator expressions. For the purposes of answering this question, I will simply present the final, most simplified form of your desired result:
coord_sum = sum(e['x'] * e['y'] for e in d)
Here, the generator expression iterates through every element in d (using for e in d), multiplies the numbers stored in the dictionary keys 'x' and 'y' of each element (using e['x'] * e['y']), and then sums each of those products from the entire sequence.
There is also some documentation on generator expressions, but it's a bit technical, so it's probably not approachable for the Python beginner.
I am a beginner in APL and am writing a dfm function to check whether two strings are an anagram of one another. The method I thought of was:
{⍵[⍋⍵] ≡ ⍺[⍋⍺]}
However, it returns 0 for 'ALBERT EINSTEIN' and 'TEN ELITE BRAINS' that are anagrams. I tried to check why:
a ← 'ALBERT EINSTEIN'
b ← 'TEN ELITE BRAINS'
a[⍋a] ≡ b[⍋b]
0
a[⍋a]
ABEEEIILNNRSTT
b[⍋b]
ABEEEIILNNRSTT
a[⍋a] = b[⍋b]
LENGTH ERROR
a[⍋a]=b[⍋b]
Is it because the second rearrangement seems to have a leading space? Why does that happen? Can anyone suggest a way I can make this program work?
In your specific case, you would need to filter out the spaces from the vectors you're comparing. This is because your vectors will have different lengths after grading up, since one of them has an extra space.
One solution could be:
'albert einstein'{(a b)←(⍺~' ')(⍵~' ')⋄a[⍋a]≡b[⍋b]}'ten elite brains'
The first part of the code, (a b)←(⍺~' ')(⍵~' '), assigns ⍺ and ⍵, without spaces (~' '), to a and b respectively. Then, you can just compare the vectors the same way you're doing now.
You can check the output of the code above on Try it online!
I'm studying project euler solutions and this is the solution of problem 4, which asks to
Find the largest palindrome made from the product of two 3-digit
numbers
problem_4 =
maximum [x | y<-[100..999], z<-[y..999], let x=y*z, let s=show x, s==reverse s]
I understand that this code creates a list such that x is a product of all possible z and y.
However I'm having a problem understanding what does s do here. Looks like everything after | is going to be executed everytime a new element from this list is needed, right?
I don't think I understand what's happening here. Shouldn't everything to the right of | be constraints?
A list comprehension is a rather thin wrapper around a do expression:
problem_4 = maximum $ do
y <- [100..999]
z <- [y..999]
let x = y*z
let s = show x
guard $ s == reverse s
return x
Most pieces translate directly; pieces that aren't iterators (<-) or let expressions are treated as arguments to the guard function found in Control.Monad. The effect of guard is to short-circuit the evaluation; for the list monad, this means not executing return x for the particular value of x that led to the false argument.
I don't think I understand what's happening here. Shouldn't everything to the right of | be constraints?
No, at the right part you see an expression that is a comma-separated (,) list of "parts", and every part is one of the following tree:
an "generator" of the form somevar <- somelist;
a let statement which is an expression that can be used to for instance introduce a variable that stores a subresult; and
expressions of the type boolean that act like a filter.
So it is not some sort of "constraint programming" where one simply can list some constraints and hope that Haskell figures it out (in fact personally that is the difference between a "programming language" and a "specification language": in a programming language you have "control" how the data flows, in a specification language, that is handled by a system that reads your specifications)
Basically an iterator can be compared to a "foreach" loop in many imperative programming languages. A "let" statement can be seen as introducing a temprary variable (but note that in Haskell you do not assign variable, you declare them, so you can not reassign values). The filter can be seen as an if statement.
So the list comprehension would be equivalent to something in Python like:
for y in range(100, 1000):
for z in range(y, 1000):
x = y * z
s = str(x)
if x == x[::-1]:
yield x
We thus first iterate over two ranges in a nested way, then we declare x to be the multiplication of y and z, with let s = show x, we basically convert a number (for example 15129) to its string counterpart (for example "15129"). Finally we use s == reverse s to reverse the string and check if it is equal to the original string.
Note that there are more efficient ways to test Palindromes, especially for multiplications of two numbers.
I am the beginner of haskell. I want to delete some same functions in the same list and concatenate the two list get together.
For example:
db1 = ["David","worksfor.isa", "IBM" ]
db2 = ["David","isa'.worksfor'", "IBM"]
db3 = ["Tom","worksfor.isa", "IBM" ]
the program can be known that "isa'.worksfor' and "worksfor.isa" is the same String. And then use "Concat" to get the new db: db1 =["David","worksfor.isa", "IBM" ] and the others: db3 = ["Tom","worksfor.isa", "IBM" ]
(map (\(a,b,c) -> concat (map(\(a',b',c') -> if ( a b == b' a') then [] else [(a,b ++ "." ++ b',c')])))) ??????
I want to "split the string, if there are ' characters, reverse it, then remove ' characters and check for equivalence"
This should be a comment, but it is far too long:
I assume you find it hard to express yourself in English. I can relate to that; I find it hard myself. However, beyond English there are two other ways to communicate here:
Using precise technical terms.
Using several, diverse examples. A single example will not suffice, and several examples which are too similar give little information.
As for option 1, you are using the wrong terminology. It is not easy for me to see how can a list with 3 items can be considered a database (as hinted by the names db1, db2). Perhaps you wanted to use a list of triples?
[ ("David","isa'.worksfor'", "IBM") ]
You are not specific about what exactly do you want to concatenate, but the term concatenation always refers to an operation that must be "additive", i.e. length(x ++ y) == length(x) ++ length(y). This does not seem to be the case in your question.
Do you want a union of two databases (lists of triples) up to equivalence?
You want the program to understand that
"isa'.worksfor'" and "worksfor.isa" are the same string
But they are not. They might be equivalent strings. You can generally do that using a map operation, like you tried, but you should note that the character ' is not an operation over strings. So a b == b' a' does nothing close to what you want - it calls the function a on the variable b, and compares this with calling the function b' over the variable a'. I can only assume you want something like "split the string, if there are ' characters, reverse it, then remove ' characters and check for equivalence" but this is completely a guesswork.
To conclude:
Please explain in detail what is the general problem you are trying to solve. Try to find the precise terms; it is difficult, but this way you can learn.
Please add different examples of input and output
Please try to explain what have you tried and where are you stuck
As a last tip, maybe you want to solve this problem in a more forgiving language than Haskell (such as JavaScript, Python, Ruby, etc.)
So I'm playing with Sympy in an effort to build a generic solver/generator of physics problems. One component is that I'm going for a function that will take kwargs and, according to what it got, rearrange the equation and substitute values in it. Thanks to SO, I managed to find the things I need for that.
However..... I've tried putting sympy.solve in a for loop to generate all those expressions and I've ran into.... something.
import sympy
R, U, I, eq = sympy.symbols('R U I eq')
eq = R - U/I
for x in 'RUI':
print(x)
print(sympy.solve(eq, x))
The output?
R
[U/I]
U
[I*R]
I
[]
However, whenever I do sympy.solve(eq, I) it works and returns [U/R].
Now, I'm guessing the issue is with sympy using I for imaginary unit and with variable hiding in blocks, but even when I transfer the symbol declaration inside the for loop (and equation as well), I still get the same problem.
I'm not sure I'll need this badly in the end, but this is interesting to say the least.
It's more like an undocumented feature than a bug. The loop for x in 'RUI' is equivalent to for x in ['R', 'U', 'I'], meaning that x runs over one-character strings, not sympy symbols. Insert print(type(x)) in the loop to see this. And note that sympy.solve(eq, 'I') returns [].
The loop for x in [R, U, I] solves correctly for each variable. This is the right way to write this loop.
The surprising thing is that you get anything at all when passing a string as the second argument of solve. Sympy documentation does not list strings among acceptable arguments. Apparently, it tries to coerce the string to a sympy object and does not always guess your meaning correctly: works with sympy.solve(eq, 'R') but not with sympy.solve(eq, 'I')
The issue is that some sympy functions "accidentally" work with strings as input because they call sympify on their input. But sympify('I') gives the imaginary unit (sqrt(-1)), not Symbol('I').
You should always define your symbols explicitly like
R, U, I = symbols("R U I")
and use those instead of strings.
See https://github.com/sympy/sympy/wiki/Idioms-and-Antipatterns#strings-as-input for more information on why you should avoid using strings with SymPy.