I have the following list in Python:
l = [[2], [3], [2, 2], [5], [2], [3], [7], [2, 2, 2], [3, 3], [2], [5], [11], [2, 2], [3], [13], [2], [7], [3], [5], [2, 2, 2, 2], [17], [2], [3, 3], [19], [2, 2], [5]]
I want to write a function that will return the uniquely-valued sublists of maximum length. In this case, the function would return:
l = [[5], [7], [3, 3], [11], [13], [2, 2, 2, 2], [17], [19]]
I am still a beginner at python, and I have very little idea as to how to write such a function, however. The furthest I got was figuring out that I could iterate over the sublists by using nested loops. But from what I’ve seen of Python, it seems like there must be some simpler way to return the list I am looking for than using loops.
Update:
Here’s what I was doing with the code: solving project euler #5, the non-brute force way!
I’m sure this code could be refactored, but whatever.
Thanks for your help, guys. itemgetter was just what I needed.
#!/usr/bin/python
# coding = UTF-8
import argparse, sys, math
from itertools import groupby
from collections import defaultdict
from operator import itemgetter
parser = argparse.ArgumentParser()
parser.add_argument('filename', nargs='?')
args = parser.parse_args()
if args:
intinput = int(sys.argv[1])
elif not sys.stdin.isatty():
intinput = int(sys.stdin.read())
else:
parser.print_help()
def prime_factorize(n):
factors = []
number = math.fabs(n)
while number > 1:
factor = get_next_prime_factor(number)
factors.append(factor)
number /= factor
if n < -1:
factors[0] = -factors[0]
return factors
def get_next_prime_factor(n):
if n % 2 == 0:
return 2
for x in range(3, int(math.ceil(math.sqrt(n)) + 1), 2):
if n % x == 0:
return x
return int(n)
def mkfactors(n):
tpf = []
for i in range(n+1):
tpf.extend(prime_factorize(i))
return tpf
l = [list(g) for k,g in groupby(mkfactors(intinput))]
m = [max(g) for _,g in groupby(sorted(l,key=itemgetter(0)),key=itemgetter(0))]
prod = 1
for list in m:
for element in list:
prod *= element
print prod
out: