Create a python function that returns a number that is the amount of equal values of two columns

Asked

Viewed 363 times

1

I am trying to create a function that returns me a number that is the amount of equal values in two columns. (I am new to programming)

I tried the following (I don’t know how wrong it is):

e = 0
df_08['cmb_mpg'] = A
df_18['cmb_mpg'] = B
def equal():
    while e < A(len):
        for b in 'B': 
            for a in 'A':
                if a == b:
                    e = e+1
return e 
  • 1

    Can you describe your code line by line? I can tell you that it does not make sense, but I prefer to see what was your reasoning when drafting it. Maybe you’d better start studying algorithm building before venturing into a programming language.

  • I thought the following: in the first line I wanted the function to be executed while the value of e was less than the length of A, then I wanted to search inside B, values that resemble A and if this function was true add 1 to and.

  • you know that when you assign a variable with = the new variable is on the left side, isn’t it? The sign of = in Python and in almost no language is not like in mathematics where he "defines" that two things are equal - he assigned to the left name the result of the right side expression.

1 answer

3


Well, there are some syntax errors in your code. I will try to list them.

1º - To declare a variable of type string just do:

nomeVariavel = "conteúdo da string"

2º - Your function is not receiving any parameters. The function should receive parameters, which will be the values used within the function. Ex.:

def quantosIguais(a, b):

3º - The variable and, which will be used as a counter, must be declared within the scope of the function.

4º - To find out the size of the string, it is made len(nomeString) and not (len)nomeString.

5th - In the ties for that you used, they only go through 1 value, which is the letter you placed. To use the variable, just put the variable name after the in. Using quotation marks, you traverse a new string, unlike the string stored in the variable. Do:

for a in nomeString

instead of:

for a in 'nomeString'

Well, I tried to list the syntax errors, but like I said, your code doesn’t make sense. I’d also like to understand what your logic was for getting to this code.

I’ll leave an example of a function that does what you tried to do:

def quantasIguais(strA, strB):
    e = 0
    for i in range(len(strA)):
        if strA[i] == strB[i]:
            e += 1
    return e
  • Great, thanks for the excellent explanation.

  • I thought the following: I wanted to make a loop that looked for elements in A and compared with B. If this function was true, I would add 1 to and.

  • @Did this answer solve your problem? If yes, the best way to thank you is to mark it as "solved"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.