![](/img/trans.png)
[英]Python - I'm not sure why this function I'm defining isn't working. Very fresh to programming
[英]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
結果是 0 如果我輸入 15 而不是,它應該是 60。 我不知道為什么,但 n_numlist 是空的。 我的錯誤在哪里? 我找不到它了!! 有人能找到嗎? 請幫我!!
#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()
您需要將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))
因為isdigit()
是一個函數,所以需要在它的末尾加上()
才能調用它。
因為您將數字作為字符串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.