Como verificar e imprimir valores que se repetem em um vetor em python

Criar um algoritmo que dada uma sequência de n números reais, determinar os números que compõem a sequência e o número de vezes que cada um deles ocorre na mesma.

Exemplo: n = 8
Sequência: -1.7, 3.0, 0.0, 1.5, 0.0, -1.7, 2.3, -1,7
Saída: -1.7 ocorre 3 vezes
3.0 ocorre 1 vez
0.0 ocorre 2 vezes
1.5 ocorre 1 vez
2.3 ocorre 1 vez

python – Why is my Sieve of Eratosthenes using generators so slow

This is my prime sieve based on the Sieve of Eratosthenes.

import itertools
sieve = itertools.count(2)
primes = ()
nprime = 0
for _ in range(10000):
    nprime = next(sieve)
    primes.append(nprime)
    sieve = filter(eval(f"lambda x: x % {nprime} != 0"), sieve)

On my computer this code takes 13.4 seconds to generate 10,000 primes.

Edit:
As suggested by Dannnno, replacing eval(f"lambda x: x % {nprime} != 0")
with asmod(nprime) with asmod defined as:

def asmod(a):
    def inner(x):
        return x % a != 0
    return inner

improves the efficiency of the code.

python – Django Appointment Model

I am building a doctor appointment app with Django and Django Rest Framework. The app will have the functionality for secretaries to add appointments to a Doctor’s calendar, and each Doctor may have more than one clinic (and multiple secretaries).

I build this Calendar Model to store the availability information of a doctor, which needs to basically inform:

  • on a given day, at what time the doctor starts and finishes work
  • on a given day, at what time the doctor starts and finishes their break time (if they do).

Is this the optimal way to do it?

class Calendar(models.Model):
    doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE, related_name="appointments")
    clinic = models.ForeignKey(Clinic, on_delete=models.CASCADE, related_name="appointments")
    monday_start =  models.TimeField()
    monday_end =  models.TimeField()
    monday_break_start =  models.TimeField()
    monday_break_end =  models.TimeField()
    # continues for every single day of the week

python – Finding the number of moves a knight can perform while standing on a given square

Python already has a function called map()
Defining your new map() function can cause a lot of confusion, and undefined behaviour in your program.

Since you have asked for an alternate solution, here it is

Being a chess engine developer, I would never calculate something trivial like the number of knight attacks since a simple array of size 64 with the pre-calculated ones can easily work. All you need is a simple function that converts a square like a1 to 0 and h8 to 63.

Here is the implementation,

def str_sq_to_int(sq):
    return (ord(sq(0))-97) + ((ord(sq(1))-49) * 8);

def knightAttacks(cell):
    attacks = (
        2, 3, 4, 4, 4, 4, 3, 2,
        3, 4, 6, 6, 6, 6, 4, 3,
        4, 6, 8, 8, 8, 8, 6, 4,
        4, 6, 8, 8, 8, 8, 6, 4,
        4, 6, 8, 8, 8, 8, 6, 4,
        4, 6, 8, 8, 8, 8, 6, 4,
        3, 4, 6, 6, 6, 6, 4, 3,
        2, 3, 4, 4, 4, 4, 3, 2
    )
    return attacks(str_sq_int(cell))

The explanation is simple, the function str_sq_to_int() takes a square like 'a1' and returns an index using the ASCII value of the character to calculate the index. You can also use a simple dictionary to map each square to an index, but this one is easy

Then, it uses a pre-calculated set of values, to return the correct answer.

¿Por qué pasa esto? Bucle for en Python

Al introducir este código en Python:

for i in (0,7):
    print('i is '+str(i))
    i=i+1

Obtengo esto:

i is 0
i is 7

¿Por qué sucede? Me gustaría que aparecieran todos los números del 0 al 7. Es decir, i is 0, i is 1, i is 2, y así sucesivamente hasta el 7.

coding style – Python import order, mixing from … import … and import … (and import … as …)

This is the mess of imports currently at the top of my file:

import argparse
from copy import deepcopy
from functools import cmp_to_key, partial
from itertools import chain
import math
from multiprocessing import Pool
import os
import re
from typing import Dict, List, Set, Tuple
import xml.etree.ElementTree as ET

from third_party import Tool

I organised them alphabetically, by package (?) name.

I think it looks extremely ugly.

What are the standard ways to organise this section?

PEP8 (which I have read) is not helpful in this case:

Imports should be grouped in the following order:

Standard library imports.
Related third party imports.
Local application/library specific imports.
You should put a blank line between each group of imports.

python – navigation bar not worl

i want to know whr is my mistake cause the navigation bar not work with me it shuld be like black button in ( item1,item2,item3) and in navbar-brand also (NewProject) ther r shown up without bar

index.html:

{% extends 'new2/base.html'%}

<html>
     <head>
     </head>

     <body>
          {% block body %}
          {% if list_task %}
                <ul>
                    {% for i in list_task %}
                 <li>
                    <a href="{% url 'new2:details' i.id %}">{{i.Name_task}}</a>
             </li>
            {% endfor %}
                 </ul>
                {% else %}
                {% endif %}
                {% endblock %}

     </body>
</html>

base.html:

{% load static %}
    <html>
        <head>
            <link rel="stylesheet" type="text/css" href=" {% static 'new2/style.css' %} ">
            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
        </head>
        <body>
             <nav class="navbar navbar-inverse">
                 <div class="container-fluid">
                    <div class="navbar-header">
                     <a class= "navbar-brand" href="#">NewProject</a>
                    </div>
                    <ul class="nav navbar-nav navbar-right">
                         <li class="active"><a href="#">item1</a></li>
                         <li><a herf="#">item2</a></li>
                         <li><a href="#">item3</a></li>
                    </ul>
                 </div>
             </nav>
             {% block body%}
             {% endblock %}
        </body>
    </html>

details.html:

{% extends 'new2/base.html'%}
{% block body%}
{{detail.Name_task}}</br>
{{detail.Age_task}}
{% endblock %}

style.css:

body{
    background: white url("BK.jpg");
}

python 3.x – ¿Cual puede ser la causa del error “cannot convert the series to “, en éste caso?

Dispongo del siguiente DataFrame.

resultados =  datos_basicos(("Fecha_Inv", "Fech_End_Anal","Cotiz_Ini_Anal", "Cotiz_End_Anal"))
# Creamos dos columnas nuevas
resultados = resultados.reindex(columns = resultados.columns.tolist() + ("NDias", "CAGR"))
resultados.info()

<class 'pandas.core.frame.DataFrame'>
Index: 14 entries, TrueValue to renta4
Data columns (total 6 columns):
 #   Column          Non-Null Count  Dtype         
---  ------          --------------  -----         
 0   Fecha_Inv       14 non-null     datetime64(ns)
 1   Fech_End_Anal   14 non-null     datetime64(ns)
 2   Cotiz_Ini_Anal  14 non-null     float64       
 3   Cotiz_End_Anal  14 non-null     float64       
 4   NDias           0 non-null      float64       
 5   CAGR            0 non-null      float64 

Necesito introducir en la columna “NDias”, los días resultado de restar las fechas de las columnas siguientes

resultados("NYears") = (resultados("Fech_End_Anal") - resultados("Fecha_Inv")) 

El resultado de esta sentencia, no me devuelve los dias, pero en formato timedelta64(ns)

           Fecha_Inv Fech_End_Anal  Cotiz_Ini_Anal  Cotiz_End_Anal  NDias  
Nombre                                                                      
TrueValue 2017-10-11    2020-09-15          12.689          16.069    NaN   
TrueValue 2018-01-08    2020-09-15          12.689          16.069    NaN   

           CAGR    NYears  
Nombre                     
TrueValue   NaN 1070 days  
TrueValue   NaN  981 days  

Mi objetivos final es tener el número de años transcurridos entre cada dos fechas, como número decimal. Para ello hago

resultados("NYears") = (resultados("Fech_End_Anal") - resultados("Fecha_Inv")) 
resultados("NYears")  = (pd.to_numeric(resultados("NYears") .dt.days, downcast='float')) 
resultados("NYears") = resultados("NYears")/365

Esto me devuelve

Data columns (total 6 columns):
 #   Column          Non-Null Count  Dtype         
---  ------          --------------  -----         
 0   Fecha_Inv       14 non-null     datetime64(ns)
 1   Fech_End_Anal   14 non-null     datetime64(ns)
 2   Cotiz_Ini_Anal  14 non-null     float64       
 3   Cotiz_End_Anal  14 non-null     float64       
 4   NYears          14 non-null     float32       
 5   CAGR            0 non-null      fl

Si acontinuación opero con estos campos, para calcular la columna “CAGR”,

resultados("CAGR") =  get_CAGR(resultados("Valor_Ini_Anal"),resultados("Valor_End_Anal"),resultados("NYears"))

me devuelve el siguiente error:

TypeError                                 Traceback (most recent call last)
<ipython-input-178-b7f046c64997> in <module>
      8 resultados("NYears") = resultados("NYears")/365
      9 
---> 10 resultados("CAGR") =  get_CAGR(resultados("Valor_Ini_Anal"),resultados("Valor_End_Anal"),resultados("NYears"))
     11 resultados(:3)

<ipython-input-172-bfa37d17d58d> in get_CAGR(v1, v2, nYears)
      5     nYears : Duration of the investment.
      6     '''
----> 7     v_grow = float(v2)/v1
      8     cagr   = v_grow**(1./nYears) - 1
      9     return cagr

~/anaconda3/lib/python3.8/site-packages/pandas/core/series.py in wrapper(self)
    127         if len(self) == 1:
    128             return converter(self.iloc(0))
--> 129         raise TypeError(f"cannot convert the series to {converter}")
    130 
    131     wrapper.__name__ = f"__{converter.__name__}__"

TypeError: cannot convert the series to <class 'float'>

Agradeceré sugerencias para resolver este problema.

complexity – Most efficient solution for USACO: Cow Gymnastics – Python

I was trying to figure out this problem, and I did. However, my code is so abhorrently ugly that I want to tear out my eyeballs when I look at it:

with open("gymnastics.in", "r") as fin:
  rounds, cows = (int(i) for i in fin.readline().split())
  nums = (tuple(map(int, line.split())) for line in fin)

def populatePairs(cows):
  pairs = ()
  for i in range(cows):
      for j in range(cows):
          if i != j:
              pairs.append((i+1,j+1))
  return pairs

def consistentPairs(pairs, nums):
  results = ()

  for i in pairs:
      asdf = True
      for num in nums:
          for j in num:
              if j == i(1):
                  asdf = False
                  break
              if j == i(0):
                  break
          if not asdf:
              break
      if asdf:
          results.append(i)

  return results

pairs = populatePairs(cows)

with open("gymnastics.out", "w+") as fout:
  print(len(consistentPairs(pairs, nums)), file=fout)

I feel like that there should definitely be a better solution that is faster than $O(n^3)$, and without the triple nested for-loop with the if-statements trailing behind them, but I cannot, for the love of god, think of a better solution.

Problem synopsis:

Given an $n$ by $m$ grid of points, find the number of pairs in which number is consistently placed before the other.

python – How does AI voice work?

Google AI or Siri or Alexa they have their own voices and I want to know how the voices was given.
I want to make a Pdf reader but with custom voice and language so how can I develop one.
I have tried gTTS in python but that doesn’t allow me to change voice or add custom voice according
to my needs.

I have no idea about AI voices so please help and try to answer how can I make my own custom voice text to Speech.