使用函数来分解代码

时间:2015-10-13 17:52:12

标签: python

嘿伙计们,我的任务是"选择你已编写的程序,并通过将此程序分解为FUNCTIONS来提高效率。您的目标应该是具有单独的INPUT,PROCESS和OUTPUT功能"

所以我已经完成了前两个功能(我认为),但我不知道怎么做最后一点:(

以下是原始代码:

compatibility = 100 #max compatibility level which is 100%
compatibility1 = 100 #max compatibility level which is 100%

yourname = input ("Please enter your name: ") #the 2 names will be asked in     this section
othername = input ("Please enter his/her name: ")

weight = 100/ len(yourname) #weighted % of each letter/character to be used later
weight = 100/ len(othername)

for char in yourname: #This will simply be your name
    if char.lower() not in ['l','o','v','e','s']:
        compatibility -= weight #if one of these letters are not in the names provided, it will take away the weighted % of each character from 100

for char in othername: # And this is the name you will be providing to check    the compatibility
    if char.lower() not in ['l','o','v','e','s']:
        compatibility1 -= weight

result = compatibility+compatibility1 #the variable result is used to add up     the 2 values above
final =  result/200*100 #And finally this variable will make it into a percentage 100(max)+100(max) = 200, so result/200*100 ---> percentage


print("Your compatibility is: " + str(int(final)) + "%" )

我的新代码是:

def inputs():
yourname = input
othername = input
return inputs

def processing():
    compatibility = 100 #max compatibility level which is 100%
    compatibility1 = 100 #max compatibility level which is 100%
    weight = 100/ len(yourname) #weighted % of each letter/character to be used later
    weight = 100/ len(othername)
    for char in yourname: #This will simply be your name
        if char.lower() not in ['l','o','v','e','s']:
            compatibility -= weight #if one of these letters are not in the names provided, it will take away the weighted % of each character from 100

    for char in othername: # And this is the name you will be providing to check the compatibility
        if char.lower() not in ['l','o','v','e','s']:
            compatibility1 -= weight
    return processing

1 个答案:

答案 0 :(得分:0)

我想你想要这样的东西:

#INPUT FUNCTIONS
def inputMyName():
    myName=raw_input("Please Enter Your Name: ")
    return myName

def inputOtherName():
    return raw_input("Enter Other Name: ")

#PROCESS FUNCTIONS
def getWeights(name1,name2):
    w1=100/len(name1)
    w2=100/len(name2)
    weight=[w1,w2]
    return weight

def getComp(weights,name1,name2):
    comp1 = 100
    comp2 = 100
    for i in name1:
        if i.lower() not in ['l','o','v','e','s']:
            comp1-=weights[0]
    for i in name2:
        if i.lower() not in ['l','o','v','e','s']:
            comp2-=weights[1]
    return [comp1,comp2]

#OUTPUT FUNCTIONS
def outComp(comps):
    result = comps[0]+comps[1]
    final = result/200*100
    print("Your Compatibility is: "+str(int(final))+"%") 

a=inputMyName()
b=inputOtherName()
w=getWeights(a,b)
c=getComp(w,a,b)
outComp(c)