Dongxuan Zhang
Dongxuan Zhang

Reputation: 1

Combine the 2 for loops

def getList(num):
        result = []
        while num>0:
            remain=num%10
            if remain >0:
                result.append(remain)
            elif remain ==0:
                result.append(float('inf'))
            num /= 10
        return result
    
    not_ans = []
    for i in range(left, right+1):
        for num in getList(i):
            if i%num != 0:
                not_ans.append(i)
    
    ans = []
    for i in range(left, right+1):
        if i not in not_ans:
            ans.append(i)
            
    
    return ans

I have always been struggling with how I should write the code and append the result, when all the conditions should be met in for loop. I can only do it with a negative list. Can you guys help me with this? Thank you!

Upvotes: 0

Views: 47

Answers (1)

why don't you just append the anses in an else block:

def main():  
    not_ans = []
    ans = []
    for i in range(left, right+1):
        for num in getList(i):
            if i%num != 0:
                not_ans.append(i)
            else:
                ans.append(i)
    return ans

Upvotes: 1

Related Questions