我目前正在编写一段代码,该代码生成数字的数字总和并仅在它们是 5 的倍数时才打印它们。
因此,例如:0、5 和 14 将是本例中打印出来的前三位数字。
num = 0
while num < 100:
sums = sum([int(digit) for digit in str(num)])
if sums % 5 == 0: #determines if the sum is a multiple of 5
print(num)
num += 1
Run Code Online (Sandbox Code Playgroud)
这段代码效果很好!绝对可以完成 1 到 100 之间的总和。但是,我在 python 方面没有很多经验,并认为我会推动自己并尝试在一行代码中完成它。
目前,这就是我正在使用的:
print(sum(digit for digit in range(1,100) if digit % 5 == 0))
Run Code Online (Sandbox Code Playgroud)
我觉得我在正确的轨道上的某个地方,但我无法到达那里的其余部分。目前,此代码正在吐出 950。
我知道这digit % 5 == 0是完全错误的,但我完全没有想法!任何帮助和/或智慧之言将不胜感激。
我正在开发一个函数,该函数将使用两个六个六边形的骰子,并在元组列表中返回配对的所有可能性。
因此,我希望我的程序返回如下内容:
[(1,1),(1,2),(1,3),(1,4),(1,5),(1,6),
(2,1),(2,2),(2,3),(2,4),(2,5),(2,6),
(3,1),(3,2),(3,3),(3,4),(3,5),(3,6),
(4,1),(4,2),(4,3),(4,4),(4,5),(4,6),
(5,1),(5,2),(5,3),(5,4),(5,5),(5,6),
(6,1),(6,2),(6,3),(6,4),(6,5),(6,6)]
Run Code Online (Sandbox Code Playgroud)
我认为我的头可能在正确的常规区域,但是执行起来有点麻烦,因为我是Haskell的新手。这是我所拥有的:
rolls :: [(Integer, Integer)]
fstDice = [1, 2, 3, 4, 5, 6]
sndDice = [1, 2, 3, 4, 5, 6]
rolls
| zip fstDice sndDice
| drop 1 sndDice
| otherwise = rolls
Run Code Online (Sandbox Code Playgroud)
我知道最后一部分是非常错误的,相信我。我以前是zip将两个骰子放在一起,然后想到要放下head第二个骰子,然后重复该过程,直到sndDice没有空并找到所有的骰子对为止。
我不确定这个想法是否错误,或者只是我的业余执行不正确。
(根据记录,我知道它不会编译!我也不知道如何处理该错误。)
I'm a beginner in Haskell and I've been having trouble with my practice programs. For this particular one, I want to find the index of an element in a list (the first element being at 0). If the element given does not appear in the list, I am having the program return -1.
Here is my code:
indexOf :: (Eq a) => a -> [a] -> Int
indexOf n [] = (-1)
indexOf n (x:xs)
| n == x = …Run Code Online (Sandbox Code Playgroud)