archivo – como hacer que funcione ciclo while empleando el método startswith en la condición en python?

Hola amigos he creado el siguiente codigo con el fin de que alguen pueda abrir un archivo de texto y hacer una consulta de una palabra y este le diga cuantas veces esta la palabra buscada en el texto. Así mismo que el usuario pueda finalizar el programa cuando escriba en la consulta “fin” o cualquier palabra que empiece por fin, desplegando dos opciones las cuales le digas que si presiona 1 se finalice el programa o cualquier otro numero para que consulte cuantas veces se encuentra la palabra fin en el programa.

archivo_nombre=str(input('introduzca el nombre del archivo, no olvide poner el .txt al final ejemplo "archivo.txt" : '))
with open(archivo_nombre,'r',encoding='utf8')as ar:#abrimos el archivo en modo read
    archivo= ar.read()
print(archivo) #imprimimos el archivo 
l_text = archivo.split()#aplicamos el metodo split para guardar el texto del archivo en una lista llamada l_text
print(l_text)# imprimimos la lista
n_palabras = len(l_text)#tenemos la cantidad de palabras de la lista
print(n_palabras)#imprime la cantidad de palabras en la lista
p_buscar = (input('que palabra quiere buscar: ')) #el usuario busca una palabras de la lista 
cantidad_palabra_buscada =l_text.count(p_buscar)#cantidad de veces que aparece la palabra buscada
print('la canridad de veces que aparece la palabra buscada es: ',cantidad_palabra_buscada) #imprimimos la cantidad de veces que aparece la palabra buscada 

while  cantidad_palabra_buscada == 0 : # mientras la cantidad de palabras buscadas sea igual a 0 va a ejecutar 
    p_buscar = (input('la palabra no existe busque de nuevo: ')) # aqui puide nuevamente al usuario que consulte la palabra
    cantidad_palabra_buscada =l_text.count(p_buscar) #da la cantidad de veces que aparece la palabra buscada en el texto
    print('la cantidad de veces que aparece la palabra buscada es: ',cantidad_palabra_buscada) #imprime la cantidad de veces que aparece la palabra en el texto
    while p_buscar.startswith == 'fin': # mientras la palabra buscada sea igual a fin o empiece por fin ejecute lo siguiente 
        opcion= int(input('ingrese 1 para finalizar o 2 para buscar la palabra fin')) #el usuario introduce una opcion 
        if opcion==1:# si es igual a 1 
            print('gracias por ejecutar el programa') #imprime este mensaje 
            exit#termina la ejecucion del programa 
        else:# si no 
            print('la cantidad de veces que aparece fin en el texto es: ',cantidad_palabra_buscada)# imprime la cantidad de veces que aparece fin en el texto 
            

mi problema está al ejecutar el ultimo while en donde pretendo generar el condicional para que finalice el programa.. anexo aqui abajo la parte del codigo que me esta dando el problema

while p_buscar.startswith == 'fin': # mientras la palabra buscada sea igual a fin o empiece por fin ejecute lo siguiente 
            opcion= int(input('ingrese 1 para finalizar o 2 para buscar la palabra fin')) #el usuario introduce una opcion 
            if opcion==1:# si es igual a 1 
                print('gracias por ejecutar el programa') #imprime este mensaje 
                exit#termina la ejecucion del programa 
            else:# si no 
                print('la cantidad de veces que aparece fin en el texto es: ',cantidad_palabra_buscada)# imprime la cantidad de veces que aparece fin en el texto 
                

No sé como hacer para que sirva este ciclo y en donde está mi error

python – First non-repeating Character

As has been pointed out in the comments and @Kraigolas’s answer, the existing algorithm doesn’t work. Here’s why.

In the string "xxy":

  1. The algorithm first considers the third character, "y". It finds it has not encountered it before, so records it as a preliminary out value. It adds it to smap with value 1.
  2. The algorithm next considers the second character, "x". It finds it has not encountered this character before, either. It discards its previous preliminary out value, "y", and adopts "x" as its new preliminary out value. It adds "x" to the dictionary with value 1.
  3. The algorithm now moves on to the first character, "x". It realises that it has seen this one before, so adds 1 to the associated value in smap.
  4. The algorithm has now finished iterating through the loop. Its current out value is "x", but when it looks it up in the dictionary, it finds it has encountered "x" more than once. As a result, it assumes that there are 0 characters that it has seen only once, and returns None.

It is impossible to fix the current implementation of the algorithm while keeping to the condition that there should be “only a single loop”. If you were to relax this restriction, you could fix your current algorithm like this:

def first_non_repeater(string):
    smap = {}

    for i in range((len(string) - 1), 1, -1):
        char = string(i)
        if char in smap:
            smap(char) += 1
        else:
            smap(char) = 1

    while True:
        try:
            key, val = smap.popitem()
        except KeyError: # raised when the dictionary is empty
            return None
        else:
            if val == 1:
                return key

But at I say, this breaks the condition that only one loop is allowed.

I like @FMc’s answer using collections.Counter a lot; I think this is probably the most pythonic way of doing this.
The following solution, however, would be my attempt at a solution that only uses builtin data structures (nothing from collections), and that only uses a single loop. The solution only works on python 3.6+, as it relies on dicts being ordered. Feedback welcome:

from typing import TypeVar, Union, Optional

T = TypeVar('T')

def first_non_repeating_char(
    string: str,
    default: Optional(T) = None
) -> Union(str, T, None):

    """
    Returns the first non-repeating character in a string.
    If no character in the string occurs exactly once,
    the function returns  the default value.
    """
        
    # Using a dictionary as an ordered set,
    # for all the characters we've seen exactly once.
    # The values in this dictionary are irrelevant.
    uniques: dict(str, None) = {}
        
    # a set for all the characters we've already seen more than once
    dupes: set(str) = set()   
    
    for char in string:
        if char in dupes:
            continue
        if char in uniques:
            del uniques(char)
            dupes.add(char)
        else:
            uniques(char) = None

    # return the first key in the dictionary
    # if the dictionary isn't empty
    try:
        return next(k for k in uniques.keys())
    # return the default value
    # if the dictionary is empty 
    except StopIteration:
        return default

python – Problema con formatos

Amigos les saludo desde México, esperando que alguien me pueda ayudar, tengo una función que va y revisa los precios de un simbolo, pero me los devuelve siempre en formato de notación científica, el problema es que cuando quiero regresar ese mismo valor, no acepta la notación científica, ya intenté con format y no valió, adjunto el código

def comprarsell(simbolo, presicion, lacantidad):
    cantidad=float(lacantidad)
    miorden=()
    while True:
        try:
            cantidad=format(cantidad,"f")
            miorden = cliente.order_market_sell(symbol=simbolo, quantity=cantidad)
            break
        except BinanceAPIException as error:
            print(error.code)
            if error.code==-2010:
                #vamos a reducir una a una la cantidad
                cantidad=float(cantidad)-(1/10**presicion)
                cantidad=round(cantidad,presicion)
            else:
                print(error.message,error.code)
                break
    return miorden

La idea es la siguiente, el lote debe llevar una cantidad exacta, así que si arroja el codigo -2010 (lote inexacto) reduce según la presición, fracción a fracción, pero haga lo haga (por ejemplo arriba puse format(cantidad,”f”) que se supone que forza a un float, me sigue devolviendo notación científica y la parte del servidor no reconoce ese formato, alguna sugerencia?

python – Simple interface for collecting issues after a list of validations

In this case, I would really keep it simple. I would drop the OOP and just write a simple function that validates the radar and returns a list of issues. To be clear:

def check_radar(radar: Radar) -> Set(str):
    return {
        *_check_1(radar),
        *_check_2(radar),
        ...
    }

def _check_1(radar: Radar) -> Set(str):
    # perform check and return set() or {"issue"}

The example above is just an idea for the implementation, you can then implement the internals as you wish, for instance by defining a list of checker functions and iterating and appending to the list as you’re doing in your sample code. The issues could be str or some more complicated object, depending on your needs.

This not only avoids having to write and maintain a class that in the end has just a single method kind of an unusual interface, but also writing a class that behaves like an Iterable(str) and which make the API harder to understand.

Another note: instead of ok, issue = checker() you could just return None when there’s no issue, which would simplify early returns from the checker functions.

I know it’s not really OOP, but there’s no need to use OOP everywhere if another pattern solves the problem more intuitively.

python – Scapy isn’t outputting any computers connected to network

I’m using Scapy to output all connected computers and VMs connected to network:

 from scapy.all import ARP, Ether, srp

 target_ip = '192.168.1.1/24'
 arp = ARP(pdst=target_ip)
 ether = Ether(dst='ff:ff:ff:ff:ff:ff')
 packet = ether/arp
 result = srp(packet, timeout=3)(0)
 clients = ()
  
 for s, r in result:
    clients.append({'ip': r.psrc, 'mac': r.hwsrc})
      
 for client in clients:
    print(f'{client("ip")} {client("mac")}')

There are 6 IPs on the network 1 of which is a virtual machine.
Running the script above gives me:

Begin emission:
.Finished sending 256 packets.
............
Received 13 packets, got 0 answers, remaining 256 packets

As this is a recon part of the whole pentest process it is concerning that
scapy isn’t giving me any devices.

Any suggestions ?

Edit:

(owasp) mark@work:~/owasp$ nmap -n -sV 192.168.1.1/24
Starting Nmap 7.80 ( https://nmap.org ) at 2021-07-26 18:59 BST
Nmap scan report for 192.168.1.2
Host is up (0.018s latency).
Not shown: 998 closed ports
PORT   STATE SERVICE VERSION
23/tcp open  telnet  DD-WRT telnetd (DD-WRT v24-sp2 micro (c) 2009 NewMedia-NET GmbH)
80/tcp open  http    DD-WRT milli_httpd
Service Info: OS: Linux; Device: WAP; CPE: cpe:/o:linux:linux_kernel

Nmap scan report for 192.168.1.64
Host is up (0.0075s latency).
Not shown: 998 closed ports
PORT   STATE SERVICE VERSION
22/tcp open  ssh     Dropbear sshd 2012.55 (protocol 2.0)
80/tcp open  http    TP-LINK embedded httpd
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

Nmap scan report for 192.168.1.218
Host is up (0.00014s latency).
All 1000 scanned ports on 192.168.1.218 are closed

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 256 IP addresses (3 hosts up) scanned in 10.61 seconds

python 3.x – Filtering string by given keywords

Im currently working on a filtering keywords. I have two lists which I called positive and negative.

Scenarios:

  1. if POSITIVE matches and NOT NEGATIVEmatches = True
  2. if POSITIVE matches and NEGATIVEmatches = False
  3. if NOT POSITIVE(Then no need to check NEGATIVE) = False.

I have done something like this:

import re
from typing import List

# In the future it will be a longer list of keywords
POSITIVE: List(str) = (
    "hello+world",
    "python",
    "no"
)

# In the future it will be a longer list of keywords
NEGATIVE: List(str) = (
    "java",
    "c#",
    "ruby+js"
)


def filter_keywords(string) -> bool:
    def check_all(sentence, words):
        return all(re.search(r'b{}b'.format(word), sentence) for word in words)

    if not any(check_all(string.lower(), word.split("+")) for word in POSITIVE) or 
            any(check_all(string.lower(), word.split("+")) for word in NEGATIVE):
        filtered = False
    else:
        filtered = True

    print(f"Your text: {string} is filtered as: {filtered}")
    return filtered


filter_keywords("Hello %#U&¤AU(1! World ¤!%!java")
filter_keywords("Hello %#U&¤AU(1! World ¤!%!")
filter_keywords("I love Python more than ruby and js")
filter_keywords("I love Python more than myself!")

Regarding the + in the list, that means that if hello and world is in the string then its a positive match

It does work of course, but I do believe I am doing too many “calculations” and I believe it could be shorted, I wonder if there is a possibility of it?

python – Como eu poderia melhorar esse código? Uma brincadeira que aprendi em um curso

python – Como eu poderia melhorar esse código? Uma brincadeira que aprendi em um curso – Stack Overflow em Português

how to get every inputs signature from a raw hex bitcoin transaction using python?

I have this raw transaction :
01000000000105330279cf447f9bb7fda6126fa9dccec60aa5d88fc337f5277937a876453915ff0000000017160014fa19560857496be932b9bd97743dd9f6903bb766ffffffffbcd372e8706a2d82a43cf76da29c93cd41c0034b4dc80ee588c07048e693d3f80100000017160014fa19560857496be932b9bd97743dd9f6903bb766ffffffff5564b82766e450bb9da37ebc024f1a65929202f0dec762ff232578e761af21170400000017160014fa19560857496be932b9bd97743dd9f6903bb766ffffffff98f7a465ab6e524a9974da0f98539480b5e0ff460754fbbec9cc312eba3ded740100000017160014fa19560857496be932b9bd97743dd9f6903bb766ffffffff14c0ed8059c6e0045144ba42d802ec8da0bf3bcb23b09993bfdba91c5dc417700100000017160014fa19560857496be932b9bd97743dd9f6903bb766ffffffff02ad141900000000001976a9142956ec12b882a6fbb96a49be0bf18a54385c975488ac7b6f00000000000017a9144fad3f234dc8acced507798cd64d1d8ed7357e99870247304402205bfc32d6b5c8e7f2059f60047d76ae8d600bf9e19fd964110430729b9b60d1e202204c7ce43c174e2fd7e2fba937b422f7dad7c1e62e62f1dc3a212cd3cafc744e0a0121022347931ca8ce8a645ccdc340684375fa94918d7c3643619e24bb461fd0f985730248304502210099dddb3e17f183630210e39aae43967ce3ab824117878bb372a2ef4c232c5e620220453cbb9484aeea881dca96898a511191412149f4f153c0f59197f69b9c4ea7a10121022347931ca8ce8a645ccdc340684375fa94918d7c3643619e24bb461fd0f985730247304402203cdabf0747658f43028e2c8c78c256498a759bcebefd0de81e30540a5c8f3bf502203910ec0623d9730b02359888533d49436a54131e0095b51e9ae854b67be0ec890121022347931ca8ce8a645ccdc340684375fa94918d7c3643619e24bb461fd0f985730247304402206c989bd6fdbc6502f8c05f973b601e01428b2c81eba068ac9a925984963452ff022029db750831ffa70cf50ec5b9170a80b3f8eca177aebb0d50d0633fd098cbb7760121022347931ca8ce8a645ccdc340684375fa94918d7c3643619e24bb461fd0f98573024730440220369527cfbdc32612dccc71787b1aada23de5915739ae246b27b6b017a12a52b30220063367dc3ae31af55aee79c51b9648aae781586b3d595ad8e6a9b7e645e5cd060121022347931ca8ce8a645ccdc340684375fa94918d7c3643619e24bb461fd0f9857300000000

It has 5 inputs, and I would like to get the signatures of all of them.
I can use bitcoinlib to get the info about this transaction, but the info doesnt give me the signatures.

I used ‘transaction_deserialize()’ from the transaction module to get the info.

I already have, server=1 and txindex=1, into the bitcoin.conf file

How can I decript any raw transaction to get the signature of all the inputs?

performance – Python case insensitive dictionary

This is a Python case insensitive dictionary that is ordered and has integer indexes for the keys and values.

I just wrote it today.

It is ordered because I am using Python 3.9.6 and plain dict is already ordered by default.

It prevents case insensitive duplicate keys from entering the dictionary (e.g. if ‘Adele’ is already in the dictionary, there can’t be another key named ‘adele’), and access the keys case insensitively, and updates existing key with same lowercase if found, preserves the cases of the keys when they are first inserted, and finally, it uses lists to index the keys and values.

The code:

class UDict(dict):
    @staticmethod
    def _key(k):
        return k.lower() if type(k) == str else k
    
    @classmethod
    def fromkeys(cls, keys, val=None):
        dic = cls()
        for i in keys:
            dic(i) = val
        return dic
    
    def __init__(self, *args, **kwargs):
        super(UDict, self).__init__(*args, **kwargs)
        self.KEYS = dict()
        self.Keys = list()
        self.Values = list()
        if self.keys():
            for k in list(self.keys()):
                v = super(UDict, self).pop(k)
                self.__setitem__(k, v)
    
    def _delete(self, key):
        k = UDict._key(key)
        self.KEYS.pop(k)
        i = self.Keys.index(k)
        self.Keys.pop(i)
        self.Values.pop(i)
    
    def _get_key(self, key):
        k = UDict._key(key)
        if k in self.KEYS:
            key = self.KEYS(k)
        return key
    
    def _process(self, key, val, modify=True):
        k = UDict._key(key)
        if k not in self.KEYS:
            self.KEYS.update({k: key})
            self.Keys.append(k)
            self.Values.append(val)
        else:
            key = self.KEYS(k)
            if modify:
                i = self.Keys.index(k)
                self.Values(i) = val
        return key
    
    def __contains__(self, key):
        key = self._get_key(key)
        return super(UDict, self).__contains__(key)
    
    def __delitem__(self, key):
        key = self._get_key(key)
        if key in self:
            self._delete(key)
            super(UDict, self).__delitem__(key)
    
    def __getitem__(self, key):
        key = self._get_key(key)
        if key in self:
            return super(UDict, self).__getitem__(key)
    
    def __setitem__(self, key, val):
        key = self._process(key, val)
        super(UDict, self).__setitem__(key, val)
    
    def at(self, i: int):
        if i not in range(len(self)):
            return None
        k = self.Keys(i)
        key = self.KEYS(k)
        val = self.Values(i)
        return (key, val)
    
    def clear(self):
        super(UDict, self).clear()
        self.KEYS.clear()
        self.Keys.clear()
        self.Values.clear()
    
    def copy(self):
        return UDict(self.items())
    
    def get(self, key, *args, **kwargs):
        key = self._get_key(key)
        if key in self:
            return super(UDict, self).get(key, *args, **kwargs)
        return None
    
    def index(self, key):
        k = UDict._key(key)
        if k not in self.KEYS:
            return None
        return self.Keys.index(k)
    
    def key_at(self, i: int):
        if i not in range(len(self)):
            return None
        k = self.Keys(i)
        return self.KEYS(k)
    
    def multiget(self, keys=None):
        if not keys:
            return None
        return (self.get(i) for i in keys)
    
    def multipop(self, keys):
        if not keys:
            return None
        for i in keys:
            self.pop(i)
    
    def pop(self, key, *args, **kwargs):
        key = self._get_key(key)
        if key in self:
            self._delete(key)
            return super(UDict, self).pop(key, *args, **kwargs)
        return None
    
    def setdefault(self, key, val=None):
        key = self._process(key, val, False)
        return super(UDict, self).setdefault(key, val)
    
    def update(self, obj=None):
        if not obj:
            return None
        
        if type(obj) == dict:
            obj = obj.items()
        
        for key, val in obj:
            key = self._process(key, val)
            super(UDict, self).update({key: val})
    
    def value_at(self, i: int):
        if i not in range(len(self)):
            return None
        return self.Values(i)

I have properly overridden all key related methods to make it behave exactly as I wanted it to, everything works as intended and I do need to get integer indexes.

Actually I implemented a function to get keys from values, by using the index of value in the Values list, but since values can be non-unique and Python lists only return indexes of first occurrences I removed it.

It is fully functional but performance wise it is considerably slower than plain dicts.

How can it be faster?

DreamProxies - Cheapest USA Elite Private Proxies 100 Private Proxies 200 Private Proxies 400 Private Proxies 1000 Private Proxies 2000 Private Proxies 5000 Private Proxies ExtraProxies.com - Buy Cheap Private Proxies Buy 50 Private Proxies Buy 100 Private Proxies Buy 200 Private Proxies Buy 500 Private Proxies Buy 1000 Private Proxies Buy 2000 Private Proxies ProxiesLive.com Proxies-free.com New Proxy Lists Every Day Proxies123.com Buy Cheap Private Proxies; Best Quality USA Private Proxies