How to do this in Groovy? - groovy

Lets say that there are two variable, the value of the variable is taken from the users. That is:
a=0
b=1
c=a-b
For some cases i need the variable c to be always positive, is there is any method in Groovy to do this?

Couple of options, depending on want behaviour you actually want when c is negative:
c = Math.abs(c) // -1 will become 1
c = Math.max(0,c) // -1 will become 0
// or it's an error condition
if( c < 0 ){
tellUserToStopMessingAroundAndEnterTheCorrectValues()
return
}

Related

Python adding column with condition not working as expected

I am trying to add a column based on a condition like
for i in range(len(data) - 1):
a = data.loc[i, 'column1']
b = data.loc[i+1, 'column1']
if a == b:
data['column2'] = 1
else:
data['column2'] = 0
This shows no error and the new column has been created, however the logic does not work, the new column is filled with 0 regardless of the logic. I have checked if a == b by printing the values for a and b with a == b and the result is as I expected. I am not sure why that is?
Note that the reason why I am using if statements is because my logic involves if and, else if
Inside the if statement, it should be data.loc[i,'column2'] this way it will right in the value at that location

Why does this fibonacci sequence work? Can someone help me?

Python beginner problem
(I am a beginner programmer)
So I was making a simple Fibonacci sequence generator and I made a working version, but I'm confused about how it works. In the code (lines 8-9), the first number (0) is being made the new value of the second value (1). But then that should make all the other numbers 0 as well, but it seems like the defining process is backward. Generally, the new value is on the left of the equal sign and the old value is on the right. But then that means everything should turn to 0. But actually, every number turns to 0 if I try to re-define the variables in the regular way (b = a; c = b). Why is this? I've attached my code at the bottom.
def seq_loop():
a = 0
b = 1
for i in range(15):
print(a)
c = a + b
a = b
b = c
print(seq_loop())
Have a good look at your code. Walk through it, and write down a,b and c in each iteration (or if you know how to use a debugger, set a break point in the loop te verify your variable's values). You'll see that your thinking is not right: in your first iteration: a = b is equivalent to a = 1 and b = c is equivalent to b = 1 + 1.
I am not sure that your interpretation of assignments is correct: An assignment goes right to left. The value (of the variable) on the right side of = is assigned to the variable on the left side of =
I don't really understand what you are asking, but a good way to understand code is to simply execute it by hand with pen&paper and keep a list of all the variables in scope and their current values. So, let's do that now.
In the first line, we define and initialize the variable a to the value 0. Our variables in scope and their values are { a = 0 }.
In the second line, we define and initialize the variable b to the value 1. Our variables in scope and their values are { a = 0; b = 1 }.
In the first line of the loop, we print the current value of the variable a, which we can look up in our variable list is 0. We haven't assigned any variables, so our variables in scope are still unchanged: { a = 0; b = 1 }. And the console looks like this:
0
In the second line of the loop, we define and initialize the variable c to the result of evaluating the expression a + b. We have to dereference the two variables, i.e. look up their values in our list, and their values are 0 and 1. 0 + 1 is 1, which means we initialize c to 1. Our variables in scope and their values are { a = 0; b = 1; c = 1 }.
In the third line of the loop, we assign the variable a. The value we assign to the variable a is the current value of the variable b. So, we look at our variable list, and we see that the current value of b is 1, which means we assign 1 to a. Our variables in scope and their values are { a = 1; b = 1; c = 1 }.
In the fourth line of the loop, we assign the variable b. The value we assign to the variable b is the current value of the variable c. So, we look at our variable list, and we see that the current value of c is 1, which means we assign 1 to b. Our variables in scope and their values are { a = 1; b = 1; c = 1 }.
After the fourth line of the loop, the variable c goes out of scope. Our variables in scope and their values are now { a = 1; b = 1 }.
As you can see, we started the first iteration of the loop with { a = 1; b = 0 } but after the first iteration of the loop, we have { a = 1; b = 1 }, which is what we start the second iteration of the loop with. It is important that something has changed here, otherwise each iteration of the loop would do the same thing, and we would always get the same result.
So, let's look at the second iteration of the loop.
In the first line of the loop, we print the current value of the variable a, which we can look up in our variable list is 1. We haven't assigned any variables, so our variables in scope are still unchanged: { a = 1; b = 1 }. And the console looks like this:
0
1
In the second line of the loop, we define and initialize the variable c to the result of evaluating the expression a + b. We look up their values in our list, and their values are 1 and 1. 1 + 1 is 2, which means we initialize c to 2. Our variables in scope and their values are { a = 1; b = 1; c = 2 }.
In the third line of the loop, we assign the variable a. The value we assign to the variable a is the current value of the variable b. So, we look at our variable list, and we see that the current value of b is 1, which means we assign 1 to a. Our variables in scope and their values are { a = 1; b = 1; c = 2 }.
In the fourth line of the loop, we assign the variable b. The value we assign to the variable b is the current value of the variable c. So, we look at our variable list, and we see that the current value of c is 2, which means we assign 2 to b. Our variables in scope and their values are { a = 1; b = 2; c = 2 }.
After the fourth line of the loop, the variable c goes out of scope. Our variables in scope and their values are now { a = 1; b = 2 }.
Now for the third iteration.
In the first line of the loop, we print the current value of the variable a, which we can look up in our variable list is 1. We haven't assigned any variables, so our variables in scope are still unchanged: { a = 1; b = 2 }. And the console looks like this:
0
1
1
In the second line of the loop, we define and initialize the variable c to the result of evaluating the expression a + b. We look up their values in our list, and their values are 1 and 2. 1 + 2 is 3, which means we initialize c to 3. Our variables in scope and their values are { a = 1; b = 2; c = 3 }.
In the third line of the loop, we assign the variable a. The value we assign to the variable a is the current value of the variable b. So, we look at our variable list, and we see that the current value of b is 2, which means we assign 2 to a. Our variables in scope and their values are { a = 2; b = 2; c = 3 }.
In the fourth line of the loop, we assign the variable b. The value we assign to the variable b is the current value of the variable c. So, we look at our variable list, and we see that the current value of c is 3, which means we assign 3 to b. Our variables in scope and their values are { a = 2; b = 3; c = 3 }.
After the fourth line of the loop, the variable c goes out of scope. Our variables in scope and their values are now { a = 2; b = 3 }.
And this is the fourth iteration of the loop.
In the first line of the loop, we print the current value of the variable a, which we can look up in our variable list is 2. We haven't assigned any variables, so our variables in scope are still unchanged: { a = 2; b = 3 }. And the console looks like this:
0
1
1
2
In the second line of the loop, we define and initialize the variable c to the result of evaluating the expression a + b. We look up their values in our list, and their values are 2 and 3. 2 + 3 is 5, which means we initialize c to 5. Our variables in scope and their values are { a = 2; b = 3; c = 5 }.
In the third line of the loop, we assign the variable a. The value we assign to the variable a is the current value of the variable b. So, we look at our variable list, and we see that the current value of b is 3, which means we assign 3 to a. Our variables in scope and their values are { a = 3; b = 3; c = 5 }.
In the fourth line of the loop, we assign the variable b. The value we assign to the variable b is the current value of the variable c. So, we look at our variable list, and we see that the current value of c is 5, which means we assign 5 to b. Our variables in scope and their values are { a = 3; b = 5; c = 5 }.
After the fourth line of the loop, the variable c goes out of scope. Our variables in scope and their values are now { a = 3; b = 5 }.
Let's do one last iteration of the loop.
In the first line of the loop, we print the current value of the variable a, which we can look up in our variable list is 3. We haven't assigned any variables, so our variables in scope are still unchanged: { a = 3; b = 5 }. And the console looks like this:
0
1
1
2
3
In the second line of the loop, we define and initialize the variable c to the result of evaluating the expression a + b. We look up their values in our list, and their values are 3 and 5. 3 + 5 is 8, which means we initialize c to 8. Our variables in scope and their values are { a = 3; b = 5; c = 8 }.
In the third line of the loop, we assign the variable a. The value we assign to the variable a is the current value of the variable b. So, we look at our variable list, and we see that the current value of b is 5, which means we assign 5 to a. Our variables in scope and their values are { a = 5; b = 5; c = 8 }.
In the fourth line of the loop, we assign the variable b. The value we assign to the variable b is the current value of the variable c. So, we look at our variable list, and we see that the current value of c is 8, which means we assign 8 to b. Our variables in scope and their values are { a = 5; b = 8; c = 8 }.
After the fourth line of the loop, the variable c goes out of scope. Our variables in scope and their values are now { a = 5; b = 8 }.
I hope it is somewhat clearer now.
One thing that is very important in programming is naming. Good names should be intention-revealing. In this case, none of the names are very good: what does the name a tell you about what the intent of the programmer is? The same goes for b, c, and i. seq_loop is also not very intention-revealing, i.e. what does this function actually do? It prints the Fibonacci sequence. How can I tell from the name that it prints the Fibonacci sequence? Well, I simply can't!
So, here is the code with some better names, which should clear up some confusion:
def print_fibonacci_sequence():
previous = 0
current = 1
for _ in range(15):
print(previous)
after = previous + current
previous = current
current = after
print(print_fibonacci_sequence())
You might ask yourself "How is _ a more intention-revealing name than i?" The reason is that _ has a well-known meaning in the Python community: it is used as the name for a variable that is being ignored. Which is exactly what we are doing in this case.
Also, why after and not next? next is already defined in Python and it is considered bad style to shadow or even worse redefine Python builtins.
There are a couple of other oddities in the code. For example, the function prints the elements of the Fibonacci sequence and it doesn't return anything. And then you call the function and print the result of the call … but there is no result because the function doesn't return anything! Renaming the function to have print in its name so that it is clear that it doesn't return anything but prints it, makes that mistake more obvious:
print(print_fibonacci_sequence())
You can immediately see that you print something which prints something, which makes no sense. It should just be
print_fibonacci_sequence()
Another oddity is that the function always prints the first 15 terms of the Fibonacci sequence. Usually, you would want to let the caller decide how many terms to print. Maybe the caller only needs 3? Maybe 20? So, let's do that:
def print_fibonacci_sequence(number_of_elements):
previous = 0
current = 1
for _ in range(number_of_elements):
print(previous)
after = previous + current
previous = current
current = after
print_fibonacci_sequence(15)
Speaking of letting the caller decide what to do, what if the caller doesn't want to print the Fibonacci sequence? What if the caller wants to format it as HTML or insert it into an Excel table?
You should always separate computation from input/output. So, in this case, instead of printing the Fibonacci sequence, we will return the Fibonacci sequence, and then the caller can print it if they want to:
def fibonacci_sequence(number_of_elements):
fibonacci_sequence = []
previous = 0
current = 1
for _ in range(number_of_elements):
fibonacci_sequence.append(previous)
after = previous + current
previous = current
current = after
return fibonacci_sequence
print(fibonacci_sequence(15))
Actually, if you think about it, having the caller pass the number of terms as an argument is still somewhat restrictive. What if the caller doesn't want the first n terms, but the first terms smaller than n? In that case, they would have to compute the Fibonacci sequence first to see how many terms there are smaller than n and then ask for that number of terms of the Fibonacci sequence, which obviously defeats the purpose of having the function in the first place.
The best solution for the caller would be to produce an infinite number of terms and let the caller decide which condition to use to decide how many terms to take:
def fibonacci_sequence():
previous = 0
current = 1
while True:
yield previous
after = previous + current
previous = current
current = after
Now you can use it like this:
from itertools import islice, takewhile
first_15_terms = islice(fibonacci_sequence(), 15)
terms_less_than_100 = takewhile(lambda term: term < 100, fibonacci_sequence())
And you can decide what to do with the result. For example print it:
for term in first_15_terms:
print(term)
for term in terms_less_than_100:
print(term)
Or you can turn it into a list:
list_of_first_15_terms = list(first_15_terms)
list_of_terms_less_than_100 = list(terms_less_than_100)
And many other things.
This is a general principle in programming, software engineering, and API design: not only separate input/output from computation, but also break up the computation into separate parts for producing values, consuming values, transforming values, filtering values, representing values as strings (to be output later), parsing string representations into values (coming in from the outside), and so on.
In one sentence, we could say: separate the things that change.

Haskell - How to modify existing function values

i have a basic question regarding Haskell that boggles my mind since i am new to functional programming.
i've got simple functions for example
foo 1 1 = 0
foo 1 2 = 1
foo 2 1 = 1
foo 2 2 = 0
and i want to change the function values depending on a condition via another function (for example from 1 to 0, if the value is 1). How can i do that? I'm comming from python and am somehow stuck in the way of thought that i can simply assign the new value in the function body.
im trying something along this lines:
changeValue x y
|(foo x y == 1) = foo x y = 0
A little hint would be appreciated, since it feels like a simple question that i just can't find a solution for. Thanks!
Maybe having a look at http://learnyouahaskell.com/syntax-in-functions helps? Think of haskell functions as mathematical functions, there's no assignment there either.
Anyway, you can ask an other function for a value to compare to, and e.g. in that case return 1:
foo 0 1 = 1
foo x y
| otherfunction x y == 7 = 1
| otherwise = 0

Why am i getting a list index out of range error in my code?

The error occurs in line if data[l][0] == value:
def binary_pairs(data, value):
l = 0
h = len(data) - 1
while l < h and data[l]!= value:
m = (h + l) // 2
if data[m][0] == value:
l = m
elif data[m][0] < value:
l = m + 1
else:
h = m - 1
print("done")
if data[l][0] == value:
return l
else:
return -1
example input:
[ [ "dead", ["brian.txt","grail.txt"] ],
[ "eunt", ["brian.txt"] ],
[ "spank", ["grail.txt"] ]
]
I can see two potential issues with your code:
It seems odd that you use both data[l] and data[l][0] in comparisons.
If, for example, l==0 and h==1 and you end up taking the else (h = m - 1), you'd end up with h==-1, which is out of bounds. There could be other similar issues.
I can't run your code right now but here are a few ideas.
If you are trying to solve a problem, rather than trying to learn to write a binary search, consider using Python's bisect module.
http://docs.python.org/2/library/bisect.html
It is best practice in Python to comply with the coding standard called PEP 8; this recommends not using lower-case L as a variable name, or upper-case I.
http://www.python.org/dev/peps/pep-0008/
It would be cleaner to have the loop immediately return the index when it finds the value, rather than having the loop test at the top to make sure the value hasn't been found yet, causing the loop to end and then the value to be returned from the bottom of the function. If the loop ends, you can return -1 at the end of the function.
Your loop checks that the index is < h but does not check that the index is I >= 0. I suspect that this could be your problem.
When debugging a loop like this, it is often helpful to add print statements that log what is going on. You should print the value of the index, and print enough other lines to know whether it is being increased or decreased, and by how much.

groovy: how to simplify/rewrite this method in groovy

protected int xMethod (Integer a, Integer b) {
if (a<b)
return 1
else if (a>b)
return 2
else
return 3
}
I wonder if there is some way of rewriting above method differently in groovy? as now is very Java style.
It seems that the function just needs to return 3 different values depending on whether a is less than, equal to, or greater than b. There is already an operator in Groovy that does this:
a <=> b
The return values are -1, 0 and 1. Perhaps the best thing to do is refactor the code to use this operator instead of xMethod, if that is possible.
Of course, if the precise values 1, 2 and 3 are important and not just 3 distinct values then you can't do this.
Just to expand on Mark's answer:
protected int xMethod (Integer a, Integer b) {
switch ( a <=> b ) {
case -1: 1; break
case 1: 2; break
case 0: 3; break
}
}
However, you have to question whether this method has any value. If the caller can be changed to accept -1, 0, 1 then the method has no reason to exist.
How about:
return (a <=> b) + 2
If you remove the two occurrences of Integer from the signature, you can call the method with any parameters for which < is defined.
E.g.
assert x.xMethod(1, 2)==1
assert x.xMethod("2", "1")==2
assert x.xMethod(2.0, 2.0)==3

Resources