How use ' '.join() in Python? - cpython

I was studying PEP8's Programming Recommendations.
It was recommended to use ''.join to combine strings, but I did not understand when to do so:
Should I concatenate every time that way?
How useful is this?
At what times are ideal to use join() to String? In Path, URL, Texts?
In [PEP 484](https://www.python.org/dev/peps/pep-0484/
Should this have been return ' '.join('Hello', name) ?

Imagine you have four strings: a, b, c and d.
Say you want their concatenation, e = a + b + c + d. However, the + operator is only defined for two operands, so you would apparently need to concatenate the individual strings one by one.
The naive way to calculate this might be the following:
e = ((a + b) + c) + d
But this is inefficient, because it generates two throwaway strings: a + b and a + b + c.
Now, imagine we created a buffer-like object holding all the characters we wanted to combine:
e_buffer = [a, b, c, d]
We could create e from this all at once, avoiding the need to create many intermediate strings.
This requires a function, which, in Python, we call join; it is a method of a str, and intersperses that string between the arguments provided. Therefore, when you execute some_separator.join([a, b, c]), you get, in effect, a + some_separator + b + some_separator + c.
To answer your question: in general, when concatenating many strings, it should be faster to use join, and it will at least be more readable, especially when using a separator. For the case given in the question, I would instead use an f-string:
def greeting(name: str) -> str:
return f'Hello {name}'

Related

How to concatenate two vectors in Julia?

Given two vectors a = [1, 2] and b = [3, 4], how do I obtain the concatenated vector c = [1, 2, 3, 4]? It seems that hcat or vcat could be used as they work on arrays, but when using vectors to store collections of elements it seems unfitting to first think about the orientation of the data; it's just supposed to be a list of values.
You can write
[a; b]
Under the hood this is the same as vcat, but it's terser, looks better, and is easier to remember, as it's also consistent with literal matrix construction syntax.
An alternative for concatenating multiple vectors is
reduce(vcat, (a, b))
Most Array methods treat arrays as general "tensors" of arbitrary ranks ("data cubes"), so you do need to think about the orientation. In the general case, there's cat(a, b; dims), of which hcat and vcat are special cases.
There is another class of methods treating Vectors as list like. From those, append! is the method that, well, appends a vector to another. The problem is that it is mutable. So you can, for example, append!(copy(a), b), or use something like BangBang.NoBang.append (which just selects the right method internally, though).
For the case of more than two vectors to be concatenated, I like the pattern of
reduce(append!, (a, b), init=Int[])

Elementwise arithmetic operations in Kotlin

What's the best way to make elementwise operations on arrays/lists of Doubles in kotlin?
I'd like to achieve something concise as
zip(vec1, weights1).map(*) + zip(vec2, weights2).map(*)
where the plus operation should add the resulting products elementwise (+ as an arithmetic addition, not a concatenation of lists)
Kotlin way would be to use regular Collection/Sequence operators, which there are plenty.
In this case, if you want to do something on every corresponding (index-wise) pair of elements of two lists, you would want to use zip operator, which makes list of Pairs. You can operate on pairs pretty easy with Kotlin destructuring.
If I understood what you want to achieve correctly, your example would be represented as (I used variables just for readability sake):
val result1 = vec1.zip(weights1) { a, b -> a * b }
val result2 = vec2.zip(weights2) { a, b -> a * b }
result1.zip(result2).map { (a, b) -> a + b }

Define the notion of "pairs" using higher-order logic

Revising for a course on automated reasoning and I don't quite understand how to answer this question:
Show how the notion of pairs (x, y) can be defined in higher-order logic using a lambda abstraction. Define a function π1 that returns the first element of such a pair. Finally, show that π1(x, y) = x.
I've found similar questions on stackoverflow, but they're all to do with scheme, which I've never used. An explanation in English/relevant mathematical notation would be appreciated
Here you go
PAIR := λx. λy. λp. p x y
π1 := λp. p (λx. λy. x)
π2 := λp. p (λx. λy. y)
π1 (PAIR a b) => a
π2 (PAIR a b) => b
Check the wiki entry on Church encoding for some good examples, too
The main topic of this question is to understand how data can be represented as functions. When you're working with other paradigms , the normal way of thinking is "data = something that's stored in a variable" (could be an array, object, whatever structure you want).
But when we're in functional programming, we can also represent data as functions.
So let's say you want a function pair(x,y)
This is "pseudo" lisp language:
(function pair x y =
lambda(pick)
if pick = 1 return x
else return y )
That example, is showing a function that returns a lambda function which expects a parameter.
(function pi this-is-pair = this-is-pair 1)
this-is-pair should be constructed with a pair function, therefore, the parameter is a function which expects other parameter (pick).
And now, you can test what you need
(pi (pair x y ) ) should return x
I would highly recommend you to see this video about compound data. Most of the examples are made on lisp, but it's great to understand a concept like that.
Pairs or tuples describes Products Domain, is the union of all elements of the set A and all elements of the set B:
A × B = { (a, b) | a ∈ A, b ∈ B }
Here, A and B are diferent types, so if you for example are in a laguage program like C, Java, you can have pair like (String, Integer), (Char, Boolean), (Double, Double)
Now, the function π1, is just a function that takes a pair and returns the first element, this function is called in usually first, and that's how it looks like π1(x, y) = x, on the other hand you have second, doing the same thing but returning the second element:
fst(a, b) = a
snd(a, b) = b
When I studied the signature "Characteristics of the programming languages" in college our professor recommended this book, see the chapter Product Domain to understand well all this concepts.

Prolog sum all throwing error

I have to write a predicates that sums all the items in a list. The items can be a list with list of list in it. for example,
sum1([1,[2,3],4,[5]],X).
i have some code that SHOULD work, but is giving an arguments are not sufficiently instantiated error. I am very new to prolog but these look alright to me. here is my full code for this predicate (function)
suml([],0).
suml([H|T],X) :- atomic(H),S2 is H + X, suml(T,S2).
suml([H|T],X) :- suml(H,S1), S3 is S1 + X, suml(T,S3).
Change the order of the following two conditions: S2 is H + X, suml(T,S2) and change the way you use is/2. Although this is logic programming, the order of the conditions in a rule matters. Put sum1(T, S2) first because you need S2 to be instantiated before computing the sum. Second, is arithmetically evaluates the right part and unifies it with the left part. So, you actually want to sum S2 and H to get X:
suml([H|T],X) :- atomic(H), suml(T,S2), X is H + S2.

Manipulating expressions in R

I am looking for a way to create an expression that is the product of two given expressions. For example, suppose I have
e1 <- expression(a+b*x)
e2 <- expression(c+d*x)
Now I want to create programatically the expression (e1)*(e2):
expression((a+b*x)*(c+d*x))
Background
I am writing a model fitting function. The model has two pieces that are user-defined. I need to be able to "handle" them separately, and then create a combined expression and "handle" it as one model. "Handling" involves taking numeric derivatives, and the deriv function wants expressions as an input.
I don't deal with this too often but something like this seems to be working
e1 <- expression(a + b*x)
e2 <- expression(c + d*x)
substitute(expression(e1*e2), list(e1 = e1[[1]], e2 = e2[[1]]))
# expression((a + b * x) * (c + d * x))
Try this:
e1 <- quote(a+b*x) # or expression(*)[[1]]
e2 <- quote(c+d*x)
substitute(e1 * e2, list(e1=e1, e2=e2))
It's probably overkill in your case, but the Ryacas package can be nice for performing more complicated symbolic manipulations of this sort:
library(Ryacas)
yacas(expression(e1*e2))$text
# expression((a + b * x) * (c + d * x))
Also, instead of using substitute(), you can construct the same expression in base R like this:
as.expression(as.call(list(as.symbol("*"), e1[[1]], e2[[1]])))
# expression((a + b * x) * (c + d * x))
Explanatory note: One initially confusing aspect of dealing with expression objects is that they are really lists of language objects -- even when (as is often the case) those lists contain just one object. For example, in your question, both e1 and e2 are length 1 lists containing a single call object each.
Working from the inside out, the code above:
Extracts the two call objects using [[1]]
Uses as.call() to constructs a new call that is the product of the two call objects.
Finally, wraps the resultant call back up as the expression object that you want.

Resources