I can't came up with an algorithm to solve the following problem:
- Generate an array of first
nprime numbers. - Remove
knumbers from this array in such way that after concatenating all numbers left we get the largest possible result.
E.G.
Input: 4 2
- First value(4) is
n Second value(2) is
kArray [2, 3, 5, 7] is generated
- the program have to remove numbers 2 and 3 from this array(to get 57, which is the max possible number we can get from this array after deleting
knumbers and merging all the numbers left together). - e.g. If it removes 2 and 7 - we will get 35(which is not the max number). So, this solution is wrong.
Output: 57
This is the code I have so far:
def getInputedVals():
return [int(el) for el in input().split(" ")]
def get_primes_array(x):
primes = []
a = 2
# for a in range(2, 10000):
while(len(primes) != x):
for b in range(2, a):
if a % b == 0:
break
else:
primes.append(a)
a += 1
if len(primes) == x:
return primes
def combine_numbers(nums):
s = [str(i) for i in nums]
return int("".join(s))
# Algorithm to find the max number should be written here
def get_result(nums, n_nums_to_delete):
print("algorithm goes here")
def main(item):
primes = get_primes_array(item["n_first"])
summed = sum(primes)
# print(get_result(primes, item["n_nums_to_delete"]))
print("Primes: ", primes)
n_first, n_nums_to_delete = getInputedVals()
item = {"n_first": n_first, "n_nums_to_delete": n_nums_to_delete}
main(item)
1 Answer 1
You have the answer, sort your results and take the sorted list starting from the n_nums_to_delete :
def get_result(nums, n_nums_to_delete):
return sorted(nums)[n_nums_to_delete:]
As @Yuri Ginsburg mentioned in the comment, your prime number list is already sorted, so you can simply do :
def get_result(nums, n_nums_to_delete):
return nums[n_nums_to_delete:]
answered Nov 12, 2019 at 18:33
Florian Bernard
2,5991 gold badge11 silver badges24 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py
knumbers?knumbers have to be removedknumbers? If the best choice is always the firstkthen the problem becomes much simpler.