Featured Post

Keyword to create root window in python

random numbers, Decorators, Generators in python - part 3

 

(12)RANDON NUMBERS:

In python, random numbers are the numbers that are generated randomly by a module called random numbers.

1.Generating Random numbers:

To generate a float value between 0 and 1 of about 16 digits.

for example:

import random

= random.random()
print(a)

output = 0.8821935775679937


To give the random module a range between two numbers use 'uniform'.

for example:

import random

= random.uniform(110)
print(a)

output = 6.543223699039947


To print only integer value in a range use 'randint'.

for example:

import random

= random.randint(110)
print(a)

output = 2


To set the range excluding the upper number in this case 10.

for example:

import random

= random.randrange(110)
print(a)

output = 5


#normalvariate(self, mu, sigma)


To learn more about normal variant go to :- https://en.wikipedia.org/wiki/Normal_distribution


To print random number from the mean of the mu and standard variation of sigma

for example: 

import random 

= random.normalvariate(01)
print(a) 

output = 0.5926561552500919


To randomly choose an element from a list use '.choice()'.

for example:

import random

mylist = list("ABCDEFGH")

= random.choice(mylist)
print(a)

output = C


To randomly pick more than one element only one time from the list use sample.

for example:


output = ['H', 'E', 'B']


To randomly pick elements from the list use '.sample()'.

for example: 

import random

mylist = list("ABCDEFGH")

= random.sample(mylist, 3)
print(a)

output = ['B', 'D', 'D']


To shuffle the elements use shuffle.

for example:

import random

mylist = list("ABCDEFGH")
random.shuffle(mylist)
print(mylist)

output = ['F', 'G', 'H', 'A', 'B', 'E', 'D', 'C']


To make a set or group use 'seed'. Every seed has its own number which is in 'seed()'.

for example:

import random               

random.seed(1)
print(random.random())
print(random.randint(1,10))
random.seed(2)
print(random.random())
print(random.randint(1,10))
random.seed(1)
print(random.random())
print(random.randint(1,10))
random.seed(2)
print(random.random())
print(random.randint(1,10))

output = 

0.13436424411240122

2

0.9560342718892494

1

0.13436424411240122

2

0.9560342718892494

1


To 

for example:

import secrets

= secrets.randbelow(10)
print(a)

output = 7


for security purposes use the secrets module. To make a random number from a number of bits you entered suppose you entered 4 in randbit, which means it takes 4 random binary

values like 1010, 0110, etc., and converts it into an integer

for example:

import secrets

# random integer in range [0, n).
= secrets.randbelow(10)
print(a)

# return an integer with k random bits.
= secrets.randbits(5)
print(a)

# choose a random element from a sequence
= secrets.choice(list("ABCDEFGHI"))
print(a)

output = 

7

30

G




(13)DECORATORS:

A decorator is a function that takes another function as an argument that extends the behavior of this function without explicitly modifying it.


It allows you to add new functionality to an existing function. There are two types of decorators class decorators and function decorators first function decorator.


1.Function decorator:

for example: 

def start_end_decorator(func):
    
    def wrapper():
        print('Start')
        func()
        print('End')
    return wrapper

def print_name():
    print('Alex')
    
print_name()

print()

# Now wrap the function by passing it as argument to the decorator function
# and asign it to itself -> Our function has extended behaviour!
print_name = start_end_decorator(print_name)
print_name()

output = 

Alex


Start

Alex

End


To print sum with help of the decorators.

for example:

def start_end_decorator_3(func):

    def wrapper(*args**kwargs):
        print('Start')
        result = func(*args, **kwargs)
        print('End')
        return result
    return wrapper

@start_end_decorator_3
def add_5(x):
    return x + 5

result = add_5(10)
print(result)

output = 

Start

End

15

 

To identify the function.

for example:

def start_end_decorator_3(func):

    def wrapper(*args**kwargs):
        print('Start')
        result = func(*args, **kwargs)
        print('End')
        return result
    return wrapper

@start_end_decorator_3
def add5(x):
    return x + 5
print(help(add5))
print(add5.__name__)

output = Help on function wrapper in module __main__:


wrapper(*args, **kwargs)


None

wrapper


To print a sentence multiple times.

for example:

import functools

def my_decorator(func):
    @functools.wraps(func)
    def wrapper(*args**kwargs):
        # Do something before
        result = func(*args, **kwargs)
        # Do something after
        return result
    return wrapper

def repeat(num_times):
    def decorator_repeat(func):
        @functools.wraps(func)
        def wrapper(*args**kwargs):
            for _ in range(num_times):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator_repeat

@repeat(num_times=3)
def greet(name):
    print(f"Hello {name}")
    
greet('Alex')

output = 

Hello Alex

Hello Alex

Hello Alex


2.Class decorator:

for exmple:

import functools



class CountCalls:
    def __init__(selffunc):
        functools.update_wrapper(self, func)
        self.func = func
        self.num_calls = 0

    # extend functionality, execute function, and return the result

    def __call__(self*args**kwargs):
        self.num_calls += 1
        print(f"Call {self.num_calls} of {self.func.__name__!r}")
        return self.func(*args, **kwargs)

@CountCalls
def say_hello(num):
    print("Hello!")

say_hello(5)
say_hello(5)

output = 

Call 1 of 'say_hello'

Hello!

Call 2 of 'say_hello'

Hello!



 

(14)GENERATORS:

Generators are functions that produce items one at a time and produce only when asked which can save a lot of memory.

for example:

import sys

def firstn(n):
    num, nums = 0, []
    while num < n:
        nums.append(num)
        num += 1
    return nums

sum_of_first_n = sum(firstn(1000000))
print(sum_of_first_n)
print(sys.getsizeof(firstn(1000000)), "bytes")

output = 499999500000

8697464 bytes

1.Creating generators:

A generator is defined like a normal function but with yield instead of return.

for example:
def my_generator():
    yield 1
    yield 2
    yield 3

2.Executing generators:

Calling a generator does not executes it, because it returns a generators object which is used to control execution.
To execute call the function next().

Comments