Python sum of prime factors function to produce finite sequence - python-2.7

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]

Related

Getting Time out error and run time error in test case 2 and 3 in hackerrank. How to resolve this?

The objective of this code is to print sum of multiples of 3 and 5 between given range. In hackerrank, I am getting error in test case 2 and 3. Anyone knows how to resolve the issue?
t =int(raw_input())
for i in range(0,t):
range = int(raw_input())
a=3
b=5
aa=[]
res=[]
def forA(a): #Calculating Multiple of 3
while True:
if a >=range :
a = a-3
break
else:
aa.append(a)
a += 3;
def forB(b): #Calculating Multiple of 5
while True:
if b >=range :
b=b-5
return b
break
else:
aa.append(b)
b += 5;
forA(a)
forB(b)
for i in aa: #eliminate duplicate values of multiples.
if i not in res:
res.append(i)
print sum(res)
This might resolve your problems because it uses pythons builtin features that are "smart" instead of creating a list one item a time yourself. Therefore they are faster... which might solve the timing errors you get.
You get all the numbers up to your input from 3 or 5 till t by
from itertools import chain
t =15
threes = range(0,t+1,3) # range provides [lower..higher[ not including higher value
fives = range(0,t+1,5)
sums = sum(chain(threes,fives)) # without itertools: sums=sum(threes) + sum(fives)
print(threes)
print(fives)
print(sums)
If you want to avoid multiples, avoid chain(..), uses sets and join them together before summing them up
s = set(threes) | set(fives)
print(sum(s))
Output:
[0, 3, 6, 9, 12, 15] # threes up to 15
[0, 5, 10, 15] # fives up to 15
75 # sum of chained ones
60 # sum of set

python2.7 : i % 10 == 0 does not work

from __future__ import print_function
i = 0
for i in range (0, 100)
print(i, end = " ")
i += 1
if i % 10 == 0
print(" ")
print()
I just start my python learning several days ago.
It is about the for_loop training.
As my codes tell, it should print out numbers from 0 to 98 increasing by 2 till 98. As 10 digits printed out, it should print another 10 digits in the next line and keep going on. But it do not work properly. However, it works from changing function to
range(0,100) `
range(0,100)
But do not work when I change the function to
range(0, 100, 2)`
range(0, 100, 2)
Hint: When you use range(0, 100, 2), i is always even and i += 1 would make it odd, hence never satisfying i % 10 == 0. Try using different variable for digit counter or modifying the operands for addition and modulus.

Recursive function call - Python [closed]

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

Powerball number generator

To win the Powerball lottery (an extremely unlikely event so don't waste your time) you have to pick six numbers correctly. The first five numbers are drawn from a drum containing 53 balls and the sixth is drawn from a drum containing 42 balls. The chances of doing this are 1 in 120,526,770.
The output needs to be in the form:
Official (but fruitless) Powerball number generator
How many sets of numbers? 3
Your numbers: 3 12 14 26 47 Powerball: 2
Your numbers: 1 4 31 34 51 Powerball: 17
Your numbers: 10 12 49 50 53 Powerball: 35
import random
#Powerball
print "Offical Powerball number generaor"
x = int(raw_input("How many sets of numbers? "))
z = range(1,42)
z1 = random.choice(z)
def list1():
l1=[]
n=1
while n<=5:
y = range(1,53)
y1 = random.choice(y)
l1.append(y1)
n +=1
print sorted(l1)
i=1
while i<=x:
# print "Your numbers: " + list1() + "Powerball: "+ str(z1)
print list1()
raw_input("Press<enter>")
My code's output goes on a infinite loop. I have to kill it. And the message is:
None
[2, 7, 22, 33, 42]
None
[15, 19, 19, 26, 48]
None
[1, 5, 7, 26, 41]
None
[7, 42, 42, 42, 51]
None
..... etc ....
while i<=x: - you never increment i, so it is stuck in your last loop...
To avoid such things and remove the noise of i+=1 lines in your code I suggest using for loops for i in range(x) and for n in range(5).
Better yet, the following expression can replace list1:
[random.choice(range(1,53)) for x in xrange(5)]
At least, that does the same as your code. But what you probably really want (to avoid the same ball being chosen twice) is:
random.sample( range(1,53), 5 )

List all combinations of 'select 10 different numbers from 1-100'

It is known that there exists C(100,10) possibilities of selecting 10 different numbers from 1 to 100. each possibility is a combination like [1, 2,..., 10] or [2,3,...,11], or [11, 22, 33, .., 99, 100], as long as the 10 numbers are different.
How to list all the combinations by programming??
I don't want to write 10 Loops, python or c preferred
Using python and itertools.combinations.
Warning - Printing will take a long time
for i in itertools.combinations(xrange(1,101),10):
print i
My friend, Yujie Liu came up this idea. Using pure iteration.
# select n diff numbers from min - max
def traceArr(arr, min, max, n):
if n > 0:
for i in range(min, max-n+2):
arr1 = arr[:]
arr1.append(i)
traceArr(arr1, i+1, max, n-1)
elif n == 0:
print arr
# Demo, select 5 diff numbers from 1-10
traceArr([], 1, 10, 5);