Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import itertools as it
import random
import secrets


def squares(start, end):
Expand Down Expand Up @@ -221,7 +221,7 @@ def tabu_generator(n, len_, recent=None):
recent = n // 2
tabu = []
while len_ > 0:
v = random.randint(0, n - 1)
v = secrets.SystemRandom().randint(0, n - 1)
if v not in tabu:
yield v
tabu.append(v)
Expand All @@ -233,7 +233,7 @@ def tabu_generator(n, len_, recent=None):
# Count how many permutations occur for different values of recent.

for recent in range(0, 6):
itemgen = (random.randint(0, 7) for i in tabu_generator(8, 10**5, recent))
itemgen = (secrets.SystemRandom().randint(0, 7) for i in tabu_generator(8, 10**5, recent))
total = 0
for _ in unique_permutations(itemgen, 8):
total += 1
Expand Down
28 changes: 14 additions & 14 deletions python3/10_Modules/09_random/01_random_numbers.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import random
import secrets

"""
Purpose: Demonstration of random module
Expand All @@ -15,28 +15,28 @@
In Python3, 'secret' module is used for cryptographic purpose.
"""
# Generate a pseudo-random number between 0 and 1.
print("random.random() :", random.random())
print("random.random() :", secrets.SystemRandom().random())

# Generate a large pseudo-random number
print("random.random() * 100:", random.random() * 100)
print("random.random() * 100:", random.random() * 100)
print("random.random() * 100:", secrets.SystemRandom().random() * 100)
print("random.random() * 100:", secrets.SystemRandom().random() * 100)

# if we set the seed, we guarantee that we will get the same answer
random.seed(18485)
secrets.SystemRandom().seed(18485)
# NOTE: only supported seed types are: None,int, float, str, bytes, and bytearray.

print(random.random()) # should give 0.6797936184081204
print(random.random()) # should give 0.9122712611873796
print(random.random()) # should give 0.12926723301605425
print(secrets.SystemRandom().random()) # should give 0.6797936184081204
print(secrets.SystemRandom().random()) # should give 0.9122712611873796
print(secrets.SystemRandom().random()) # should give 0.12926723301605425

random.seed("slartibartfast")
s = [random.random() for i in range(3)]
secrets.SystemRandom().seed("slartibartfast")
s = [secrets.SystemRandom().random() for i in range(3)]
print(s) # should give [0.7725766895236029, 0.850635131875668, 0.11481894112205038]
print()

print("os.urandom(1024)", os.urandom(1024))
random.seed(os.urandom(1024))
secrets.SystemRandom().seed(os.urandom(1024))

print(random.random()) # should give 0.7819713562511514
print(random.random()) # should give 0.4669615948613485
print(random.random()) # should give 0.6987920562874854
print(secrets.SystemRandom().random()) # should give 0.7819713562511514
print(secrets.SystemRandom().random()) # should give 0.4669615948613485
print(secrets.SystemRandom().random()) # should give 0.6987920562874854
22 changes: 11 additions & 11 deletions python3/10_Modules/09_random/02_random_numbers.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import random
import secrets

"""
Purpose: demonstration of random module
Expand All @@ -7,40 +7,40 @@
called the Mersenne Twister.
"""
# Pick a random number between 1 and 100.
print(random.randint(1, 100)) # 75
print(secrets.SystemRandom().randint(1, 100)) # 75
# randint also includes the upper bound value

# Pick a random floating point number between 1 and 10
# random.uniform(a,b) => a <= N <= b
print(random.uniform(1, 10))
print(secrets.SystemRandom().uniform(1, 10))

# Generate a randomly selected element from range(start, stop, step)
# random.randrange(start, stop[, step])
for i in range(3):
print(random.randrange(0, 101, 5))
print(secrets.SystemRandom().randrange(0, 101, 5))


items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Pick a random item from the list
x = random.sample(items, 1)
x = secrets.SystemRandom().sample(items, 1)
print(x)
# Pick 4 random items from the list
y = random.sample(items, 4)
y = secrets.SystemRandom().sample(items, 4)
print(y)

mountains = ["Andes", "Himalayas", "Alphes", "Aplachein", "Ural", "Vindhya"]

# Pick a random item from the list
x = random.sample(mountains, 1)
x = secrets.SystemRandom().sample(mountains, 1)
print(x[0])

# Pick 3 random items from the list
y = random.sample(mountains, 3)
y = secrets.SystemRandom().sample(mountains, 3)
print(y)

# Pick a random item from the list
x = random.choice(mountains)
x = secrets.choice(mountains)
print(x)
print()

Expand All @@ -49,7 +49,7 @@
def shuffler(mylist):
new_list = []
while len(mylist):
rand_pos = random.randint(0, len(mylist))
rand_pos = secrets.SystemRandom().randint(0, len(mylist))
new_list.append(mylist[rand_pos])
del mylist[rand_pos]
return new_list
Expand All @@ -58,5 +58,5 @@ def shuffler(mylist):
print(shuffler(["a", "b", "c", "d", "e"]))

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
random.shuffle(numbers)
secrets.SystemRandom().shuffle(numbers)
print("after shuffle", numbers)
4 changes: 2 additions & 2 deletions python3/10_Modules/09_random/03_tossing_coin.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# coin -- head/tail
import random
import secrets

outcomes = {
"heads": 0,
Expand All @@ -9,7 +9,7 @@


for i in range(10000):
outcome = random.choice(sides)
outcome = secrets.choice(sides)
outcomes[outcome] += 1

print("In 10000 tosses,")
Expand Down
10 changes: 5 additions & 5 deletions python3/10_Modules/09_random/04_random_name_generator.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import random
import secrets


def random_name_generator(first, second, count):
_names = []
for _ in range(count):
fst_name = random.choice(first)
lst_name = random.choice(second)
fst_name = secrets.choice(first)
lst_name = secrets.choice(second)
name = f"{fst_name} {lst_name}"
_names.append(name)
return _names
Expand All @@ -14,8 +14,8 @@ def random_name_generator(first, second, count):
def random_name_generator(first, second, count):
_names = set()
while len(_names) < count:
fst_name = random.choice(first)
lst_name = random.choice(second)
fst_name = secrets.choice(first)
lst_name = secrets.choice(second)
name = f"{fst_name} {lst_name}"
_names.add(name)
return _names
Expand Down
4 changes: 2 additions & 2 deletions python3/10_Modules/09_random/05_cards_game.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
## A deck of cards has 13 cards each of 4 suits: heart(♥), spade(♠), diamond(♦), club(♣).
## THOUGHT PROCESS: Construct an unshuffled deck by using two lists, one for suits, another for cardValues -> Shuffle the deck by iterating over all cards one by one using their indexes, and swapping the index with any random index.

import random
import secrets

suits = ["♠", "♥", "♦", "♣"]
cardValues = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]
Expand All @@ -21,7 +21,7 @@
# SHUFFLING CARDS: iterating over all cards one by one using their indexes, swapping the index with any random index
# Iterate over all cards one by one using their indexes
for index in range(0, len(deck)):
randomCardForSwitching = random.randrange(len(deck))
randomCardForSwitching = secrets.SystemRandom().randrange(len(deck))
# Swapping indexes
temporaryIndex = deck[index]
deck[index] = deck[randomCardForSwitching]
Expand Down
16 changes: 8 additions & 8 deletions python3/10_Modules/09_random/06_password_generator.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
import random
import secrets

alphabet = "abcdefghijklmnopqrstuvwxyz .,!@_-(*)-+/|$%&=?^"
pw_length = 34 # can change the length of your password by changing this number


mypw = "".join(random.sample(alphabet, pw_length))
mypw = "".join(secrets.SystemRandom().sample(alphabet, pw_length))
print(mypw)
print()

mypw = ""
for i in range(pw_length):
next_index = random.randrange(len(alphabet))
next_index = secrets.SystemRandom().randrange(len(alphabet))
mypw += alphabet[next_index]
print(mypw)
print()


# replace 1 or 2 characters with a number
for i in range(random.randrange(1, 3)):
replace_index = random.randrange(len(mypw) // 2)
mypw = mypw[0:replace_index] + str(random.randrange(10)) + mypw[replace_index + 1 :]
for i in range(secrets.SystemRandom().randrange(1, 3)):
replace_index = secrets.SystemRandom().randrange(len(mypw) // 2)
mypw = mypw[0:replace_index] + str(secrets.SystemRandom().randrange(10)) + mypw[replace_index + 1 :]

# replace 1 or 2 letters with an uppercase letter
for i in range(random.randrange(1, 3)):
replace_index = random.randrange(len(mypw) // 2, len(mypw))
for i in range(secrets.SystemRandom().randrange(1, 3)):
replace_index = secrets.SystemRandom().randrange(len(mypw) // 2, len(mypw))
mypw = (
mypw[0:replace_index] + mypw[replace_index].upper() + mypw[replace_index + 1 :]
)
Expand Down
12 changes: 6 additions & 6 deletions python3/10_Modules/09_random/07_password_generator.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
import string
from random import choice, randint, randrange, sample
import secrets

print("string.ascii_letters :", string.ascii_letters)
print("string.digits :", string.digits)
print("string.punctuation :", string.punctuation)

characters = string.ascii_letters + string.punctuation + string.digits
password1 = "".join(choice(characters) for x in range(randint(8, 16)))
password1 = "".join(secrets.choice(characters) for x in range(secrets.SystemRandom().randint(8, 16)))
print("password1 :", password1)

password2 = "".join(choice(characters) for x in range(randrange(8, 16)))
password2 = "".join(secrets.choice(characters) for x in range(secrets.SystemRandom().randrange(8, 16)))
print("password2 :", password2)


print(
"".join(sample(string.ascii_letters, 4))
+ "".join(sample(string.digits, 4))
+ "".join(sample(string.punctuation, 4))
"".join(secrets.SystemRandom().sample(string.ascii_letters, 4))
+ "".join(secrets.SystemRandom().sample(string.digits, 4))
+ "".join(secrets.SystemRandom().sample(string.punctuation, 4))
)
4 changes: 2 additions & 2 deletions python3/10_Modules/09_random/08_random_gaussion_numbers.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import random
import secrets

histogram = [0] * 20

# calculate histogram for gaussian
# noise, using average=5, stddev=1
for i in range(1000):
i = int(random.gauss(5, 1) * 2)
i = int(secrets.SystemRandom().gauss(5, 1) * 2)
histogram[i] = histogram[i] + 1

# print the histogram
Expand Down
4 changes: 2 additions & 2 deletions python3/10_Modules/09_random/cipherwheel.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# cipherwheel.py
import string
from random import randrange
import secrets

# functions for encryption and decryption

Expand All @@ -11,7 +11,7 @@ def encrypt(m):
outer_wheel = inner_wheel
# calculate random secret key
while True:
key = randrange(26)
key = secrets.SystemRandom().randrange(26)
if key != 0:
break
cipher_dict = {}
Expand Down
4 changes: 2 additions & 2 deletions python3/10_Modules/13_console_coloring/coloroma_ex3.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
#!/usr/bin/env python

import os
import random
import sys
import time

from colorama import *
import secrets

width, height = 80, 24
colors = [
Expand Down Expand Up @@ -33,7 +33,7 @@ def main():
position = middle_x - string_center

while True:
color_seed = random.randint(0, len(colors))
color_seed = secrets.SystemRandom().randint(0, len(colors))
color = colors[color_seed]
print((pos(position, middle_y) + color + string))
time.sleep(1000)
Expand Down
8 changes: 4 additions & 4 deletions python3/10_Modules/15_turtle_module/08_spirals.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
#!/usr/bin/python

from random import randint
from turtle import bgcolor, colormode, exitonclick, fd, pencolor, rt, speed
import secrets

bgcolor("black")
x = 1
speed(0)

while x < 400:
r = randint(0, 255)
g = randint(0, 255)
b = randint(0, 255)
r = secrets.SystemRandom().randint(0, 255)
g = secrets.SystemRandom().randint(0, 255)
b = secrets.SystemRandom().randint(0, 255)

colormode(255)
pencolor(r, g, b)
Expand Down
10 changes: 5 additions & 5 deletions python3/10_Modules/15_turtle_module/12_christmas_tree.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
from random import randint
from turtle import *
import secrets


def create_rectangle(turtle, color, x, y, width, height):
Expand Down Expand Up @@ -88,12 +88,12 @@ def create_circle(turtle, x, y, radius, color):

# now add few stars in sky
oogway.speed(10)
number_of_stars = randint(20, 30)
number_of_stars = secrets.SystemRandom().randint(20, 30)
# print(number_of_stars)
for _ in range(0, number_of_stars):
x_star = randint(-(screen.window_width() // 2), screen.window_width() // 2)
y_star = randint(tree_height, screen.window_height() // 2)
size = randint(5, 20)
x_star = secrets.SystemRandom().randint(-(screen.window_width() // 2), screen.window_width() // 2)
y_star = secrets.SystemRandom().randint(tree_height, screen.window_height() // 2)
size = secrets.SystemRandom().randint(5, 20)
oogway.penup()
oogway.color("white")
oogway.goto(x_star, y_star)
Expand Down
4 changes: 2 additions & 2 deletions python3/10_Modules/15_turtle_module/13_user_input_pattern.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
"""
Purpose: User Input Pattern - Outside_In
"""
import random
import time
import turtle
import secrets

print("This program draws shapes based on the number you enter in a uniform pattern.")
num_str = input("Enter the side number of the shape you want to draw: ")
Expand All @@ -21,7 +21,7 @@

numshapes = 8
for x in range(numshapes):
turtle.color(random.random(), random.random(), random.random())
turtle.color(secrets.SystemRandom().random(), secrets.SystemRandom().random(), secrets.SystemRandom().random())
x += 5
y += 5
turtle.forward(x)
Expand Down
Loading
Loading