Finding Minimum of Long List Python - python

I am working with numbers in a list separated by commas. I am trying to find the minimum number in this data for multiple ranges.(i.e. Find the minimum number listed in the range 0-100)
My problem is whenever I run the following code, I get a long list of about 4 repeating integers. Any ideas on how to get just one number?
Thank you!
mylist = []
def sort_data(x, y):
for line in filename:
for number in line.split():
if int(number) > x and int(number) < y:
mylist.append(int(number))
print(min(mylist))

This is what you can use:
from itertools import ifilter # only needed in Python 2
def sort_data(x, y):
if x > y: x, y = y, x # x should be less than or equal to y
Min = None
for line in File:
_Min = min(ifilter(lambda num: x < num < y, map(int, line.split(","))))
Min = min(_Min, Min) if Min is not None else _Min
return Min
ifilter is just an iterator version of filter(function, iterable), which constructs a sequence of elements from iterable for which function returns True
map(function, iterable) applies function to each element of iterable
Please note that if your data is comma-separated, you should use line.split(",").
Also, if you're running Python 3.x, you should use simply filter as it already returns an iterator, unlike the Python 2 version. This code is based on iterators, which allow you to work with large streams of data without copying them into memory, which makes this function very memory and speed efficient.

You can try this:
x = 3
y = 95
l = [1, 3, 100, 340, 678, 89, 123, 67]
new_l = [i for i in l if i in range(x, y)]
Output:
[3, 89, 67]

Minor edits to your code should work
mylist = []
def sort_data(x, y):
for line in filename:
for number in line.split(','):#added comma
if int(number) > x and int(number) < y:
mylist.append(int(number))
print(min(mylist)) #changed tab level

Related

Creating a list of square of numbers in a given range

Edit: Sorry guys, I meant to use the power function, not squaring, i hope this clears it up
I'm a new to python, and I'm trying to create a function that lets the user input x and y and will give the output of the powers of those numbers in a loop, so create_list(2,8) returns the list [1,2,4,8,16,32,64,128,256].
I have this code so far, but I feel like it's way off as it only allows for 1 input, whereas I'm looking for 2
import math
a=int(input())
while a<=10000:
print (a)
a=a*2
An example output of this is if a=4, output:
4
8
16
32
64
128
256
512
1024
2048
4096
8192
The previous answers already explain how to solve your question, here I explain how to create a function. Notice that for simple operation like power, you don't need import math. With the following code you define a function create_list(x, y) that takes as input 2 numbers x and y and gives your output, regardless of how they are passed to the function:
def create_list(x, y):
my_list = []
for i in range(y+1):
my_list.append(x**i)
return my_list
After that, you can call the create_list function by giving the numbers programmatically (maybe they are the results of previous operations), but if you want to give them explicitly by keyboard, use this code:
x = int(input())
y = int(input())
my_list = create_list(x,y)
print(my_list)
First, use the input() function twice to let the user input two numbers.
Use the formula square = x * x (instead of x*2) to calculate the square.
Iterate over all numbers between a and b by using the range(a, b) function.
Collect all square numbers in a list and print the list afterwards.
a = int(input())
b = int(input())
squares = []
for i in range(a, b):
square = i * i
squares.append(square)
print(squares)
The more pythonic way in one line:
squares = [i*i for i in range (a,b)]
print(squares)
a=int(input())
b=int(input())
def create_list(a,b):
return [a**i for i in range(b+1)]
print(create_list(a,b))
output for create_list(2,8)
[1, 2, 4, 8, 16, 32, 64, 128, 256]
You can use python pow function
import math
def get_powers(power, length):
return [int(math.pow(power, x)) for x in range(1, length + 1)]
power_input = int(input('power:'))
length_input = int(input('length:'))
print(get_powers(power_input, length_input))
run
power:3
length:5
[3, 9, 27, 81, 243]
[ x * x for x in range (int(input("lower bound")), int(input("upper bound")))]
The above is a list comprehension. It takes every element in range and accesses it through the variable x. The expression on the left is what will actually end up in the list. For example, putting x + 1 would result in storing a value 1 greater than x being stored.
Inputs are evaluated from left to right so you can directly put them in as the parameters to the range function.
The evaluation order is:
Call 'lower bound' input
Convert to int
As above for right input
Evaluate range
Run list comprehension

Why is my Program Returning the Amount of Times Rather Than the Number Itself?

I am trying to return the number in the list that occurs an odd number of times. Right now, it is returning the amount of times the number is present in the list. For instance, in this code, what is being returned is [3, 3, 3] I want it to return 4
def num_occurrence_lc(arr, num):
lc = [1 for x in arr if x == num]
return sum(lc)
def getOddOccurrence_lc(arr):
"""returns the number stated an odd number of times in the
sequence"""
num_occ_list = [num_occurrence_lc(arr, x) for x in arr]
odd_occ_list = [z for z in [z for z in num_occ_list if z%2!=0]]
return odd_occ_list
print(getOddOccurrence_lc([1,2,4,2,4,1,4]))
I believe you have made a mistake in num_occurrence_lc(arr, num). You are storing the counts rather than the number itself. Try instead the following:
from collections import namedtuple
def count_num(arr, num):
return arr.count(num)
def getOddOccurrence_lc(arr):
count_tup = namedtuple('num_count', ['num', 'count'])
arr_counts = [count_tup(str(num), count_num(arr, num)) for num in list(set(arr))]
odd_arr_counts = [int(tup.num) for tup in arr_counts if tup.count%2 != 0]
return odd_arr_counts
If you run print(getOddOccurrence_lc([1,2,4,2,4,1,4])) you will get the output:
>>> print(getOddOccurrence_lc([1,2,4,2,4,1,4]))
[4]
The reason why I made the output a list instead of a single number is to generalize the arr input, to take into account the possibility that there may be more than one number with an odd number of occurrences. So for example, with print(getOddOccurrence_lc([1,2,4,2,4,1,1,4])) you will get:
>>> print(getOddOccurrence_lc([1,2,4,2,4,1,1,4]))
[1, 4]
num_occurrence_lc just returns the number of occurrences, and you never look at arr again, so it should be pretty clear that you're not going to be able to recover the original list elements. If this isn't clear, I'd suggest printing num_occ_list.
One option is to have num_occ_list store a pair: each element in the list along with its count. Something like this:
num_occ_list = [(x,num_occurrence_lc(arr, x)) for x in arr]
You can then pull out just the original list element once you've checked its count:
odd_occ_list = [x for (x,z) in num_occ_list if z%2!=0]
If you run this, you'll see the result is [4,4,4]. This is because you called num_occurrence_lc every time an element appeared. Since you really just want to call it once for each unique element, you can transform the array into a set first:
num_occ_list = [(x,num_occurrence_lc(arr, x)) for x in set(arr)]
Again, I'd suggest printing out num_occ_list to understand what this is producing. With these two lines, you should get [4], as desired.
Little modification and it is working
def num_occurrence_lc(arr, num):
lc = [1 for x in arr if x == num]
return sum(lc)
def getOddOccurrence_lc(arr):
odd_occ_list = [x for x in list(set(arr)) if num_occurrence_lc(arr, x)%2!=0]
return odd_occ_list
print(getOddOccurrence_lc([1,2,4,2,4,1,4]))
returning [4]
Explanation:
x for x in list(set(arr)) Put the value of x from the set of arr only if function num_occurrence_lc(arr, x) returns an odd number

Find elements in a list of which all elements in another list are factors, using a list comprehension

I have a list of numbers from which I have extracted common factors of all these numbers. For example, from list b = [16, 32, 96], I have produced list_of_common_factors = [1, 8, 16, 2, 4].
I have another list of integers, a and I wish to extract the numbers from list_of_common_factors of which all elements of a are factors. So if a = [2, 4], then I should end up with [4, 8, 16], as these are the numbers in list_of_common_factors of which 2 and 4 are factors.
However, I am struggling to figure out how to implement this step in a list comprehension, even in pseudocode. It should look something like this: [x for x in list_of_common_factors if all elements of a are factors of x]. It's the if statement that I'm having trouble with because I believe it should contain a for loop, but I can't think of a concise way to write it.
I have managed to do it the long way, using a nested for loop and it looks like this:
between_two_lists = []
# Determine the factors in list_of_common_factors of which all elements of a are factors.
for factor in list_of_common_factors:
# Check that all a[i] are factors of factor.
""" Create a counter.
For each factor, find whether a[i] is a factor of factor.
Do this with a for loop up to len(a).
If a[i] is a factor of factor, then increment the counter by 1.
At the end of this for loop, check if the counter is equal to len(a).
If they are equal to each other, then factor satisfies the problem requirements.
Add factor to between_two_lists. """
counter = 0
for element in a:
if factor % element == 0:
counter += 1
if counter == len(a):
between_two_lists.append(factor)
between_two_lists is the list I am trying to produce by converting the above code into a list comprehension. How can I do that, if it is even possible?
It is what you are looking for:
[x for x in list_of_common_factors if all(x % i==0 for i in a)]
So basically, you need to have a function returning the factors from a list of numbers. This function would return a list. And then you simply need to find the intersection of both list. Since each factor is unique, I suggest to use a set implementation which will be more efficient. To resume, the code would look like:
A = set(factors(#Input 1))
B = set(factors(#Input 2))
N = A.intersection(B)
It might be more efficient to calculate the least common multiple of the elements of a first, especially if a has more than 2 elements:
from functools import reduce
def gcd(x, y): # greatest common divisor
while y:
x, y = y, x % y
return x
def lcm(x, y): # least common multiple
return (x*y)//gcd(x,y)
lcm_of_a = reduce(lcm, a)
result = [x for x in list_of_common_factors if (x % lcm_of_a == 0)]

How can I fix this algorithm?

I am trying to create a function in Python. This function should be able to create a list of whole numbers less than or equal to the number provided. I've created an empty list, a variable called y and a while loop. In this while loop, as long as y <= x, the results of the subsequent equations are appended to the empty list, and y increments by 1. However, when I call this function, I get a list with only one element. How can I fix this?
def fff(x):
numbers = []
y = 2
while(y <= x):
x = x - (x - y)
numbers.append(x)
y += 1
return numbers
>>> fff(10)
[2]
That function already exists, more or less.
Python 2
def fff(x):
return range(1,x+1)
Python 3
def fff(x):
return list(range(1,x+1))
If you look at this line x = x - (x - y) and think of your inputs, you will see the problem. if x initially equals 10, then x - (x - y) equals 2, and y will equal 3, therefore breaking out of your loop.
If you are trying to mimic the range function then this is how you would do it:
def fff(x):
numbers = []
y = 1
while(y <= x):
numbers.append(y)
y += 1
return numbers

List and Integer query

If i had a list of numbers and some maybe negative, how would i ensure all numbers in my list were positive? I can covert the items in the list to integers thats no problem.
Another question, I want to compare items in my list to an integer value say 'x' and sum all the values in my list that are less than x.
Thank you.
If you have a list Ns of numbers (if it's a list of strings as in several similar questions asked recently each will have to be made into an int, or whatever other kind of number, by calling int [[or float, etc]] on it), the list of their absolute values (if that's what you mean by "ensure") is
[abs(n) for n in Ns]
If you mean, instead, to check whether all numbers are >= 0, then
all(n >= 0 for n in Ns)
will give you a bool value respecting exactly that specification.
The sum of the items of the list that are <x is
sum(n for n in Ns if n < x)
Of course you may combine all these kinds of operations in one sweep (e.g. if you need to take the abs(n) as well as checking if it's < x, checking if it's >= 0, summing, whatever).
# input list is named "lst"
pos_list = [int(a) for a in lst if int(a) > 0]
# And num 2 (notice generator is used instead of list)
return sum(a for a in lst if a < x)
Answer / First part:
>>> a = [1, 2, -3, 4, 5, 6]
>>> b = [1, 2, 3, 4, 5, 6]
>>> max(map(lambda x: x < 0, a))
False
>>> max(map(lambda x: x < 0, b))
True
Or just use min:
>>> min(a) < 0
True
>>> min(b) < 0
False
Second part:
>>> x = 3
>>> sum(filter(lambda n: n < x, a))
>>> 0
>>> sum(filter(lambda n: n < x, b))
>>> 3
If I understand correctly your question, I guess you are asking because of some class about functional programming.
In this case, what you are asking for can be accomplished with functional programming tools available in Python.
In particular, the first point can be solved using filter, while the second with map and reduce (or, better, with map and sum).
>>>mylist = [1,2,3,-2]
>>>any(item for item in mylist if item < 0)
True
>>>mylist.pop()
-2
>>>any(item for item in mylist if item < 0)
False
answers your first question.
>>> x = 3
>>> sum(item for item in mylist if item < x)
3
answers your second question.

Categories

Resources