In Python2.7 I would like to generate finite sequences for a given integer by repeating the sum of prime factors (sopfr) function over the result(s) until it reaches a prime. The following code for sopfr(n) comes from OEIS A001414.
from sympy import factorint
def sopfr(n):
return sum(p*e for p, e in factorint(n).items())
>>>sopfr(888)
46
>>>
I'd like to alter this code so that it will give this result
>>>sopfrs(888)
46 25 10 7
>>>
Where 46 = sopfr(888), 25 = sopfr(46)... and so on, until this terminates at a prime, in this case 7. I've read some on and experimented with while and for loops without luck. Experiments that, I'm sure would be good for a laugh. Forgive the novice nature of this question, any help would be appreciated.
You can use something like this example:
from sympy import factorint
def sopfr(n):
sub = []
while True:
a = sum(k*v for k,v in factorint(n).items())
if a == n:
break
else:
sub.append(a)
n = a
return sub
# Tests
a = sopfr(888)
print(a)
a = sopfr(65)
print(a)
Output:
[46, 25, 10, 7]
[18, 8, 6, 5]
newarray = [x + 0.5 for x in range(1, 10)]
this code will give me following result:
newarray
[1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5]
Instead of adding 0.5 with x I want to increase my x by 0.5 for each 1 increment of x. The output suppose to be
newarray=[0.5,1,1.5,2,2.5......5.5].
Keep in mind that my range must be fix in 1 to 10. What can be better approach to make that?
[0.5 * x for x in range(1, 12)]
Will do the thing, I'm afraid generating that array with range(1, 10) is impossible
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
No sure why, but the context['user_activity_percentage'] is showing 0 when it should be showing 25. This is because context['user_activity'] is 1 and it is int(1/4 * 100) = 25. I verified this in the manage.py shell_plus. Why is it showing 0 instead of 25?
context['user_activity'] = CommunityProfile.list_all_users.date_search(
date1, date2, column="last_activity").count()
context['user_activity_percentage'] = int(context['user_activity']/
CommunityProfile.objects.count() * 100)
If you are using Python 2.x, 1/4 is 0, not 0.25:
>>> 1 / 4
0
If you want to get 0.25, convert one of the value to float:
>>> float(1) / 4
0.25
This behavior is different from Python 3.x's (PEP-238: True division). If you want / works like Python 3.x, do the following:
>>> from __future__ import division
>>> 1 / 4
0.25
What is a pythonic way of making list of arbitrary length containing evenly spaced numbers (not just whole integers) between given bounds? For instance:
my_func(0,5,10) # ( lower_bound , upper_bound , length )
# [ 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5 ]
Note the Range() function only deals with integers. And this:
def my_func(low,up,leng):
list = []
step = (up - low) / float(leng)
for i in range(leng):
list.append(low)
low = low + step
return list
seems too complicated. Any ideas?
Given numpy, you could use linspace:
Including the right endpoint (5):
In [46]: import numpy as np
In [47]: np.linspace(0,5,10)
Out[47]:
array([ 0. , 0.55555556, 1.11111111, 1.66666667, 2.22222222,
2.77777778, 3.33333333, 3.88888889, 4.44444444, 5. ])
Excluding the right endpoint:
In [48]: np.linspace(0,5,10,endpoint=False)
Out[48]: array([ 0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5])
You can use the following approach:
[lower + x*(upper-lower)/length for x in range(length)]
lower and/or upper must be assigned as floats for this approach to work.
Similar to unutbu's answer, you can use numpy's arange function, which is analog to Python's intrinsic function range. Notice that the end point is not included, as in range:
>>> import numpy as np
>>> a = np.arange(0,5, 0.5)
>>> a
array([ 0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5])
>>> a = np.arange(0,5, 0.5) # returns a numpy array
>>> a
array([ 0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5])
>>> a.tolist() # if you prefer it as a list
[0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5]
f = 0.5
a = 0
b = 9
d = [x * f for x in range(a, b)]
would be a way to do it.
Numpy's r_ convenience function can also create evenly spaced lists with syntax np.r_[start:stop:steps]. If steps is a real number (ending on j), then the end point is included, equivalent to np.linspace(start, stop, step, endpoint=1), otherwise not.
>>> np.r_[-1:1:6j, [0]*3, 5, 6]
array([-1. , -0.6, -0.2, 0.2, 0.6, 1.])
You can also directly concatente other arrays and also scalars:
>>> np.r_[-1:1:6j, [0]*3, 5, 6]
array([-1. , -0.6, -0.2, 0.2, 0.6, 1. , 0. , 0. , 0. , 5. , 6. ])
You can use the folowing code:
def float_range(initVal, itemCount, step):
for x in xrange(itemCount):
yield initVal
initVal += step
[x for x in float_range(1, 3, 0.1)]
Similar to Howard's answer but a bit more efficient:
def my_func(low, up, leng):
step = ((up-low) * 1.0 / leng)
return [low+i*step for i in xrange(leng)]