I want to write a function called find_integer_with_most_divisors that accepts a list of integers and returns the integer from the list that has the most divisors. In case of a tie, return the first item that has the most divisors.
For example:
if the list is:
[8, 12, 18, 6]
In this list, 8 has four divisors which are: [1,2,4,8] ; 12 has six divisors which are: [1,2,3,4,6,12]; 18 has six divisors which are: [1,2,3,6,9,18] ; and 6 has four divisors which are: [1,2,3,6]. Notice that both 12 and 18 are tied for maximum number of divisors (both have 6 divisors). My function should return the first item with maximum number of divisors; so it should return:
12
Now I wrote bellow code for find division of each number, that are in list. Can any body help me to continue this function.
Thanks.
def find_integer_with_most_divisors(input_list):
for i in input_list:
my_list = []
for x in range(1,i+1):
if i % x == 0:
my_list.append(i)
You can create a list of the number of divisors in your function and then match the highest number in that list to your original list:
def find_integer_with_most_divisors(input_list):
nr_divisors = []
for i in input_list:
my_list = []
for x in range(1, i+1):
if i % x == 0:
my_list.append(x)
nr_divisors.append(len(my_list))
return input_list[nr_divisors.index(max(nr_divisors))]
a = [8, 12, 18, 6]
print find_integer_with_most_divisors(a)
returns
12
Why not just use max with the number of divisors as key?
>>> max([8, 12, 18, 6], key=lambda n: sum(n%d == 0 for d in range(1, n+1)))
12
All you need to do is keep track of the number with the most so far. I also changed your creation of my_list to something a little simpler:
def find_integer_with_most_divisors(input_list):
winning_list = []
winning_number = None
for i in input_list:
my_list = [x for x in range(1, i + 1) if i % x == 0]
if len(my_list) > len(winning_list):
winning_list = my_list
winning_number = i
return winning_number
Yet another flavor of solution that uses sorted:
def find_integer_with_most_divisors(input_list):
def divisor_length(num):
length = 0
for i in range(1,num+1):
if num % i == 0:
length += 1
return length
return sorted(input_list, key=lambda x: divisor_length(x), reverse=True)[0]
print(find_integer_with_most_divisors([8,12,18,6]))
12
Related
I am able to calculate the length of the longest ascending subsequence formed by consecutive numbers in a list, or the largest sum of any subsequence. However, I am a bit struggling to print out the longest subsequence with consecutive numbers (e.g: 8,9,10,11,12). How can I do that? Should I create an empty list and override the values every time the num value is being checked in the new_list?
Thanks in advance,
lanuit72
def longest_largest_seq(list):
list = [5,6,3,8,3,4,9,8,10,12,11,99,98]
largest = 0
sum = 0
new_list = set(list) #using set to get unique value from the list
max_count = 0
count = 0
for num in list:
if num - 1 not in new_list:
sum = 0
count = 0
while num in new_list:
sum += num
count += 1
num += 1
if sum > largest:
largest = sum
if count > max_count:
max_count = count
return largest, max_count
print(f'Largest consecutive sum and longest consecutive subsequence', longest_largest_seq(list))
Something like this?
from more_itertools import consecutive_groups
a_list = [5,6,3,8,3,4,9,8,10,12,11,99,98]
sorted_list = sorted(a_list)
grouped = [list(i) for i in consecutive_groups(sorted_list)]
for i in grouped:
print(i)
print('\n', max(grouped, key=len), sep='')
[3]
[3, 4, 5, 6]
[8]
[8, 9, 10, 11, 12]
[98, 99]
[8, 9, 10, 11, 12]
I think this is what you want?
import copy
seq = sorted([5,6,3,8,3,4,9,8,10,12,11,99,98])
sub_seq1 = []
sub_seq2 = []
for index, num in enumerate(seq):
if index < len(seq) - 1:
if num + 1 == seq[index + 1]:
sub_seq2.append(num)
else:
sub_seq2.append(num)
if len(sub_seq2) > len(sub_seq1):
sub_seq1 = copy.deepcopy(sub_seq2)
sub_seq2.clear()
print(sub_seq1)
Question
You have L, a list containing some digits (0 to 9). Write a function solution(L) which finds the largest number that can be made from some or all of these digits and is divisible by 3.
If it is not possible to make such a number, return 0 as the solution. L will contain anywhere from 1 to 9 digits. The same digit may appear multiple times in the list, but each element in the list may only be used once.
Test Cases
Input:
solution.solution([3, 1, 4, 1])
Output:
4311
Input:
solution.solution([3, 1, 4, 1, 5, 9])
Output:
94311
My code
def sum(L):
totalSum = 0
for x in range(len(L)):
totalSum = totalSum + L[x]
return totalSum
def listToInteger(L):
strings = [str(integer) for integer in L ]
concatString = "".join(strings)
finalInt = int(concatString)
return finalInt
def solution(L):
num = sum(L)
if not num % 3:
L.sort(reverse=True) # sort list in descending order to create largest number
return listToInteger(L)
else:
n = num % 3
flag = False
while not flag: # locate digit causing indivisiblity
if n in L:
L.remove(n)
L.sort(reverse=True)
return listToInteger(L)
elif(n > num):
return 0
else:
n += 3
I get the two test cases correct, but there is one hidden case that keeps failing. I'm not sure if the input is not strict enough, or if there is a fault in my logic
the only fault in logic I can think of is if the input was [8,5,3] , the sum would be 16 and 16 % 3 = 1
so it would check the list for 1, 4, 7, 10, 13 , 16 but it wouldnt be in the list so it wouldn't remove 8 or 5. it would return 0 when it should actually return [3].
I added a function for this but even then it was still failing the hidden test case. . .
Any suggestions would be appreciated
Your code seems to assume that there can only be one digit that is wrong. What would you do with input like 1,1,3? sum is 5, n is 2 and you'll try to remove 2, 5, and then fail and return 0.
You need to change your assumptions and check other digits too, and make it possible to remove more than 1 digit when working toward a solution.
This code worked fine for [8,5,3]
example: [8,5,3,6]
sum will be 22
sum%3 will be 1
so numbers need to check in list to delet are 1,4 7,10,13,16,19,22 and it will never delet any elements,since there are no these elements in the list
so still there are 6 and 3 which can be multilple of 3.
so take 3 and 6 in a list and sort them and answer will be 63
def sum(L):
totalSum = 0
for x in range(len(L)):
totalSum = totalSum + L[x]
return totalSum
def listToInteger(L):
strings = [str(integer) for integer in L ]
concatString = "".join(strings)
finalInt = int(concatString)
return finalInt
def solution(L):
num = sum(L)
if not num % 3:
L.sort(reverse=True) # sort list in descending order to create largest number
return listToInteger(L)
else:
n = num % 3
flag = False
while not flag: # locate digit causing indivisiblity
if n in L:
L.remove(n)
L.sort(reverse=True)
return listToInteger(L)
elif(n > num):
k=[]
for i in L:
if i%3==0:
k.append(i)
if len(k)!=0:
k.sort(reverse=True)
return listToInteger(k)
else:
return 0
else:
n += 3
l=[8,5,3]
print(solution(l))
I've been making a program that finds two numbers in a random list and prints them if their sum is 8.
Honestly, I've been sitting here for half an hour and idk what's going on. I think I'm pretty close, but in rare cases it doesn't find an exitsting combination(list = [1,4,4,9] -> No combination). Also in rare cases I will get an error saying
RecursionError: maximum recursion depth exceeded in comparison
Here's my code:
import random
list = []
for i in range(1,5,1):
newNum = random.randint(1,10)
list.append(newNum)
list.sort()
sum = 8
print('\nRandomly generated list:')
print(list)
firstNum = list[0]
lastNum = list[-1]
newList = []
def isSum(a,b):
if a + b == sum:
if list.index(a) == list.index(b):
print('\nThere isnt a combination.')
else:
newList.append(a)
newList.append(b)
print('\nCombination:')
print(newList)
elif a + b < sum:
temp = list.index(a)
temp += 1
if temp > list.index(lastNum):
print('\nThere isnt a combination.')
else:
a = list[temp]
isSum(a,b)
else:
temp = list.index(b)
temp -= 1
if temp < list.index(firstNum):
print('\nThere isnt a combination.')
else:
b = list[temp]
isSum(a,b)
isSum(firstNum,lastNum)
I'm just a beginner, don't get angry if I made a stupid mistake :3
You can use itertools module for generating all combinations of your list, then filter that by calculating the sum of each combination, for example this:
import itertools
a = [1, 4, 4, 9] # any list of nums
groups = 2
result = 8
combinations = [combination for combination in itertools.combinations(a, groups)]
output = [combination for combination in combinations if sum(combination) == result]
print(output)
>>> [(4, 4)]
Recursion really isn't ideal in Python, and your code could certainly be simplified.
This should return all the pairs.
import itertools as itt
import random
from typing import List, Tuple
def is_comb_sum(nums: List[int], comb_size: int, target_sum: int) -> List[Tuple[int, ...]]:
combs = []
for curr_pair in itt.combinations(nums, comb_size):
curr_sum = sum(curr_pair)
if curr_sum == target_sum:
combs.append(curr_pair)
return combs
nums_list = [random.randint(0, 10) for _ in range(5)]
print(nums_list)
res = is_comb_sum(nums_list, 2, 8)
print(res)
If you only want to print each combination once, you can use a set to identify the distinct numbers that are present. Then, for each of these number, you determine which complementing value is need to reach your target (8) and if it is also in the set then the pair exists. The only exception to this is when the number is exactly half of the target (i.e. 4) in which case you have to make sure there are at least two instances of that number in the list:
target = 8
count = 4
numbers = [random.randint(1,10) for _ in range(count)]
print(numbers)
numberSet = set(numbers)
for number in numberSet:
other = target-number
if other not in numberSet: continue
if other > number: continue # avoid duplicates such as 2+6=8 and 6+2=8
if other == number and numbers.count(number) < 2: continue
print(number,"+",other,"=",target)
Output:
[7, 2, 6, 1]
6 + 2 = 8
7 + 1 = 8
If you want to print all the combinations, you can use the Counter object from the collection modules and either print the number of occurrences or repeat the printed lines:
target = 12
count = 8
numbers = [random.randint(1,10) for _ in range(count)]
print(numbers)
from collections import Counter
numberCounts = Counter(numbers)
for number in numberCounts:
other = target-number
if other > number: continue
pairCount = numberCounts[number] * numberCounts[other]
if number == other:
pairCount = (pairCount - numberCounts[number]) // 2
if pairCount > 0:
print(number,"+",other,"=",target,"occurred",pairCount,"time(s)")
Output (target of 12 in list of 8):
[7, 6, 5, 5, 6, 6, 3, 4]
7 + 5 = 12 occurred 2 time(s)
6 + 6 = 12 occurred 3 time(s)
I have a problem: Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
How can I add together some elements in a list of integers?
Of which the code I wrote is:
a = [10, 15, 3, 7]
k = 17
while i < k:
if i + i != k:
return False
else:
return True
For each number num in the list, calculate k - num and check if that number exists in your list.
For increased performance, it's best to turn the list into a dict that counts how many times each number occurs in the input. (Lists have O(n) membership tests while dicts have O(1).)
a = [10, 15, 3, 7]
k = 17
from collections import Counter
occurences = Counter(a) # count how many times each number occurs
for num in a:
complement = k - num
if complement not in occurences:
continue
# if the number is its own complement, check if it
# occurred at least twice in the input
if num == complement and occurences[num] < 2:
continue
print('The pair {} + {} adds up to {}'.format(num, complement, k))
break
else:
print('No combination of two numbers adds up to {}.'.format(k))
You can use any() with itertools.combinations:
from itertools import combinations
def sum_available(lst, k):
return any(x + y == k for x, y in combinations(lst, 2))
Usage:
>>> a = [10, 15, 3, 7]
>>> k = 17
>>> sum_available(a, k)
True
this need to work, however, this is a very slow code:
a = [10, 15, 3, 7]
k = 17
done = False #define a flag
#use two for loops to check if two numbers add up to k
for i in a:
for p in a:
if i + p == k:
print(str(i) + '+' + str(p) + '=' + str(k))
done = True
break #to break out of inner loop
if done:
break #to break out of outer loop
if done == False:
print('No such numbers exist.')
I am having trouble finding information on using sum to take from a list. I know how to use sum with range, for example:
sum = 0
for i in range(50):
sum=sum + i
print (sum)
But I can't get my code to work when I am using a list such as [1, 2, 6, 7, 8, 10] and taking the even numbers using sum. Can anyone point me in the right direction?
You can filter out odd-values:
def is_even(x):
# if the remainder (modulo) is 0 then it's evenly divisible by 2 => even
return x % 2 == 0
def sum_of_evens(it):
return sum(filter(is_even, it))
>>> sum_of_evens([1,2,3,4,5])
6
Or if you prefer a conditional generator expression:
>>> lst = [1,2,3,4,5]
>>> sum(item for item in lst if item % 2 == 0)
6
Or the explicit (long) approach:
lst = [1,2,3,4,5]
sum_ = 0
for item in lst:
if item % 2 == 0:
sum_ += item
print(sum_) # 6