这是我的代码:
def L_value_Change(k):
global L
L = k
return L
def applyF_filterG(L, f, g):
L
k = []
for i in L:
if g(f(i)):
k.append(i)
L = k
L_value_Change(k)
if L == []:
return -1
else :
return max(L)
当我输入此代码时,评分者告诉我这是不正确的!所以我读了测验的介绍,导师写道“全局变量不起作用”。如何在不使用单词L
的情况下使用函数更改global
变量?如果你尝试我的代码并给它所需的输入,它会给你一个正确的答案,但是评分者告诉我这是错误的。
答案 0 :(得分:2)
如果要将全局变量重新绑定到其他对象,则需要{
"from": 0,
"size": 20,
"query": {
"function_score": {
"query": {
"bool": {
"filter": [
{
"bool": {
"should": {
"terms": {
"categories.category1Id": [
63
]
}
}
}
}
]
}
},
"functions": [
{
"gauss": {
"updatedDate": {
"origin": "2016-10-03 05:10:18",
"scale": "0.5h",
"decay": 0.1,
"offset": "1h"
}
}
},
{
"filter": {
"term": {
"productQuality": "EXCELLENT"
}
},
"weight": 7
},
{
"filter": {
"term": {
"productQuality": "HIGH"
}
},
"weight": 5
},
{
"filter": {
"term": {
"productQuality": "MEDIUM"
}
},
"weight": 3
},
{
"filter": {
"term": {
"productQuality": "LOW"
}
},
"weight": 1
}
],
"score_mode": "sum"
}
}
}
关键字。但是如果您想要做的就是更改可变对象,则不需要它。在您的情况下,global
是一个列表,可以使用切片操作L
进行调整。为了证明:
L[:] = k
答案 1 :(得分:2)
列表是可变对象,因此,要更改它们,您只需将它们作为参数传递给函数即可。
def f(i):
return i + 2
def g(i):
return i > 5
l = [0, -10, 5, 6, -4]
def applyF_filterG(L, f, g):
for val in L[:]:
if not g(f(val)):
L.remove(val)
return -1 if not L else max(L)
print(l) # [0, -10, 5, 6, -4]
applyF_filterG(l, f, g) # Return 6
print(l) # [5, 6]
答案 2 :(得分:0)
这是我的代码,它避免了你试图迭代的列表上的变异。
def applyF_filterG(L,f,g):
"""
Assumes L is a list of integers
Assume functions f and g are defined for you.
f takes in an integer, applies a function, returns another integer
g takes in an integer, applies a Boolean function,
returns either True or False
Mutates L such that, for each element i originally in L, L contains
i if g(f(i)) returns True, and no other elements
Returns the largest element in the mutated L or -1 if the list is empty
"""
# Applying the functions & Mutating L
i = len(L)-1
largestnum=0
if (len(L)==0):
return -1
else:
while i>=0:
if not g(f(L[i])):
del L[i]
i-=1
#Finding the largest number
if not L:
return -1
if (len(L)==1):
return L[0]
else:
for num in range(len(L)-1):
if (L[num]>L[num+1]):
largestnum=L[num]
else:
largestnum=L[num+1]
return largestnum