在环顾四周寻找类似问题而没有找到任何问题后,我会在这里问一下它。我会尝试尽可能具体。使用Python,我试图制作一段代码,贯穿所有可能的Harshad数字,并在列表中返回[i]数量的Harshad数字。为此,我首先制作了一个方法isHarshad,它可以确定列表中的数字是否为Harshad数字。之后,我实现此方法只打印列表中的Hardshad数字。
def isHarshad(i):
l = list(str(i))
a = sum([int(e) for e in l])
if a == 0:
return False
if i % a == 0:
return True
else:
return False
def ithHarshad(i):
a = []
count = 0
top = 999999999
for x in (range (1,top)):
if isHarshad(x):
a = a + [x]
count += 1
if count == i:
print(a)
ithHarshad(25)
运行此代码将返回前25个Harshad数字,这是我想要它做的。现在我的问题是:是否有可能形成一个循环来检查Harshad数字的范围,而不是在我的代码中执行“top”变量?循环到像999999这样的任意数字感觉很麻烦。
我希望我的问题有点清楚,并提前感谢任何意见!
尝试用while True:
替换它并在生成足够的数字时打破循环。在您的代码中,您正在运行所有可能非常低效的数字。
def isHarshad(i):
l = list(str(i))
a = sum([int(e) for e in l])
if a == 0:
return False
if i % a == 0:
return True
else:
return False
def ithHarshad(i):
a = []
count = 0
x = 0
while True:
x += 1
if isHarshad(x):
a = a + [x]
count += 1
if count == i: # Breaks when enough numbers are generated.
break
print(a)
ithHarshad(25)
这将继续向x
添加1,直到您的计数终止它为止。
我不太确定你的意思是“检查范围”。你的意思是想要显示start
和end
之间的所有Hardshad数字吗?是的,你可以这样做:
def isHarshad(i):
l = list(str(i))
a = sum([int(e) for e in l])
if a == 0:
return False
if i % a == 0:
return True
else:
return False
def ithHarshad(start, end):
a = []
count = 0
for x in (range (start,end)):
if isHarshad(x):
a = a + [x]
print(a)
ithHarshad(50,100)
感谢您的反馈,使用一段时间True:为我工作。这是我的解决方案:
def isHarshad(i):
l = list(str(i))
a = sum([int(e) for e in l])
if a == 0:
return False
if i % a == 0:
return True
else:
return False
def ithHarshad(i):
a = []
count = 0
x=1
while True:
if isHarshad(x):
a = a + [x]
count += 1
x+=1
if count == i:
print(a)
else:
x+=1
ithHarshad(25)