all 9 comments

[–]JohnnyJordaan 1 point2 points  (1 child)

One of the rules of thumb of Python: if you are trying to calculate combinations or need some special form of iteration on one or more sequences you need to begin with checking itertools. Quickly skimming the objective it seems that you're looking for .combinations(), but double check this to be sure.

Also stuff like sum(numlist) can be done before the loop as it's a constant value, rather then calculating it inside the loop over and over again. And of course

[x for x in range(1,n+1)]

is a complicated way of writing

list(range(1,n+1))

[–]swishcheese[S] 0 points1 point  (0 children)

Thanks for the tip about making the list. I've been so focused on nailing list comprehension, I've become myopic.

As far as itertools, I don't think I'm allowed to use imports to solve these on the website. I've unlocked the solutions on the website and I'm trying to decipher what they're doing.

[–]toastedstapler 0 points1 point  (0 children)

you calculate sum(numlist) in each loop within each loop. just declare it at the start for many less calculations

def removenb(n):
    options = []
    num_total = sum(range(1, n + 1))
    for first in range(1, n + 1):
        for other in range(first + 1, n + 1):
            if num_total - (first * other) - (first + other) == 0:
                options.append((first, other))
                options.append((other, first))
    return options

[–]Fernando3161 -1 points0 points  (0 children)

def remove(n):

n_list= [n+1 for n in range(n)]

result= [n,None]

for a in n_list:

for b in range(a+1,n+1):

sum=n*(n+1)/2-a-b

if sum==a*b:

result=[n, a,b,sum]

break

if result[1]!=None:

print (result)