finding the maximum in a HashSet<u32> in rust? [closed] - rust

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last year.
The community reviewed whether to reopen this question last year and left it closed:
Original close reason(s) were not resolved
Improve this question
how can i find the maximum or minimum value in a HashSet without looping through all the elements in it? Is there any function or one liner way to do so ?

You can do something like this:
let hs: HashSet<u32> = HashSet::from_iter(vec![54, 23, 55, 6, 3, 100]);
let min_value = *hs.iter().min().unwrap();
let max_value = *hs.iter().max().unwrap();
That way you won't have to loop yourself, but internally that's exactly what is going to happen. It's not possible to find the min or max value in a hash set (or a hash map, for that matter), without checking all the values.
BTW there is another (relatively common) set type, BTreeSet, which keeps its values ordered. That would allow you to simply get the first or the last element (via iter().next() or iter().next_back()) and you've got you min/max value w/o any extra work. Performance-wise that would be much faster of course.

Related

Rust ownership, how to return a ref for a struct? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last month.
Improve this question
I generate an instance A from instance B's method and managed by B, but I want return A. How to implement this?
For this codes (playground link) I want generate a history for the RedPacket, managed by RedPacket (push into the Vec) and return history ref to print, but the compiler throw out: cannot move out of history because it is borrowed
How implement this? Or is this a right way in rust world?
It isn’t right way in only “Rust world”, it’s completely wrong in whole programming world. 1. Local variables are stored on the stack, so after function call they are deleted. 2. You’re trying to move your local variable after borrowing it. You are trying to return reference to invalid buffer, and compiler prevents it.
You can return a reference to the last Vec member though:
self.histories.push(history);
self.histories.last()

why does any() work in python for a fibonacci sequence [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
Improve this question
In the case of a it works. However in case of `b it doesn't. Why does this happen?
a = [0,1]
b = [0,1]
any(map(lambda _:a.append(sum(a[-2:])), range(2,8)))
map(lambda _:b.append(sum(b[-2:])), range(2,8))
print(a)
print(b)
This is extremely obfuscated code. Nobody would write code like this without an ulterior motive (such as Code Golf, or trying to wedge everything onto a single line), as it's doing a whole bunch of strange things that can much more simply be done some other way.
To address the thing you're asking about, any is called to consume all the values being produced by map. The return value of the map call is an iterator that lazily invokes the function it was given (a lambda expression) on successive values of the iterator it was given (a range). However, this code doesn't actually care about the values, which are all None. It wants the lambda function to be run for its side effects, which are appending values to the a or b lists. All of the values are None, since that's what list.append returns. Because None is falsey, the any function consumes all of them without stopping early (as it would do for any truthy value).
A much more natural way to write this code would be:
a = [0, 1]
for _ in range(2, 8):
a.append(sum(a[-2:]))
Here it is much more clear that we don't care about the return values from a.append. That's because that method is something we're calling to modify a in place.

Why doesn't rust allow float/int division by default? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 months ago.
Improve this question
The following snippet:
let a: f32 = 2.0;
let b: i32 = 12;
println!("{}",a/b);
fails to compile, with the error message indicating that there is "no implementation for 'f32 / i32'. Now, I understand what this error means, and that I could easily fix it by casting b before dividing. More to the point, the compiler also tells me that I could fix this without modifying the snippet above by implementing the trait Div<i32> for f32.
I don't actually need to divide ints by floats in this manner, but the compiler's message I got made me curious enough to ask the following question: why isn't Div<i32> already implemented for f32?
Of course it would be pretty easy for anyone to implement this by themselves, but I assume it must mean something that it's not a default feature. Is there some complication with the implementation I'm not thinking of? Or is it that the possibility of f32/i32 division somehow lead to "language gotcha's"? Or maybe it's just that rust is more "barebones" in this regard than I assumed?
There are multiple reasons. For one, it's not clear what the return values should be. Should 12 / 2.0 return a float or an integer? What about 12.0 / 2? Many languages opt to just return floats, but this results in hidden conversion costs. Rust as a language tries to be very explicit, especially in case of non-zero cost abstractions.
There is also type safety to consider. Sometimes doing arithmetic between ints and floats indicates a logic error.

What's the practical use of Option in rust? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Consider this example
fn main() {
let mut i: Option<i32> = None;
//after some processing it got some value of 55
i = Some(55);
println!("value is {:?}", i.unwrap());
}
In go, nil represents the zero-value of that type.
However in rust, it represents absence of a value. How is absence of a value useful in practice?
When a variable with a type is declared, it must have some value either initialized or un-initialized. Why will one declare it to have it absent?
Also please explain, at what point the memory is allocated for i during the initial declaration or when i gets some value?
I might be asking a stupid question, but want to get my head around the need of this concept.
How is absence of a value useful in practice?
A simple example is a function that looks for the first matching element in a collection. It may find it, and return it, or not find any.
The docs give a few more cases:
Initial values
Return values for functions that are not defined over their entire input range (partial functions)
Return value for otherwise reporting simple errors, where None is returned on error
Optional struct fields
Struct fields that can be loaned or "taken"
Optional function arguments
Nullable pointers
Swapping things out of difficult situations
Now, you may ask: why don't we use one of the values to mark an empty one? For two reasons:
There are cases where you do not have a valid "zero-value" or a valid "invalid" value. In this case, you have to use some flag somewhere else to store the fact that something is invalid.
In general, it is simpler to use the same solution everywhere than having to mark and document which is the "none" value.
Why will one declare it to have it absent?
This is different than initialized/uninitialized values. Option is simply a type that contains either "nothing" (None) or a "value" of some type (Some(value))
You can conceptually see it as a struct with a flag and some space for the value itself.
Also please explain, at what point the memory is allocated for i during the initial declaration or when i gets some value?
That depends on the implementation. One could decide to implement Option using a pointer to the value, which means it could delay allocating.
However, the most likely implementation is avoiding pointers and keeping the value plus an extra flag. Note that, for some types, you can also optimize further and avoid the flag altogether. For instance, if you have an Option of a pointer, you can simply use the zero value for None. In fact, Rust does such a thing for types like Option<Box<T>>.

want someone to do my homework for me [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
# Change this program to output each letter of the text entered on a separate line
# with space in front of each letter, increasing to the right for each letter.
# For example, 'Python' input should output:
# P
# y
# t
# h
# o
# n
text = input('Enter text: ')
for letter in text:
print(letter)
I already tried to look online for the solution, there are none.
This code is for homework but i cant figure it out help wold be appreciated
As you haven't told us what you have tried to do so far, or what you have tried to learn to figure it out, I'm not going to post the Python code. Instead, lets think about what the program should be doing. Your assignment statement gives a broad overview, but as a programmer you need to take this overview and turn it into a set of smaller instructions. These smaller steps do not have to be in code. They can be in whatever form you like, even plain english.
For functional analysis (which is what you are doing for this problem) start with the inputs and outputs then fill in the stuff in-between.
1) Input: a string
X) Output: multiple lines with a single character and whitespace
Now how do you want to get from 1 to X. You already have the code to loop through each letter and print it, but you are missing two things to get to your required output.
A) way to place a string on a new line
B) way to add whitespace to a string
I'll give you a couple of hints. A) is something that is extremely common in almost any programming language. In fact, it is done the exact same way is any language that you are likely to use. Another hint. Your final output will be a single string that spans multiple lines. Ask yourself how a word processor or text editor gives works with blank lines.
B is a little more tricky, as there are a couple of nifty Python tricks that makes it simpler to do than in other languages. I'm guessing that you already know what happens when you add two numbers together such as 3 + 5. But what happens when you add two strings together such as "foo" + "bar". Notice how the behavior for adding numbers with the + operator is completely different than the behavior is for adding strings together with the same operator? That difference in behavior applies to other common operators as well. Play around with the other three common mathematical operators on both string and numbers to see what happens

Resources