[英]I'm making a function that return the sum of the all number in the FizzBuzz list. I thought it would be fine but not working. In Python
The result is 0 It should be 60 if I type 15 but not.结果是 0 如果我输入 15 而不是,它应该是 60。 I don't know why but n_numlist is empty.
我不知道为什么,但 n_numlist 是空的。 Where is my mistake?
我的错误在哪里? I cannot find it!!
我找不到它了!! Is there someone who can find?
有人能找到吗? Please help me!!
请帮我!!
#This is my code:
def to_fizzbuzz(number):
if number % 15 == 0:
return 'FizzBuzz'
if number % 3 == 0:
return 'Fizz'
if number % 5 == 0:
return 'Buzz'
else:
return str(number)
# return i
def main():
N = int(input())
# this list concludes "FizzBuzz", "Fizz" or "Buzz"
fblist = []
for number in range(1, 10**6):
result = to_fizzbuzz(number)
fblist.append(result)
# the list up to N
n_list = fblist[0:N]
# this list contains only numbers and up to N
n_numlist = []
for s in n_list:
if s.isdigit == True:
n_numlist.append(s)
print(sum(n_numlist))
main()
You need to change your for s in n_list
loop to this:您需要将
for s in n_list
循环中的for s in n_list
更改for s in n_list
:
for s in n_list:
if s.isdigit() == True:
n_numlist.append(int(s))
Because isdigit()
is a function, you need to add ()
to the end of it to call it.因为
isdigit()
是一个函数,所以需要在它的末尾加上()
才能调用它。
Because you return your numbers as strings - return str(number)
- it can't sum them, so you need to convert them back to integers when you append them to n_numlist
.因为您将数字作为字符串
return str(number)
- return str(number)
- 它无法对它们求和,因此当您将它们附加到n_numlist
时,您需要将它们转换回整数。
x = int(input())
inputList = list(range(1,x+1)) #creating a list [1,x]
stringList = [str(a) for a in inputList] #changing int elements to string
for n, i in enumerate(stringList): #n shows which element from list, i shows this element
if int(i) %15 == 0: #changing to int because we are doing math
stringList[n] = "FizzBuzz"
elif int(i) %5 == 0:
stringList[n] = "Fizz"
elif int(i) %3 == 0:
stringList[n] = "Buzz"
print(stringList) #let's see our new list
last_list = [] #lets add output list
for a in stringList:
if a.isdigit() == True: #you forgot put () to isdigit by the way
last_list.append(a)
int_last_list = [int(a) for a in last_list] #we are changing all elements to int because we are going to do some math.
print(sum(int_last_list))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.