Remove integer from list when condition is met

3115 views python
6

I am trying to remove an integer from a list when a condition is met. I have the following code:

def isHarshad(x):
    x1 = str(x)
    x2 = list(x1)
    x3 = [int(i) for i in x2]
    x4 = sum(x3)
    if x%x4 == 0:
        return True
    else:
        return False

def ithHarshad(y):
    y1 = []
    for i in range(y):
        y1.append(i+1)
    for r in y1:
        if isHarshad(r) == False:
            r.remove(y1)
            return y1

ithHarshad(13)

To which I receive the following error.

AttributeError: 'int' object has no attribute 'remove'

I would like for when isHarshad returns false that this value is removed from the list.

answered question

y1.remove(r).

4 Answers

10

You are writing opposite in second loop

for r in y1:
  if isHarshad(r) == False:
     y1.remove(r) # You wrote r.remove(y1)

posted this
4

y1 is your list and r is your integer in that list. You need to remove from the list.

posted this
11

Not the best code, but this works:

def isHarshad(x):
    x1 = str(x)
    x2 = list(x1)
    x3 = [int(i) for i in x2]
    x4 = sum(x3)
    if x%x4 == 0:
        return True
    else:
        return False

def ithHarshad(y):
    y1 = []
    for i in range(y):
        y1.append(i+1)
    for r in y1:
        if not isHarshad(r):
            print('r: %s; y1:%s' % (r, y1))
            y1.remove(r)
            return y1

if __name__ == "__main__":
    result = ithHarshad(13)
    print('Result for ithHarshad(13) = %s' % result

posted this
0

Your code seems to be trying to remove the list from the integer. Swap your variable names in the loop as follows:

if not isHarshad(x):
    y1.remove(r)

I changed your condition to make it more pythonic: when comparing to Boolean values you don't have to write it explicitly. So in this case, if isHarshad returns True, the the not inverts it and the code below is not run, but when it returns false, it is inverted to True, and the item is removed.

posted this

Have an answer?

JD

Please login first before posting an answer.