Jump to content
ghonghi

Algoritm de generare scaderi in Python

Recommended Posts

Posted

Salut, Incerc in python sa generez niste scaderii care sa implice 2 numere intre 10 si 100 si modul 10 al scazatorului sa fie mai mare ca modul 10 al descazutului.

Mica mea functie pare sa functioneze, dar cum am implementat-o nu mi se pare ok. Are cineva alte idei?

Multumesc,

def genScaderiCuTrecere(n):
""" Genereaza scaderi cu trecere peste 10"""
assert int(n), "you need to give an integer as parameter"
for i in range (0,n):
while True:
a = random.randrange(10,100)
b = random.randrange(10,100)
print "Am generat a= " + str(a) + " si b= " + str (
if a > b and a%10 < b%10:
break
print "\n\nscaderea generata este: \n\n\t" + str(a) + "-" + str( + "="
return None

Posted

#! /usr/bin/env python
## generare scaderi prin calcule
## 16.10.2011 cmiN


IVAL = [10, 99] # interval compact
MOD = 10


def generare(nr):
""" Complexitate maxima O(N^2 * (1+1/mod)/2) amortizata de 'nr' """
tmp = None # un fel de switch ce memoreaza primul pozitiv
vec = list() # aici pastram perechile valide
a = IVAL[1] # max sau ce valoare vrei tu din interval
while a > IVAL[0]:
if a % MOD == MOD - 1:
a -= 1 # nu putea avea perechi
b = a - 1 # a > b
while b >= IVAL[0]:
if b % MOD > a % MOD:
if tmp is None:
tmp = b
if nr:
vec.append((a, )
nr -= 1
else:
return vec # returnam lista de 'nr' perechi
b -=1
else:
if tmp is None:
b -= 1
else:
b = tmp - MOD
tmp = None
a -= 1
return vec # s-au epuizat toate posibilitatile


def main():
nr = input("Numar de elemente: ")
vec = generare(nr)
for el in vec: # si le afisam
print el,

if __name__ == "__main__":
main()

In codul tau ai O(nr*R) unde R variaza in functie de randomuri, ceea ce poate lua destul de mult pentru a satisface ambele conditii, pe cand in codul meu am O(nr) unde conditiile sunt indeplinite calculand pe b in functie de a in timp ce decrementez pe a.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...