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.
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
This challenge in Hackerrank is to shift the string using Julia(programming language( and return the string. I have a function that takes in 3 arguments.
shiftStrings("string", leftShifts, rightShifts)
Left Shift: A single circular rotation of the string in which the first character becomes the last character and all other characters are shifted one index to the left. For example, abcde becomes bcdea after 1 left shift and cdeab after 2 left shifts.
Right Shift: A single circular rotation of the string in which the last character becomes the first character and all other characters are shifted to the right. For example, abcde becomes eabcd after 1 right shift and deabc after 2 right shifts.
I passed only 3 out of 13 test cases. Here is my solution. Please let me know the better solution.
Please refer this, they have done by python
How to shift characters in a string? - Hackerrank challenge
If you take a look at the question you linked they already had an answer to that in python.
def getShiftedString(s, leftShifts, rightShifts):
i = (leftShifts - rightShifts) % len(s)
return s[i:] + s[:i]
If you want to shift a string to the right and then to the left you just need the difference of both. I.e. if you shift 3 to the right and 3 to the left it's like you didn't change anything. "abcde" 3 to the left -> "deabc" 3 to the right -> "abcde".
Therefore, this leads to:
function shiftStrings(str, l, r)
i = mod(l - r, length(str))
str[i+1:end] * str[1:i]
end
Note:
i is the total amount of leftshifts (you take the modulo of leftshifts minus the rightshifts)
Python indexing starts from 0, whereas Julia indexing starts from 1, while modulo returns a 0 if l-r==0, that's why [i+1:end] and [1:i]
If you have Utf8 encoding then you can formulate it like this:
function shiftStrings(str, l, r)
i = mod(l - r, length(str))
indices = collect(eachindex(str))
str[indices[i+1]:end] * str[1:indices[i]]
end
Utf8 characters do not correspond to 1 byte per character, that's why the character indices are different that the String indices. (String indexing starts at every new byte, but some characters like the German "ö" need more than 1 byte)
function getShiftedString(s, leftShifts, rightShifts)
len=length(s)
lr=mod(leftShifts,len)
rr=len-mod(rightShifts,len)
ls1=SubString(s,lr+1,length(s))
ls2=SubString(s,1,lr)
ls=ls1*ls2
rs1=SubString(ls,rr+1,length(s))
rs2=SubString(ls,1,rr)
rs=rs1*rs2
end
So I'm using the String.sub function and I'm wondering if there's any way to get all the characters in a string until the end of the string. Since String.sub takes in a string, int (the index of where to start getting chars), and then a number of how many chars, I'm not sure what the easiest way of doing all chars since we want a possibly positive infinite amount
For String.sub you just have to subtract from the length of the string. There's no simpler way, i.e., there's no value for length that has a special meaning. A value larger than the remainder of the string is an error in OCaml (which tends to be strict when checking parameters).
Assume i is >= 0 and < length of the string:
String.sub s i (String.length s - i)
You can use Str.last_chars, but you still need to know how many characters you want. I.e., you still have to subtract from the length of the string.
Str.last_chars s (String.length s - i)
I believe there are no LeftStr(str,n) (take at most n first characters), RightStr(str,n) (take at most n last characters) and SubStr(str,pos,n) (take first n characters after pos) function in Go, so I tried to make one
// take at most n first characters
func Left(str string, num int) string {
if num <= 0 {
return ``
}
if num > len(str) {
num = len(str)
}
return str[:num]
}
// take at most last n characters
func Right(str string, num int) string {
if num <= 0 {
return ``
}
max := len(str)
if num > max {
num = max
}
num = max - num
return str[num:]
}
But I believe those functions will give incorrect output when the string contains unicode characters. What's the fastest solution for those function, is using for range loop is the only way?
As mentioned in already in comments,
combining characters, modifying runes, and other multi-rune
"characters"
can cause difficulties.
Anyone interested in Unicode handling in Go should probably read the Go Blog articles
"Strings, bytes, runes and characters in Go"
and "Text normalization in Go".
In particular, the later talks about the golang.org/x/text/unicode/norm package which can help in handling some of this.
You can consider several levels increasingly of more accurate (or increasingly more Unicode aware) spiting the first (or last) "n characters" from a string.
Just use n bytes.
This may split in the middle of a rune but is O(1), is very simple, and in many cases you know the input consists of only single byte runes.
E.g. str[:n].
Split after n runes.
This may split in the middle of a character. This can be done easily, but at the expense of copying and converting with just string([]rune(str)[:n]).
You can avoid the conversion and copying by using the unicode/utf8 package's DecodeRuneInString (and DecodeLastRuneInString) functions to get the length of each of the first n runes in turn and then return str[:sum] (O(n), no allocation).
Split after the n'th "boundary".
One way to do this is to use
norm.NFC.FirstBoundaryInString(str) repeatedly
or norm.Iter to find the byte position to split at and then return str[:pos].
Consider the displayed string "cafés" which could be represented in Go code as: "cafés", "caf\u00E9s", or "caf\xc3\xa9s" which all result in the identical six bytes. Alternative it could represented as "cafe\u0301s" or "cafe\xcc\x81s" which both result in the identical seven bytes.
The first "method" above may split those into "caf\xc3"+"\xa9s" and cafe\xcc"+"\x81s".
The second may split them into "caf\u00E9"+"s" ("café"+"s") and "cafe"+"\u0301s" ("cafe"+"́s").
The third should split them into "caf\u00E9"+"s" and "cafe\u0301"+"s" (both shown as "café"+"s").
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).