我有一個應該驗證關系是否是函式的函式。
這是我的功能:
def isFunction(A,B,f):
ky = [i for i,j in f] ##fetching the first element of f and placing it in ky
for i in A:
if ky.count(i) != 1: ##checks whether the all elements of A have a unique image in B
return False
for i in f:
if i not in A:
return False
return True
這些是采取的輸入:
A = [1, 2, 3,] ##change inputs according to the needs
B= [4,5]
f=[[1,4],[2,5],[3 ,4], [7, 4]]
print (isFunction(A,B,f))
我應該得到一個False,這是正確的,但如果我做另一個測驗用例:
A = [1, 2, 3,]
B = [4, 5]
f = [[1,4], [2,5], [3,4]]
print('Returns: ', isFunction(A, B, f))
我現在也得到了false一份宣告,但我應該得到一份True宣告。錯誤是什么,我該怎么做才能改變我的功能?
uj5u.com熱心網友回復:
對您的程式進行以下修改會導致我懷疑是所需的行為
選項 1 迭代ky而不是f在第二個 for 回圈中:
def isFunction(A,B,f):
ky = [i for i,j in f] ##fetching the first element of f and placing it in ky
for i in A:
if ky.count(i) != 1: ##checks whether the all elements of A have a unique image in B
return False
for i in ky:
if i not in A:
return False
return True
這是另一種方法
選項 2:將 i 作為每對 f 而不是整個對的第一個元素。
def isFunction(A,B,f):
ky = [i for i,j in f] ##fetching the first element of f and placing it in ky
for i in A:
if ky.count(i) != 1: ##checks whether the all elements of A have a unique image in B
return False
for i,_ in f:
if i not in A:
return False
return True
從技術上講,這兩種方法都是有缺陷的,因為它們允許域僅由 A 的子集組成的函式。例如,對于
A = [1,2]
B = [1,2]
f = [(1,1)]
此外,您似乎假設 f 中的對是不同的,即每對(i,j)最多只能在 "function" 中出現一次f。
這是我將采取的方法。這假設域必須由整個集合 A 組成,并且 f 中的對是不同的。
def isFunction(A,B,f):
inputs = [i for i,_ in f]
in_set = set(inputs)
return in_set == set(A) and\
len(in_set) == len(inputs)
in_set == set(A)如果輸入集等于整個域 A,則條件回傳len(in_set) == len(inputs)True,并且如果每個輸入 i 僅與 f 中的一對 (i,j) 一起出現一次,則條件回傳 True。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/517642.html
標籤:Python功能if 语句
上一篇:JetpackComposeanimateFloatAsState替換為Transition.animateFloat不起作用
