Search code examples
pythonfunctionglobal-variables

Python function that changes variable parameters


How can I rewrite my function so that when it runs, it changes the variables input as arguments? I have read you have to write global before each variable name but writing global before a, b, c parameters doesn't work and I can't figure out another way to make it work.

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)

Note that this is a solution to USACO problem: 2018 December Contest, Bronze Problem 1. Mixing Milk -> http://www.usaco.org/index.php?page=viewproblem2&cpid=855


Solution

  • I think this is what you're looking for:

    [...]
    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)
    [...]