From the given program below, in Python, Print a data set with every number, 100
ID: 3911650 • Letter: F
Question
From the given program below, in Python, Print a data set with every number, 1000-9999 and their number of prime permutations.
import math
def getAllCombinations(s, length):
if length == 0:
return ['']
else:
ret = []
for idx, c in enumerate(s):
combos = getAllCombinations(s[0:idx] + s[idx+1:], length - 1)
for i in range(len(combos)):
combos[i] = c + combos[i]
ret += combos
return ret
def getPermutations(s, ret, swapIdx = 0):
if swapIdx == len(s):
ret.append(int(''.join(s)))
for i in range(swapIdx, len(s)):
cpy = [c for c in s]
cpy[swapIdx], cpy[i] = cpy[i], cpy[swapIdx]
getPermutations(cpy, ret, swapIdx + 1)
def getAllPermutations(i):
s = str(i)
allPerms = set()
for i in range(len(s)):
curCombos = getAllCombinations(s, i + 1)
for combo in curCombos:
ret = []
getPermutations(combo, ret)
allPerms = allPerms.union(set(ret))
return list(allPerms)
def isPrime(n):
for i in range(2, math.ceil(n**(1/2)) + 1):
if n % i == 0:
return False
return True
def getNumPrimes(i):
perms = getAllPermutations(i)
numprimes = 0
for perm in perms:
if (isPrime(perm)):
numprimes += 1
return numprimes
def find_maxPrimes():
max = 0
maxNum = 0
for i in range (1000, 10000):
cur = getNumPrimes(i)
if (max < cur):
max = cur
maxNum = i
return maxNum
print(find_maxPrimes())
Explanation / Answer
The task can be easily done by modifying the find_maxPrimes() function and the call to it.
Program:
import math
def getAllCombinations(s, length):
if length == 0:
return ['']
else:
ret = []
for idx, c in enumerate(s):
combos = getAllCombinations(s[0:idx] + s[idx+1:], length - 1)
for i in range(len(combos)):
combos[i] = c + combos[i]
ret += combos
return ret
def getPermutations(s, ret, swapIdx = 0):
if swapIdx == len(s):
ret.append(int(''.join(s)))
for i in range(swapIdx, len(s)):
cpy = [c for c in s]
cpy[swapIdx], cpy[i] = cpy[i], cpy[swapIdx]
getPermutations(cpy, ret, swapIdx + 1)
def getAllPermutations(i):
s = str(i)
allPerms = set()
for i in range(len(s)):
curCombos = getAllCombinations(s, i + 1)
for combo in curCombos:
ret = []
getPermutations(combo, ret)
allPerms = allPerms.union(set(ret))
return list(allPerms)
def isPrime(n):
for i in range(2, math.ceil(n**(1/2)) + 1):
if n % i == 0:
return False
return True
def getNumPrimes(i):
perms = getAllPermutations(i)
numprimes = 0
for perm in perms:
if (isPrime(perm)):
numprimes += 1
return numprimes
#Modified below
def find_maxPrimes():
max = 0
maxNum = 0
#Printing here directly
for i in range (1000, 10000):
print(i, " ---> ", getNumPrimes(i))
find_maxPrimes()
Output:
The output is too large for chegg's answer character limits. Nevertheless, I have uploaded the output as a text file in the link below if neccessary.
mega.nz/#!ekoxSToS!Oi-t7LQ6Bc1PxfH4a4vn9M-SlPYpXY79zcina11_CuA
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.