I need a code to swap the value of two variables without using third variable but only with AND, OR & NOT operators
I have tried it but i always lost one value
Exact code
a = 1
b = 2
# swap
a, b = b, a
For integers, you can use xor:
x = x ^ y
y = x ^ y
x = x ^ y
But otherwise you should just stick to standard swapping practice:
x, y = y, x
The code above creates the tuple (y, x) and unpacks it to x and y
>>> a = 5
>>> b = 6
>>> a+=b
>>> b = a - b
>>> a = a - b
>>> a
6
>>> b
5
>>>
As the pythonic approach and the arithmetic approach have already been submitted as answers, I will present the bitwise xor approach, as outlined on wikipedia:
a = a ^ b
b = b ^ a
a = a ^ b
Of course, you can simplify that if you want:
a ^= b
b ^= a
a ^= b
It's really important to note that this only works on things that can be represented bitwise, like integers. Python will raise an error if you try it on floats or strings or most other datatypes.
Related
I am new to Haskell and trying few things. I have a small program.
module Collatz where
compute_collatz :: Integer -> Integer
compute_collatz x = if even x then evenComputation else oddcomputation
where evenComputation = div x 2
oddcomputation = 3 * x + 1
compute_steps :: Integer -> Integer
compute_steps 1 = 0
compute_steps num = 1 + compute_steps(compute_collatz(num))
I wanted to print the sequence of numbers generated by each compute_collatz(num) call. How can I add a print or show statement in either compute_steps or compute_collatz functions
This is not a good approach.
A better alternative is to make the result of the function a list of visited numbers, instead of just the final one.
collatzSeq :: Integer -> [Integer]
collatzSeq 1 = [1]
collatzSeq x
| even x = x : collatzSeq (x`div`2)
| otherwise = x : collatzSeq (3*x + 1)
Then you can use this list for counting steps, printing, whatever. Note that thanks to lazyness you need need to worry that the whole list would need to be computed before the printing starts – it'll just print as you go in the computation.
If I have a function, for example
f :: Int -> Int -> Int
f x y = x + y
and I want to have different functionality based on the parameters, I use pattern matching.
I have only found the syntax of how to match against concrete values, e.g.
f 0 y = y
Is it possible to match against something more general?
I would like to have different functionality in the case that the first parameter is less than 0. A second case could be if the second parameter exceeds a certain value.
You can use guards:
f x y | x < 0 = ...
f x y | y > someValue = ...
f x y | otherwise = ...
Sure, there is a mechanism called guards for that:
f x y | x < 0 = y
I was reading the Haskell Prelude and finding it pretty understandable, then I stumbled upon the exponention definition:
(^) :: (Num a, Integral b) => a -> b -> a
x ^ 0 = 1
x ^ n | n > 0 = f x (n-1) x
where f _ 0 y = y
f x n y = g x n where
g x n | even n = g (x*x) (n `quot` 2)
| otherwise = f x (n-1) (x*y)
_ ^ _ = error "Prelude.^: negative exponent"
I do not understand the need for two nested wheres.
What I understood so far:
(^) :: (Num a, Integral b) => a -> b -> a
The base must be a number and the exponent intege, ok.
x ^ 0 = 1
Base case, easy.
g x n | even n = g (x*x) (n `quot` 2)
| otherwise = f x (n-1) (x*y)
Exponention by squaring... kind of ... Why is the f helper needed? Why are f and g given single letter names? Is it just optimization, am I missing something obvious?
_ ^ _ = error "Prelude.^: negative exponent"
N > 0 was checked before, N is negative if we arrived here, so error.
My implementation would be a direct translation to code of:
Function exp-by-squaring(x, n )
if n < 0 then return exp-by-squaring(1 / x, - n );
else if n = 0 then return 1; else if n = 1 then return x ;
else if n is even then return exp-by-squaring(x * x, n / 2);
else if n is odd then return x * exp-by-squaring(x * x, (n - 1) / 2).
Pseudocode from wikipedia.
To illustrate what #dfeuer is saying, note that the way f is written it either:
f returns a value
or, f calls itself with new arguments
Hence f is tail recursive and therefore can easily be transformed into a loop.
On the other hand, consider this alternate implementation of exponentiation by squaring:
-- assume n >= 0
exp x 0 = 1
exp x n | even n = exp (x*x) (n `quot` 2)
| otherwise = x * exp x (n-1)
The problem here is that in the otherwise clause the last operation performed is a multiplication. So exp either:
returns 1
calls itself with new arguments
calls itself with some new arguments and multiplies the result by x.
exp is not tail recursive and therefore cannot by transformed into a loop.
f is indeed an optimization. The naive approach would be "top down", calculating x^(n `div` 2) and then squaring the result. The downside of this approach is that it builds a stack of intermediate computations. What f lets this implementation do is to first square x (a single multiplication) and then raise the result to the reduced exponent, tail recursively. The end result is that the function will likely operate entirely in machine registers. g seems to help avoid checking for the end of the loop when the exponent is even, but I'm not really sure if it's a good idea.
As far as I understand it exponentiation is solved by squaring as long as the exponent is even.
This leads to the answer why f is needed in case of an odd number - we use f to return the result in the case of g x 1, in every other odd case we use f to get back in the g-routine.
You can see it best I think if you look at an example:
x ^ n | n > 0 = f x (n-1) x
where f _ 0 y = y
f x n y = g x n
where g x n | even n = g (x*x) (n `quot` 2)
| otherwise = f x (n-1) (x*y)
2^6 = -- x = 2, n = 6, 6 > 0 thus we can use the definition
f 2 (6-1) 2 = f 2 5 2 -- (*)
= g 2 5 -- 5 is odd we are in the "otherwise" branch
= f 2 4 (2*2) -- note that the second '2' is still in scope from (*)
= f 2 4 (4) -- (**) for reasons of better readability evaluate the expressions, be aware that haskell is lazy and wouldn't do that
= g 2 4
= g (2*2) (4 `quot` 2) = g 4 2
= g (4*4) (2 `quot` 2) = g 16 1
= f 16 0 (16*4) -- note that the 4 comes from the line marked with (**)
= f 16 0 64 -- which is the base case for f
= 64
Now to your question of using single letter function names - that's the kind of thing you have to get used to it is a way most people in the community write. It has no effect on the compiler how you name your functions - as long as they start with a lower case letter.
As others noted, the function is written using tail-recursion for efficiency.
However, note that one could remove the innermost where while preserving tail-recursion as follows: instead of
x ^ n | n > 0 = f x (n-1) x
where f _ 0 y = y
f x n y = g x n
where g x n | even n = g (x*x) (n `quot` 2)
| otherwise = f x (n-1) (x*y)
we can use
x ^ n | n > 0 = f x (n-1) x
where f _ 0 y = y
f x n y | even n = f (x*x) (n `quot` 2) y
| otherwise = f x (n-1) (x*y)
which is also arguably more readable.
I have however no idea why the authors of the Prelude chose their variant.
I've a question regarding list comprehension
[(x,y)| x<-[1..2], y<-[x..3], let z = x+y, odd z]
Why does this evaluate to:
[(1,2),(2,3)]
?
Where is the z going?
Thanks
Your predicate is "z = x + y for all z odd". If you "unroll" the flow:
z = predicate, and y(x) so for:
x = 1,2
y (1) = 1,2,3
y (2) = 2,3
Based on the combination of the values filtered by the predicate:
x+y <= filter(z)
1+1 = 2 NO
1+2 = 3 OK
1+3 = 4 NO
2+2 = 4 NO
2+3 = 5 OK
so the ok answers are for x = 1 and y = 2 and x = 2 and y =3 => [(1,2), (2,3)]
I have started this a new question as it became a follow-on from my previous question.
If I have two data types which are composed of similar constructors:
data A = X | Y | Z
data B = X | Y
is there no way I can somehow represent this as:
data A = C | Z
data B = C
data C = X | Y
if you can see what I am doing- I am trying to group the X | Y into one data type, which can then be used by multiple other data types. I cannot seem to get the compiler to allow this, or if it does, I cannot pattern-match against the X or Y, only the C??
I get the error message that C has been declared multiple times.
I thought I could maybe use types, but they do not allow multiple typings.
EDIT
Even if I declare the long way (like below), it still won't compile and says X and Y have multiple declarations:
data A = X | Y | Z
data B = X | Y
Not only can't you do this, you also can't do your first option - i.e. you can't have two types in the same module that both have constructors named X and Y.
If you could do this, what should the type of X be - C, A or B? The most obvious answer would be C, but then you wouldn't be able to use it in a context where an A or a B are required (note that Haskell has no subtyping), so that would defeat the purpose of the whole construct.
The best you can do is to wrap C in a constructor of A and B, i.e.:
data A = AC C | Z
data B = BC C
data C = X | Y
Then you could wrap a C with either the AC or the BC constructor to create a value of type A or B respectively.
The reason you can't do this
data A = X | Y | Z
data B = X | Y
is as follows. Say you write some code later on:
foo n = (n,X)
which builds a pair consisting of n in the first slot and X in the second slot. What type should the compiler infer? A valid type would be
foo :: a -> A -> (a,A)
since X is a constructor of type A, but equally valid is
foo :: a -> B -> (a,B)
since X is a constructor of type B. If you have two constructors with the same name, you can't infer a unique type for functions that use them. So you are disallowed from giving two constructors in the same module the same name.
You can't do this:
data A = C | Z
data B = C
data C = X | Y
(As an aside, if B is identical to C, then why have B at all?)
But what you can do is something like this:
data A = A_Other C | Z
data B = B_Other C
data C = X | Y
Then you can pattern match like this:
foo :: A -> String
foo (A_Other X) = "X"
foo (A_Other Y) = "Y"
foo ( Z) = "Z"
bar :: B -> String
bar (B_Other X) = "X"
bar (B_Other Y) = "Y"
foobar :: C -> String
foobar X = "X"
foobar Y = "Y"
If that makes sense...
You cannot do what you want because you are declaring multiple data constructors. In
data A = X | Y | Z
You are actually introducing the type A which has 3 constructors (values) X, Y, and Z. This is why your first piece of code won't compile, it sees the same name listed as constructors for two different types! If you could do this you'd have to ask yourself is
X :: A
or
X :: B
which in a non object-oriented context is scary! So you need to provide different constructor names to share that underlying data, C.
If you want to factor this, you can do as the other posts have suggested and factored-out data in unique constructors for each datatype
data A = CForA C | Z
data B = CForB C
data C = X | Y