miércoles, 31 de julio de 2024

finding dict key based on the value

st={'Ambiorix':90,'Katherine':89,'Armando':88,'Ruth':97}


names=list(st.keys())

scores=list(st.values())

print(names,scores)



def getmax(dct,p):

    names=list(dct.keys())

    scores=list(dct.values())

    post=scores.index(p)

    print(f' Found {names[post]} with score {p} in position {post}')

getmax(st,90)



['Ambiorix', 'Katherine', 'Armando', 'Ruth'] [90, 89, 88, 97]

 Found Ambiorix with score 90 in position 0



Chatgpt improve version


st = {'Ambiorix': 90, 'Katherine': 89, 'Armando': 88, 'Ruth': 97}


names = list(st.keys())

scores = list(st.values())


print(names, scores)


def getmax(dct, p):

    if p in dct.values():

        for name, score in dct.items():

            if score == p:

                post = scores.index(p)

                print(f'Found {name} with score {p} in position {post}')

                break

    else:

        print(f'Score {p} not found in the dictionary.')


getmax(st, 90)


domingo, 28 de julio de 2024

sábado, 27 de julio de 2024

Coverting datetime to string and getting date values

>>> type(str(datetime.datetime.now()).split())

<class 'list'>


>>> str(datetime.datetime.now()).split()

['2024-07-27', '21:41:04.779426']

>>> str(datetime.datetime.now()).split()[0]

'2024-07-27'


>>> str(datetime.datetime.now()).split()[0][0]

'2'

>>> str(datetime.datetime.now()).split()[0].split('-')

['2024', '07', '27']

>>> str(datetime.datetime.now()).split()[0].split('-')[2]

'27'

>>> str(datetime.datetime.now()).split()[0].split('-')[0]

'2024'

>>> str(datetime.datetime.now()).split()[0].split('-')[1]

'07'


python class

 import datetime


class Person:

    def __init__(self, id: str, name: str, birth_year: int):

        self.id = id

        self.name = name

        self.birth_year = birth_year


    def get_age(self) -> int:

        current_year = datetime.datetime.now().year

        return current_year - self.birth_year


    def person_type(self):

        age = self.get_age()

        if age >= 18:

            print("Adult")

        elif 11 < age < 18:

            print("Adolescent")

        else:

            print("Child")


# Example usage

ambiorix = Person("xy", "Ambiorix", 2010)

print("Age:", ambiorix.get_age())

ambiorix.person_type()


viernes, 26 de julio de 2024

Python class

  1. class Hombre:
  2. def __init__(self,nombre,apellido,edad):
  3. self.nombre=nombre
  4. self.apellido=apellido
  5. self.edad=edad
  6. self.placer='sexo'
  7. def __str__(self):
  8. return f"{self.nombre} {self.apellido} {self.edad}"
  9.  
  10. h1=Hombre("Jose","Ramos",35)
  11.  
  12. print(f"Mi nombre es {h1.nombre} {h1.apellido}, tengo {h1.edad} de edad")
  13.  
  14.  
  15. print(h1)
-------------

Mi nombre es Jose Ramos, tengo 35 de edad

Jose Ramos  35

Definir clases en Python permite crear objetos que encapsulan datos y funcionalidades relacionadas. Aquí te dejo un ejemplo completo y detallado sobre cómo definir y usar clases en Python.

Ejemplo Básico de una Clase en Python

Supongamos que queremos definir una clase que represente a una persona.

Definición de la Clase

python
class Persona: def __init__(self, nombre, edad): self.nombre = nombre self.edad = edad def saludar(self): return f"Hola, mi nombre es {self.nombre} y tengo {self.edad} años."

Explicación

  • __init__ Method: Este es el constructor de la clase. Es un método especial que se llama cuando se crea una nueva instancia de la clase. Inicializa los atributos nombre y edad.
  • Attributes: self.nombre y self.edad son atributos de instancia. Cada instancia de la clase Persona tendrá sus propios valores para estos atributos.
  • saludar Method: Este es un método regular que retorna un saludo utilizando los atributos de la instancia.

Crear Instancias de la Clase

python
persona1 = Persona("Juan", 30) persona2 = Persona("María", 25) print(persona1.saludar()) # Salida: Hola, mi nombre es Juan y tengo 30 años. print(persona2.saludar()) # Salida: Hola, mi nombre es María y tengo 25 años.

Métodos de Instancia y Atributos

Los métodos de instancia operan sobre una instancia específica de la clase y pueden acceder y modificar los atributos de la instancia.

Ejemplo de Métodos y Atributos

python
class Coche: def __init__(self, marca, modelo): self.marca = marca self.modelo = modelo self._velocidad = 0 # Atributo "protegido" (convención) def acelerar(self, incremento): self._velocidad += incremento return f"El coche ha acelerado a {self._velocidad} km/h." def frenar(self, decremento): self._velocidad -= decremento return f"El coche ha desacelerado a {self._velocidad} km/h." def obtener_velocidad(self): return self._velocidad # Crear una instancia de Coche mi_coche = Coche("Toyota", "Corolla") print(mi_coche.acelerar(50)) # Salida: El coche ha acelerado a 50 km/h. print(mi_coche.frenar(20)) # Salida: El coche ha desacelerado a 30 km/h. print(mi_coche.obtener_velocidad()) # Salida: 30

Atributos y Métodos de Clase

Los atributos y métodos de clase son compartidos por todas las instancias de la clase.

Ejemplo

python
class Animal: especie = "Mamífero" # Atributo de clase def __init__(self, nombre): self.nombre = nombre # Atributo de instancia @classmethod def obtener_especie(cls): return cls.especie # Crear instancias de Animal animal1 = Animal("León") animal2 = Animal("Tigre") print(animal1.obtener_especie()) # Salida: Mamífero print(animal2.obtener_especie()) # Salida: Mamífero print(animal1.nombre) # Salida: León print(animal2.nombre) # Salida: Tigre

Herencia

La herencia permite crear una nueva clase que es una extensión de una clase existente.

Ejemplo

python
class Empleado(Persona): # Empleado hereda de Persona def __init__(self, nombre, edad, salario): super().__init__(nombre, edad) # Llamar al constructor de la clase base self.salario = salario def mostrar_salario(self): return f"{self.nombre} tiene un salario de {self.salario} dólares." # Crear una instancia de Empleado empleado1 = Empleado("Carlos", 28, 50000) print(empleado1.saludar()) # Salida: Hola, mi nombre es Carlos y tengo 28 años. print(empleado1.mostrar_salario()) # Salida: Carlos tiene un salario de 50000 dólares.

Explicación

  • Herencia: La clase Empleado hereda de Persona, por lo que Empleado tiene todos los atributos y métodos de Persona.
  • super() Keyword: super() se utiliza para llamar al constructor de la clase base (Persona) desde la clase derivada (Empleado).

Conclusión

Las clases en Python son fundamentales para la programación orientada a objetos (POO). Permiten agrupar datos y comportamiento en entidades coherentes y reutilizables. A través de la definición de atributos y métodos, así como del uso de herencia, las clases pueden representar y manipular datos de manera estructurada y eficiente.

martes, 16 de julio de 2024

converting a nested list ain a singel list

>>> nested_list

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

 

>>> list=[]

>>> for  m in nested_list:

...    for t in m:

...       list.append(t)

... 

>>> list

[1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> 

>>> 


>>> 


lunes, 15 de julio de 2024

Python response module

Exceptions and Warnings

ConnectTimeout:


import requests from requests.exceptions import ConnectTimeout try: response = requests.get('https://httpbin.org/delay/10', timeout=1) except ConnectTimeout: print("The request timed out while trying to connect to the server.")

########################

ConnectionError:

from requests.exceptions import ConnectionError
try: response = requests.get('1http://thisurldoesnotexist.com') except ConnectionError: print("A network problem occurred.")

#################

DependencyWarning:



import warnings from requests import DependencyWarning warnings.warn("This is a DependencyWarning", DependencyWarning)

################

FileModeWarning:


import warnings from requests import FileModeWarning warnings.warn("This is a FileModeWarning", FileModeWarning)

#####################

HTTPError:



from requests.exceptions import HTTPError try: response = requests.get('https://httpbin.org/status/404') response.raise_for_status() except HTTPError as http_err: print(f"HTTP error occurred: {http_err}")

######################################

JSONDecodeError:

from requests.exceptions import JSONDecodeError
try: response = requests.get('https://httpbin.org/get') data = response.json() except JSONDecodeError: print("Failed to decode JSON response.")

#####

NullHandler:

import logging from requests import NullHandler logger = logging.getLogger('example_logger') logger.addHandler(NullHandler()) logger.info('This will not be output anywhere')


############

ReadTimeout:

from requests.exceptions import ReadTimeout try: response = requests.get('https://httpbin.org/delay/3', timeout=1) except ReadTimeout: print("The server did not send any data in the allotted amount of time.")



sábado, 13 de julio de 2024

viernes, 12 de julio de 2024

Running Linux command and saving as string

 You can run a Linux command in Python and save the output as a Python variable using the subprocess module. Here’s how you can do it:

  1. Import the subprocess module.
  2. Use the subprocess.run() function to execute the command.
  3. Capture the output by setting the stdout parameter to subprocess.PIPE.
  4. Decode the output from bytes to a string if needed.

Here’s an example:

python
import subprocess # Run the command and capture the output result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE, text=True) # Save the output as a Python variable output = result.stdout # Print the output print(output)

In this example, the ls -l command is executed, and its output is captured and stored in the output variable. The text=True parameter is used to ensure that the output is returned as a string instead of bytes.

Detailed Explanation:

  • subprocess.run(['ls', '-l'], stdout=subprocess.PIPE, text=True):
    • The command ls -l is passed as a list of arguments.
    • stdout=subprocess.PIPE captures the standard output of the command.
    • text=True ensures that the output is returned as a string.
  • result.stdout contains the output of the command.

Another Example:

Here’s another example where we run the uname -a command to get system information:

python
import subprocess # Run the command and capture the output result = subprocess.run(['uname', '-a'], stdout=subprocess.PIPE, text=True) # Save the output as a Python variable output = result.stdout # Print the output print(output)

In this example, the uname -a command is executed, and its output is stored in the output variable.

Error Handling:

You can also add error handling to capture any errors that might occur during the execution of the command:

python
import subprocess try: # Run the command and capture the output result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True) # Save the output as a Python variable output = result.stdout # Print the output print(output) except subprocess.CalledProcessError as e: print(f"Error: {e.stderr}")

In this example, any errors during the execution of the command will be caught, and the error message will be printed. The check=True parameter ensures that an exception is raised if the command exits with a non-zero status.

Couting occurance of a character

from math import pi

print(pi)

list=[]

dict={}

for a in str(pi):

    list.append(a)


b=set(sorted(list))

print(b)

for c in b:

    dict.update({c:list.count(c)})

print(dict)

Python String slicing

 >>> s="Ambiorix"



s[2]  #print  index  3 'b' remember index start from  0



s[2:]  #remove first 2 line  and print everyhing    'biorix'



 s[:2] #  print first 2 chars  'Am'


 s[:-2]  #'Ambior' remove last 2 chars



s[-2:]    # print the last 2  chargs  'ix'



 s[-2]     # print the char before the last value  'i'

Get index

>>> for a,b in enumerate(s):

...    print(a,b)

... 

0 A

1 m

2 b

3 i

4 o

5 r

6 i

7 x


cuando se utiliza la notación de slicing en una cadena (o lista), la sintaxis es:

python

s[start_index : before_end_index]

Donde:

  • start_index es el índice inicial desde donde se comenzará a extraer la subcadena (o sublista).
  • before_end_index es el índice hasta el cual se extraerá la subcadena (o sublista), pero sin incluir el carácter (o elemento) en esta posición.

Por ejemplo, para la cadena s = 'Ambiorix':


s[2:4]

Esto significa que se comenzará a extraer desde el índice 2 y se detendrá justo antes del índice 4. Por lo tanto, los caracteres en los índices 2 y 3 serán seleccionados.

Así, s[2:4] resulta en 'bi', que son los caracteres en los índices 2 y 3 de la cadena s.

Aquí hay un ejemplo generalizado:

ps = 'Ambiorix'
print(s[2:5]) # Esto resultará en 'bio' print(s[:3]) # Esto resultará en 'Amb', empezando desde el inicio hasta antes del índice 3 print(s[4:]) # Esto resultará en 'orix', desde el índice 4 hasta el final print(s[:]) # Esto resultará en 'Ambiorix', que es la cadena completa

Cada una de estas operaciones de slicing sigue la misma regla: s[start_index : before_end_index].