How to alter Boolean value from true to false and vice-versa - go

I have a requirement in Go of altering the bool value and store it.
I am receiving value == true but I need to alter it and store the altered value.
I can think of only storing the alerted to a var and pass it in the next statement.
Eg psuedo code:
chnagevalue := false
if value == false {
changevalue == true
}
what's the best way to do it in Go? Is there any pre-defined way to do it?

Use the logical NOT operator ! to change true to false and vice versa:
changedValue := !value

There's a short answer, written somewhere else :-)
Yours is almost good too:
changedValue := false
if !value {
changedValue == true
}
An if statement is always about something being true.
so in the above it reads : if a value equals false is true then {}.
of course your mind reads it the short way :
if a value equals false then {}.
the switch of course works the best:
changedValue := !changedValue
BTW: I would never use a fieldname like "changedValue" because...
every variable is a value of some kind, so there is no need of writing that.
"changed" should be enough.
or, when it is a boolean like this , even better:
"isChanged" or "hasChanged"

Related

How write a hash function to make such expression to be true?

pseudocode:
// deprecated x!=y && hash(x) == hash(y) // how to make this true?
x!=y && hash(x) == hash(y) && (z!=x && z!=y) && (hash(x) != hash(z) && (hash(y) != hash(z)) // how to make this true?
x and y can be any readable value
Whatever the language, the pseudocode is just help to understand what I mean.
I just wonder how to implement such hash function.
PS: For math, i am an idiot. I can not imagine if there is an algorithm that can do this.
UPDATE 1:
The pseudocode has bug, so I updated the code(actually still has bug, never mind, I will explain).
My original requirement is to make a hash function that can return same value for different parameter, and the parameter value should contains some rule. It means, only the parameter value in same category would gets same hash code, others are not.
e.g.
The following expressions are clearly(you can treat '0' as placeholder):
hash("1.1") == hash("1.0") == hash("0.1")
hash("2.2") == hash("2.0") == hash("0.2")
and
hash("2.2") != hash("2.1") != hash("1.2")
I think this question can do such description:
There are two or more different values contains implied same attribute.
Only these values have such same attribute in the world.
The attribute can obtain through some way(maybe a function), hash() will call it inside.
hash() one of the values, you can retrive the attribute, then you can get the unique hashCode.
It's looks like hash collision, but we exactly know what they are. Also looks like many-to-one model.
How to design collision rules? The values could be any character or numeric. And how to implement the designs?
PPS: This is a question full of bugs, maybe the updated parts cannot explain the the problem either. Or maybe this is a false proposition. I want abstract my issue as a general model, but it makes my mind overflowed. If necessary I will post my actual issue that I am facing.
Any constant hash trivially satisfies your condition:
hash(v) = 42
A less constant answer than yuri kilocheck's would be to use the mod operator:
hash(v) = v % 10;
Then you'll have:
hash(1) = 1
hash(2) = 2
hash(3) = 3
...
hash(11) = 1
hash(12) = 2

What the does the line if a = b mean in ruby code? [duplicate]

This question already has answers here:
Why does single `=` work in `if` statement?
(5 answers)
Closed 6 years ago.
I am trying to understand a particular line in the following piece of code:
def roman_to_integer(roman_string)
prev = nil
roman_string.to_s.upcase.split(//).reverse.inject(0) do
|running_sum, digit|
if digit_value = DIGITS[digit]
if prev && prev > digit_value
running_sum -= digit_value
else
running_sum += digit_value
end
prev = digit_value
end
running_sum
end
end
Can someone please help me understand when the line if digit_value = DIGITS[digit] means? are we assigning the value corresponding to the key 'DIGIT' from the hash to the digit_value here?
are we assigning the value
Yes, we are. And we also check the truthiness of the operation. Assignment operator returns the value that was assigned. Now, if it was a digit, it will be a truthy result and control will enter the if.
If DIGITS[digit] returns nil or false, it will be assigned to digit_value and also it will also become result of the assignment operation. Those values are falsey, so we would enter the else, if we had one there. But we don't, so we just skip the if.
are we assigning the value corresponding to the key 'DIGIT' from the hash to the digit_value here?
Yes that is exactly what is happening. The temporary variable is slightly easier to read than the extraction from the hash. In similar circumstances, obtaining the value might be more expensive (think of a database read for example instead of a Hash lookup), so it is not a bad practice to get into.
The assignment operator also returns the value assigned for the if statement to work.
Alternative equivalent syntax is a bit more verbose:
digit_value = DIGITS[digit]
if digit_value
# .... etc
so this is also a common style choice when assigning a value to a variable and wanting to check its truthiness immediately.
if digit_value = DIGITS[digit] will return true if DIGITS[digit] has value other than nil or false. This is because in Ruby nil and false are the only values that are considered falsy.
Ruby will first assign the value to variable and than evaluate if the value is falsy.

Can I shortcut-check if a variable is `nil` and replace by a default value?

Is there a way to shortcut-check if a variable is nil, and give a default value if it is? For instance, replace
result = (var == nil ? defaultvalue : var)
with something like
result = selfifnotnil(var, default)
Of course I could write selfifnotnil function like the ternary above, but is there any built in option?
It's as simple as this (assuming that false and nil are treated the same)
result = var || defaultvalue
If false is a legitimate value (not a missing one), then you have to do that ternary.
result = var.nil? ? defaultvalue : var
Since nil is a falsely value. Therefore:
result = var || defaultvalue
Or if it is to check the var itself and assign default value. Also, if you are from another language, be careful which values are false in ruby.
result ||= default

Range and the mysteries that it covers going out of my range

I am trying to understand how range.cover? works and following seems confusing -
("as".."at").cover?("ass") # true and ("as".."at").cover?("ate") # false
This example in isolation is not confusing as it appears to be evaluated dictionary style where ass comes before at followed by ate.
("1".."z").cover?(":") # true
This truth seems to be based on ASCII values rather than dictionary style, because in a dictionary I'd expect all special characters to precede even digits and the confusion starts here. If what I think is true then how does cover? decide which comparison method to employ i.e. use ASCII values or dictionary based approach.
And how does range work with arrays. For example -
([1]..[10]).cover?([9,11,335]) # true
This example I expected to be false. But on the face of it looks like that when dealing with arrays, boundary values as well as cover?'s argument are converted to string and a simple dictionary style comparison yields true. Is that correct interpretation?
What kind of objects is Range equipped to handle? I know it can take numbers (except complex ones), handle strings, able to mystically work with arrays while boolean, nil and hash values among others cause it to raise ArgumentError: bad value for range
Why does ([1]..[10]).cover?([9,11,335]) return true
Let's take a look at the source. In Ruby 1.9.3 we can see a following definition.
static VALUE
range_cover(VALUE range, VALUE val)
{
VALUE beg, end;
beg = RANGE_BEG(range);
end = RANGE_END(range);
if (r_le(beg, val)) {
if (EXCL(range)) {
if (r_lt(val, end))
return Qtrue;
}
else {
if (r_le(val, end))
return Qtrue;
}
}
return Qfalse;
}
If the beginning of the range isn't lesser or equal to the given value cover? returns false. Here lesser or equal to is determined in terms of the r_lt function, which uses the <=> operator for comparison. Let's see how does it behave in case of arrays
[1] <=> [9,11,335] # => -1
So apparently [1] is indeed lesser than [9,11,335]. As a result we go into the body of the first if. Inside we check whether the range excludes its end and do a second comparison, once again using the <=> operator.
[10] <=> [9,11,335] # => 1
Therefore [10] is greater than [9,11,335]. The method returns true.
Why do you see ArgumentError: bad value for range
The function responsible for raising this error is range_failed. It's called only when range_check returns a nil. When does it happen? When the beginning and the end of the range are uncomparable (yes, once again in terms of our dear friend, the <=> operator).
true <=> false # => nil
true and false are uncomparable. The range cannot be created and the ArgumentError is raised.
On a closing note, Range.cover?'s dependence on <=> is in fact an expected and documented behaviour. See RubySpec's specification of cover?.

The most Pythonic way of checking if a value in a dictionary is defined/has zero length

Say I have a dictionary, and I want to check if a key is mapped to a nonempty value. One way of doing this would be the len function:
mydict = {"key" : "value", "emptykey" : ""}
print "True" if len(mydict["key"]) > 0 else "False" # prints true
print "True" if len(mydict["emptykey"]) > 0 else "False" # prints false
However, one can rely on the semantics of Python and how if an object is defined it evaluates to true and leave out the len call:
mydict = {"key" : "value", "emptykey" : ""}
print "True" if mydict["key"] else "False" # prints true
print "True" if mydict["emptykey"] else "False" # prints false
However, I'm not sure which is more Pythonic. The first feels "explicit is better than implicit", however the second feels "simple is better than complex".
I also wonder if the leaving out the len call could bite me as the dict I'm working with doesn't necessarily contain strings, but could contain other len-able types (lists, sets, etc). OTOH, in the former (with the len call) if None gets stored as a value the code will blow up, whereas the non-len version will work as expected (will eval to false).
Which version is safer and more Pythonic?
Edit: clarifying assumptions: I know the key is in the dictionary, and I know values will be len-able. I also cannot avoid having zero-length values enter the dictionary.
Edit #2: It seems like people are missing the point of my question. I'm not trying to determine the most Pythonic/safest way of checking if a key is present in a dictionary, I'm trying to check if a value has zero length or not
If you know the key is in the dictionary, use
if mydict["key"]:
...
It is simple, easy to read, and says, "if the value tied to 'key' evaluates to True, do something". The important tidbit to know is that container types (dict, list, tuple, str, etc) only evaluate to True if their len is greater than 0.
It will also raise a KeyError if your premise that a key is in mydict is violated.
All this makes it Pythonic.
print (bool(mydict.get('key')))
or, in an if statement:
print ('True' if mydict.get('key') else 'False')
If you the value not being present is an error case (i.e. you expect it to be there), you should choose solution #2, i.e.
print ('True' if mydict['key'] else 'False')
That allows mydict['key'] to choose the most efficient definition for being empty. For some objects (such as ones in clusters), determining the actual length is a fairly complicated operation, whereas it's simple to determine whether the object is empty or not.
You could also compare to '', i.e. mydict['key'] == '', to make your expression abundantly clear. Using len works, but is not as intuitive.
In summary, leave it to the tested object to define whether it's empty or not and just cast it to bool.
I'd use a variation of the first option:
>>> mydict = {"key" : "value", "emptykey" : ""}
>>> print bool(mydict["key"])
True
>>> print bool(mydict["emptykey"])
False
Any class that provides __len__ can be converted into a boolean directly (see Truth Value Testing), so bool(container) is the equivalent of bool(len(container)). A length of 0 will become the boolean False while all other lengths will be True. You'll never have a negative length object. Also, the booleans True and False can be printed directly via print, so you don't need the conditional.
From here:
In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.
I think it's safe to say that directly evaluating it is your best option - although, as #phihag said, it's safer to use get instead, as it will protect you from a KeyError.
The title and the first sentence actually express two slightly different questions.
For the title question
The most Pythonic way of checking if a value in a dictionary is defined
I'd go with
"key" in mydict
and for the second question
Say I have a dictionary, and I want to check if a key is mapped to a nonempty value.
I'd go with
"key" in mydict and bool(mydict["key"])
The first part of which checks to see whether "key" is present in mydict and the second part returns true for all values of "key" other then False, None, the empty string, the empty dictionary, the empty list and 0.
Of your two examples I prefer the second.
However, I advise against storing the empty keys. Also a defaultdict would work well here:
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> d[1].append(1)
>>> 1 in d
True
If you must store empty keys you don't need the string values "True" and "False". Just do this:
print bool(mydict[key])
You can simply check that any value in the dict is zero length or not by :
# To get keys which having zero length value:
keys_list = [key for key,val in mydict.items() if not val]
# To check whether the dict has any zero length value in it (returns True or False):
any_empty_vals = bool(len(['' for x in data_dict.values() if not x]))
Since I came here to know whether we can check the dictionary key is present or not for those the answer is:
if mydict.get(key,0):
---
and for the length of the key > 0, the answer is already provided by #Ethan Furman
if mydict[key]:
---
mydict = {"key" : "value", "emptykey" : ""}
if not mydict["emptykey"]:
print("empty value")
else:
print("value of emptykey",mydict["emptykey"])
Output
empty value
The most Pythonic way would be to not define the undefined value (although whether this is usable depends on what you're using it for) and use in:
mydict = {"key" : "value"}
print "True" if "key" in mydict else "False" # prints true
print "True" if "emptykey" in mydict else "False" # prints false
Otherwise, you have three options:
Use mydict.get. You should use this if the key might or might not be in the dictionary.
Use mydict[key]. You should use this if you are certain the key you want is in the dict.
Use len(mydict[key]) > 0. This only works if the value has __len__ defined. Usually, the truth value of a container value depends on the __len__ anyway, so the above are preferable.
When parsing a function's kwargs, it does make sense why the dictionary might contain a key whose value is None, and that you'd need to know whether that function's argument was passed in equal to None, or just not defined. Here's the simplest way to disabiguate:
def myfunct(**kwargs):
if 'thiskey' not in kwargs:
# this means that 'thiskey' was never passed into myfunct().
kwargs['thiskey'] = <default value>
else:
# you can define the defaults differently;
# if was defined as None, keep it set to None this way.
kwargs['thiskey'] = kwargs.get('thiskey', None)
# otherwise, any defined value passes through.
# do stuff...
I wanted to know which key is missing, so I could go fix it (in the db for example), but I also didn't want to do an if statement for each key in my dictionary! Here is my code:
def do_sth_with_data(data):
assert isinstance(data, dict)
expected_data_keys = {
"id",
"title",
"date",
"key4",
"key5",
"key6"
}
empty_keys = [key for key in expected_data_keys if not data.get(key)]
if empty_keys:
raise ValueError(f"{empty_keys} keys are not provided or are empty!")
If you also want to distinguish between key missing and value for the key is missing, you could add a script like this (change the code logic based on your need):
assert expected_data_keys.issubset(set(data.keys()))
Remember that data.get(key) will return None by default if either the key doesn't exist or the key exists but the corresponding value is empty (e.g. [], {}, None, "")
Your initial conditions are not Pythonic. Why are you storing a key with an empty value? Can you delete the key instead of setting it to None?
The Pythonic way is to check key existence with if key in dictionary, not checking for a non-empty value.

Resources