Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
I have a list of integers larger than zero. I need to identify the one with the highest number of dividers. For this I created two functions: one that gives me all the divisors of all the elements of a list and another that filters which element that has more divisors. The problem is that I can not make the maisDivisores function directly receive a list of only the elements (without dividers), you know? If I call the function 1 (listaDivisores) within the function 2 (maisDivisores) always crashes. However if I call manually, it works good. I've tried all the possibilities and nothing. How do I call the first function in the second for this to work getting the gross list?
def listaDivisores(lista):
if lista == []:
return []
else:
lista=qs(lista)
resultado=[]
resultado.append((lista[0],[y for y in range(1,((lista[0])+1)) if (int(lista[0]))%y==0]))
return resultado+listaDivisores(lista[1:])
return listaDivisores(lista)
def maisDivisores(lista):
if len(lista)==[]:
return "Nenhum número."
else:
**lista=listaDivisores(lista)**
if int(len(lista))==1:
return lista[0]
elif int(len(lista[0][1]))<int(len(lista[1][1])):
lista.pop(0)
elif int(len(lista[0][1]))==int(len(lista[1][1])):
if lista[0]<lista[1]:
lista.pop(0)
else:
lista.pop(1)
else:
lista.pop(1)
return maisDivisores(lista)
return lista
functions working separately; error log when working together.
you can easily get the divisor of a number with list comprehension like this
def divisores(n):
if n <= 0:
raise ValueError("n must be positive")
return [x for x in range(1,n+1) if n%x==0 ]
then you can use the build in max with a key function to get the desire result
>>> test=[24, 5, 9, 42]
>>> max( test, key=lambda x:len(divisores(x)))
24
>>>
if you also want to get the divisor in the same step, you can use a generator or list comprehension to build a intermediary result from which get the max
for example
>>> max( ( (x,divisores(x)) for x in test), key=lambda y:len(y[1]))
(24, [1, 2, 3, 4, 6, 8, 12, 24])
here ( (x,divisores(x)) for x in test) is the generator, which create a tuple with the number and the list of its divisors
or
>>> test2 = [ (x,divisores(x)) for x in test ]
>>> test2
[(24, [1, 2, 3, 4, 6, 8, 12, 24]), (5, [1, 5]), (9, [1, 3, 9]), (42, [1, 2, 3, 6, 7, 14, 21, 42])]
>>> max(test2,key=lambda x:len(x[1]))
(24, [1, 2, 3, 4, 6, 8, 12, 24])
>>>
and any of those can be made into a simple function.
Your implementation is just too convoluted for what you want and frankly I have a hard time understanding it
Related
I am looking for a fast implementation of the following code; using, for instance, map() or next():
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
total_so_far = 0
for i in l:
total_so_far += i
if total_so_far > 14:
break
print(i)
The code prints the index of item in list where sum of start of list to the index is greater greater than 14.
Note: I need to continuously update the link in another loop. Therefore, a solution in numpy would probably be too slow, because it cannot update a list in-place.
You can also make use of itertools.accumulate() together with enumerate() and next():
In [1]: from itertools import takewhile
In [2]: l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [3]: next(index for index, value in enumerate(accumulate(l)) if value > 14)
Out[3]: 5
I have a set of lists that I want to compare firstly the sum values of the lists and then individual elements in the event of two or more lists having the same value.
my_list1 = [2, 3, 2, 4, 5]
my_list2 = [1, 3, 2, 3, 2]
my_list3 = [1, 1, 2, 2, 2]
my_list4 = [3, 2, 2, 4, 5]
Logic testing for an outright winner is fine but the problem I am having is isolating the lists in the event of a draw – So in the scenario above my_list1 and my_list4 would be isolated for further logic testing as their totals both come to 16.
This is what I have so far
my_list1=[1,1,2,2,2]
my_list2=[1,1,1,1,2]
my_list3=[2,2,1,1,2]
my_list1Total=sum(my_list1)
my_list2Total=sum(my_list2)
my_list3Total=sum(my_list3)
if my_list1Total>my_list2Total and my_list1Total>my_list3Total:
print("List one has the higest score")
elif my_list2Total>my_list1Total and my_list2Total>my_list3Total:
print("List two has the higest score")
elif my_list3Total>my_list2Total and my_list3Total>my_list1Total:
print("List three has the higest score")
else:
print("Draw")
##so now I want to compare the lists with the same total but this time by the first element in the list. In this case it would be my_list1[0] and my_list3[0] that would be compared next. The winner having the highest value in position 0 of the drawing lists
I suggest creating a single list which holds all of your lists. Then you can use max on that list to find the largest element. Or, if you want the index of the list and not just its value, you can write a max-like method and use that instead.
#like the built-in function `max`,
#but returns the index of the largest element
#instead of the largest element itself.
def index_of_max(seq, key=lambda item:item):
return max(range(len(seq)), key=lambda idx: key(seq[idx]))
lists = [
[2, 3, 2, 4, 5],
[1, 3, 2, 3, 2],
[1, 1, 2, 2, 2],
[3, 2, 2, 4, 5]
]
idx = index_of_max(lists, key=lambda item: (sum(item), item[0]))
#add one to this result because Python lists are zero indexed,
#but the original numbering scheme started at one.
print "List # {} is largest.".format(idx+1)
Result:
List # 4 is largest.
A little explanation about key: it's a function that you pass to max, that it uses to determine the comparative value of two items in the sequence. It calls key(someItem) on both items, and whichever item has a larger result, is considered the maximum item between the two of them. The key function I used here returns a tuple. Due to the way tuple comparison works in Python, comparison is done by sum first, then using the first element of each list as a tie breaker.
If you're thinking "but what if the first elements are also the same? I want to use each following item as a tie breaker", then you can modify the key to compare all of them in turn.
idx = index_of_max(lists, key=lambda item: [sum(item)]+item)
I want to look in an array of elements. If an element exceeds a certain value x, replace it with another value y. It could be a bunch of elements that need to be replaced. Is there a function (code) to do this at once. I don't want to use for loop.
Does the any() function help here?
Thanks
I really don't know how one could possibly achieve such a thing without the if statement.
Don't know about any() but I gave it a try with map since you don't want a for loop. But, do note that the complexity order (Big O) is still n.
>>> array = [1, 2, 3, 4, 2, -2, -3, 8, 3, 0]
>>> array = map(lambda x: x if x < 3 else 2, array)
>>> array
[1, 2, 2, 2, 2, -2, -3, 2, 2, 0]
Basically, x if x < 3 else 2 works like If an element exceeds a certain value x, replaces it with another value y.
I was wondering how i would go about counting combinations in a list. To be more precise i have a list that is comprised of smaller lists that are made up of 6 randomly chosen numbers and i want to count how many times each combinations occurs within the bigger list and then finally display the least occurring combination. So far i tried using Counter() but it seems it can't count lists.
here's an example of what i want to do:
list = [[1,2,3,4,5,6],[1,5,16,35,55,22],[1,2,3,4,5,6],[5,25,35,45,55,10],[1,5,16,35,55,22],[1,2,3,4,5,6],[9,16,21,22,23,6],[9,16,21,22,23,6]]
so after counting the combinations it should print the combination [5,25,35,45,55,10]
since it only occurred once in the list
FYI the list is going to randomly generated with around 1 billion combinations stored but given the range of numbers, there's only 175 million possible combinations
FYI 2 i'm extremely new to python
When you construct the Counter instance you can convert your lists to tuples; the latter are hashable, which is the property an object needs to be able to serve as a key of a dict.
>>> from collections import Counter
>>> l = [[1,2,3,4,5,6],[1,5,16,35,55,22],[1,2,3,4,5,6],[5,25,35,45,55,10],[1,5,16,35,55,22],[1,2,3,4,5,6],[9,16,21,22,23,6],[9,16,21,22,23,6]]
>>> c = Counter(tuple(e) for e in l)
>>> c
Counter({(1, 2, 3, 4, 5, 6): 3, (1, 5, 16, 35, 55, 22): 2, (9, 16, 21, 22, 23, 6): 2, (5, 25, 35, 45, 55, 10): 1})
>>> list(c.most_common()[-1][0])
[5, 25, 35, 45, 55, 10]
Having a sorted list and some random value, I would like to find in which range the value is.
List goes like this: [0, 5, 10, 15, 20]
And value is, say 8.
The standard way would be to either go from start until we hit value that is bigger than ours (like in the example below), or to perform binary search.
grid = [0, 5, 10, 15, 20]
value = 8
result_index = 0
while result_index < len(grid) and grid[result_index] < value:
result_index += 1
print result_index
I am wondering if there is a more pythonic approach, as this although short, looks bit of an eye sore.
Thank you for your time!
>>> import bisect
>>> grid = [0, 5, 10, 15, 20]
>>> value = 8
>>> bisect.bisect(grid, value)
2
Edit:
bisect — Array bisection algorithm
for min, max in zip(grid, grid[1:]): # [(0, 5), (5, 10), (10, 15), (15, 20), (20, 25)]
if max <= value < min: #previously: if value in xrange(min, max):
return min, max
raise ValueError("value out of range")