mardi 27 avril 2021

Changing the structure of a function with if statement Python

There is the function a could either be in the form of client.LinearKline.LinearKline_get() or in the form of client.Kline.Kline_get(). How could I make a and b modular so that both options could work the function below does not really work.

if choice ==1:
    a= LinearKline
    b= LinearKline_get
else:
    a= Kline
    b= Kline_get

client.a.b()

Python is not randomly giving a question and asks same question repeatedly

i'm having an issue with my program, a music quiz, where what is supposed to happen is that when getting it wrong and earning one point, the point system should reset and allow you to get 3 points for the next question. However, it will only give 1 point for all i get right first time after that. Also, for the questions, the first song question is asked randomly but the questions after the first are not random song questions. I'm not too sure if this makes any sense but hopefully the code will explain it better:

import csv
import random

with open("playlist.csv", "r") as input_file: #this is the name of my csv file
    csv_source = csv.DictReader(input_file)
    all_songs_and_artists = list(csv_source)

song_and_artist_chosen = random.choice(all_songs_and_artists)

song_words = song_and_artist_chosen["Songs"].split()
song_initials = "".join(item[0] for item in song_words)
initials_uppercase = song_initials.upper()

print("\n")

user_score = 0
asks = 0

while True:
    print("The artist is: " + song_artist_chosen["Artist"])
    print("and the initials are: " + initials_uppercase)
    user_guess = str(input("What's the song?"))
    if song_and_artist_chosen["Songs"].upper() == user_guess.upper(): 
       print("Correct!")
       if asks == 0: 
          user_score = user_score + 3
          print("You now have, ", user_score, "points")
          True
       elif asks == 1
           user_score = user_score + 1
           print("You have earned 1 point!")
           print("You now have ", user_score, "points")
           True
     else:
         asks = asks + 1
         if asks == 1:
            print("incorrect, you have one more try")
            user_guess = input("What's the song?")
            if song_and_artist_chosen["Songs"].upper() == user_guess.upper()
            user_score = user_score + 1
            print("Correct!")
            print("You now have ", user_score, "points")
            True
         else:
            print("------------------------")
            str(print("Unlucky, you lost, your score was ", + user_score))
            False
            quit()
            

Is it possible to create a list of numbers/letters in an if-statement without having to create multiple conditions?

(Probably noob-ish question by hey you live you learn)

So what I'm trying to do is make a list of values I want to check without having to create multiple conditions like you usually have to do:

if (a == 0 || a == 1 || a == 2 ... || a == 9) {
    // Code
}

Where you could probably do something like this:

if (a == (1,2,3,4,5,6,7,8,9)) {
    // Code
}

I couldn't find any posts on this topic and I once tried this myself at one point and it worked but nowadays it doesn't. Is it possible (Or still possible) to do something like this or in a way similar to this in an if-statement?

Creating New Dataframe Based on Cells of Other Dataframes using For loop R

I have 2 data frames with the same row and column structure that both have a lot of NA values. I want to create another data frame that simply tells me which cells in the 2 original data frames actually have values. For example

enter image description here So far I have been able to do this manually by mutating a series of if else statements for each column like this:

combined <- trial_1[,1:2] %>%
   mutate("Part1" = ifelse(!is.na(trial_1$Part1) & !is.na(trial_2$Part1), "1 & 2",
 ifelse(!is.na(trial_1$Part1) & is.na(trial_2$Part1), "1 only", ifelse(is.na(trial_1$Part1) & !is.na(trial_2$Part1),
 "2 only", ifelse(is.na(trial_1$Part1) & is.na(trial_2$Part1),
 "NA", "Failed"))))) %>%

   mutate("Part2" = ifelse(!is.na(trial_1$Part2) & !is.na(trial_2$Part2),
 "1 & 2",ifelse(!is.na(trial_1$Part2) & is.na(trial_2$Part2), "1 only",
 ifelse(is.na(trial_1$Part2) & !is.na(trial_2$Part2), "2 only", ifelse(is.na(trial_1$Part2) & is.na(trial_2$Part2), "NA", "Failed"))))) %>%

   mutate("Part3" = ifelse(!is.na(trial_1$Part3) & !is.na(trial_2$Part3), "1 & 2",
 ifelse(!is.na(trial_1$Part3) & is.na(trial_2$Part3),
 "1 only", ifelse(is.na(trial_1$Part3) & !is.na(trial_2$Part3), "2 only", ifelse(is.na(trial_1$Part3) & is.na(trial_2$Part3),
 "NA", "Failed"))))) %>%

   mutate("Part4" = ifelse(!is.na(trial_1$Part4) & !is.na(trial_2$Part4),
 "1 & 2", ifelse(!is.na(trial_1$Part4) & is.na(trial_2$Part4), "1 only", ifelse(is.na(trial_1$Part4) & !is.na(trial_2$Part4),
 "2 only", ifelse(is.na(trial_1$Part4) & is.na(trial_2$Part4), "NA", "Failed")))))

But this is obviously not efficient so I tried using a for loop, which does not work:

participants <- list('Part1', 'Part2', 'Part3', 'Part4')

combined <- trial_1[,1:2]

for (i in participants) {

combined <- combined %>%
  mutate(i = ifelse(!is.na(trial_1$i) & !is.na(trial_2$i), "1 & 2",
 ifelse(!is.na(trial_1$i) & is.na(trial_2$i), "1 only",
 ifelse(is.na(trial_1$i) & !is.na(trial_2$i), "2 only",
 ifelse(is.na(trial_1$i) & is.na(trial_2$i), "NA", "Failed")))))

}

Any help on how to restructure this for loop, which I think is the way to go, would be very helpful. Thanks!

Excel VBA IF statement returning false results

I have set a and b as variables and as true / false based on whether they appear in a row.

I want to create an IF statement that states that if b is true but a is false then it should enter this into a sheet. However, the code brings results even when a is true. What could be wrong?

If Not a Then
If b = True Then
RecordNextRow = RecordNextRow + 1
RecordNextRow = x
End If
End If`

I also tried 
If (a = False) And (b = True)Then
RecordNextRow = RecordNextRow + 1
RecordNextRow = x
End If
End If

If statement not working in Selenium Webdriver

I always have issues with if statements in selenium. Most of the time they do the opposite of what they are supposed to do.

I have deliberately typed an incorrect email address so the payment will fail. Thee Oops! is displayed on the webpage which is the correct response however my test comes back fail. The xpath is correct as it passes when I type the correct email in.

Please can someone take a look and advise me where I am going wrong.

@Test(dependsOnMethods = { "WithdrawalButtonOnNavBar" })
    public void WithdrawWinnings() throws InterruptedException {
        Thread.sleep(500);
        driver.findElement(By.cssSelector("input[name='email']")).sendKeys(skrillAccount);
        Thread.sleep(500);
        driver.findElement(By.xpath("//p[contains(text(),'Continue')]")).click();
        Thread.sleep(500);
        driver.findElement(By.cssSelector("input[name='amount']")).sendKeys("2");
        Thread.sleep(500);
        driver.findElement(By.xpath("//*[@id=\"__next\"]/div/div[1]/div[2]/div/div[3]/div/div/div")).click();
        Thread.sleep(5000);
        WebElement Success = driver.findElement(By.xpath("//p[contains(text(),'Success!')]"));
        WebElement Oops = driver.findElement(By.xpath("//p[contains(text(),'Oops!')]"));
        if (Success.isDisplayed()) {
            System.out.println("Payment was successful");
        } else if(Oops.isDisplayed())  {
            System.out.println("Payment was unsuccessful");
        }
        ;

    }

org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//p[contains(text(),'Success!')]"} (Session info: chrome=90.0.4430.85) For documentation on this error, please visit: https://selenium.dev/exceptions/#no_such_element

Two Parts: Reading arrays and switching values to be alternating, then finding the minimum number of switches needed

I've been working on an specific interview question that basically asks the following: "There are N coins, each showing either heads or tails. We would like all the coins to be alternating between heads and tails. What is the minimum number of coins to be reversed to achieve this?"

Array examples: A = [1, 0, 1, 0, 1, 1] (function should return "1"), A = [1, 1, 0, 1, 1] (function should return "2"), etc.

I'm working with Java SE 8 and am using the function given:

class Solution { public int solution(int[] A); }

I can't seem to figure out why when it loops through, it either fails or changes too many values (it doesn't always provide the minimum number of reverses). Please help!

Here is the code that I've written so far; which works for one of the test cases, but fails others:

class Solution {
    public int solution(int[] A) {
        // write your code in Java SE 8
        if (A.length == 1) return 0;
        int n = A.length;
        int result = 0;

        for (int i = 0; i < n - 1; ) {
            if(A[i] == A[i + 1])
                result = result + 1;
            i = i + 1;
        }

        if (result == n - 1) return result - 1;

        int revers = 0;
        for (int i = 0; i < n; i++) {
            int count = 0;
            if (i > 0) {
                if (A[i - 1] != A[i])
                    count = count + 1;
                else
                    count = count - 1;
            }
            if (i < n -1) {
                if (A[i + 1] != A[i])
                    count = count + 1;
                else
                    count = count - 1;
            }
            revers = Math.max(revers, count);
        }
        return result + revers;
    }
}