mardi 29 octobre 2019

Check if element is in list, then write to new column in Pandas dataframe if conditions met

Looking at a pandas dataframe containing information on all olympic athletes for past 150 years (Name, Weight, Country, Sport, etc). Available at https://www.kaggle.com/heesoo37/120-years-of-olympic-history-athletes-and-results#athlete_events.csv.

Preview of dataframe

Attempting to make a for loop that iterates through df rows, checks the value stored in the 'Sport' column against several lists and then adds a column to the df with a parent category within the same row. Code so far:

aquatic_sports = ['Swimming','Diving','Synchronized Swimming','Water Polo']
track_sports = ['Athletics','Modern Pentathlon','Triathlon','Biathlon','Cycling']
team_sports = ['Softball','Basketball','Volleyball','Beach Volleyball','Handball','Rugby','Lacrosse']
gymnastic_sports = ['Gymnastics','Rhytmic Gymnastics','Trampolining']
fitness_sports = ['Weightlifting']
combat_sports = ['Boxing','Judo','Wrestling','Taekwondo']
winter_sports = ['Short Track Speed Skating','Ski Jumping','Cross Country Skiing','Luge','Bobsleigh','Alpine Skiing','Curling','Snowboarding','Ice Hocky','Hockey','Speed Skating']

for index, row in df.iterrows():

    if df.iloc[0,11] in aquatic_sports:

        df['Sport Category'] = 'Aquatic Sport'

    elif df.iloc[0,11] in track_sports:

        df['Sport Category'] = 'Track Sport'

    elif df.iloc[0,11] in gymnastic_sports:

        df['Sport Category'] = 'Gymnastic Sport'

    elif df.iloc[0,11] in fitness_sports:

        df['Sport Category'] = 'Fitness Sport'

    elif df.iloc[0,11] in combat_sports:

        df['Sport Category'] = 'Combat Sport'

    elif df.iloc[0,11] in winter_sports:

        df['Sport Category'] = 'Winter Sport'

No errors thrown but unfortunately all values in the new column are the same. Unsure how to pass the current index to ensure each iterations returns a unique, correct value.

Making compare() function more elegant

I have this code:

function compare (a, b) {
  let comparison = 0;
  if (a.essentialsPercentage < b.essentialsPercentage) {
    comparison = 1;
  } else if (a.essentialsPercentage > b.essentialsPercentage) {
    comparison = -1;
  } else {
    if (a.skillsNicePercentage < b.skillsNicePercentage) {
      comparison = 1;
    } else if (a.skillsNicePercentage > b.skillsNicePercentage) {
      comparison = -1;
    } else {
      if (a.startDate > b.startDate) {
        comparison = 1
      } else if (a.startDate < b.startDate) {
        comparison = -1
      }
    }
  }
  return comparison;
}

What would be the most elegant way of writing it? It doesn't seems nice at the moment.

How can I reduce my if statements and shorten my code?

My code works, however, an error pops up saying there are too many statements.

I don't know how to reduce the statements because each one serves a purpose in the function.

def is_sink(elevation_map: List[List[int]], cell: List[int]) -> bool:
    """Return True if and only if cell exists in the elevation map
    elevation_map and cell is a sink.

    Precondition: elevation_map is a valid elevation map.
                  cell is a 2-element list.

    >>> is_sink(THREE_BY_THREE, [0, 5])
    False
    >>> is_sink(THREE_BY_THREE, [0, 2])
    True
    >>> is_sink(THREE_BY_THREE, [1, 1])
    False
    >>> is_sink(FOUR_BY_FOUR, [2, 3])
    True
    >>> is_sink(FOUR_BY_FOUR, [3, 2])
    True
    >>> is_sink(FOUR_BY_FOUR, [1, 3])
    False
    """    
    x = cell[0]
    y = cell[1]
    x_initial = 0
    x_final = 0
    y_initial = 0
    y_final = 0

    if x > len(elevation_map): 
        return False
    elif y > len(elevation_map[0]): 
        return False 
    if x - 1 < 0:
        x_initial = x
    else:
        x_initial = x - 1
    if x + 1 >= x:
        x_final = x
    else:
        x_final = x + 1
    if y - 1 < 0:
        y_initial = y
    else:
        y_initial = y - 1
    if y + 1 >= y:
        y_final = y
    else:
        y_final = y + 1
    validsink = True
    for i in range(x_initial, x_final + 1):
        for j in range(y_initial, y_final + 1):
            if elevation_map[i][j] < elevation_map[x][y]:
                validsink = False
    return validsink 

R0915 (too-many-statements) Number of occurrences: 1. [Line 142] Too many statements (24/20)

How to find Curved Grade in Google Sheets?

I'm working on a file where final grades of all courses are added, every students has the right to get up to 5 grades as curve for all of his/her final grades with are lower than Passing Grade. My question is: is it possible to find new final grades with added grades by a Formula and/or Script in Google Sheets. Below is a sample of the data

studentName         course          final           final (withCurve)
A                    Math             59              60
A                    Physics          58              60
A                    English          54              54
B                    English          55              55
B                    Physics          58              60
B                    French           57              60

Note: Assume the passing Grade is 60 and give the 5 grades to more courses as possible, means better to give it to 57, 58 than one single 55 (if it is possible).

Multiple outputs after if statement

if ((min(which((retail_stocks$ratio > (m + k*s))  == TRUE))) < (min(which((retail_stocks$ratio < (m - k*s)) == TRUE)))) {
  pos$open[i] <-  min(which(retail_stocks$ratio > (m + k*s)));
  pos$close[i] <- min(which(retail_stocks$ratio <= m))
} else {
  pos$open[i] <- min(which(retail_stocks$ratio < (m - k*s)))
}

If the condition is met, i want to fill the pos$open with the first index for which it's true, then I need to know where the closing point is, that's the first time the stockratio price crosses the mean again. That can't be simply be retailstock$ratio <= m; because it should be later/higher index number than the opening point. Then i need to find the next open point which is either the first value in which the ratio > mean + k sd or ratio < mean - ks; after the last opening/closing index point and then i need to find next the closing point; which index needs to be higher than of the last opening point. and i have to repeat this untill the end of the dataset. Im kind of stuck; how to implement this. I probably need to combine for/if and while loops; i dont really know how. hopefully someone can help me.

syntax error during implementation of RC4 algorithm

I am trying to modify implementation RC4 algorithm in python that i found online and i am getting a syntax error for using a if loop in place of while loop can anybody tell me why is that?

def PRGA(S):

i = 0
j = 0
if i==0 & j==0:    # here it was originally while True:, so I changed it to if statement
    i = (i + 1) % 256
    j = (j + S[i]) % 256

    S[i], S[j] = S[j], S[i]  # swap values
    K = S[(S[i] + S[j]) % 256
    print ('K')    # and here it was yield K
else:
    print ('error')

Coin flipping program incorrect result [duplicate]

This question already has an answer here:

I'm still new to Java, so apologies for the mess.

So a user would put in "heads" or "tails" into here:

 System.out.println(labExample.headsOrTails("heads"));

And the program should randomly generate a heads or tails and also say whether or not your guess is correct. e.g. "Incorrect: you guessed heads and I flipped tails."

What I've made so far seems to only say that the guess is "Correct" if the result is tails, and not whether or not the input matches the result. So my code seems to have a twist in there somewhere.

public String headsOrTails(String guess) {
        String cointoss; //input and result
        String heads = ""; //if guess == "heads"
        String tails = ""; //if guess == "tails"
        String correct = "Correct: "; //if guess matches
        String incorrect = "Incorrect: "; //if guess doesn't match
        String headsOrTails = ""; //identifying String guess input
        String result = ""; //end print of the result

            if (guess == "heads") {
                headsOrTails = heads;
            }
            if (guess == "tails") {
                headsOrTails = tails;
            }

            if (Math.random() >= 0.5) {
                cointoss = " and I flipped heads";
                heads = correct;
                tails = incorrect;
            }
            else {
                cointoss = " and I flipped tails";
                heads = incorrect;
                tails = correct;
            }

            if (heads == correct) {
                result = correct;
            }
            else {
                result = incorrect;
            }
            if (tails == correct) {
                result = correct;
            }
            else {
                result = incorrect;
            }
        return result+"you guessed "+guess+cointoss;
    }

Any help or pointers would be great. Thanks.