top of page

10 advanced Python code challenges

Immagine del redattore: Mattia GattoMattia Gatto

Aggiornamento: 17 ott 2022



In questo articolo troverai 10 sfide avanzate con il codice Python, se questo è più adatto a te

Python è un linguaggio di programmazione per computer spesso utilizzato per creare siti Web e software, automatizzare attività e condurre analisi dei dati. Può essere utilizzato per creare una varietà di programmi diversi e non è specializzato per problemi specifici. Ecco una challenge Python con l'obiettivo di dimostrare abilità generiche come la progettazione di soluzioni e l'architettura, la risoluzione dei problemi e i fondamenti dell'informatica. Ma ogni sfida Python premia anche quei candidati che hanno familiarità con il linguaggio e il suo ecosistema di librerie standard. Le sfide di programmazione Python contengono specifiche dei requisiti di alto livello. E' possibile utilizzare il seguente compiler per eseguire del codice python:


In questo articolo troverai 10 sfide avanzate in Python:


1. Converti i radianti in gradi:


# scrivi una funzione in Python che accetti un parametro numerico. Questo parametro sarà la misura di un angolo in radianti. La funzione dovrebbe convertire i radianti in gradi e quindi restituire quel valore.

import math
def radians2degres(angle_in_radians):
    degrees =angle_in_radians*180/math.pi
    return degrees
angle_in_radians=12/7
print(angle_in_radians," radians = ",radians2degres(angle_in_radians),"°")

> OUTPUT:
 1.7142857142857142  radians = 98.22133630814112  °

2. Traduttore di codice Morse:


# scrivi un codice in Python per creare un traduttore di codice Morse. La stringa può anche contenere caratteri speciali come parte del codice Morse. Il codice Python dovrebbe restituire il codice Morse equivalente alla stringa.


'''
VARIABLE KEY
'cipher' -> 'memorizza la forma tradotta in morse della stringa inglese'
'decipher' -> 'memorizza la forma tradotta in inglese della stringa morse'
'citext' -> 'memorizza il codice morse di un singolo carattere'
'i' -> 'tiene il conteggio degli spazi tra i caratteri morse'
'message' -> 'memorizza la stringa da codificare o decodificare'
'''
 
# Dictionary representing the morse code chart
MORSE_CODE_DICT = { 'A':'.-', 'B':'-...',
                   'C':'-.-.', 'D':'-..', 'E':'.',
                   'F':'..-.', 'G':'--.', 'H':'....',
                   'I':'..', 'J':'.---', 'K':'-.-',
                   'L':'.-..', 'M':'--', 'N':'-.',
                   'O':'---', 'P':'.--.', 'Q':'--.-',
                   'R':'.-.', 'S':'...', 'T':'-',
                   'U':'..-', 'V':'...-', 'W':'.--',
                   'X':'-..-', 'Y':'-.--', 'Z':'--..',
                   '1':'.----', '2':'..---', '3':'...--',
                   '4':'....-', '5':'.....', '6':'-....',
                    '7':'--...', '8':'---..', '9':'----.',
                   '0':'-----', ', ':'--..--', '.':'.-.-.-',
                   '?':'..--..', '/':'-..-.', '-':'-....-',
                   '(':'-.--.', ')':'-.--.-'}
 
# Funzione per cifrare la stringa
def encrypt(message):
    cipher = ''
    for letter in message:
        if letter != ' ':
            # Cerca nel dizionario e aggiunge il file
            # codice Morse corrispondente
            # insieme ad uno spazio per separare
            # codici Morse diversi caratteri
            cipher += MORSE_CODE_DICT[letter] + ' '
        else:
            # 1 spazio indica i differenti caratteri
            # e 2 indicano differenti parole
            cipher += ' '
    return cipher
 
# Funzione per decifrare la stringa
def decrypt(message):
    message += ' '
    decipher = ''
    citext = ''
    for letter in message:
        # verifica spazio
        if (letter != ' '):
            # contatore per tenere traccia dello spazio
            i = 0
            # memorizza codice morse di un singolo carattere
            citext += letter
        # in caso di spazi
        else:
            # if i = 1 indica un nuovo carattere
            i += 1
            # if i = 2 indica una nuova parola
            if i == 2 :
                 # aggiunta di spazio per separare le parole
               decipher += ' '
            else:
                # accedere alle chiavi utilizzando i valori (inverso della crittografia)
               decipher += list(MORSE_CODE_DICT.keys())[list(MORSE_CODE_DICT
               .values()).index(citext)]
                citext = ''

    return decipher
 
def main():
    message = "GEEKS-FOR-GEEKS"
    result = encrypt(message.upper())
    print (message,"-->",result)
 
    message = "--. . . -.- ... -....- ..-. --- .-. -....- --. . . -.- ... "
    result = decrypt(message)
    print (message,"-->",result)

main()


OUTPUT:
> GEEKS-FOR-GEEKS --> --. . . -.- ... -....- ..-. --- .-. -....- --. . . -.- ... 
> --. . . -.- ... -....- ..-. --- .-. -....- --. . . -.- ...  --> GEEKS-FOR-GEEKS 


3. Controllo lettere duplicate:


# crea una funzione in Python che accetta un parametro: una stringa che è una frase. Questa funzione dovrebbe restituire True se una parola in quella frase contiene lettere duplicate e False in caso contrario.

def verify_duplicates(phrase):
    for word in phrase.split():
       previus_letter=word[0]
        for letters in range (1,len(word)):
            if (word[letters]==previus_letter):
                return True
           previus_letter=word[letters]
    return False

def main():
   phrase="Hello, today is a beautiful day"
   print("phrase: ",phrase,"\nDoes the sentence contain duplicates?\n",verify_duplicates(phrase))
    
    phrase="Today is a beautiful day"
   print("phrase: ",phrase,"\nDoes the sentence contain duplicates?\n",verify_duplicates(phrase))
main()


OUTPUT:
> I phrase:  Hello, today is a beautiful day 
>  Does the sentence contain duplicates?
>   True
>  phrase:  Today is a beautiful day 
>  Does the sentence contain duplicates?
>   False


4. Converti un numero decimale in binario:


# scrivi una funzione in Python che accetti un numero decimale e restituisca il numero binario equivalente. Il numero decimale sarà sempre inferiore a 1.024, quindi il numero binario restituito sarà sempre inferiore a dieci cifre.

def dec_bin(n):
    if n>=1024:
        n=1023
    b=" "
    while n>0:
        if n%2==0:
           b="0"+b
        else:
           b="1"+b
       n=int(n/2)  #casting in intero
    return b
    

def main():
   n=input("Inserisci un numero decimale:")
    n=int(n)
    print("The numer",n,"in binary is",dec_bin(n))
main()

OUTPUT:
> Inserisci un numero decimale:123
> The numer 123 in binary is 1111011

5. Converti un decimale in un esadecimale:


# scrivi una funzione in Python per convertire un decimale in un esadecimale. Deve accettare una stringa di caratteri ASCII come input. La funzione dovrebbe restituire il valore di ogni carattere come stringa esadecimale.

# Tabella di conversione dei resti in equivalente esadecimale
conversion_table = {0: '0', 1: '1', 2: '2', 3: '3', 4: '4',
                    5: '5', 6: '6', 7: '7',
                    8: '8', 9: '9', 10: 'A', 11: 'B', 12: 'C',
                   13: 'D', 14: 'E', 15: 'F'}
 
 
# funzione che converte il valore decimale in valore esadecimale
def decimalToHexadecimal(decimal):
    hexadecimal = ''
    while(decimal > 0):
        remainder = decimal % 16
        hexadecimal = conversion_table[remainder] + hexadecimal
        decimal = decimal // 16
    return hexadecimal
 

def main():
   n=input("Inserisci un numero decimale:")
    n=int(n)
    print("The numer",n,"in esadecimal is",decimalToHexadecimal(n))
main()

OUTPUT:
> Inserisci un numero decimale:123
> The numer 123 in esadecimal is 7B

6. L'indirizzo IP:


#scrivere una funzione per trovare il nome di dominio dall'indirizzo IP . La funzione accetterà un indirizzo IP e restituirà il nome di dominio associato a tale indirizzo IP .

import socket
def gethostName(ind_IP):
    host = socket.gethostbyaddr(ind_IP)
    return host[0]
 

def main():
   ind_IP=socket.gethostbyname(socket.gethostname())
    print("The host Name for this IP addres",ind_IP,"is",gethostName(ind_IP))
main()


OUTPUT:
> The host Name for this IP addres XXX.XXX.XXX.XXX is *********

7. Crea una funzione calcolatrice:


# scrivi una funzione Python che accetti tre parametri. Il primo parametro è un numero intero. Il 2° operatore matematico. Anche il 3° deve essere un numero intero. La funzione dovrebbe eseguire un calcolo e restituire i risultati.


def calculator():
    hello_message = """
    Welcome to the calculator program!

     Below is a list of the various functions available:

     - To perform an Addition, +;
     - To perform a Subtraction, -;
     - To perform a Multiplication, *;
     - To carry out a Division, /;
     - To perform an Exponential Calculation, ^;
     - To exit the program you can type ESC;
    """
    while True:
       print(hello_message)

        a =input ("Enter the first number:")
        action = input ("Enter the operation:")
        b = input ("Enter the second number:")
        
        if action == "+":
            print ("\nYou chose: Addition \n")
            print ("The result of the Addition is:", str (int(a) + int(b)))
        elif action == "-":
            print ("\nYou chose: Subtraction \n")
            print ("The result of the Subtraction is:", str (int(a) - int(b)))
        elif action == "*":
            print ("\nYou chose: Multiplication \n")
            print ("The result of Multiplication is:", str (int(a) * int(b)))
        elif action == "/":
            print ("\nYou chose: Division \n")
            print ("The result of the Division is:", str (int(a) / int(b)))
        elif action == "^":
           print("\nYou have chosen: Exponential Calculation\n")
           print("The result of the Exponential Calculation is: ", str(int(a) ** int(b)))
        elif action == "ESC" or a=="ESC" or b=="ESC":
           print("\nThe Application will be closed!\n")
            break
        
   print("Soon!\n")

def main():
    calculator()
main()


OUTPUT:
>   Welcome to the calculator program!
     Below is a list of the various functions available:

     - To perform an Addition, +;
     - To perform a Subtraction, -;
     - To perform a Multiplication, *;
     - To carry out a Division, /;
     - To perform an Exponential Calculation, ^;
     - To exit the program you can type ESC;
    
    Enter the first number:23
    Enter the operation:^
    Enter the second number:2
    You have chosen: Exponential Calculation
    
    The result of the Exponential Calculation is:  529

8. Nascondi il numero di carta di credito:


# scrivi una funzione in Python che accetti un numero di carta di credito. Dovrebbe restituire una stringa in cui tutti i caratteri sono nascosti con un asterisco tranne gli ultimi quattro.

def Card(cod):
    cod=cod.split('-')
    cart_tmp=[]
    for cc in cod:
        for c in cc:
           cart_tmp.append(c)
    if (len(cart_tmp)==16):
        return cart_tmp
    else:
        print ("Wrong card number length!")
        cart_tmp=[]
    return cart_tmp

def Count(cc):
    card1=cc
    if( cc is None):
       card1=input("Copy your card number (including separator dashes '-') ")
    card=Card(card1)
    sum = 0
    for i,v in enumerate(card):
        if i%2 == 0:
            v = str(int(v)*2)
            if len(v) == 2:
               v = int(v[0])+int(v[1])
            sum += int(v)
        else: sum += int(v)
    card1="xxxx-xxxx-xxxx-"+str(card1[15:len(card1)])
    return sum,card1

def cc_format(cc):
    return cc[:4]+"-"+cc[4:8]+"-"+cc[8:12]+"-"+cc[12:]

def Main():
    cc="5245958391974279" #esempio generata online da https://cardgenerator.io/mastercard-credit-card-generator/
    total,card=Count(cc_format(cc))
    if (total%10 == 0):
        print ("Valid Card!")
        print(card)
    else:
        print ("Not Valid card!")
Main()

OUTPUT:
> Valid Card!
xxxx-xxxx-xxxx-4279


9. Tic Tac Toe blocker:


# in questa sfida Python, scrivi una funzione che accetti due numeri. Questi numeri rappresenteranno una posizione su una tavola da tris. La funzione dovrebbe restituire il numero del punto che può impedire a questi due punti di vincere la partita.import random

V="-"
X="x"
O="o"

parity=0
TurnX=1
TurnO=2
WinX=3
WinO=4

a1=V
a2=V
a3=V
b1=V
b2=V
b3=V
c1=V
c2=V
c3=V


def full():
    return a1!=V and a2!=V and a3!=V and b1!=V and b2!=V and b3!=V and c1!=V and c2!=V and c3!=V

def tris(g):
    return (a1==a2==a3==g) or (b1==b2==b3==g) or (c1==c2==c3==g) or (a1==b1==c1==g) or (a2==b2==c2==g) or (a3==b3==c3==g) or (a1==b2==c3==g) or (a3==b2==c1==g)

def print_chessboard():
   print("\tCHESSBOARD")
    s=" \t\t1\t2\t3\t \n"+"a\t[\t"+a1+"\t"+a2+"\t"+a3+"\t]"+"\n"+"b\t[\t"+b1+"\t"+b2+"\t"+b3+"\t]"+"\n"+"c\t[\t"+c1+"\t"+c2+"\t"+c3+"\t]\n"
    print (s)

def move(g,turn):
    global a1,a2,a3,b1,b2,b3,c1,c2,c3
    while True:
       m=input("enter coordinates (such as a1, b1, ..): ")
        if m=="a1" and a1==V:
            a1=g
            break
        elif m=="a2" and a2==V:
            a2=g
            break
        elif m=="a3" and a3==V:
            a3=g
            break
        elif m=="b1" and b1==V:
            b1=g
            break
        elif m=="b2" and b2==V:
            b2=g
            break
        elif m=="b3" and b3==V:
            b3=g
            break
        elif m=="c1" and c1==V:
            c1=g
            break
        elif m=="c2" and c2==V:
            c2=g
            break
        elif m=="c3" and c3==V:
            c3=g
            break

def play(g,turn,CPU):
    global a1,a2,a3,b1,b2,b3,c1,c2,c3
    
    print_chessboard()
    end=False
    while (turn==TurnX or turn==TurnO) and end==False:
        if turn==TurnX:
            print ("turn X")
            if CPU:
               Tic_Tac_Toe_blocker(X)
            else:
               move(X,turn)
            if tris(X):
               turn=WinX
                print ("X wins")
               end=True
            elif full():
               turn=parity
                print ("parity")
               end=True
            turn=TurnO
        elif turn==TurnO:
            print ("turn O")
           move(O,turn)
            if tris(O):
               turn=WinO
                print ("O wins")
                end=True
            elif full():
               turn=parity
                print ("parity")
               end=True
            turn=TurnX
       print_chessboard()
    print("END GAME!")
    return True
            
def check_win(player,g):
    global a1,a2,a3,b1,b2,b3,c1,c2,c3
    #horizontal
    if a1==player and a2==player and a3==V:
            a3=g
    elif a1==player and a2==V and a3==player:
            a2=g
    elif a1==V and a2==player and a3==player:
            a1=g
    
    elif b1==player and b2==player and b3==V:
            b3=g
    elif b1==player and b2==V and b3==player:
            b2=g
    elif b1==V and b2==player and b3==player:
            b1=g
            
    elif c1==player and c2==player and c3==V:
            c3=g
    elif c1==player and c2==V and c3==player:
            c2=g
    elif c1==V and c2==player and c3==player:
            c1=g
    
    #vertical
    elif a1==player and b1==player and c1==V:
            c1=g
    elif a1==player and b1==V and c1==player:
            b1=g
    elif a1==V and b1==player and c1==player:
            a1=g
    
    elif a2==player and b2==player and c2==V:
            c2=g
    elif a2==player and b2==V and c2==player:
            b2=g
    elif a2==V and b2==player and c2==player:
            a2=g
            
    elif a3==player and b3==player and c3==V:
            c3=g
    elif a3==player and b3==V and c3==player:
            b3=g
    elif a3==V and b3==player and c3==player:
            a3=g
    
    #oblique
    elif a1==player and b2==player and c3==V:
            c3=g
    elif a1==player and b2==V and c3==player:
            b2=g
    elif a1==V and b2==player and c3==player:
            a1=g
    
    elif a3==player and b2==player and c1==V:
            c1=g
    elif a3==player and b2==V and c1==player:
            b2=g
    elif a3==V and b2==player and c1==player:
            a3=g
    else: return True
    
#player=X or O
def Tic_Tac_Toe_blocker(player):
    global a1,a2,a3,b1,b2,b3,c1,c2,c3
   opponent=""
    if player==X: opponent=O
    else: opponent=X
    
    #win
   continue_=check_win(player,player)
    
    #defence
    if continue_==True:
       continue_=check_win(opponent,player)
    
    if continue_==True:
        #strategy
        if (a1==player and b2==V and c1==player) or (a1==player and b2==V and c1==player) or (c1==player and b2==V and c3==player):
                b2=player
        elif a1==player and a3==V and c3==player:
               a3=player
        elif a1==player and c1==V and c3==player:
               c1=player
        elif (a2==player and b2==V and b3==player) or (a2==player and b1==player and b2==V) or (b1==player and b2==V and c2==player) or (b2==V and b3==player and c2==player):
               b2=player
        elif (a2==player and b2==player and b3==V) or ( b2==player and b3==V and c2==player):
               b3=player
        elif (a2==V and b2==player and b3==player) or (a2==V and b1==player and b2==player):
               a2=player
        elif (a2==player and b1==V and b2==player) or (b1==V and b2==player and c2==player):
               b1=player
        elif (b1==player and b2==player and c2==V) or (b2==player and b3==player and c2==V):
               c2=player
        #casuale
        else:
            ok=False
            while ok==False:
                x= random.randint(0,3)
                y= random.randint(0,3)
                if x==0 and y==0 and a1==V:
                   a1=player
                   ok=True
                elif x==0 and y==1 and a2==V:
                   a2=player
                    ok=True
                elif x==0 and y==2 and a3==V:
                   a3=player
                   ok=True
                elif x==1 and y==0 and b1==V:
                   b1=player
                   ok=True
                elif x==1 and y==1 and b2==V:
                   b2=player
                   ok=True
                elif x==1 and y==2 and b3==V:
                   b3=player
                   ok=True
                elif x==2 and y==0 and c1==V:
                    c1=player
                   ok=True
                elif x==2 and y==1 and c2==V:
                   c2=player
                   ok=True
                elif x==2 and y==2 and c3==V:
                   c3=player
                    ok=True
                

def Main():
    av=input("You want to play against the CPU?")
    CPU=False
    if av.lower()=="y" or av.lower()=="yes":
       print("You are the player O!")
        CPU=True
    turn=TurnO
    play(O,turn,CPU)
   
Main()


10. Lo sconto:


# crea una funzione in Python che accetta due parametri. Il primo dovrebbe essere il prezzo intero di un articolo come numero intero. Il secondo dovrebbe essere la percentuale di sconto come numero intero. La funzione dovrebbe restituire il prezzo dell'articolo dopo l'applicazione dello sconto.


def Discount(full_price,discount_percentage):
   price_to_be_discounted=full_price*discount_percentage/100
    return full_price-price_to_be_discounted

def Main():
    price_valid=False
    while price_valid==False:
       full_price=int(input("Calculate the product discount\nEnter the price of the product to be discounted!\n"))
       if(full_price>0):
           price_valid=True
        
   discount_percentage_valid=False
    while discount_percentage_valid==False:
       discount_percentage=int(input("Enter the discount percentage to apply!\n"))
       if(discount_percentage<=100 and discount_percentage>0):
           discount_percentage_valid=True
    print("The product of price", full_price, "discounted by", discount_percentage,"% will cost",Discount(full_price,discount_percentage),"€")
    
Main()


OUTPUT:
> Calculate the product discount
> Enter the price of the product to be discounted!
> 2323
> Enter the discount percentage to apply!
> 22
> The product of price 2323 discounted by 22 % will cost 1811.94 €


60 visualizzazioni0 commenti

Post recenti

Mostra tutti

Commenti


bottom of page