我试图通过嵌套的if系列传递列表。每个if语句都调用一个单独的函数。第一个if语句完全遍历文件(列表),但是在数字首次通过第一个if语句之后,该数字将无限地重复通过第二个语句,直到第一个语句完成。
例如:列表中的前几个数字是:
['8812', '1816', '9726', '3463']
第一个if语句遍历整个列表,但第二个语句检查'8812'
第一个语句的所有4个运行,并且永远不会运行到其他数字。
知道这里发生了什么:
total = 0
counter = 0
for c in rumbers:
if (isHarshad(int(c)) == True):
#print(int(c))
total = total + int(c)
if (isSiete(int(c)) == True):
print(c)
#ofile = open(HarshOut.txt, 'w')
#ofile.close()
else:
#print(c, " is false - main")
功能
def isHarshad (number):
#conversion to iterable list
numberlist = list(str(number))
digittotal = 0
#iterate through the list
for iterate in numberlist:
digittotal += int(iterate)
#Will the numbers be divisible?
if (number % digittotal == 0):
return True
else:
return False
#isSiete Function declaration
def isSiete(number):
for number in rumbers:
if(number[-2] == '7'):
return True
else:
return False
打印语句:
7440 is false - main
isSiete number is: 8812
3110 is false - main
isSiete number is: 8812
5202 is false - main
isSiete number is: 8812
9288 is false - main
isSiete number is: 8812
7770 is false - main
isSiete number is: 8812
1170 is false - main
isSiete number is: 8812
4 is false - main
应该发生吗?
myList [' 8812',' 1816',' 9276',' 3463']
8812是Harshad号吗?
参数结束时(或失败时)。
7440 is false - main
isSiete number is: 7440
3110 is false - main
isSiete number is: 3110
5202 is false - main
isSiete number is: 5202
9288 is false - main
isSiete number is: 9288
7770 is false - main
isSiete number is: 7770
1170 is false - main
isSiete number is: 1170
答案 0 :(得分:1)
试试这个:
def is_harshad(n):
total = sum(int(d) for d in str(n))
return n % total == 0
def isSiete(number):
return str(number)[-2] == '7'
total = 0
for c in numbers:
if is_harshad(int(c)):
#print(int(c))
total = total + int(c)
if isSiete(int(c)):
print(c)
#ofile = open(HarshOut.txt, 'w')
#ofile.close()
else:
print(c, " is false - main")