简体   繁体   中英

Can I run the same function multiple times with the return value as the argument?

The code is supposed to return a final color value if you give it a string of colours, like

Colour here: GG, BG, RG, BR
Becomes colour: G, R, B, G

For example: 'RGBG' would return 'B' Here, i wrote a function to assign color tags (Assign) and another funtion which would feed the broken down primary string. It all works fine when i manually type the new_value = assign(main(again)) multiple times depending on the size of the primary string(RGBG -> BRR -> GR ->B; 4 times here but i run the first iteration in advance because the again parameter would have a value to begin with), but returns an empty value when i use again = assign(main(again)) even though i have given the parameter a value on the previous lines so it's not a "undefined param" error.. i think.

I'm pretty new to this and would greatly appreciate it if you could point me in the right way. Hoping this message finds you in safety:)

def assign(xlist):
    for x in range(len(xlist)):
        if xlist[x] in ('BG', 'GB', 'RR'): xlist[x] = 'R'
        elif xlist[x] in ('RG', 'GR', 'BB'): xlist[x] = 'B'
        elif xlist[x] in ('BR'. 'RB', 'GG'): xlist[x] = 'G'
    return ''.join(xlist)

def main(xrow):
    nrow = []
    for i in range(len(xrow)-1):
        nrow.append(xrow[i] + xrow[i+1])
    return(nrow)
        
def triangle(row):
    global again
    again = assign(main(row))
    print(row)
    print(again)
    for k in range(len(row)-1):
        again = assign(main(again))
    return again

You could do it like this:

s =  'RGBG'

dict_map = {
    'BG':'R',
    'GB':'R',
    'RR':'R',
    'RG':'B',
    'GR':'B',
    'BB':'B',
    'BR':'G',
    'RB':'G',
    'GG':'G'
    }

def process(s):
    while len(s)!=1:
        s = "".join([dict_map["".join(x)] for x in zip(s[:-1], s[1:])])
    return s

print(process(s))
# B

Lets break it down:

you can use a dictionary to translate values to other values based on their keys:

dict_map["BG"] will return "R". To use the dict we need a list of elements with 2 characters.

We create that list by using the following: [x for x in zip(s[:-1], s[1:])] This will return a list of overlapping tupels. Eg ("R", "G")

Since we cant use this tupels with the dictionary we "".join() them together resulting eg in "RG".

Now we ask the dictionary which values is used for that key by using dict_map["RG"] and get "R" in this case.

The whole thing is done here: [dict_map["".join(x)] for x in zip(s[:-1], s[1:])]

Now we have again a list of translated values. We "".join() it together again to get a new string: "BRR". We repeat the whole process until the string has a length of 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM