Saturday 13 August 2022

Day 41: Image to Pencil Sketch in Python

 


#...........Convert image to pencil sketch......!

import cv2


#specify the path to image (Loading image image)

image1 = cv2.imread('E:\demo.png')

window_name = 'Original image'


# Displaying the original image 

cv2.imshow(window_name,image1)


# convert the image from one color space to another

grey_img = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)

invert = cv2.bitwise_not(grey_img)


#image smoothing

blur = cv2.GaussianBlur(invert, (21, 21), 0)

invertedblur = cv2.bitwise_not(blur)

sketch = cv2.divide(grey_img, invertedblur, scale=256.0)


#save the converted image to specified path

cv2.imwrite("E:\sketch.png", sketch)

 

# Reading an image in default mode

image = cv2.imread("E:\sketch.png")

  

# Window name in which image is displayed

window_name = 'Sketch image'

  

# Displaying the sketch image 

cv2.imshow(window_name, image)

#waits for user to press any key 

#(this is necessary to avoid Python kernel form crashing)

cv2.waitKey(0) 

#clcoding.com  

#closing all open windows 

cv2.destroyAllWindows() 


Day 40 : Calculation of Execution Time of a Python Program

 

from time import time

start = time()


#code start

email = input("Enter Your Email: ")

email=email.strip()

slicer_index=email.index("@")

username = email[:slicer_index]

domain_name = email[slicer_index+1:]

print("Your user name is ",username," and your domain is ",domain_name)

#code end


#clcoding.com

end = time()

execution_time = end - start

print("Execution Time (s) : ", execution_time)


Enter Your Email: avc@123
Your user name is  avc  and your domain is  123
Execution Time (s) :  7.258544206619263

Day 39 : Code and Decode QR in Python

 

import pyqrcode

import png

link = "https://www.instagram.com/pythonclcoding/"

qr_code = pyqrcode.create(link)

qr_code.png("instagram1.png", scale=5)


#clcoding.com

from pyzbar.pyzbar import decode

from PIL import Image

decocdeQR = decode(Image.open('instagram1.png'))

print(decocdeQR[0].data.decode('ascii'))


#clcoding.com



Day 38 : Scrape Table from a Website using Python

 


import urllib.request

import pandas as pd


#List of publicly listed ITES companies of India

url = "https://en.wikipedia.org/wiki/List_of_publicly_listed_ITES_companies_of_India"


with urllib.request.urlopen(url) as i:

    html = i.read()

    

data = pd.read_html(html)[0]

print(data.head())


#clcoding.com

               Company       Listed  Founded            Revenue  \
0  3i Infotech Limited  BSE: 532628     1993     US$239 million   
1     HCL Technologies  BSE: 532281     1976    US$5.36 billion   
2              Infosys  BSE: 500209     1981    US$8.24 billion   
3    KPIT Technologies  BSE: 532400     1990  US$444.32 million   
4               Mastek  BSE: 523704     1982  US$150.43 million   

                 Profit Headcount Reference  
0  US$84 million (2014)      9000       [1]  
1                   NaN    197777       [2]  
2       US$1.75 billion    169638       [3]  
3                   NaN     10291       [4]  
4       US$8.37 million      3352       [5]  

Day 37 : Sequence Matcher in Python

 


from difflib import SequenceMatcher

text1 = input("Enter 1st sentence : ") 

text2 = input("Enter 2nd sentence : ")

sequenceScore = SequenceMatcher(None, text1, text2).ratio()

print(f"Both are {sequenceScore * 100} % similar")


#clcoding.com

Enter 1st sentence : I love Python
Enter 2nd sentence : Python is easy
Both are 44.44444444444444 % similar


Day 35 : Create Font Art using Python

 

pip install pyfiglet

import pyfiglet

font = pyfiglet.figlet_format('Python Coding')

print(font)


#clcoding.com


 ____        _   _                    ____          _ _             
|  _ \ _   _| |_| |__   ___  _ __    / ___|___   __| (_)_ __   __ _ 
| |_) | | | | __| '_ \ / _ \| '_ \  | |   / _ \ / _` | | '_ \ / _` |
|  __/| |_| | |_| | | | (_) | | | | | |__| (_) | (_| | | | | | (_| |
|_|    \__, |\__|_| |_|\___/|_| |_|  \____\___/ \__,_|_|_| |_|\__, |
       |___/                                                  |___/ 

Day 34 : Full Diamond Pattern in Python

 


rows = int(input("Enter Diamond Pattern Rows = "))  

print("Diamond Star Pattern")  

for i in range(1, rows + 1): 

    for j in range(1, rows - i + 1): 

        print(end = ' ') 

    for k in range(0, 2 * i - 1): 

        print('*', end = '') 

    print()  

for i in range(1, rows): 

    for j in range(1, i + 1): 

        print(end = ' ') 

    for l in range(1, (2 * (rows - i) )): 

        print('*', end = '') 

    print() 

#clcoding.com    


Enter Diamond Pattern Rows = 6
Diamond Star Pattern
     *
    ***
   *****
  *******
 *********
***********
 *********
  *******
   *****
    ***
     *


Day 33 : Python code for Pascal's Triangle

 


def printPascal(N):

    arr = [1]

    temp = []

    print("pascal's triangle of", N, "Rows...")

    for i in range(N):

        print("rows", i+1, end=" : ")

        for j in range(len(arr)):

            print(arr[j], end=' ')

        print()        #clcoding.com

        temp.append(1)

        for j in range(len(arr)-1):

            temp.append(arr[j] + arr[j + 1])

        temp.append(1)

        arr = temp

        temp = []

N=int(input("Enter the Number for the pascal triangle :"))

printPascal(N)

Enter the Number for the pascal triangle :4
pascal's triangle of 4 Rows...
rows 1 : 1 
rows 2 : 1 1 
rows 3 : 1 2 1 
rows 4 : 1 3 3 1 



Day 32 : Resistor Color Code detection using Python

 

color=["black","brown","red","orange","yellow"

       ,"green","blue","violet","grey","white"]


n=color.index((input("Enter the 1st color :")))

m=color.index((input("Enter the 2nd color :")))

p=color.index((input("Enter the 3rd color :")))


q=int(((n*10)+(m))*(10**(p)))

z=q/1000 

#clcoding.com

print("\nThe Resister Value Is :")

print(f"{q}Ω  and in Kiloohm :  {z}kΩ")

Enter the 1st color :green
Enter the 2nd color :grey
Enter the 3rd color :blue

The Resister Value Is :
58000000Ω  and in Kiloohm :  58000.0kΩ


Day 31 : Radar Plot using Python

 


import plotly.express as px

import pandas as pd

data = pd.DataFrame(dict(keys=[10, 20, 30, 40], 

                         values=["Labour Cost", "Manufacturing Cost", "Promotion Cost", "Selling Cost"]))

figure = px.line_polar(data, r='keys', theta='values', line_close=True)

figure.update_traces(fill="toself")

figure.show() #clcoding.com



Day 30 : Password Authentication using Python

 

#code

import getpass

database = {"clcoding": "976729", "pythonclcoding": "2502"}

username = input("Enter Your Username : ")

password = getpass.getpass("Enter Your Password : ")

for i in database.keys():

    if username == i:

        while password != database.get(i):

            password = getpass.getpass("Enter Your Password Again : ")

        break

print("Verified")


#clcoding.com

Enter Your Username : pythonclcoding
Enter Your Password : ········
Enter Your Password Again : ········
Enter Your Password Again : ········
Verified


Day 29 : Defang IP Address using Python

#CODE

def ip_address(address):
    new_address = ""
    split_address = address.split(".")
    separator = "[.]"
    new_address = separator.join(split_address)
    return new_address
IPad=input("Enter your IP address : ")
ipaddress = ip_address(IPad)
print(ipaddress)

#clcoding.com

Enter your IP address : 	40.124.46.157
	40[.]124[.]46[.]157

Tuesday 3 May 2022

Day 28 : Bar Graph using Matplotlib in Python




#!/usr/bin/env python
# coding: utf-8

# # Bar Graph using Matplotlib in Python

# In[2]:


import matplotlib.pyplot as pyplot
# Set up the data
labels = ('Python', 'Scala', 'C#', 'Java', 'PHP')
index = (1, 2, 3, 4, 5) # provides locations on x axis
sizes = [45, 10, 15, 30, 22]
# Set up the bar chart
pyplot.bar(index, sizes, tick_label=labels)
# Configure the layout
pyplot.ylabel('Usage')
pyplot.xlabel('Programming Languages')
# Display the chart
pyplot.show() #clcoding.com


# In[ ]:




Day 27 : Pie Charts using Matplotlib in Python

 



#!/usr/bin/env python

# coding: utf-8


# # Pie Charts using Matplotlib in Python


# In[2]:



#Pie Charts using Matplotlib in Python

import matplotlib.pyplot as pyplot

labels = ('Python', 'Java', 'Scala', 'C#')

sizes = [45, 30, 15, 10]

pyplot.pie(sizes,

labels=labels,

autopct='%1.f%%',

counterclock=False,

startangle=105)

# Display the figure

pyplot.show() 

#clcoding.com



# In[ ]:






# In[ ]:





Day 26 : Real time Currency Converter with Python

 



#!/usr/bin/env python

# coding: utf-8


# In[ ]:



pip install forex_python



# # Real-time Currency Converter with Python


# In[7]:



from forex_python.converter import CurrencyRates

c = CurrencyRates()

amount = int(input("Enter the amount: "))

from_currency = input("From Currency: ").upper()

to_currency = input("To Currency: ").upper()

print(from_currency, " To ", to_currency, amount)

result = c.convert(from_currency, to_currency, amount)

print(result)


#clcoding.com



# In[ ]:





Day 24 : Validate Anagrams using Python




#!/usr/bin/env python
# coding: utf-8

# # Validate Anagrams using Python

# In[4]:


def anagram(word1, word2):
    word1 = word1.lower()
    word2 = word2.lower()
    return sorted(word1) == sorted(word2)

print(anagram("cinema", "iceman"))
print(anagram("cool", "loco"))
print(anagram("men", "women"))
print(anagram("python", "pythno"))
#clcoding.com


# In[ ]:






Day 23 : Contact Book in Python


#!/usr/bin/env python
# coding: utf-8

# # Contact Book in Python

# In[1]:


names = []
phone_numbers = []
num = int(input("Enter no of contact you want to save : "))
for i in range(num):
    name = input("Name: ")
    phone_number = input("Phone Number: ") 
    names.append(name)
    phone_numbers.append(phone_number)
print("\nName\t\t\tPhone Number\n")
for i in range(num):
    print("{}\t\t\t{}".format(names[i], phone_numbers[i]))
search_term = input("\nEnter search term: ")
print("Search result:")
if search_term in names:
    index = names.index(search_term)
    phone_number = phone_numbers[index]
    print("Name: {}, Phone Number: {}".format(search_term, phone_number))
else: #clcoding.com
    print("Name Not Found")
    
#clcoding.com    


# In[ ]:






Day 22 : Pick a Random Card using Python

 



#!/usr/bin/env python

# coding: utf-8


# # Pick a Random Card using Python


# In[8]:



import random

cards = ["Diamonds", "Spades", "Hearts", "Clubs"]

ranks = [2, 3, 4, 5, 6, 7, 8, 9, 10,

         "Jack", "Queen", "King", "Ace"]


def pick_a_card():

    card = random.choices(cards)

    rank = random.choices(ranks)

    return(f"The {rank} of {card}")


print(pick_a_card())


#clcoding.com



# In[ ]:





Day 21 : Fidget Spinner game with Python


 


#!/usr/bin/env python

# coding: utf-8


# # Fidget Spinner game with Python


# In[7]:



from turtle import *

state = {'turn': 0}

def spinner():

    clear()

    angle = state['turn']/10

    right(angle)

    forward(100)

    dot(120, 'cyan')

    back(100)

    right(120)

    forward(100)

    dot(120, 'green')

    back(100)

    right(120)

    forward(100)

    dot(120, 'blue')

    back(100)

    right(120)

    update()

def animate():

    if state['turn']>0:

        state['turn']-=1

    spinner() #clcoding.com

    ontimer(animate, 20)

def flick():

    state['turn']+=10

setup(420, 420, 370, 0)

hideturtle()

tracer(False)

width(20)

onkey(flick, 'space')

listen()

animate()

done()



# In[ ]:






# In[ ]:





Day 20 : Spelling Correction with Python





#!/usr/bin/env python
# coding: utf-8

# In[ ]:


pip install textblob


# # Spelling Correction with Python

# In[28]:


from textblob import TextBlob
def Convert(string):
    li = list(string.split())
    return li  
str1 = input("Enter your word : ")
words=Convert(str1)
corrected_words = []
for i in words:
    corrected_words.append(TextBlob(i))
print("Wrong words :", words)
print("Corrected Words are :")
for i in corrected_words:
    print(i.correct(), end=" ")
#clcoding.com


# In[ ]:




Day 19 : Chessboard using Matplotlib in Python

 


#!/usr/bin/env python

# coding: utf-8


# # Chessboard using Matplotlib in Python


# In[17]:



import matplotlib.pyplot as plt

dx, dy = 0.015, 0.015

x = np.arange(-4.0, 4.0, dx)

y = np.arange(-4.0, 4.0, dy)

X, Y = np.meshgrid(x, y)

extent = np.min(x), np.max(x), np.min(y), np.max(y)

z1 = np.add.outer(range(8), range(8)) % 2

plt.imshow(z1, cmap="binary_r", interpolation="nearest", extent=extent, alpha=1)


def chess(x, y):

    return (1 - x / 2 + x ** 5 + y ** 6) * np.exp(-(x ** 2 + y ** 2))

z2 = chess(X, Y)

plt.imshow(z2, alpha=0, interpolation="bilinear", extent=extent)

plt.title("Chess Board in Python")

plt.show()

#clcoding.com



# In[ ]:





Day 18 : Three Dimensional contour plots



#!/usr/bin/env python
# coding: utf-8

# # Three-Dimensional contour plots

# In[15]:


import numpy as np
import matplotlib.pyplot as plt
def f(x, y):
    return np.sin(np.sqrt(x ** 2 + y ** 2))
x = np.linspace(-6, 6, 30)
y = np.linspace(-6, 6, 30)
x, y = np.meshgrid(x, y)
z = f(x, y)              #clcoding.com
fig = plt.figure()
ax = plt.axes(projection='3d')
ax.contour3D(x,y,z,50, cmap='binary')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show()
fig = plt.figure()
ax = plt.axes(projection='3d')
ax.plot_wireframe(x,y,z, color='black')
ax.set_title('wireframe')
plt.show()
ax = plt.axes(projection='3d')
ax.plot_surface(x, y, z, rstride=1,
                cstride=1, cmap='viridis',
                edgecolor='none')
ax.set_title('surface')
plt.show()


# In[ ]:




Saturday 16 April 2022

Day 16 : Live Weather Updates with Python

 



#!/usr/bin/env python

# coding: utf-8


# # Live Weather Updates with Python


# In[7]:



from bs4 import BeautifulSoup

import requests

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)           AppleWebKit/537.36 (KHTML, like Gecko)            Chrome/58.0.3029.110 Safari/537.3'}

def weather(city):

    city=city.replace(" ","+")

    res = requests.get(f'https://www.google.com/search?q={city}    &oq={city}&aqs=chrome.0.35i39l2j0l4j46j69i60.6128j1j7&sourceid=                       chrome&ie=UTF-8',headers=headers)

    print("Searching......\n")

    soup = BeautifulSoup(res.text,'html.parser')   

    location = soup.select('#wob_loc')[0].getText().strip()  

    time = soup.select('#wob_dts')[0].getText().strip()       

    info = soup.select('#wob_dc')[0].getText().strip() 

    weather = soup.select('#wob_tm')[0].getText().strip()

    print(location)

    print(time)

    print(info)

    print(weather+"°C") 

city=input("Enter the Name of Any City >>  ")

city=city+" weather"

weather(city) 

#clcoding.com



# In[ ]:





Day 15 : Violin Plot using Python

 



#!/usr/bin/env python

# coding: utf-8


# In[ ]:



pip install seaborn



# # Violin Plot using Python


# In[9]:



import seaborn as sns

import matplotlib.pyplot as plt


data = sns.load_dataset("tips")

plt.figure(figsize=(10, 4))

sns.violinplot(x=data["total_bill"])

plt.show()


#clcoding.com



# In[6]:






# In[ ]:





Day 14 : Text wrapping in Python

 



#!/usr/bin/env python

# coding: utf-8


# # Text wrapping in Python


# In[17]:



import textwrap

value = """This function wraps the input paragraph such that each line

in the paragraph is at most width characters long. The wrap method

returns a list of output lines. The returned list

is empty if the wrapped

output has no content."""


# Wrap this text.

wrapper = textwrap.TextWrapper(width=70)


word_list = wrapper.wrap(text=value)


# Print each line.

for element in word_list:

print(element)


#clcoding.com



# In[ ]:





Day 13 : Country info in Python




#!/usr/bin/env python
# coding: utf-8

# In[ ]:


pip install countryinfo


# # Country info in Python

# In[1]:


from countryinfo import CountryInfo
#user input for Country Name
count=input("Enter your country : ")
country = CountryInfo(count)
print("Capital is : ",country.capital())
print("Currencies is :",country.currencies())
print("Lanuage is : ",country.languages())
print("Borders are : ",country.borders())
print("Others names : ",country.alt_spellings())

#clcoding.com



# In[ ]:




Saturday 9 April 2022

Day 11 : Python Program to Generate Password


#!/usr/bin/env python
# coding: utf-8

# # Python Program to Generate Password

# In[10]:


#import random module 
import random

#User input for password length 
passlen = int(input("Enter the length of password : "))

#storing letters, numbers and special characters
s="abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?"

#random sampling by joining the length of the password and the variable s
p = "".join(random.sample(s,passlen ))
print(p)

#clcoding.com


# In[ ]:




Day 10 : Dice Roll Simulator in Python


#!/usr/bin/env python
# coding: utf-8

# # Dice Roll Simulator

# In[ ]:


#importing module for random number generation
import random
#range of the values of a dice
min_val = 1
max_val = 6
#to loop the rolling through user input
roll_again = "yes"
#loop
while roll_again == "yes" or roll_again == "y":
    print("Rolling The Dices...")
    print("The Values are :")
    
    #generating and printing 1st random integer from 1 to 6
    print(random.randint(min_val, max_val))
    
    #asking user to roll the dice again. 
    #Any input other than yes or y will terminate the loop
    roll_again = input("Roll the Dices Again?") 
    
    #clcoding.com


# In[ ]:




Day 9 : BMI Calculator with Python

 #!/usr/bin/env python

# coding: utf-8



# # BMI Calculator with Python


# In[7]:



Height=float(input("Enter your height in centimeters: "))

Weight=float(input("Enter your Weight in Kg: "))

Height = Height/100

BMI=Weight/(Height*Height)

print("your Body Mass Index is: ",BMI)

if(BMI>0):

if(BMI<=16):

print("you are severely underweight")

elif(BMI<=18.5):

print("you are underweight")

elif(BMI<=25):

print("you are Healthy")

elif(BMI<=30):

print("you are overweight")

else: print("you are severely overweight")

else:("enter valid details")

 

    #clcoding.com 



# In[ ]:





Day 8 : Fahrenheit to Celsius in Python




#!/usr/bin/env python
# coding: utf-8

# # Fahrenheit to Celsius in Python

# In[16]:


def convert(s):
    f = float(s)    
#formula Applied below  
    c = (f - 32) * 5/9
    return c
celsius=input("Enter Values in Fahrenheit : ")
convert(celsius)

#clcoding.com


# In[ ]:





# In[ ]:




Day 7 : Treemap using Python



#!/usr/bin/env python
# coding: utf-8

# # Treemap using Python

# In[2]:


import plotly.graph_objects as go

fig = go.Figure(go.Treemap(
    labels = ["A","B", "C", "D", "E", "F", "G", "H", "I"],
    parents = ["", "A", "A", "C", "C", "A", "A", "G", "A"]
))

fig.show()

#clcoding.com


# In[ ]:




Sunday 3 April 2022

Day 6 : Text to Handwriting using Python



#!/usr/bin/env python
# coding: utf-8

# # Text to Handwriting using Python

# In[ ]:


import pywhatkit as kit
import cv2
Handwritten=input("Enter your text to convert in Handwriting : ")
kit.text_to_handwriting(Handwritten, save_to="pythoncoding.png")
img = cv2.imread("pythoncoding.png")
cv2.imshow("Python Coding", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

#clcoding.com


# In[ ]:




Day 5 : Roman Numbers to Decimals in Python


 

#!/usr/bin/env python

# coding: utf-8


# # Roman Numbers to Decimals in Python


# In[6]:



tallies = {'I': 1,'V': 5,'X': 10,'L': 50,

           'C': 100,'D': 500,'M': 1000}

def RomanNumeralToDecimal(romanNumeral):

    sum = 0

    for i in range(len(romanNumeral) - 1):

        left = romanNumeral[i]

        right = romanNumeral[i + 1]

        if tallies[left] < tallies[right]:

            sum -= tallies[left]

        else:

            sum += tallies[left]

    sum += tallies[romanNumeral[-1]]

    return sum 

roman=input("Enter Roman Numbers :")

RomanNumeralToDecimal(roman)


#clcoding.com



# In[ ]:





Day 4 : LCM using Python



#!/usr/bin/env python
# coding: utf-8

# # LCM using Python

# In[13]:


def least_common_multiple(a,b):
  
    if a > b:
        greater = a
    elif b > a:
        greater = b
    while(True):
        if ((greater % a == 0) and (greater % b == 0)):
            lcm = greater
            break
        greater = greater + 1
    return lcm
a=int(input("Enter 1st number: "))
b=int(input("Enter 2nd number: "))
print(least_common_multiple(a,b))

#clcoding.com


# In[ ]:




Day 3 : Palindrome Words using Python



#!/usr/bin/env python
# coding: utf-8

# # Palindrome Words using Python

# In[6]:


def palindrome(sentence):
    for i in (",.'?/><}{{}}'"):
        sentence = sentence.replace(i, "")
    palindrome = []
    words = sentence.split(' ')
    for word in words:
        word = word.lower()
        if word == word[::-1]:
            palindrome.append(word)
    return palindrome
sentence = input("Enter a sentence : ")
print(palindrome(sentence))

#clcoding.com


# In[ ]:




Day 2 : Count Character Occurrences using Python


 

#!/usr/bin/env python

# coding: utf-8


# # Count Character Occurrences using Python


# In[5]:



def count_characters(s):

    count = {}

    for i in s:

        if i in count:

            count[i] += 1

        else:

            count[i] = 1

    print(count)

word=input("Enter your string:")

count_characters(word)


#clcoding.com


Day 1: Line continuation characters in Python


#!/usr/bin/env python
# coding: utf-8

# # Day 1 :  Line continuation characters in Python

# In[28]:


print("I know Python and its very easy for everyone")


# In[29]:


print("I know Python and
its very easy for everyone")

#clcoding.com


# In[30]:


#In Python, a backslash ( \ ) is a continuation character.

print("I know Python and its very easy for everyone")

#clcoding.com


# In[ ]:




Tuesday 29 March 2022

How to generate password using python?

random: 
Python has a built-in module that you can use to make random numbers.
The random module has a set of methods:

  • random(): Returns a random float number between 0 and 1
  • sample(): Returns a given sample of a sequence
  • shuffle(): Takes a sequence and returns the sequence in a random order
  • choice(): Returns a random element from the given sequence
  • choices(): Returns a list with a random selection from the given sequence
  • randint(): Returns a random number between the given range
  • uniform(): Returns a random float number between two given parameters

array:
An array is a collection of items stored at contiguous memory locations. 
This module defines an object type which can compactly represent an array of basic values: characters, integers, floating point numbers.

import random
import array

#  password length
MAX_LEN = 12


DIGITS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
LOCASE_CHARACTERS = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'm', 'n', 'o', 'p', 'q',
'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
'z']

UPCASE_CHARACTERS = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'M', 'N', 'O', 'P', 'Q',
'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
'Z']

SYMBOLS = ['@', '#', '$', '%', '=', ':', '?', '.', '/', '|', '~', '>',
'*', '(', ')', '<']

# combines all the character arrays above to form one array
COMBINED_LIST = DIGITS + UPCASE_CHARACTERS + LOCASE_CHARACTERS + SYMBOLS

# randomly select at least one character from each character set above
rand_digit = random.choice(DIGITS)
rand_upper = random.choice(UPCASE_CHARACTERS)
rand_lower = random.choice(LOCASE_CHARACTERS)
rand_symbol = random.choice(SYMBOLS)

# combine the character randomly selected above

temp_pass = rand_digit + rand_upper + rand_lower + rand_symbol



# the password length by selecting randomly from the combined

for x in range(MAX_LEN - 4):
temp_pass = temp_pass + random.choice(COMBINED_LIST)

# changing the position of the elements of the sequence.

temp_pass_list = array.array('u', temp_pass)
random.shuffle(temp_pass_list)

# traverse the temporary password array and append the charsto form the password
password = ""
for x in temp_pass_list:
password = password + x
# print out password
print(password)




Thank you 😊 for reading. Please read other blogs. And also share with your friends and 
family.
Please also go to following blog:   https://pythoholic.blogspot.com/

Friday 25 March 2022

Sequence Matcher in Python

 


#!/usr/bin/env python

# coding: utf-8


# # Sequence Matcher in Python


# In[3]:



from difflib import SequenceMatcher

text1 = input("Enter 1st sentence : ") 

text2 = input("Enter 2nd sentence : ")

sequenceScore = SequenceMatcher(None, text1, text2).ratio()

print(f"Both are {sequenceScore * 100} % similar")


#clcoding.com



# In[ ]:





Age Calculator using Python

 

#!/usr/bin/env python
# coding: utf-8

# # Age Calculator using Python

# In[20]:


def ageCalculator(y, m, d):
    import datetime
    today = datetime.datetime.now().date()
    dob = datetime.date(y, m, d)
    age = int((today-dob).days / 365.25)
    print(age)

#y=year m=month d=day    
ageCalculator(2001 , 8, 1)

#clcoding.com


# In[ ]:




Saturday 19 March 2022

Image to Pencil Sketch in Python


#!/usr/bin/env python
# coding: utf-8

# # Image to Pencil Sketch in Python 

# In[ ]:


#...........Convert image to pencil sketch......!
import cv2

#specify the path to image (Loading image image)
image1 = cv2.imread('E:\demo.png')
window_name = 'Original image'

# Displaying the original image 
cv2.imshow(window_name,image1)


# convert the image from one color space to another
grey_img = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
invert = cv2.bitwise_not(grey_img)

#image smoothing
blur = cv2.GaussianBlur(invert, (21, 21), 0)
invertedblur = cv2.bitwise_not(blur)
sketch = cv2.divide(grey_img, invertedblur, scale=256.0)

#save the converted image to specified path
cv2.imwrite("E:\sketch.png", sketch)
 
# Reading an image in default mode
image = cv2.imread("E:\sketch.png")
  
# Window name in which image is displayed
window_name = 'Sketch image'
  
# Displaying the sketch image 
cv2.imshow(window_name, image)
#waits for user to press any key 
#(this is necessary to avoid Python kernel form crashing)
cv2.waitKey(0) 
  
#closing all open windows 
cv2.destroyAllWindows() 


# In[ ]:




Sunday 13 March 2022

Voice Recorder in Python




#!/usr/bin/env python
# coding: utf-8

# In[13]:


pip install sounddevice


# In[14]:


pip install scipy


# # Voice Recorder in Python

# In[15]:


#import required modules
import sounddevice
from scipy.io.wavfile import write
#sample_rate
fs=44100

#Ask to enter the recording time
second=int(input("Enter the Recording Time in second: "))
print("Recording....\n")
record_voice=sounddevice.rec(int(second * fs),samplerate=fs,channels=2)
sounddevice.wait()
write("MyRecording.wav",fs,record_voice)
print("Recording is done Please check you folder to listen recording")

#clcoding.com


# In[ ]:




Popular Posts

Categories

AI (27) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (117) C (77) C# (12) C++ (82) Course (62) Coursera (180) Cybersecurity (22) data management (11) Data Science (95) Data Strucures (6) Deep Learning (9) Django (6) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (92) Leet Code (4) Machine Learning (44) Meta (18) MICHIGAN (5) microsoft (4) Pandas (3) PHP (20) Projects (29) Python (753) Python Coding Challenge (227) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (40) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses