Python 改变变量参数的函数
Python function that changes variable parameters
我如何重写我的函数,以便在它运行时更改作为参数输入的变量?我读过你必须在每个变量名之前写 global
但在 a
、b
、c
参数之前写 global 不起作用,我想不出另一个让它工作的方法。
import sys
sys.stdin = open("/Users/isym444/Desktop/PythonCP/CP1/Codewars/Practice/input.txt", "r")
sys.stdout = open("/Users/isym444/Desktop/PythonCP/CP1/Codewars/Practice/output.txt", "w")
""" sys.stdin = open("mixmilk.in", "r")
sys.stdout = open("mixmilk.out", "w") """
c1, m1 = map(int, input().split())
c2, m2 = map(int, input().split())
c3, m3 = map(int, input().split())
def fun1(a, b, c):
amt = min(a, b - c)
a -= amt
c += amt
# pours 1 to 99
for i in range(1, 34):
fun1(m1, c2, m2)
fun1(m2, c3, m3)
fun1(m3, c1, m1)
# pour 100
fun1(m1, c2, m2)
result = [m1, m2, m3]
for i in result:
print(i)
请注意,这是 USACO 问题的解决方案:2018 年 12 月竞赛,铜牌问题 1. 混合牛奶 -> http://www.usaco.org/index.php?page=viewproblem2&cpid=855
我想这就是您要找的:
[...]
def fun1(a, b, c):
amt = min(a, b - c)
a -= amt
c += amt
return (a, b, c)
# pours 1 to 99
for i in range(1, 34):
m1, c2, m2 = fun1(m1, c2, m2)
m2, c3, m3 = fun1(m2, c3, m3)
m3, c1, m1 = fun1(m3, c1, m1)
# pour 100
m1, c2, m2 = fun1(m1, c2, m2)
[...]
我如何重写我的函数,以便在它运行时更改作为参数输入的变量?我读过你必须在每个变量名之前写 global
但在 a
、b
、c
参数之前写 global 不起作用,我想不出另一个让它工作的方法。
import sys
sys.stdin = open("/Users/isym444/Desktop/PythonCP/CP1/Codewars/Practice/input.txt", "r")
sys.stdout = open("/Users/isym444/Desktop/PythonCP/CP1/Codewars/Practice/output.txt", "w")
""" sys.stdin = open("mixmilk.in", "r")
sys.stdout = open("mixmilk.out", "w") """
c1, m1 = map(int, input().split())
c2, m2 = map(int, input().split())
c3, m3 = map(int, input().split())
def fun1(a, b, c):
amt = min(a, b - c)
a -= amt
c += amt
# pours 1 to 99
for i in range(1, 34):
fun1(m1, c2, m2)
fun1(m2, c3, m3)
fun1(m3, c1, m1)
# pour 100
fun1(m1, c2, m2)
result = [m1, m2, m3]
for i in result:
print(i)
请注意,这是 USACO 问题的解决方案:2018 年 12 月竞赛,铜牌问题 1. 混合牛奶 -> http://www.usaco.org/index.php?page=viewproblem2&cpid=855
我想这就是您要找的:
[...]
def fun1(a, b, c):
amt = min(a, b - c)
a -= amt
c += amt
return (a, b, c)
# pours 1 to 99
for i in range(1, 34):
m1, c2, m2 = fun1(m1, c2, m2)
m2, c3, m3 = fun1(m2, c3, m3)
m3, c1, m1 = fun1(m3, c1, m1)
# pour 100
m1, c2, m2 = fun1(m1, c2, m2)
[...]