A list of puns related to "Tuples"
Hi, I have a data frame with a column describing a line (multiple coordinates) in the form of a list of dictionaries.
Each record in this column looks like
[{'x': 121.049278, 'y': 14.553939}, {'x': 121.05041, 'y': 14.553588}, {'x': 121.052174, 'y': 14.553022}]
Iβm wondering how I can convert this into a list of tuples with the form:
[(y-value 1, x-value-1), (y-value 2, x-value-2)β¦]
Using the actual values it would look like:
[(14.553939, 121.049278), (14.553588, 121.05041), (14.553022, 121.052174)]
From here, I plan to plot them on folium as Polylines.
As seen above, I only care about the values of the dict and not the keys. Iβm also dealing with a large DF with around 10k, records and each list can get quite long. A memory efficient approach would be greatly appreciated.
Thank you in advance!
I am not sure when to use tuples. I understand that they're a quick way to return multiple values from a method, but it seems like defining a simple class to hold the values is more readable, can internally enforce a specific range of values for it's members, and barely requires more typing otherwise.
Could somebody give me a specific example of when you would use a tuple, and why you would not use a class in that scenario?
I want to define a type that follows the pattern [A, B, A, B, A, B, A, B, A, ...]
.
How can I do this?
type A = ['A1', 'A2'];
type B = 'B';
// Tuple type of fixed length.
type C = [...A, ...[B, A]];
type D = [...A, ...[B, A], ...[B, A]];
type E = [...A, ...[B, A], ...[B, A], ...[B, A]];
// Tuple type of non-fixed length.
type F = [...A, ...(...[B, A][])]; // Doesn't work
It's a pretty nifty feature and it's a much easier to extend or extend, like selectively flattening some values in a dictionary based on the key, for instance. I've written about it extensively on Mastering Structural Pattern Matching
https://preview.redd.it/c1rdtjjqw4181.png?width=1550&format=png&auto=webp&s=f59e0e94dd7d987c40b61e65bd5303d35ed7e16a
This is a little tricky to articulate, but I think my code is close.
I'm trying to determine if a text is written in the third person. For this, I check the name
of said text against the actual text (which has been POS tagged) and if the name
of the person who has written the text is followed by a tuple in which the 1 element is 'AUX'
then the text is written in the third person. (i.e., a text written by 'chris' with the form 'chris is' must be written in the third person).
My code is able to identify the two texts in this list of lists which have this structure, but I'm trying to mark third person texts as 1s and non-third person texts as 0s in a list but it's just outputting all 0's.
def third_check(names, pos_list):
third = []
for name, sublist in zip(names, pos_list):
for idx, tup in enumerate(sublist):
if(idx<(len(sublist)-1)):
next_element_pos = sublist[idx + 1][0]
if tup[1] == name and next_element_pos == 'AUX':
print(tup[1], next_element_pos)
value = 1
else:
value = 0
third.append(value)
return third
third_person = third_check(first_names, pos_list)
third_person
Output:
chris AUX
katz AUX
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
As you can see, it does print those elements whereby a person's name is then followed by a tuple which contains 'AUX' but appending the values to a list does not work.
I'm writing a function which is a way to search through an index for tuples. The way to structure your query is by passing in a tuple of classes and the return type is an array of tuples of class instances.
Is there a way to do that? Is this a poor approach in the first place?
My current solution is to just cast the results with "as", but that doesn't feel ideal
Edit: Code example
I want to change the param from string[] to be an array of classes from which I can infer the return type.
Right now the return type is Component[][], but I need it to be for example [AirComponent, FireComponent][] where AirComponent and FireComponent extend Component.
This is the current implementation with string[] as the way to search
type Entity = Map<string, Component>
type ComponentTuple = Component[]
type QueryResult = ComponentTuple[]
getTuplesByQuery(queryTypes: string[]) {
const tuples:QueryResult = []
this.entitiesById.forEach((entity: Entity) => {
if (queryTypes.every((qt) => entity.has(qt))) {
tuples.push(queryTypes.map((qt) => entity.get(qt) as Component))
}
})
return tuples
}
getTuplesByQuery([INPUT, POSITION]).forEach((tuple) => {
const [inputComponent, positionComponent] = tuple as [InputComponent, PositionComponent]
Hello,
I was told that using Tuple<int, int> (for example) is bad practice in API Models that you return to the frontend.
One guy said it was not strongly typed, another guy said it is because JS doesn't know how to serialize it.
Is there any truth to this and what is the truth?
Regards
Hi! I'm trying to take a vector of struct references and generate a vector of all the possible coupling combinations between them, for example
[ &Dot1, &Dot2, &Dot3 ]
->
[
(&Dot1, &Dot2),
(&Dot1, &Dot3),
(&Dot2, &Dot3),
]
What I tried:
dots
.iter()
.enumerate()
.flat_map(|(index, dot)| {
dots
.iter()
.enumerate()
.filter(|(inner_index, _inner_dot)| *inner_index <= index)
.map(|(_, inner_dot)| (dot, inner_dot))
.collect::<Vec<(&Dot, &Dot)>>()
})
.collect::<Vec<(&Dot, &Dot)>>()
.to_vec(),
But this should dereference the dots and move them, how could I do this? Also this could be an n*log(n) I think but it's n^2, so any suggestions on how to implement a faster solution would be nice.
EDIT: I just realized this is an implementation of a graph-like data structure, so I'll look into that
A function with multiple parameters is sometimes cumbersome when you need to chain/pipe it in a functional style. The obvious choice to solve this today would be function currying, but I have another interesting idea to consider.
The idea is that all functions can only take one single parameter behind the scene; multiple parameters functions are just a syntactic sugar of a function that accepts a tuple as the argument.
This reflects very nicely in languages with `foo(1, 2)` as its function call syntax since it already looked like a function name followed by a tuple. And it addressed chaining/piping as well since now function can return a tuple to be passed onto the following function easily.
What are your thoughts on this?
I've heard super smart people say it both ways, so obviously either is fine. (For the record, the two ways I'm talking about are "rhymes with 'couple'" or "rhymes with 'scruple'") But I wonder what considerations come up, like is one way easier to confuse with something else, or is one way going to be judged negatively by a certain type of listener, etc.?
Given a k-tuple of n-dimensional vectors (k > n), how could I construct a representation that is invariant to rotation (edit: and reflection) in n-dimensional space (where the same rotation is applied to every vector in the tuple)?
The mapping should also be continuous, i.e., small changes in the underlying set of vectors result in small changes in the invariant representation. Also, the representation should not be permutation invariant.
One possibility I can think of is to store all k^2 pairwise distances between every 2 vectors, as well as the distance from each vector to the origin. But does this actually uniquely define every tuple of vectors up to rotation? And is there a more space-effecient way of doing this (better than k^2 )?
Edit: After thinking about this, I realized that for my use case, it's more desirable to have a representation that's invariant to both rotation and reflection (specifically, the composition of any number of reflections, not just one)
https://github.com/cristi1990an/tuple
I'm really proud of this one because prior to writing it, I never fully grasped how it would look like and I think (hope) it's pretty usable.
Hi, I'm a Rust newbie. I've come up with a working solution to a problem, but I'd like to ask for some feedback on my approach.
The problem:
I have two vectors of type Vec<64>. Let's say they're:
I'd like to merge these into a "list of pairs", i.e.: Vec<(f64, f64)> so that I can plot x vs y using plotlib (see plotlib example here).
So using my example above, the desired output is:
My approach
// Add itertools = "0.10.3" to Cargo.toml dependencies
use itertools::Itertools;
fn main() {
// Define the two vectors
let xvector = vec[0., 1. , 2., 3., 4.];
let yvector = vec![0., 2. , 4., 6. ,8.];
// Create a couple of iterators
let x_iter = xvector.iter();
let y_iter = yvector.iter();
// Interleave x_iter with y_iter and group into tuples of size 2 using itertools
let mut v = Vec::new();
for (a,b) in x_iter.interleave(y_iter).tuples(){
v.push((*a,*b)); // If I don't de-reference with *, I get Vec<(&f64, &f64)>
}
println!("{:?}",v);
}
Would you approach it like this, or is there a better way? "Better" here could mean more idiomatic, elegant, or resource efficient.
EDIT: Thanks all for suggesting zip!
Do you ever wish you could do more with tuples, without manually coding cases for each tuple length? What about tedious cases of mapping each type to a wrapper struct like a Result
or Option
? I know I do. If that sounds interesting to you, then tuple_tricks might be for you. The basic idea is to allow induction on tuples, so if you can define your trait on a tuple of length one, and given a tuple of length n
you can define it recursively for a tuple of length n+1
. Github repo here: tuple_tricks.
This actually came out of a desire to automate de-serialising tuples of structs from select statements while playing around with SPI in pgx. But as another example, I've implemented a simple method for tuple addition:
fn main() {
let smol = true;
let small = 1u8;
let mid = 1u16;
let big = 1u32;
let bigg = 1u64;
let biggg = 1u128;
let left_tuple = (smol, small, mid).t() + (big, bigg, biggg).t();
let right_tuple = (smol, small, mid, big, bigg, biggg);
assert_eq!(left_tuple.unwrap(), right_tuple);
}
(The .t()
and .unwrap()
are because I have to implement a wrapper type in order to implemented a custom std::ops::Add
).
There currently appears to be a small runtime cost, but a bigger downside I can envision with these kinds of generalised abstract traits is inscrutable type errors in the compiler if some small trait condition is missing (e.g. you only want something to work with tuples of Copy
types, but forget to implement Copy
for your specific struct).
I'd love to get y'all's feedback on this.
e.g:
my_list = [[1,2,3],[4,5,6]]
location = (0,1)
x, y = location
values = my_list[x][y]
Is there any way I can feed that tuple directly into the index reference without first extracting location[0] location[1] into x and y?
I want to avoid doing values = my_list[ location[0] ] [ location [1] ])
I am having troubles figuring out how to find the average in a tuple using a for-loop when designing a function that has an accumulator. So far I have been able to get the addition part correct but I don't know what variable to use to divide by.
Any suggestions on what variable I need to use to get the average to work?
def avg(tup):
"""
Returns average of all of the elements in the tuple.
Remember that the average of a tuple is the sum of all of the elements in the
tuple divided by the number of elements in the tuple.
Examples:
avg((1.0, 2.0, 3.0)) returns 2.0
avg((1.0, 1.0, 3.0, 5.0)) returns 2.5
Parameter tup: the tuple to check
Precondition: tup is a tuple of numbers (int or float)
"""
result = 0
for x in tup:
result = (result + x)
return result
How is this actually happening?
data (,) a b = (,) a b
At first sight, it seems circular. But then it works
Ξ»> (,) 1 2
(1,2)
I found this, but then I don't follow how Solo
is/becomes (,)
. I understand that (,)
is a product type since it's definitely not a sum type of any sort. Can someone point me to some details on the whole product type theory, as well as how the (,)
data type definition results in the two arguments being surrounded in parens and separated by a comma, and treated as a tuple.
A named tuple is essentially a map with keys known at compile time and potentially heterogenous values. A potential use case that I can think of is passing large numbers of arguments with default values. Here, being able to treat the named tuple as a value would make it easy to implement behaviors like overriding default values, and the fact that the keys are known at compile time would allow the compiler to make sure that all necessary values (and no unwanted values) are supplied. However, being a novice, I mostly just want to see how this could be done in Idris 2.
Is there a fast and pythonic way for searching a value in a set of tuples?
For example: Letβs say my set = {(βaβ,1), (βbβ,2), (βaβ, 3)}
And I want to check if (βaβ, any number) exists?
Is there anyway to generalize this:
type PipeFunctions<T, A, B, C, ...> =
| []
| [Operation<T, A>]
| [Operation<T, A>, Operation<A, B>]
| [Operation<T, A>, Operation<A, B>, Operation<B, C>]
| ...;
I'm not sure if it can be done.
I'm working on typing a pipe function as you may have guessed. I've managed to get it all working when the operations are explicitly given; but when a function that returns an operation is called within the pipe; I can't infer the types on that function without me use the mass overload strategy.
If possible, I want to generalize the type.
I have two functions, 'f1, f2 :: [String] -> String, and a function
g :: String -> Int. I would like to create a new function of type
[String] -> Maybe (Int, Int)`. (This came up as part of working with my AOC template, and seemed like a good opportunity to learn something; the actual functions have much longer names.)
I have the following different equivalent working approaches, in order of discovery:
\s -> Just (g $ f1 s, g $ f2 s)
Just . \s -> (g $ f1 s, g $ f2 s)
Just . liftM2 (,) (g . f1) (g . f2)
Just . bimap g g . liftM2 (,) f1 f2 --- Bifunctors
Just . over both g . liftM2 (,) f1 f2 --- Control.Lens
This brought up a few different questions for me.
liftM2
before; I came to it when I gave pointfree.io
the expression above it. Looking at the type, I see liftM2 :: Monad m => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r
. What is the monad here? How should I think about viewing an expression like (g . f1)
(which I normally think of as just an ordinary function composition) with m a1
? I think of the r
as just being the "return type" of (,)
, so I'm a little confused by the m r
. I guess in general I'm a little confused here.bimap
expression isn't very helpful on its own, since I'm still writing g
(remember, longer names) twice. I did this in the hopes that I was on a path to using Data.Bifunctor.Join
, but I haven't figured out how to use that and don't see any actual fully worked examples. Is that a good idea here, and if so, any advice on how to do it?Control.Lens
here (which I've also never used before) is a pretty big move? I did it because I found a comment, but I'm not attached to it.bimap
or Control.Lens
, I'd initially thought I'd use (g .)
as the function rather than g
, but I couldn't make that work. Is this possible? (I'm not saying I'd particularly want to, just trying to deepen my understanding.)Any other suggestions on the right way to do this, or other good lessons to learn here?
Hello everyone !
I'm a bit new to typescript, and yesterday, playing with a bit complicated generic function, I found that arrays passed as generic arguments are described as Arrays and not Tuples. Though, I can make it interpreted as tuple when asserted with the 'const' keyword. But specifying cont everywhere in my code doesn't sound ok. In my opinion, there is probably a way to infer the array as a tuple, with conditional generics or something else, but I can't seem to find the solution.
Here is a codesandbox that shows the issue more specifically : https://codesandbox.io/s/infering-tuples-passed-in-generics-jkz2e?file=/src/App.tsx
Any advices appreciated ;)
Both output:
<<72, 105>>
"Hi"
...and that made it difficult to use Set to implement a fill algorithm to find the largest basin. You can't use [x, y]
arrays as arrays are shallow equals.
I could have used https://github.com/tc39/proposal-record-tuple with babel, but that would have been a PITA to setup.
What I ended up doing was encoding coordinates as a string like ${x}-${y}
but then I had to decode it back out every single time. It is very unperformant, but worked well enough for the puzzle.
Did anybody else run into this problem with JavaScript? how did you solve it?
duple exports trait Remove
with methods that remove nth element from the tuple β’ the methods are generic over the tuple length β’ however, a trait must be implemented for tuple of each supported length β’ the upside is that each method .remn()
(where n
is the index of the field) must only be implemented once to work for all supported lengths β’ for now duple
supports tuples of 2 to 6 elements but it is trivial to add implementations for any desired length
use duple::Remove;
assert_eq!(('a', 'b', 'c').rem0(), ('b', 'c'));
assert_eq!(('a', 'b', 'c').rem1(), ('a', 'c'));
assert_eq!(('a', 'b', 'c').rem2(), ('a', 'b'));
assert_eq!(('a', 'b', 'c', 'd').rem0(), ('b', 'c', 'd'));
assert_eq!(('a', 'b', 'c', 'd').rem1(), ('a', 'c', 'd'));
assert_eq!(('a', 'b', 'c', 'd').rem2(), ('a', 'b', 'd'));
assert_eq!(('a', 'b', 'c', 'd').rem3(), ('a', 'b', 'c'));
all of the methods follow the same pattern: they take a type implementing TupleWrap
with the Wrapped
associated type of desired 'depth' β’ calling TupleWrap::wrap
on a 'flat' tuple returns a corresponding nested tuple, i.e. (a, b, c)
is turned into (a, (b, (c, ())))
β’ then, a function generic over the 'tail' of the nested tuple removes the nth level β’ a nested tuple with the nth level removed is then unwrapped into a corresponding 'flat' tuple
it should be possible to also add popping from and pushing onto both ends of the tuple as well as removing nth element from the end β’ operations on the right end of the tuple requires wrapping the tuples from the left, i.e. ((((), a), b), c)
note that the library has not been published on crates.io
Please note that this site uses cookies to personalise content and adverts, to provide social media features, and to analyse web traffic. Click here for more information.