Finding the median of an array of floating point numbers - groovy

I've looked through all the examples in here already of this and nothing quite answers my question. I'm very new to Groovy.
I want to create something like a list or an array of floating point numbers, prices such as 239.99.
I then want to pass that array or list to a method that will determine the median price in that array or list of numbers. The total size will vary.
Is there any quick and easy code to do this? How do I add each number to the array or list and must I use doubles?
Any help is appreciated, this one has me stuck and frustrated.
Thanks!

The following function determines the median for non-empty lists.
def median(data) {
def copy = data.toSorted()
def middle = data.size().intdiv(2)
// you can omit the return in groovy for the last statement
data.size() % 2 ? copy[middle] : (copy[middle - 1] + copy[middle]) / 2
}
It works with all types that support addition and division.
For example:
assert median([1, 7, 4, 3]) == 3.5
assert median([1, 7, 4]) == 4
assert median([1, 7]) == 4
assert median([1]) == 1
assert median([1.7, 3.4, 10.9, 4.2]) == 3.8
In terms of what you can do with lists check the Lists overview and then the List API.

Related

Currying in python

I wrote the following function
def addsub(a):
def add(a):
def subtract(b):
return a-b
return subtract
return add(a)
addsub(9)(4)
returns 5
but what if I do not know to number of add subtract I want to perform
addsub(9)(3)(4)(5).
The above function does not work for it
could I write something general which works for any length of input?
PS. I do not want to use functools
It is not possible exactly like you describe (with currying). But if all you want is to sum the numbers of a list with a varying sign, this looks the most straightforward to me:
import itertools
coefficients = itertools.cycle((1, -1))
numbers = [9, 3, 4, 5]
result = sum(a * c for a, c in zip(numbers, coefficients))

How to add numbers within a list

the_list = ['diced tomatoes', 3, 'olives', 2, 'tomato soup', 3, 'tuna', 7]
def count_cans():
print(len(the_list))
So in this list there are 15 cans of food. how do I make a function that counts and returns the total amount of cans in the list.
Create a dictionary then sum the values in your dictionary:
the_list = {'diced tomatoes': 3, 'olives': 2, 'tomato soup': 3, 'tuna': 7}
sum(the_list.values())
Here you go
total_cans = 0
for food in the_list:
if (isinstance(food,int)): total_cans += food
print(total_cans)
With O(n) performance, goes through the list once.
Hi and welcome to StackOverFlow! As a general tip, it would be a lot more helpful for us to answer your question if you added what you've done so far like #Victor Wilson said, but nonetheless, we will try to help.
Think about what you may need to "increment" a "counter" variable (major hint here!). Since you are working with a list, you know that it is an iterable so you know you can use iterative processes like for-loops/while-loops and range() function to help you.
Once you find the "number of cans" (hint: type int), then you can increment that with your counter variable (hint: addition here).
Knowing what data types you're working with and what built-in methods that can be used with those types can be extremely helpful when learning to debug your own code.
And... by the time I finished my post, #bashBedlam seems to have answered you with a full program already ;). Hope this helps!
If you want to add only the numbers in a list, you can extract numbers from that list and then sum that sublist. That would mean something like,
def get_number(whatever):
try:
return float(whatever)
except ValueError:
return 0
your_list = ['diced tomatoes', 3, 'olives', 2, 'tomato soup', 3, 'tuna', 7]
total = sum([get_number(i) for i in your_list])
However, if you tell us your actual problem statement, I feel we can tackle the problem more efficiently. You should more likely use a different data structure. Use a hash-map/dictionary if you know that the items (condiments) in your list are unique or maybe use tuple/namedtuple to provide a structure to your input data - name-of-item: count-of-item. And then you can use more efficient techniques to extract your desired data.
I feel like this is some homework problem, and I am not quite sure about the policy of SO regarding that. Regardless of that, I would suggest focusing on the ideas provided by the answers here and apply yourself instead of copy-pasting the (pseudo-)solutions.
Yes you can use range function with loop to count numbers. Range function return sequence of numbers and takes 3 parameters
Syntax
range(start, stop, step).
start and step are optional.
To learn about range function, visit
https://www.w3schools.com/python/ref_func_range.asp
the_list = ['diced tomatoes', 3, 'olives', 2, 'tomato soup', 3, 'tuna', 7]
def count_cans():
count=0
for i in range(1,len(the_list)+1,2):
count+=int(the_list[i])
return count
Pick out the numbers and then add them up.
the_list = ['diced tomatoes', 3, 'olives', 2, 'tomato soup', 3, 'tuna', 7]
def count_cans (list) :
sum = 0
for element in list :
if type (element) == int :
sum += element
return sum
print (count_cans (the_list))
the_list = ['diced tomatoes', 3, 'olives', 2, 'tomato soup', 3, 'tuna', 7]
sum([the_list[i] for i in range(1,len(the_list),2)])
It works by :
creating a new list using a comprehension of the_list index by a range
starting with 1 and iterating every other value
then passing that to the sum() function

How can i convert many variable to int in one line

I started to learn Python a few days ago.
I know that I can convert variables into int, such as x = int (x)
but when I have 5 variables, for example, is there a better way to convert these variables in one line? In my code, I have 2 variables, but what if I have 5 or more variables to convert, I think there is a way
You for help
(Sorry for my English)
x,y=input().split()
y=int(y)
x=int(x)
print(x+y)
You could use something like this .
a,b,c,d=[ int(i) for i in input().split()]
Check this small example.
>>> values = [int(x) for x in input().split()]
1 2 3 4 5
>>> values
[1, 2, 3, 4, 5]
>>> values[0]
1
>>> values[1]
2
>>> values[2]
3
>>> values[3]
4
>>> values[4]
5
You have to enter value separated with spaces. Then it convert to integer and save into list. As a beginner you won't understand what the List Comprehensions is. This is what documentation mention about it.
List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
So the extracted version of [int(x) for x in input().split()] is similar to below function,
>>> values = []
>>> input_values = input().split()
1 2 3 4 5
>>> for val in input_values:
... values.append(int(val))
...
>>> values
[1, 2, 3, 4, 5]
You don't need to create multiple variables to save your values, as this example all the values are saved in values list. So you can access the first element by values[0] (0th element is the first value). When the number of input values are large, let's say 100, you have to create 100 variables to save it. But you can access 100th value by values[99].
This will work with any number of values:
# Split the input and convert each value to int
valuesAsInt = [int(x) for x in input().split()]
# Print the sum of those values
print(sum(valuesAsInt))
The first line is a list comprehension, which is a handy way to map each value in a list to another value. Here you're mapping each string x to int(x), leaving you with a list of integers.
In the second line, sum() sums the whole array, simple as that.
There is one easy way of converting multiple variables into integer in python:
right, left, top, bottom = int(right), int(left), int(top), int(bottom)
You could use the map function.
x, y = map(int, input().split())
print x + y
if the input was:
1 2
the output would be:
3
You could also use tuple unpacking:
x, y = input().split()
x, y = int(x), int(y)
I hope this helped you, have a nice day!

create list from list where values only increase by 1

I have the code below that gets the maximum value from a list. It then compares it to the maximum value of the remaining values in the list, and if it is more than 1 higher than the next greatest value, it replaces the original list maximum with 1 higher than the next greatest value. I would like the code to search the entire list and make sure that any value in the list is at most 1 larger than any other value in the list. I know this ins’t the best worded explanation, I hope the example lists below make what I’m trying to accomplish clearer.
for example I don’t want to get a final list like:
[0,2,0,3]
I would want the final list to be
[0,1,0,2]
input:
empt=[0,2,0,0]
Code:
nwEmpt=[i for i in empt if i !=max(empt)]
nwEmpt2=[]
for i in range(0,len(empt)):
if (empt[i]==max(empt))&(max(empt)>(max(nwEmpt)+1)):
nwEmpt2.append((max(nwEmpt)+1))
elif (empt[i]==max(empt))&(max(empt)==(max(nwEmpt)+1)):
nwEmpt2.append(max(empt))
else:
nwEmpt2.append(empt[i])
output:
nwEmpt2
[0,1,0,0]
min_value = min(empt)
empt_set = set(empt)
for i in empt:
nwEmpt.append(min_value + len(list(filter(lambda x: x < i, empt_set))))
This gives e.g. for input empt = [8, 10, 6, 4, 4] output nwEmpt = [6, 7, 5, 4, 4].
It works by mapping each element to (the minimum value) + (the number of distinct values smaller than element).

How I add values in a list I am using as the parameter for a function?

I am trying to understand these instructions.
Set up a new function in your main program file named “summer” that takes a list as a parameter and returns a value we will determine in the next steps.
In the “summer” function, set up a loop that uses a counter variable named “n” that will take on the values 0, 2, 4, 6, 8, 10, 12.
Each time through the loop, you are to call your “powerval” function from the “mymath” module passing as parameters item “n” and “n+1” from the list of data passed into “summer”. Add up all these values and return the final result to the caller.
So far I have:
def summer(list):
for n in range(0,13,2):
value=powerval(n,n+1)
After that I am lost. How do i perform step 3?
You add them up:
from mymath import powerval
def summer(somelist):
sum = 0
for n in range(0, 13, 2):
sum += powerval(somelist[n], somelist[n + 1])
return sum
So the return value of powerval() is added to the total sum so far, which was started at 0. You do need to pass in the somelist[n] and somelist[n + 1] values, not the indices themselves.
You need to add them up:
from mymath import powerval
def summer(lst):
total = 0
for n in range(0, 13, 2):
total += powerval(lst[n], lst[n + 1])
return total
I'm not sure where you use lst (I renamed list to lst, as list is a built-in function), so I'm guessing you're trying to get the nth and n + 1th elements from that list.
You can use the sum method to accomplish this in a very fashionable way :)
def summer(myList):
return sum(powerval(myList[n], myList[n+1]) for n in range(0, 13, 2))
This is also the fastest way.
PS: It's not a good idea to name you list "list", bacause that's a reserved name in python. That's why I have renamed it to myList in the example above.

Resources