vendredi 1 janvier 2021

Python if condition optimization

Hi i wrote a little easy python code to help my girlfriend learn her psy lessons but i made a condition that looks so UGLY !!!

I mean all lines looks pretty the same, so maybe there would be a way to regroup the same looking stuff, maybe with a loop ?

I was wondering if there is somehow a way to optimize it...?

Here's the code

import random
import sys
import time

list_domaine=["Communication","Reciprocal social interaction","Communication and social"]
list_autism=["Neurotypical","Borderline","Autist"]
    
def intro():
    global player_name
    
    player_name=input("What's your name ?\n")
    print("Hi "+player_name+" !\n"+"Welcome to ADOS-2 'Autism trainer' V1.0 !!!\n")
    time.sleep(3)
    print("It's time for you to start your training !\n")
    time.sleep(3)
    print("Oh wait "+player_name+" !")
    while True:
        try:
            player_age=int(input("How old are you ?\n"))
            break
        except ValueError:
            print("Tell me your age please !\n")  
            continue
    if player_age>30:
        print("Wow ! Aren't you too old to be a psychologist ?! Nah ! I'm just kidding you "+player_name+"!\n")
    else:
        print("Wow ! Aren't you too young to be a psychologist ?! Nah ! I'm just kidding you "+player_name+"!\n")
    time.sleep(3)
    print ("To tell you the truth...")
    time.sleep(3)
    print ("This app don't need your age ! ;)\n")
    time.sleep(3)
    print ("But as you told it to me, let's make it useful somehow !\nYou are "+str(player_age)+" years old.\n")
    time.sleep(3)
    print ("So... "+player_name+" Your training will begin in "+str(player_age)+" seconds !\n")
    for i in range(player_age):
        if i==player_age-1:
            print(str(player_age-i)+ " second remaining...\n")
        else:
            print(str(player_age-i)+ " seconds remaining...")
        time.sleep(1)
    build()
    

def rebuild():
    global new_builder,individu,individu2,individu3,dom1,dom2,dom3,player_name
    
    dom1=str(list_domaine[random.randrange(len(list_domaine))])
    dom2=str(list_domaine[random.randrange(len(list_domaine))])
    dom3=str(list_domaine[random.randrange(len(list_domaine))])
    individu=str(list_autism[random.randrange(len(list_autism))])
    individu2=str(list_autism[random.randrange(len(list_autism))])
    individu3=str(list_autism[random.randrange(len(list_autism))])
    if (dom1!=dom2 and dom1!=dom3 and dom2!=dom3):
        new_builder = "\nCome on "+player_name+" !\n"+"Create a person "+individu+" in "+dom1+" and "+individu2+" in "+dom2+" and "+individu3+" in "+dom3+"\n"
    else:
        rebuild()

def build():
    global new_builder,individu,individu2,individu3,dom1,dom2,dom3,player_name
    
    dom1=str(list_domaine[random.randrange(len(list_domaine))])
    dom2=str(list_domaine[random.randrange(len(list_domaine))])
    dom3=str(list_domaine[random.randrange(len(list_domaine))])
    individu=str(list_autism[random.randrange(len(list_autism))])
    individu2=str(list_autism[random.randrange(len(list_autism))])
    individu3=str(list_autism[random.randrange(len(list_autism))])

    if (dom1!=dom2 and dom1!=dom3 and dom2!=dom3):
        builder = "\nCome on"+player_name+" !\n"+"Create a person "+individu+" in "+dom1+" and "+individu2+" in "+dom2+" and "+individu3+" in "+dom3+"\n"
        print(builder)
    else:
        rebuild()
        print(new_builder)

    while True:
        try:
            reponse1 =int(input("Input a "+dom1+" score ?\n"))
            break
        except ValueError:
            print("Input a number please !\n")  
            continue
    while True:
        try:
            reponse2 =int(input("Input a "+dom2+" score ?\n"))
            break
        except ValueError:
            print("Input a number please !\n")  
            continue
    while True:
        try:
            reponse3 =int(input("Input a "+dom3+" score ?\n"))
            break
        except ValueError:
            print("Input a number please !\n")
            continue
        
    if ((((individu=="Neurotypical" and dom1=="Communication" and int(reponse1)<2)
        or (individu=="Neurotypical" and dom1=="Reciprocal social interaction" and int(reponse1)<4)
        or (individu=="Neurotypical" and dom1=="Communication and social" and int(reponse1)<7))
        and ((individu2=="Neurotypical" and dom2=="Communication" and int(reponse2)<2)
        or (individu2=="Neurotypical" and dom2=="Reciprocal social interaction" and int(reponse2)<4)
        or (individu2=="Neurotypical" and dom2=="Communication and social" and int(reponse2)<7))
        and ((individu3=="Neurotypical" and dom3=="Communication" and int(reponse3)<2)
        or (individu3=="Neurotypical" and dom3=="Reciprocal social interaction" and int(reponse3)<4)
        or (individu3=="Neurotypical" and dom3=="Communication and social" and int(reponse3)<7)))

        or (((individu=="Borderline" and dom1=="Communication" and 2<=int(reponse1)<3)
        or (individu=="Borderline" and dom1=="Reciprocal social interaction" and 4<=int(reponse1)<6)
        or (individu=="Borderline" and dom1=="Communication and social" and 4<=int(reponse1)<10))
        and ((individu2=="Borderline" and dom2=="Communication" and 2<=int(reponse2)<3)
        or (individu2=="Borderline" and dom2=="Reciprocal social interaction" and 4<=int(reponse2)<6)
        or (individu2=="Borderline" and dom2=="Communication and social" and 4<=int(reponse2)<10))
        and ((individu3=="Borderline" and dom3=="Reciprocal social interaction" and 4<=int(reponse3)<6)
        or (individu3=="Borderline" and dom3=="Communication" and 2<=int(reponse3)<3)
        or (individu3=="Borderline" and dom3=="Communication and social" and 4<=int(reponse3)<10)))

        or (((individu=="Autist" and dom1=="Communication" and int(reponse1)>=3)
        or (individu=="Autist" and dom1=="Reciprocal social interaction" and int(reponse1)>=6)
        or (individu=="Autist" and dom1=="Communication and social" and int(reponse1)>=10))
        and ((individu2=="Autist" and dom2=="Communication" and int(reponse2)>=3)
        or (individu2=="Autist" and dom2=="Reciprocal social interaction" and int(reponse2)>=6)
        or (individu2=="Autist" and dom2=="Communication and social" and int(reponse2)>=10))
        and ((individu3=="Autist" and dom3=="Communication" and int(reponse3)>=3)
        or (individu3=="Autist" and dom3=="Reciprocal social interaction" and int(reponse3)>=6)
        or (individu3=="Autist" and dom3=="Communication and social" and int(reponse3)>=10)))):

        print ("\nCongratulations "+player_name+" ! You created a person "+individu+" in "+dom1+" and "+individu2+" in "+dom2+" and "+individu3+" in "+dom3+"\n")
        time.sleep(3)
    else:
        print ("\nWhat happened "+player_name+"?! You failed your creation ! Go back to read documentation !\n")
        time.sleep(3)
        print ("I'm kind...I'll give you some hints.\n")
        time.sleep(3)
        while True:
            press=input("Type 'c' then hit 'enter' to continue...\n")
            if press=="c":
                print("\n\n#######DOCUMENTATION ON ADOS-2 SCORES#######\n\nScoring Results :\nScores relate to minimum required scores to meet the specified diagnostic cut-off in five domains.\nThe scores measure impairments, so the higher the number, the more severe the impairment, according to the test.\n\nCommunication:\nThe minimum score for autism is three, and the minimum score is two for the spectrum. If the child scores a seven, he or she would fall into 'autism' in the realm of communication.\n\nReciprocal social interaction:\nThe minimum score for autism is six, and the minimum for the spectrum is four. If the child scores a five, he or she falls into the spectrum (not necessarily classical autism) in this realm.\n\nCommunication and social:\nThe minimum score for autism is 10, and seven for the spectrum.\n\n")
                break
            else:
                print("You really need to learn more "+player_name+" ! Please press 'c' !\n")
                continue
        time.sleep(3)
    while True:
        replay=input("Replay ? (y/n)\n")
        if replay=="y":
            build()
            break
        elif replay=="n":
            sys.exit("Bye bye "+player_name+" ! Come back soon !\n")
            break
        else:
            print("Input 'y' or 'n' please !\n")
            continue

   
intro()

Thanks for help ! :)

How to do if and statement on a particular row, and if true to sent a message with row contents to my phone in Python?

So I am running live data and want to be notified if the column Line Variance is greater than five. That also needs to depend on other column values as well, such as the half being "1st half", Time Remaining being over 10, and the side being "Favorite". I'm having difficulty writing my if statement so that it searches for all these in the same row. I am using Twilio to notify me, and I am trying to include the event name, live line, line variance, team, and time remaining in the message of the row that is true. Does anyone know how I can do this?

if np.any(df['Line Variance'] <= 5) and np.any(df['Side'] == "Favorite"):
    # send message
        client.messages.create(to="+X", 
                       from_="+X", 
                       body= np.any(df['Line Variance']))
        print('message sent')
    

Data Picture

How to conduct an if/elif/else statement [closed]

I have a problem. I am not getting on so well with the If statements. Of course I can work with numbers and can write simple programs where you have to look whether a number is smaller, larger or the same. Today I wanted to write a program that resembles a conversation where there are questions and perfect answers. For example, the program asks if "you want to go out" and then you answer with "yes" to which the program answers with "Oh that's nice". But if you say "no", the program answers with " Oh what a shame ". You can suggest any route (I'm new).

How to make program working properly after using goto?

After any selection, I want to ask the user if they want to use the program again, or quit. But if y is inputted code doesn't work properly again. I tried the other solutions like clearing memory etc but I am not very experienced so I don't know what I am doing. Also sorry about my language. This is a part of my code. I have 13 different selections each of them work the same


    char str[100];
    int selection;
    char selection2;
    int i;
    begin:

    printf("Welcome to the Character/String Specification program\n");
    printf("Please enter whatever you want \n");
    scanf(" %s", str);

      printf("\nSelect the specification you want\n");
      printf("1) is your input a letter?\n");
      printf("2) is your input a whitespace?\n");
      printf("3) is your input a decimal digit?\n");
      printf("4) is your input a hexadecimal digit?\n");
      printf("5) is your input an upper-case letter?\n");
      printf("6) is your input a lower-case letter?\n");
      printf("7) is your input a letter or a decimal digit?\n");
      printf("8) is your input a control character?(ACSII 0..31 and 127)\n");
      printf("9) is your input a not a letter, digit, whitespace, or invisible control character?\n");
      printf("10)is your input a printable (ASCIII ' '..'~')\n");
      printf("11)is your input have a graphical representation\n");
      printf("12)Do you want to see your input as all upper characters?\n");
      printf("13)Do you want to see your input as all lower characters?\n\n");
      scanf(" %d",&selection);
      printf("\n");

      while(true)
      {
      if(selection == 1)
      {
       while(str[i])
          {
            if(isalpha(str[i]))
            {
                printf("%c is an alphabet\n",str[i]);
            }
            else
            {
                printf("%c is not an alphabet\n",str[i]);
            }
            i++;
          }
          printf("Do you want to go back to the start point? (y) for yes,(n) for no\n");
          scanf(" %c",&selection2);
          if(selection2=='y')
          {
              goto begin;
          }
          else if(selection2=='n')
          {
              printf("Goodbye\n");
              break;
          }

Python >= comparison operator throwing syntax error [duplicate]

It seems my if else statement throws a syntax error. I've read up on how if statements should be written (and the other if else statements in my script work with no issues) so I am not sure why there's an issue.

if small_wh <= 5.0:
    emColor = discord.Color.red
elif small_wh <= 15.0 and >= 5.1:
    emColor = discord.Color.orange

The >= (in the elif statement) is where it states the syntax error is.

For and If in R data programming

I want to evaluate the distance between non-zero data. So if i have 50 data, and only the first and last data is non-zero, thus i want the result to be 49.

For example, my data is:

1. 0
2. 0
3. 5
4. 6
5. 0
6. 1
7. 0

Based on my data above, i want to get 4 variables:

v0 = 3 (because the distance between 0th to 3rd data is 3 jumps)
v1 = 1 (because the distance between 3rd to 4th data is 1 jump)
v2 = 2 (because the distance between 4rd to 6th data is 2 jump)
v3 = 1 (because the distance between 6rd to 7th data is 1 jump)

This is my code:

data=c(0,0,5,6,0,1,0)

t=1
for (i in data) {
  if (i == 0) {
    t[i]=t+1
  }
  else {
    t[i]=1
  }
}

t

The result is:

[1]  1 NA NA NA  1  1

Could you help me in figuring out this problem? I also hope that the code is using some kind of loop, so that it can be applied to any other data.

is there a way to make the code return to the first line?

def input_nilai():

nilai = input(f"Masukan nilai huruf matkul {list_matkul[a]} (A-F): ").upper()

if nilai == "A":
    nilai = 4
    list_nilai.append(nilai)
elif nilai == "B":
    nilai = 3
    list_nilai.append(nilai)
elif nilai == "C":
    nilai = 2
    list_nilai.append(nilai)
elif nilai == "D":
    nilai = 1
    list_nilai.append(nilai)
elif nilai == "E" or "F":
    nilai = 0
    list_nilai.append(nilai)
else:
    input_nilai()

hey, so i'm a first semester student at one of the institutes in Indonesia, i want to make a code so everytime the user input letter besides A, B, C, D, E and F, the code will not proceed and return to the first question, but i tried this code and it doesn't work, can somebody help me solve this? thanks