For example a negative number -1
I think this is an expression with a unary operator '-' and a numeric literal '1'.
But I cannot be sure.
In terms of the Python grammar, -1 is not a literal. It's a unary negation applied to a literal 1. As well as being deducible from the lexical rules of Python, this is also explicitly stated in the documentation of Python's lexical structure:
Note that numeric literals do not include a sign; a phrase like -1 is actually an expression composed of the unary operator ‘-‘ and the literal 1.
Most of the time, though, people will refer to -1 as a literal, much the same way they refer to [1, 2, 3] as a "list literal" even though the grammar calls that a "list display".
Well, I could say, "a little of this and a little of that", check this expressions in a python's prompt:
2-3
=> -1
--1
=> 1
-1
=> -1
---1
=> -1
----1
=> 1
-(5+10)
=> -15
It depends on the context though, look at this example:
-1
=> -1
here, - denotes the negative of the int , but look at this one:
2-3
=> -1
here is unary operation:
-(5+10)
=> -15
here, the - denotes the sub function, and the others... just cancelations.
Related
I am currently learning python, but also other programming languages. Now I've run into a dilemma. I have the following code that i need to translate to three different programming languages, but before I do that I want to know in detail how the code works. The code (in python) is :
my_secret_key = 5
def decrypt(secret_string, secret_number):
result = ""
for x in secret_string:
result = result + chr(ord(x) ^ int(secret_number))
return result
print(decrypt("alq%lv%``k%b`m`lh", my_secret_key))
Now I have basic knowledge of Python and understand parts of this code, but the calculation it is making is difficult for me to understand.
Are there people willing to help me translate this code to human language so I can then find my way to translate this into other programming languages.
Thanks!
I have tried to look up the functions of chr and ord, and combined this with the x ^ int(secret_number). I tried to devide the code into blocks which helped me understand parts of it.
I tried just applying the calculation blocks but that doesnt work, it needs the full code to work
Explained with comments above each line:
def decrypt(secret_string, secret_number):
result = ""
# for each character in the encrypted string:
for x in secret_string:
# 1. convert the character to `int` using the `ord` function
# 2. convert the secret_number to `int` using the `int` function (this
# is redundant is this example, as `my_secret_key` is already `int`)
# 3. XOR the two integers with each other
# 4. convert the result from `int` back to `char` (actually 1-element
# string) using `chr`, and append it to the result string
result = result + chr(ord(x) ^ int(secret_number))
# return the decrypted string
return result
Regarding the ^ operator, from Python docs:
The ^ operator yields the bitwise XOR (exclusive OR) of its arguments [...]
This means that the result is an integer, whose binary representation will have:
zeros on bit positions where both arguments had 0, or both arguments had 1
ones on bit positions where one of the arguments had 0, and the other had 1
Example:
argument 1: 001 (binary), 1 (decimal)
argument 2: 011 (binary), 3 (decimal)
---
XOR result: 010 (binary), 2 (decimal)
^
bits in argument 1 and 2 on this position have different values,
so the result is 1
You can find more info on the XOR operation e.g. on Wikipedia: Exclusive or, XOR Cipher
Trying to decipher some Excel formulas and I see some stuff like SUMPRODUCT(--Left(...)...)
What is the -- doing? Naturally seems like decrementing to me but couldn't find any documentation on it.
The double-dash is known as a double unary operator.
Try this link: Why use -- in SUMPRODUCT formulae
Specifically:
SUMPRODUCT() ignores non-numeric entries. A comparison returns a boolean (TRUE/FALSE) value, which is non-numeric. XL automatically coerces boolean values to numeric values (1/0, respectively) in arithmetic operations (e.g., TRUE + 0 = 1).
The most efficient way to coerce the value is first to apply the unary minus operator, coercing TRUE/FALSE to -1/0, then applying it again to negate the value, e.g., +1/0.
A single unary operator (-) coerces true/false values into -1/0. By using the double unary operaor, we coerce the values again to 1/0.
The unary operator (-) is a shorthand method to convert a true/false statement into -1/0.
A single operator will convert -(true) into -1, so a double unary operator is used to convert that back into 1:
-(-(true)) = -(-(1)) = 1
-(-(false)) = -(-(0)) = 0
I've been using SUMPRODUCT for a while and have always used the * symbol instead of the --. I'm sure I asked the same question you've asked, but I can't remember the reason they gave me, but I was told that there wasn't really a need for --as sumproduct managed itself quite well without the it.
Anyway, =sumproduct(()*()*()*()) has always worked for me, and it's less confusing.
Boolean values TRUE and FALSE in excel are treated as 1 and 0, but we need to convert them. To convert them into numbers 1 or 0, do some mathematical operation. The Unary operator negates the boolean (math operation), hence, converts the boolean to number. Same works in TRUE * FALSE = 0
I would like to ask something about data types in Lua.
I get from serial link some message (command:value) like this:
tmp_string = "BRAKE:1"
then I parse this string to command and value in two different functions (one is for command and other one is for value). This is function for parsing value
function parser(value)
index = string.find(value, ":")
result = value.sub(value, index+1)
return result
end
I would like to now what sort of data type result is? If I use string match it works.
...if string.match(state, "1") then...
However it also works when I do something like this
x = (state*65536)/3.2808)
I thought the result is string, but I don't understand why it works also with numerical operations. Thank you in advance.
Lua 5.3 Reference Manual, §3.4.1 - Arithmetic Operators
With the exception of exponentiation and float division, the arithmetic operators work as follows: If both operands are integers, the operation is performed over integers and the result is an integer. Otherwise, if both operands are numbers or strings that can be converted to numbers (see §3.4.3), then they are converted to floats, the operation is performed following the usual rules for floating-point arithmetic (usually the IEEE 754 standard), and the result is a float.
Emphasis is mine.
When dealing with operations, Lua will attempt to convert string operands to floats, and if it works - it works. If it fails, you get an error.
>| '55' / 2
<| 27.5
>| 'foo' / 2
<| error: [string "return 'foo' / 2"]:1: attempt to perform arithmetic on a string value
If you want to be explicit about this (and safe) use tonumber, and handle the nil-case.
If you need to know the type of a value in Lua, you can pass the variable to type and check the resulting string.
I am doing some classification and needed to convert an integer code to strings for that reason. I wrote something like this:
s(1).class = 1;
s(2).class = 7;
s(3).class = 9;
[s([find([s.class] == 1)]).class] = deal('c1'); %first conversion
[s([find([s.class] > 1)]).class] = deal('c2'); %second conversion
and was surprised to find s being a 1x4 struct array after the second conversion instead of the expected 1x3 struct array with the values.
Now, after some research, I understand that after the first conversion the value of s(1).class is 'c1' and the argument to find in the second conversion is not what I assumed it would be. The [s.class] statement actually returns something like the string 'c1\a\t' with ASCII escape sequences for bell and horizontal tab.
As the comparison does work (returning the matrix [1 1 1 1] and thus expanding my structure) I assume that matlab converts either the operand [s.class] or the operand 1.
Which is it? What actually is compared here numbers or characters?
And on the other hand is there a built in way to make > more restrictive, i. e. to require the operands to be of the same type and if not to throw an error?
When you do the comparison 'ab' > 1, the char array 'ab' gets converted to a double array, namely the ASCII codes of the characters. So 'ab' > 1 is equivalent to double('ab') > 1, which gives [1 1].
To get the behaviour you want (issue an error if one of the arguments is char) you could define a function:
function z = greaterthan(x,y)
if ischar(x) || ischar(y)
error('Invalid comparison: one of the input arguments is of type char')
else
z = x>y;
end
so that
>> greaterthan([0 1 2], 1)
ans =
0 0 1
>> greaterthan('ab', 1)
??? Error using ==> greaterthan at 3
Invalid comparison between char and int
Because you have not provided any expected output yet, I am going with the observations.
You are using a comprehension method (by invoking find) to determine which locations you will be populating for struct s with the results from your method deal (takes the argument c1 and c2). You have already set your type for s{whatever).class in the first snippet you provided. Which means it is number you are comparing, not character.
There is this isa function to see which class your variable belongs to. Use that to see what it is you are actually putting in (should say int32 for your case).
I'm fairly new to Haskell programming and I'm having trouble understanding why I'm receiving this error in my code.
My problem is as follows: Any positive integer i can be expressed as i = 2^n*k, where k is odd, that is, as a power of 2 times an odd number. We call n the exponent of 2 in i. For example, the exponent of 2 in 40 is 3 (because 40 = 2^3*5) whereas the exponent of 2 in 42 is 1. If i itself is odd, then n is zero. If, on the other hand, i is even, that means it can be divided by 2. Write a function exponentOfTwo for finding the exponent of 2 in its argument.
I understand the psuedocode and it seems fairly simple: recursively divide i by 2 until result is odd, the number of times the division happens is n
here is my code (line 31-32):
exponentOfTwo :: Int -> Int
exponentOfTwo i = if odd i then 0 else 1 + exponentOfTwo (i 'div' 2)
I'm receiving the error "lexical error in string/character literal at character 'i'" on line 32 column 62.
I've tried searching for a solution to this error everywhere and so far I've had no luck.
To use a function in infix for, surround it with backticks (`), not with single quotes ('). The latter are for character literals, which, well are only one character long.
Are the characters around div backquotes rather than normal quotes? They need to be to allow a function name to be used as an infix operator. I changed that in your definition and the code worked for me.