简体   繁体   中英

Add integer from list when condition is met

So if I want to determine the first 20 (not until 20) Harshard numbers how would I do this? The code I have only inputs until it reaches 20, not the first 20.

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(n):
return [i for i in range(1, n+1) if isHarshad(i)]

ithHarshad(20) 

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.

In general, you could really shorten your code if you use a list comprehension:

def ithHarshad(n):
    return [i for i in range(1, n+1) if isHarshad(i)]

This code means that it will create a list of the values 1 -> n (inclusive) and only include the value if the result of filtering it through isHarshad is True

You had a logical error.Just change

r.remove(y1) 

to

y1.remove(r) in function ithHarshad()

That would work !

You are writing opposite in second loop

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

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

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

You will get a ZeroDivisionError if you divide something by zero. In your code, the only division is happening when you use the modulo operator. If the number you pass to isHarshad() is 0, then you will get this error. Also, there is no need to convert an int to a list of characters, you can implement isHarshad() using pure integer arithmetic:

def isHarshad(x):
  sum = 0
  y = x
  while y:
    sum += y % 10
    y //= 10
  return sum != 0 and x % sum == 0

Doing it this way also allows you to easily change the function to determine if a number is a Harshad number in a different base than 10.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM