给定一个数字列表和一个数字k,返回列表中的任意两个数字加起来是否为k。
例如,给定 [10, 15, 3, 7] 和 k of 17,则返回 true,因为 10 + 7 是 17。
程序必须提示用户输入。
程序必须接受列表作为逗号分隔值的集合。
这些值应全部为整数。
输入列表的长度可以介于 1 到 42 个数字之间。
我做了什么
我已经能够将整数列表输入为列表并用逗号分隔,但是当 2 个数字加到 k 时无法返回 true
toList :: String -> [Integer]
toList input = read ("[" ++ input ++ "]")
main = do
putStrLn "Enter a list of numbers (separated by comma):"
input <- getLine
print $ k (toList input)
有以下方法。
1(创建一个列表 pf 对,这些对都是组合 [(10,10(,(10,15(,..,(15,10(,(15,3(..]。 现在,您可以使用此列表中的简单任意函数来检查是否有任何对加起来达到给定的数字。
getCoupleList :: [a]->[(a,a)]
getCoupleList [] = []
getCoupleList [x] = []
getCoupleList (x:xs) = map (y->(x,y)) xs ++ getCoupleList xs
getSumOfCoupleList :: Num a => [(a,a)]->[a]
getSumOfCoupleList xs = map (x -> fst x + snd x) xs
isSum :: [Int]->Int->Bool
isSum xs k = any (==k) $ (getSumOfCoupleList.getCoupleList) xs
或直接查看 wuthout getSumOfCoupleList
isSum xs k = any ((a,b)-> a + b == k) $ (getSumOfCoupleList.getCoupleList) xs
如果您选中创建情侣列表并找到不需要的总和。我们可以通过简单的更改直接获得总和列表。
getSumList :: Num a=>[a]->[a]
getSumList [] = []
getSumList [x] = []
getSumList (x:xs) = map (+x) xs ++ getSumList xs
isSum1 :: [Int]->Int->Bool
isSum1 xs k = any (==k) $ getSumList xs
2( 通过从 17 中减去每个元素,从给定列表中创建另一个列表。现在只需检查第二个列表中是否存在第一个列表中的任何数字。
isSum2 :: [Int]->Int->Bool
isSum2 xs k = let newList = map (k-) xs
intersectList = xs `intersect` newList
in not (null intersectList)
这是一个幼稚的方法,没有优化,只是展示一个例子。
toList :: String -> [Integer]
toList input = read ("[" ++ input ++ "]")
check :: Integer -> [Integer] -> Bool
check k (x:xs) = if ((k-x) `elem` xs)
then True
else (check k xs)
check k x = False
main = do
let k = 12
putStrLn "Enter a list of numbers (separated by comma):"
input <- getLine
print $ (check k (toList input))
我最近在一次采访中被问到同样的问题,这是我的答案之一
import util
arr = [10, 15, 3, 8]
k = 17
for i in range(0, len(arr)):
arr_new.append(abs(arr[i] -17))
res= list(set(arr).intersection(arr_new))
if (len(res)>0):
print(str(res[0]) + " + " + str(res[1]) +"= "+ str(k ))
else:
print("No numbers add up to k")