python – Python substring anagram index

I am working to improve my Python skills and I have been doing a daily code problem. For the problem:

Given a word W and a string S, find all the initial indexes in S that are anagrams of W

Is there a more efficient / python solution than the code I wrote? Storing the queue as a list and converting it twice per cycle seems to be inefficient.

def anagram_indices(w, s):

  w = set(list(w))

  queue = ()
  index = ()

  for x, i in enumerate(list(s)):
    queue.append(i)

    while(w.issubset(set(queue(1:)))):
      queue.pop(0)

    if w == set(queue):
      index.append(x-1)

  return(index)

word = "ab"
string = "abxaba"

print(anagram_indices(word, string))

python 3.7 – Agenda: People Data

I am trying to schedule an agenda where I can save different information, name, surname, billing town etc …

I have been going around it but I always end up at the same point, I enter the data of the people one by one and save them in a file. I open the file and see that the data is well saved. Then to be able to modify that data, what I do is open the file and save it in a list (in this way all the modifications I will make will make them on the list and then update the file).

The problem I have is that the list is always loaded with the data of the last person in the file. I have tried the steps one by one and I am reading all the data of the people but the last one always crushes me all the previous ones.

Thank you

import io
import tkinter

#Importamos la clse Bezeroak de modulo creado por nosotros
#from Klase_Bezeroak import bezeroak


class interface:
def __init__(self,lista_clientes):
    self.lista_clientes=lista_clientes    

    #Programa para generar una ventana donde puedo introducir nombres y 
    datos
    #Crea una ventada de la clase TK
    self.ventana= tkinter.Tk()
    #Titulo de la Ventada
    self.ventana.title('Egurra')
    #Posicion y Tamaño
    self.ventana.geometry('400x400+600+100')
    #introducimos un widget
    tkinter.Label(self.ventana, text='').pack()


    #Generamos un menu y la asociamos a la wich ventana
    self.menu = tkinter.Menu(self.ventana)

    #Generamos la pestaña de clientes y la primera opcion en la cascada
    self.pest_clientes = tkinter.Menu(self.menu)
    self.pest_clientes.add_command(label = 'Nuevo Cliente')

    #Generamos la segunda opcion dentro del Clientes
    self.pest_clientes.add_separator()
    self.pest_clientes.add_command(label = 'Ver Lista Clientes')

    #Generamos la tercera opcion dentro del Clientes
    self.pest_clientes.add_separator()
    self.pest_clientes.add_command(label = 'Buscar Cliente')

    #Generamos la cuarta opcion dentro del Clientes
    self.pest_clientes.add_separator()
    self.pest_clientes.add_command(label = 'Borrar Cliente')

    #Generamos la pestaña de consultas y la primera opcion en la cascada
    self.pest_consultas = tkinter.Menu(self.menu)
    self.pest_consultas.add_command(label = 'Facturacion')

    #Generamos la segunda opcion dentro del Consultas
    self.pest_consultas.add_separator()
    self.pest_consultas.add_command(label = 'Gastos')

    #Generamos la tercera opcion dentro del Consultas
    self.pest_consultas.add_separator()
    self.pest_consultas.add_command(label = 'Ordenar clientes por Gasto')

    #Generamos la cuarta opcion dentro del Consultas
    self.pest_consultas.add_separator()
    self.pest_consultas.add_command(label = 'Consumo de leña por medida')

    #Generamos la quinta opcion dentro del Consultas
    self.pest_consultas.add_separator()
    self.pest_consultas.add_command(label = 'Estado Almacen')


    self.menu.add_cascade(label = 'Clientes', menu = self.pest_clientes)
    self.menu.add_cascade(label = 'Consultas', menu = self.pest_consultas)

    self.ventana.config(menu = self.menu)



    izena_Var = tkinter.StringVar()
    abizena_Var = tkinter.StringVar()
    herria_Var = tkinter.StringVar()
    tlf_Var = tkinter.IntVar()
    neurria_Var = tkinter.IntVar()
    bidaiak_Var = tkinter.IntVar()
    prezioa_Var = tkinter.IntVar()
    fakturazioa_Var = tkinter.DoubleVar()
    self.num_lista_Var = tkinter.IntVar() 

    #Generamos la entrada de Izena
    tkinter.Label(self.ventana, text='Izena').place(x=10,y=10)
    tkinter.Entry(self.ventana, textvariable=izena_Var, width=10).place(x=70,y=10)

    #Generamos la entrada de Abizena
    tkinter.Label(self.ventana, text='Abizena'). place(x=140,y=10)
    tkinter.Entry(self.ventana, textvariable=abizena_Var, width=10).place(x=200,y=10)

    #Generamos la entrada de Herria
    tkinter.Label(self.ventana, text='Herria').place(x=10,y=40)
    tkinter.Entry(self.ventana, textvariable=herria_Var, width=10).place(x=70,y=40)

    #Generamos la entrada de Telefonoa
    tkinter.Label(self.ventana, text='Telefonoa').place(x=140,y=40)
    tkinter.Entry(self.ventana, textvariable=tlf_Var, width=10).place(x=200,y=40)

    #Generamos la entrada de Neurria
    tkinter.Label(self.ventana, text='Neurria').place(x=10,y=70)
    tkinter.Entry(self.ventana, textvariable=neurria_Var, width=10).place(x=70,y=70)

    #Generamos la entrada de bidaiak
    tkinter.Label(self.ventana, text='Bidaiak').place(x=140,y=70)
    tkinter.Entry(self.ventana, textvariable=bidaiak_Var, width=10).place(x=200,y=70)

    #Generamos la entrada de prezioa
    tkinter.Label(self.ventana, text='Prezioa').place(x=10,y=100)
    tkinter.Entry(self.ventana, textvariable=prezioa_Var, width=10).place(x=70,y=100)

    #Generamos la entrada de Fakturazioa
    tkinter.Label(self.ventana, text='Fakturazioa').place(x=140,y=100)
    tkinter.Entry(self.ventana, textvariable=fakturazioa_Var, width=10).place(x=200,y=100)

    #Imprimir un cliente
    tkinter.Label(self.ventana, text='Numero en la lista').place(x=80,y=300)
    tkinter.Entry(self.ventana, textvariable=self.num_lista_Var, width=10).place(x=200,y=300)
    tkinter.Button(self.ventana, text="Sakatu", command =self.escribir).place(x=250,y=300)




    #Creamos un tipo de dato bezeroak en la variable bezeroa
    self.bezeroa = bezeroak()
    self.bezeroa.izena = izena_Var
    self.bezeroa.abizena = abizena_Var
    self.bezeroa.herria = herria_Var
    self.bezeroa.tlf = tlf_Var
    self.bezeroa.neurria = neurria_Var
    self.bezeroa.bidaiak = bidaiak_Var
    self.bezeroa.prezioa = prezioa_Var
    self.bezeroa.fakturazioa = fakturazioa_Var

    tkinter.Button(self.ventana, text="Bezero Berria", command =self.crear_cliente).place(x=10,y=150)
    tkinter.Button(self.ventana, text="Datuak_Kargatu", command =self.cargar_datos).place(x=200,y=150)

    tkinter.Button(self.ventana, text="Gorde", command =self.Guardar).place(x=10,y=200)
    tkinter.Button(self.ventana, text="Irten", command=quit).place(x=200,y=200)

    self.ventana.mainloop()

####### Funcion  Escribir          #########################################################       
def escribir(self):
    print('Izena:',self.lista_clientes(0).izena)
    print('Abizena:',self.lista_clientes(0).abizena)
    print('Herria:',self.lista_clientes(0).herria)
    print('Telefonoa:',self.lista_clientes(0).tlf)
    print('Neurria',self.lista_clientes(0).neurria,'cm')
    print('Bidai Kopurua',self.lista_clientes(0).bidaiak)
    print('prezioa',self.lista_clientes(0).prezioa)
    print('Fakturazioa',self.lista_clientes(0).fakturazioa)

######## End Funcion Escribir     #########################################################


####### Funciona Guardar          ######################################################### 
def Guardar(self):
    if (self.pos_bezeroa == 0):        
            lineas = ""
    else:
            lineas = "n"                

    Datos_Bezeroa =lineas+self.lista_clientes(self.pos_bezeroa).izena.get()+";"
    Datos_Bezeroa += self.lista_clientes(self.pos_bezeroa).abizena.get()+";"
    Datos_Bezeroa += self.lista_clientes(self.pos_bezeroa).herria.get()+";"
    Datos_Bezeroa += str(self.lista_clientes(self.pos_bezeroa).tlf.get())+";"
    Datos_Bezeroa += str(self.lista_clientes(self.pos_bezeroa).neurria.get())+";"
    Datos_Bezeroa += str(self.lista_clientes(self.pos_bezeroa).bidaiak.get())+";"
    Datos_Bezeroa += str(self.lista_clientes(self.pos_bezeroa).prezioa.get())+";"
    Datos_Bezeroa += str(self.lista_clientes(self.pos_bezeroa).fakturazioa.get())+";" #Añadimos el "end" como final de datos del cliente

    archivo=io.open('Log_Datos.ods','a')
    archivo.write(Datos_Bezeroa)
    archivo.close()
######## End funcion Guardar       #########################################################

####### Funciona Crear Cliente     #########################################################
def crear_cliente(self):
    self.lista_clientes.append(self.bezeroa)
    print (len(self.lista_clientes))
    self.pos_bezeroa=len(self.lista_clientes)-1
    print (self.pos_bezeroa)
    self.Guardar()
######## End funcion Crear Cliente #########################################################

######## Funciona Cargar Datos     #########################################################
def cargar_datos(self):
    ######## Abrir tranferir a Datos_clientes y cerrar archivo#######################################
    #        Lo leemos con redlines y nos devuelve una lista                                #
    archivo=io.open('Log_Datos.ods','r')
    datos_clientes=archivo.readlines()
    archivo.close()

    print (datos_clientes)
    i=0

     ######## Bucle While #############################################################################

    while i < len(datos_clientes):
            var_clientes             = datos_clientes(i).split(";")
            self.lista_clientes.append(self.bezeroa)       
            self.lista_clientes(i).izena       = var_clientes(0)
            self.lista_clientes(i).abizena     = var_clientes(1)
            self.lista_clientes(i).herria      = var_clientes(2)
            self.lista_clientes(i).tlf         = var_clientes(3)
            self.lista_clientes(i).neurria     = var_clientes(4)
            self.lista_clientes(i).bidaiak     = var_clientes(5)
            self.lista_clientes(i).prezioa     = var_clientes(6)
            self.lista_clientes(i).fakturazioa = var_clientes(7)             
            print (self.lista_clientes(i).izena)
            print (self.lista_clientes(i).abizena)
            print (self.lista_clientes(i).herria)
            print (self.lista_clientes(i).tlf)
            print (self.lista_clientes(i).neurria)
            print (self.lista_clientes(i).bidaiak)
            print (self.lista_clientes(i).prezioa)
            print (self.lista_clientes(i).fakturazioa)

            if i>=1 :                        
                    print (self.lista_clientes(i-1).izena)
                    print (self.lista_clientes(i-1).abizena)
                    print (self.lista_clientes(i-1).herria)
                    print (self.lista_clientes(i-1).tlf)
                    print (self.lista_clientes(i-1).neurria)
                    print (self.lista_clientes(i-1).bidaiak)
                    print (self.lista_clientes(i-1).prezioa)
                    print (self.lista_clientes(i-1).fakturazioa)

            i=i+1

    ######## Fin Bucle While
    ######## #############################################################################

    print (self.lista_clientes(1).izena)
    print(self.lista_clientes(1).abizena)
    print(self.lista_clientes(1).herria)
    print(self.lista_clientes(1).tlf)
    print(self.lista_clientes(1).neurria)
    print(self.lista_clientes(1).bidaiak)
    print(self.lista_clientes(1).prezioa)
    print(self.lista_clientes(1).fakturazioa)
    print('longitud listabezeroak', len(self.lista_clientes))

    ######## End funcion cargar datos #########################################################

def main():
    lista_clientes=()
    mi_app = interface(lista_clientes)
    return 0

if __name__ == 'main':
 main()

python: print the first 20 narcissistic numbers

My project is to generate the first 20 Armstrong numbers. I have been able to generate the numbers, but the number 370 is repeated twice.

My code is:

def print_narcissistic_nums(start, end):
for i in range(start, end + 1):
    digits = list(map(int, str(i)))
    total = 0
    length = len(digits)
    for d in digits:
        total += d ** length
        if total == i:
            print(i)

print_narcissistic_nums (0, 11000)

How to use the For loop in Python?

I want a for loop that can print the srting value if any item in the list is of string data type, how can it be possible?

I am running under the code:

mylist = (1,2,3,4,5,6,7,8,9,10,'anku','vipan')
    for hello in mylist:
        if hello % 2 ==0:
            print(f"Even number:{hello}")
        elif hello == str:
            print(f"This is string:{hello}")
        else:
            print(f"Odd Number is:{hello}")

Result that contains error

Odd Number is:1
Even number:2
Odd Number is:3
Even number:4
Odd Number is:5
Even number:6
Odd Number is:7
Even number:8
Odd Number is:9
Even number:10
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
 in 
      1 for hello in mylist:
----> 2     if hello % 2 ==0:
      3         print(f"Even number:{hello}")
      4     elif hello == str:
      5         print(f"This is string:{hello}")

TypeError: not all arguments converted during string formatting

Image – Cartesian Python Plans

Good evening, good afternoon and good morning. I am 15 years old and I am studying quadratic equations, Cartesian plane and functions. Because of that, I made a code to calculate the roots, the vertex coordinates, the graph and the image. The only parts I can't do are the graphic and the image that I have no idea how to do, if someone can help me, I'm very grateful. Thank you very much in advance.

follow the following code:

import math

print('-' * 30, ' Coeficientes ', '-' * 30)
valorA = int(input('Insira o coeficiente de A: '))
valorB = int(input('Insira o coeficiente de B: '))
valorC = int(input('Insira o coeficiente de C: '))

print('-' * 30, ' Raízes ', '-' * 30)
delta = math.pow(valorB, 2) - (4 * valorA * valorC)
x1 = (-valorB + math.sqrt(delta)) / 2 * valorA
x2 = (-valorB - math.sqrt(delta)) / 2 * valorA
print('Raízes: {:.0f} e {:.0f}'.format(x1, x2))

print('-' * 30, ' Coordenada das vértices ', '-' * 30)
Xv = -valorB / (2 * valorA)
Yv = valorA * math.pow(Xv, 2) + valorB * Xv + valorC
print('V({:.0f}; {:.0f})'.format(Xv, Yv))

python – Error (traceback) when bringing api data

good day
I have this code

if __name__ == '__main__':
url = 'http://127.0.0.1:5000/api/v1/listar'
payload = {"cc": 1046}
headers = {'Conten-Type': 'application/json'}
response = requests.post(url, json = payload, headers = headers)
h = response.headers
server = h('server')

if response.status_code == 200:
    res = response.json()
    print(res)#trae todos los datos del usuario por su 'cc'
    for aux in res:
        apellido = aux('apellido1')
        nombre = aux('nombre1')
        print(apellido +' '+nombre)

what I want is to save in a variable the name and surname as it shows in the for cycle, but I get this error of treceback

ramirez martha 

Traceback (most recent call last):
  File "app.py", line 20, in 
    apellido = aux('apellido1')
KeyError: 'apellido1'

It shows me the first and last name but it tells me that I have an error in the line where I look for 'surname1'

How can I make it work correctly?

NOTE: I believe it is connected to firebase.

How to build a new type of syntax for an object in Python

Well, I need to build a new type of syntax that works like a string but runs the data in os.system.
The syntax should be like! Threw out! + Shell (x)
Get the data between! Y! then use it in os.system
That I have to do.

opencv – Find a specific cow in the picture frame using Python

I have trouble finding and trimming cow A in the frame of the image obtained from our CCTV camera because the barn contains many cows. Only the top views of the specific cow should be recognized. We try to match templates, but I think it does not match the project requirements. Can anyone suggest what codes in Python 3.7 we can use? Cow A is on the right side, and the other cow is on the left side, which is not necessary to recognize.
In addition, we proposed using SIFT in predictive modeling using Python 3.7 in Random Forest, knn and SVM.
This is my first time here … I hope someone helps / guides me and will really help our group for this project … Thank you.

This is a sample of the picture frame: https://drive.google.com/file/d/1JzdrZjdKmyq7YyMakKEicHYqO9yNF3gk/view?usp=sharing
This is the current result:
https://drive.google.com/file/d/1urPK_gChxOR4SxUZrUBdKHoKfq0uKccu/view?usp=sharing

The current code I used:

import os
import cv2
import numpy as np
import glob

path='C:UsersTest_Cow'
#empty list to store template images
template_data=()
#make a list of all template images from a directory
files1= glob.glob('C:UsersTest_Cow*.jpg')

for myfile in files1:
    image = cv2.imread(myfile,0)
    template_data.append(image)

test_image=cv2.imread(r'C:UsersCOW_AFrame3.jpg',0)
methods = ('cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',
             'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED')


for meth in methods:
    method = eval(meth)

#loop for matching
for tmp in template_data:
    (tH, tW) = tmp.shape(::-1);
    result = cv2.matchTemplate(test_image, tmp, method)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
    if method in (cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED):
        top_left = min_loc
    else:
        top_left = max_loc
    bottom_right = (top_left(0) + tW, top_left(-1) + tH)

rect_img = test_image(top_left(1) : bottom_right(1), top_left(0) : bottom_right(0))   # modify value
cv2.imshow('img',test_image)
cv2.imshow('cropped',rect_img)
i=1
cv2.imwrite(os.path.join(path, 'FR'+str(i)+'.jpg'), rect_img)
i=i+1
cv2.waitKey(0)

Python: how to eliminate this great error when creating a superuser?

I have three applications in django. When I makemigrations, you only added one application after migrating to the database. After using the python command maange.py createsuperuserIt is giving me a mistake. I am using the mongodb database.

djongo.sql2mongo.SQLDecodeError: FAILED SQL: INSERT INTO "auth_user" ("password", "last_login", "is_superuser", "username", "first_name", "last_name", "email", "is_staff", "is_active", "date_joined") VALUES (%(0)s, %(1)s, %(2)s, %(3)s, %(4)s, %(5)s, %(6)s, %(7)s, %(8)s, %(9)s)
Params: 

('pbkdf2_sha256$150000$Lpi7ZmtZQTKU$Rgi4yfUgX/lNGMOnhDIIyCELKvz/JvwUutBPVyTv6/o=', None, True, 'bilalkhangood4', '', '', '', True, True, datetime.datetime(2019, 8, 21, 6, 41, 58, 512948))
Pymongo error: {'writeErrors': ({'index': 0, 'code': 11000, 'errmsg': 'E11000 duplicate key error collection: firstapp_db.auth_user index: username_1 dup key: { : "bilalkhangood4" }', 'op': {'id': 4, 'password': 'pbkdf2_sha256$150000$Lpi7ZmtZQTKU$Rgi4yfUgX/lNGMOnhDIIyCELKvz/JvwUutBPVyTv6/o=', 'last_login': None, 'is_superuser': True, 'username': 'bilalkhangood4', 'first_name': '', 'last_name': '', 'email': '', 'is_staff': True, 'is_active': True, 'date_joined': datetime.datetime(2019, 8, 21, 6, 41, 58, 512948), '_id': ObjectId('5d5ce7b62dd232236aa5a188')}}), 'writeConcernErrors': (), 'nInserted': 0, 'nUpserted': 0, 'nMatched': 0, 'nModified': 0, 'nRemoved': 0, 'upserted': ()}

How to use Python to mimic the Linux "su" command

I need to imitate a lot like "su" to save the user's password.

Therefore, I need the same interactive interface and the same result.

(opl@localhost)$ python su.py it is like (opl@localhost)$ su


I tried pexpect to get user input and send it, but it didn't work.

pwd=getpass.getpass("Password:")
p=pexpect.spawn("su")
p.expect("Password:",timeout=3)
p.sendline(pwd)
p.expect("(((^())*))#",timeout=3)
p.sendline("ls")

Not return anything


Is there any other way to do it?
Or did I miss something onpexpect?