Compare commits
4 Commits
All-Projec
...
Advanced-P
| Author | SHA1 | Date | |
|---|---|---|---|
| a5f2f28f0c | |||
| 82e5e31cee | |||
| 8b8b041e88 | |||
| 1fbd6e873c |
@@ -1,86 +0,0 @@
|
||||
"""
|
||||
----------------------------------------
|
||||
Alarm Clock
|
||||
----------------------------------------
|
||||
This is an interesting Command Line Interface (CLI)
|
||||
Python application for an intermediate-level developer.
|
||||
People across the globe use alarm clock features in their
|
||||
devices but this project can be altered in a bit different
|
||||
manner. Some certain YouTube links can be added to a text
|
||||
file and the project is programmed in a way that when a user
|
||||
sets an alarm then the code shall pick a random link from the
|
||||
video and will start playing the YouTube link.
|
||||
----------------------------------------
|
||||
"""
|
||||
|
||||
import datetime
|
||||
import os
|
||||
import time
|
||||
import random
|
||||
import webbrowser
|
||||
|
||||
# If video URL file does not exist, create one
|
||||
if not os.path.isfile("youtube_alarm_videos.txt"):
|
||||
print('Creating "youtube_alarm_videos.txt"...')
|
||||
with open("youtube_alarm_videos.txt", "w") as alarm_file:
|
||||
alarm_file.write("https://www.youtube.com/channel/UCz6SDxk2KQqJAD6Ra_YPm6A")
|
||||
|
||||
def check_alarm_input(alarm_time):
|
||||
# Checks to see if the user has entered in a valid alarm time
|
||||
if len(alarm_time) == 1: # [Hour] Format
|
||||
if alarm_time[0] < 24 and alarm_time[0] >= 0:
|
||||
return True
|
||||
if len(alarm_time) == 2: # [Hour:Minute] Format
|
||||
if alarm_time[0] < 24 and alarm_time[0] >= 0 and \
|
||||
alarm_time[1] < 60 and alarm_time[1] >= 0:
|
||||
return True
|
||||
elif len(alarm_time) == 3: # [Hour:Minute:Second] Format
|
||||
if alarm_time[0] < 24 and alarm_time[0] >= 0 and \
|
||||
alarm_time[1] < 60 and alarm_time[1] >= 0 and \
|
||||
alarm_time[2] < 60 and alarm_time[2] >= 0:
|
||||
return True
|
||||
return False
|
||||
|
||||
# Get user input for the alarm time
|
||||
print("Set a time for the alarm (Ex. 06:30 or 18:30:00)")
|
||||
while True:
|
||||
alarm_input = input(">> ")
|
||||
try:
|
||||
alarm_time = [int(n) for n in alarm_input.split(":")]
|
||||
if check_alarm_input(alarm_time):
|
||||
break
|
||||
else:
|
||||
raise ValueError
|
||||
except ValueError:
|
||||
print("ERROR: Enter time in HH:MM or HH:MM:SS format")
|
||||
|
||||
# Convert the alarm time from [H:M] or [H:M:S] to seconds
|
||||
seconds_hms = [3600, 60, 1] # Number of seconds in an Hour, Minute, and Second
|
||||
alarm_seconds = sum([a*b for a,b in zip(seconds_hms[:len(alarm_time)], alarm_time)])
|
||||
|
||||
# Get the current time of day in seconds
|
||||
now = datetime.datetime.now()
|
||||
current_time_seconds = sum([a*b for a,b in zip(seconds_hms, [now.hour, now.minute, now.second])])
|
||||
|
||||
# Calculate the number of seconds until alarm goes off
|
||||
time_diff_seconds = alarm_seconds - current_time_seconds
|
||||
|
||||
# If time difference is negative, set alarm for next day
|
||||
if time_diff_seconds < 0:
|
||||
time_diff_seconds += 86400 # number of seconds in a day
|
||||
|
||||
# Display the amount of time until the alarm goes off
|
||||
print("Alarm set to go off in %s" % datetime.timedelta(seconds=time_diff_seconds))
|
||||
|
||||
# Sleep until the alarm goes off
|
||||
time.sleep(time_diff_seconds)
|
||||
|
||||
# Time for the alarm to go off
|
||||
print("Wake Up!")
|
||||
|
||||
# Load list of possible video URLs
|
||||
with open("youtube_alarm_videos.txt", "r") as alarm_file:
|
||||
videos = alarm_file.readlines()
|
||||
|
||||
# Open a random video from the list
|
||||
webbrowser.open(random.choice(videos))
|
||||
@@ -1,59 +0,0 @@
|
||||
"""
|
||||
----------------------------------------
|
||||
Binary Search Algorithm
|
||||
----------------------------------------
|
||||
The name is evident enough to give an overview of the project.
|
||||
The program requires you to create a list of numbers between 0
|
||||
to whatever range you prefer, with every succeeding number having
|
||||
a difference of 2 between them.
|
||||
|
||||
When the user inputs a random number to be searched the program b
|
||||
egins its search by dividing the list into two halves. The first
|
||||
half is searched for the required number and if found, the other half
|
||||
is rejected and vice versa. The search continues until the number is
|
||||
found or the subarray size becomes zero. This Python project idea could
|
||||
also help you write a program to search an element in the list.
|
||||
----------------------------------------
|
||||
"""
|
||||
|
||||
# iterative implementation of binary search in Python
|
||||
def binary_search(a_list, item):
|
||||
a_list = 'path/to/file/or/array'
|
||||
"""
|
||||
Performs iterative binary search to find the position of an integer in a given, sorted, list.
|
||||
a_list -- sorted list of integers
|
||||
item -- integer you are searching for the position of
|
||||
"""
|
||||
first = 0
|
||||
last = len(a_list) - 1
|
||||
while first <= last:
|
||||
i = (first + last) / 2
|
||||
if a_list[i] == item:
|
||||
return ' found at position '.format(item=item, i=i)
|
||||
elif a_list[i] > item:
|
||||
last = i - 1
|
||||
elif a_list[i] < item:
|
||||
first = i + 1
|
||||
else:
|
||||
return ' not found in the list'.format(item=item)
|
||||
|
||||
# recursive implementation of binary search in Python
|
||||
def binary_search_recursive(a_list, item):
|
||||
"""
|
||||
Performs recursive binary search of an integer in a given, sorted, list.
|
||||
a_list -- sorted list of integers
|
||||
item -- integer you are searching for the position of
|
||||
"""
|
||||
first = 0
|
||||
last = len(a_list) - 1
|
||||
if len(a_list) == 0:
|
||||
return ' was not found in the list'.format(item=item)
|
||||
else:
|
||||
i = (first + last) // 2
|
||||
if item == a_list[i]:
|
||||
return ' found'.format(item=item)
|
||||
else:
|
||||
if a_list[i] < item:
|
||||
return binary_search_recursive(a_list[i+1:], item)
|
||||
else:
|
||||
return binary_search_recursive(a_list[:i], item)
|
||||
@@ -1,76 +0,0 @@
|
||||
"""
|
||||
----------------------------------------
|
||||
Calculator
|
||||
----------------------------------------
|
||||
Building this project you would learn to design a graphical UI
|
||||
and make you familiar with a library like Tkinter. This library
|
||||
enables you to create buttons to perform different operations and
|
||||
display results on the screen.
|
||||
----------------------------------------
|
||||
"""
|
||||
|
||||
def addition ():
|
||||
print("Addition")
|
||||
n = float(input("Enter the number: "))
|
||||
t = 0 # Total number enter
|
||||
ans = 0
|
||||
while n != 0:
|
||||
ans = ans + n
|
||||
t+=1
|
||||
n = float(input("Enter another number (0 to calculate): "))
|
||||
return [ans,t]
|
||||
def subtraction ():
|
||||
print("Subtraction");
|
||||
n = float(input("Enter the number: "))
|
||||
t = 0 # Total number enter
|
||||
sum = 0
|
||||
while n != 0:
|
||||
ans = ans - n
|
||||
t+=1
|
||||
n = float(input("Enter another number (0 to calculate): "))
|
||||
return [ans,t]
|
||||
def multiplication ():
|
||||
print("Multiplication")
|
||||
n = float(input("Enter the number: "))
|
||||
t = 0 #Total number enter
|
||||
ans = 1
|
||||
while n != 0:
|
||||
ans = ans * n
|
||||
t+=1
|
||||
n = float(input("Enter another number (0 to calculate): "))
|
||||
return [ans,t]
|
||||
def average():
|
||||
an = []
|
||||
an = addition()
|
||||
t = an[1]
|
||||
a = an[0]
|
||||
ans = a / t
|
||||
return [ans,t]
|
||||
# main...
|
||||
while True:
|
||||
list = []
|
||||
print(" My first python program!")
|
||||
print(" Simple Calculator in python by Puranjay Savar Mattas")
|
||||
print(" Enter 'a' for addition")
|
||||
print(" Enter 's' for substraction")
|
||||
print(" Enter 'm' for multiplication")
|
||||
print(" Enter 'v' for average")
|
||||
print(" Enter 'q' for quit")
|
||||
c = input(" ")
|
||||
if c != 'q':
|
||||
if c == 'a':
|
||||
list = addition()
|
||||
print("Ans = ", list[0], " total inputs ",list[1])
|
||||
elif c == 's':
|
||||
list = subtraction()
|
||||
print("Ans = ", list[0], " total inputs ",list[1])
|
||||
elif c == 'm':
|
||||
list = multiplication()
|
||||
print("Ans = ", list[0], " total inputs ",list[1])
|
||||
elif c == 'v':
|
||||
list = average()
|
||||
print("Ans = ", list[0], " total inputs ",list[1])
|
||||
else:
|
||||
print ("Sorry, invilid character")
|
||||
else:
|
||||
break
|
||||
139
ContentAggregator.py
Normal file
139
ContentAggregator.py
Normal file
@@ -0,0 +1,139 @@
|
||||
"""
|
||||
----------------------------------------
|
||||
Content Aggregator
|
||||
----------------------------------------
|
||||
Surfing through different websites and articles
|
||||
in search of good and authentic content is a
|
||||
time-consuming process. This Python project can
|
||||
help you save time looking for content. A content
|
||||
aggregator searches popular websites in search for
|
||||
relevant content and then complies with all the
|
||||
content and provides the user with unbiased content.
|
||||
----------------------------------------
|
||||
"""
|
||||
|
||||
import urllib, os, requests, datetime, subprocess
|
||||
|
||||
# reddit imports
|
||||
import praw, pprint
|
||||
|
||||
# pip install feedparser
|
||||
import feedparser
|
||||
|
||||
# stockexchange
|
||||
from nsetools import Nse
|
||||
|
||||
# Place your CLIENT_ID & CLIENT_SECRET below
|
||||
reddit = praw.Reddit(client_id='XXXXXXX',
|
||||
client_secret='XXXXXXXXXXX',
|
||||
grant_type_access='client_credentials',
|
||||
user_agent='script/1.0')
|
||||
# class Reddit:
|
||||
# def TopNews(self):
|
||||
# Add your favorite NEWS subreddits in the argument as many as you'd like.
|
||||
# for submission in reddit.subreddit('News+WorldNews+UpliftingNews+').top(limit=10):
|
||||
# top_news = reddit.domain(submission).top('month')ls
|
||||
|
||||
# print(top_news)
|
||||
|
||||
"""
|
||||
Each class contains functions which further calls
|
||||
APIs from the neccesary packages and the rest is
|
||||
self explanatory I suppose
|
||||
"""
|
||||
|
||||
class News:
|
||||
def Indian_News(self):
|
||||
newsfeed = feedparser.parse(
|
||||
"http://feeds.feedburner.com/ndtvnews-india-news"
|
||||
)
|
||||
print("Today's News: ")
|
||||
for i in range(0, 20):
|
||||
entry = newsfeed.entries[i]
|
||||
print(entry.title)
|
||||
print(entry.summary)
|
||||
print("------News Link--------")
|
||||
print(entry.link)
|
||||
print("###########################################")
|
||||
print(' ')
|
||||
print('-------------------------------------------------------------------------------------------------------')
|
||||
print(' ')
|
||||
|
||||
class Medium:
|
||||
|
||||
# https://github.com/thepracticaldev/dev.to/issues/28#issuecomment-325544385
|
||||
def medium_programming(self):
|
||||
feed = feedparser.parse(
|
||||
"https://medium.com/feed/tag/programming"
|
||||
)
|
||||
print("Programming Today: ")
|
||||
for i in range(10):
|
||||
entry = feed.entries[i]
|
||||
print(entry.title)
|
||||
print("URL: ")
|
||||
print(entry.link)
|
||||
print("###########################################")
|
||||
print(' ')
|
||||
print('-------------------------------------------------------------------------------------------------------')
|
||||
print(' ')
|
||||
|
||||
def medium_python(self):
|
||||
feed_python = feedparser.parse(
|
||||
"https://medium.com/feed/tag/python"
|
||||
)
|
||||
print("Python Today: ")
|
||||
for i in range(10):
|
||||
entry = feed_python.entries[i]
|
||||
print(entry.title)
|
||||
print("URL: ")
|
||||
print(entry.link)
|
||||
print("###########################################")
|
||||
print(' ')
|
||||
print('-------------------------------------------------------------------------------------------------------')
|
||||
print(' ')
|
||||
|
||||
def medium_developer(self):
|
||||
feed_developer = feedparser.parse(
|
||||
"https://medium.com/feed/tag/developer"
|
||||
)
|
||||
print("Developer News Today: ")
|
||||
for i in range(5):
|
||||
entry = feed_developer.entries[i]
|
||||
print(entry.title)
|
||||
print("URL: ")
|
||||
print(entry.link)
|
||||
print("###########################################")
|
||||
print(' ')
|
||||
print('-------------------------------------------------------------------------------------------------------')
|
||||
print(' ')
|
||||
|
||||
class StockExchange:
|
||||
def nse_stock(self):
|
||||
nse = Nse()
|
||||
print("TOP GAINERS OF YESTERDAY")
|
||||
pprint.pprint(nse.get_top_gainers())
|
||||
print("###########################################")
|
||||
print(' ')
|
||||
print("TOP LOSERS OF YESTERDAY")
|
||||
pprint.pprint(nse.get_top_losers())
|
||||
print("###########################################")
|
||||
print(' ')
|
||||
print('-------------------------------------------------------------------------------------------------------')
|
||||
print(' ')
|
||||
|
||||
#/ objects inititalization
|
||||
# reddit_object = Reddit()
|
||||
|
||||
News_object = News()
|
||||
Medium_object = Medium()
|
||||
StockExchange_object = StockExchange()
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
# Functions call of each class
|
||||
# reddit_object.TopNews()
|
||||
News_object.Indian_News()
|
||||
Medium_object.medium_python()
|
||||
Medium_object.medium_programming()
|
||||
Medium_object.medium_developer()
|
||||
StockExchange_object.nse_stock()
|
||||
@@ -1,46 +0,0 @@
|
||||
"""
|
||||
----------------------------------------
|
||||
Currency Converter
|
||||
----------------------------------------
|
||||
This is a straightforward project with a simple GUI.
|
||||
The name quite evidently describes the role of the
|
||||
project is to convert currencies from one unit into another.
|
||||
For example, converting Indian rupee to USD or euro. Tkinter,
|
||||
the standard Python interface can be used to design and develop
|
||||
this application.
|
||||
----------------------------------------
|
||||
"""
|
||||
|
||||
import urllib.request
|
||||
import json
|
||||
|
||||
def currency_converter(currency_from, currency_to, currency_input):
|
||||
yql_base_url = "https://query.yahooapis.com/v1/public/yql"
|
||||
yql_query = 'select%20*%20from%20yahoo.finance.xchange%20where%20pair' \
|
||||
'%20in%20("'+currency_from+currency_to+'")'
|
||||
yql_query_url = yql_base_url + "?q=" + yql_query + "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"
|
||||
try:
|
||||
yql_response = urllib.request.urlopen(yql_query_url)
|
||||
try:
|
||||
json_string = str(yql_response.read())
|
||||
json_string = json_string[2:]
|
||||
json_string = json_string[:-1]
|
||||
print(json_string)
|
||||
yql_json = json.loads(json_string)
|
||||
last_rate = yql_json['query']['results']['rate']['Rate']
|
||||
currency_output = currency_input * float(last_rate)
|
||||
return currency_output
|
||||
except (ValueError, KeyError, TypeError):
|
||||
print(yql_query_url)
|
||||
return "JSON format error"
|
||||
except IOError as e:
|
||||
print(str(e))
|
||||
|
||||
currency_input = 1
|
||||
|
||||
# currency codes : http://en.wikipedia.org/wiki/ISO_4217
|
||||
|
||||
currency_from = "USD"
|
||||
currency_to = "TRY"
|
||||
rate = currency_converter(currency_from, currency_to, currency_input)
|
||||
print(rate)
|
||||
@@ -1,77 +0,0 @@
|
||||
"""
|
||||
----------------------------------------
|
||||
Directory Tree Generator
|
||||
----------------------------------------
|
||||
This project is useful for visualizing the
|
||||
relationship between files and directories
|
||||
and making their positioning easy to comprehend.
|
||||
Python OS library can be used to list the
|
||||
files and directories within a specific directory.
|
||||
The excellent frameworks of this project are Docopt
|
||||
and Argparse.
|
||||
----------------------------------------
|
||||
Library to import for the project:
|
||||
`pip install walkdir`
|
||||
----------------------------------------
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
from walkdir import filtered_walk
|
||||
|
||||
parser = argparse.ArgumentParser(description='Print the directory-tree code for the LaTeX dirtree package.')
|
||||
parser.add_argument(dest='path', type=str, help="Root directory of the tree")
|
||||
parser.add_argument('-d', '--maxDepth', dest='maxDepth', type=int, help="Max depth for tree expansion")
|
||||
parser.add_argument('-H', '--includeHidden', dest='includeHidden', action='store_true', help='Include hidden files')
|
||||
parser.add_argument('-S', '--includeSystem', dest='includeSystem', action='store_true', help='Include system files')
|
||||
system_file_names = [".DS_Store"]
|
||||
|
||||
# Delete trailing / in rootDir which can lead to errors
|
||||
def delete_trailing_slash(path_name):
|
||||
while path_name.endswith('/'):
|
||||
path_name = path_name[:-1]
|
||||
return path_name
|
||||
|
||||
# Count how many levels deep is the directory with respect to dirRoot
|
||||
def get_relative_depth(dir_path, level_offset):
|
||||
return dir_path.count(os.path.sep) - level_offset
|
||||
|
||||
# Escape illegal symbols for LaTeX
|
||||
def escape_illegal(name):
|
||||
illegal_char_array = ['\\', '&', '%', '$', '#', '_', '{', '}', '~', '^']
|
||||
for char in illegal_char_array:
|
||||
name = name.replace(char, "\\" + char)
|
||||
return name
|
||||
rootDir = delete_trailing_slash(parser.parse_args().path)
|
||||
includeHidden = parser.parse_args().includeHidden
|
||||
includeSystem = parser.parse_args().includeSystem
|
||||
maxDepth = parser.parse_args().maxDepth
|
||||
|
||||
# if the directory exists
|
||||
if os.path.isdir(rootDir) and os.path.exists(rootDir):
|
||||
indentChar = " "
|
||||
|
||||
# Depth of the root (i.e. number of "/")
|
||||
levelOffset = rootDir.count(os.path.sep) - 1
|
||||
|
||||
# Create filter
|
||||
excluded_filter = []
|
||||
if not includeHidden:
|
||||
excluded_filter.append(".*")
|
||||
if not includeSystem:
|
||||
excluded_filter += system_file_names
|
||||
print ("\dirtree{%")
|
||||
for dirName, subdirList, fileList in sorted(filtered_walk(rootDir, depth=maxDepth, excluded_dirs=excluded_filter,
|
||||
excluded_files=excluded_filter)):
|
||||
level = get_relative_depth(dirName, levelOffset)
|
||||
baseName = os.path.basename(dirName)
|
||||
if level == 1: # for the first level only print the whole path
|
||||
print(indentChar + "." + str(level) + " {" + escape_illegal(dirName) + "} .")
|
||||
else:
|
||||
print(indentChar * level + "." + str(level) + " {" + escape_illegal((os.path.basename(dirName))) + "} .")
|
||||
level += 1
|
||||
for fileName in sorted(fileList):
|
||||
print(indentChar * level + "." + str(level) + " {" + escape_illegal(fileName) + "} .")
|
||||
print ("}")
|
||||
else:
|
||||
print ("Error: root directory not found")
|
||||
@@ -1,41 +0,0 @@
|
||||
"""
|
||||
----------------------------------------
|
||||
Mad Libs Generator
|
||||
----------------------------------------
|
||||
This python beginner project is a good start for beginner software developers as it has concepts
|
||||
like strings, variables, and concatenation. Mad Libs Generator teaches to manipulate user-inputted
|
||||
data as the Mad Libs refer to a series of inputs that a user enters. The input from the user could be
|
||||
anything from an adjective, a pronoun, or even a verb. After all the inputs are entered the application
|
||||
takes all the data and arranges it to build a story template.
|
||||
----------------------------------------
|
||||
"""
|
||||
|
||||
# Loop back to this point once code finishes
|
||||
loop = 1
|
||||
while (loop < 10):
|
||||
# All the questions that the program asks the user
|
||||
noun = input("Choose a noun: ")
|
||||
p_noun = input("Choose a plural noun: ")
|
||||
noun2 = input("Choose a noun: ")
|
||||
place = input("Name a place: ")
|
||||
adjective = input("Choose an adjective (Describing word): ")
|
||||
noun3 = input("Choose a noun: ")
|
||||
# Displays the story based on the users input
|
||||
print ("------------------------------------------")
|
||||
print ("Be kind to your",noun,"- footed", p_noun)
|
||||
print ("For a duck may be somebody's", noun2,",")
|
||||
print ("Be kind to your",p_noun,"in",place)
|
||||
print ("Where the weather is always",adjective,".")
|
||||
print ()
|
||||
print ("You may think that is this the",noun3,",")
|
||||
print ("Well it is.")
|
||||
print ("------------------------------------------")
|
||||
# Loop back to "loop = 1"
|
||||
continue_program = input("Do you want to continue(Y/N): ")
|
||||
if (continue_program == "n"):
|
||||
break
|
||||
elif (continue_program == "y"):
|
||||
loop = loop + 1
|
||||
else:
|
||||
print("Wrong input!")
|
||||
break
|
||||
@@ -1,63 +0,0 @@
|
||||
"""
|
||||
----------------------------------------
|
||||
Number Guessing Game
|
||||
----------------------------------------
|
||||
This project is an exciting fun game for beginners to build up. The program generates
|
||||
a random number from 1 to 10, or 1 to 100 any range that is specified and the user must
|
||||
guess the number after a hint from the computer. Every time a user’s guess is wrong they
|
||||
are prompted with more hints to make it easier for them to guess the number but at the
|
||||
cost of reducing the score. The clue any math clue like multiples, divisible, greater or
|
||||
smaller, or a combination of all.
|
||||
|
||||
The program also requires functions to check if an actual number is entered by the user
|
||||
or not, to compare the input number with the actual number, to find the difference between
|
||||
the two numbers.
|
||||
----------------------------------------
|
||||
"""
|
||||
|
||||
import random
|
||||
|
||||
attempts_list = []
|
||||
def show_score():
|
||||
if len(attempts_list) <= 0:
|
||||
print("There is currently no high score, it's yours for the taking!")
|
||||
else:
|
||||
print("The current high score is {} attempts".format(min(attempts_list)))
|
||||
def start_game():
|
||||
random_number = int(random.randint(1, 10))
|
||||
print("Hello traveler! Welcome to the game of guesses!")
|
||||
player_name = input("What is your name? ")
|
||||
wanna_play = input("Hi, {}, would you like to play the guessing game? (Enter Yes/No) ".format(player_name))
|
||||
# Where the show_score function USED to be
|
||||
attempts = 0
|
||||
show_score()
|
||||
while wanna_play.lower() == "yes":
|
||||
try:
|
||||
guess = input("Pick a number between 1 and 10 ")
|
||||
if int(guess) < 1 or int(guess) > 10:
|
||||
raise ValueError("Please guess a number within the given range")
|
||||
if int(guess) == random_number:
|
||||
print("Nice! You got it!")
|
||||
attempts += 1
|
||||
attempts_list.append(attempts)
|
||||
print("It took you {} attempts".format(attempts))
|
||||
play_again = input("Would you like to play again? (Enter Yes/No) ")
|
||||
attempts = 0
|
||||
show_score()
|
||||
random_number = int(random.randint(1, 10))
|
||||
if play_again.lower() == "no":
|
||||
print("That's cool, have a good one!")
|
||||
break
|
||||
elif int(guess) > random_number:
|
||||
print("It's lower")
|
||||
attempts += 1
|
||||
elif int(guess) < random_number:
|
||||
print("It's higher")
|
||||
attempts += 1
|
||||
except ValueError as err:
|
||||
print("Oh no!, that is not a valid value. Try again...")
|
||||
print("({})".format(err))
|
||||
else:
|
||||
print("That's cool, have a good one!")
|
||||
if __name__ == '__main__':
|
||||
start_game()
|
||||
6
Order Of Programs (AP) .md
Normal file
6
Order Of Programs (AP) .md
Normal file
@@ -0,0 +1,6 @@
|
||||
# Advanced Projects:
|
||||
|
||||
| Serial No. | Program Name |
|
||||
|------------|--------------|
|
||||
|1 | [ContentAggregator.py](https://github.com/psavarmattas/Python-Projects/blob/master/ContentAggregator.py) |
|
||||
|2 | [PlagiarismChecker.py](https://github.com/psavarmattas/Python-Projects/blob/master/PlagiarismChecker.py) |
|
||||
@@ -1,9 +0,0 @@
|
||||
# Beginner Projects:
|
||||
|
||||
| Serial No. | Program Name |
|
||||
|------------|--------------|
|
||||
|1 | [MadLabGenerator](https://github.com/psavarmattas/Python-Projects/blob/master/MadLabGenerator.py) |
|
||||
|2 | [NumberGuessing](https://github.com/psavarmattas/Python-Projects/blob/master/NumberGuessing.py) |
|
||||
|3 | [RockPaperScisors](https://github.com/psavarmattas/Python-Projects/blob/master/RockPaperScissors.py) |
|
||||
|4 | [WebsiteBlocker](https://github.com/psavarmattas/Python-Projects/blob/master/WebsiteBlocker.py) |
|
||||
|5 | [BinarySearch](https://github.com/psavarmattas/Python-Projects/blob/master/BinarySearch.py) |
|
||||
@@ -1,9 +0,0 @@
|
||||
# Intermediate Projects:
|
||||
|
||||
| Serial No. | Program Name |
|
||||
|------------|--------------|
|
||||
|1 | [Calculator](https://github.com/psavarmattas/Python-Projects/blob/master/Calculator.py) |
|
||||
|2 | [AlarmClock](https://github.com/psavarmattas/Python-Projects/blob/master/AlarmClock.py) & [youtube_alarm_videos](https://github.com/psavarmattas/Python-Projects/blob/master/youtube_alarm_videos.txt) |
|
||||
|3 | [TikTacToe](https://github.com/psavarmattas/Python-Projects/blob/master/TikTacToe.py) |
|
||||
|4 | [DirectoryTreeGenerator](https://github.com/psavarmattas/Python-Projects/blob/master/DirectoryTreeGenerator.py) |
|
||||
|5 | [CurrencyConverter](https://github.com/psavarmattas/Python-Projects/blob/master/CurrencyConverter.py) |
|
||||
107
PlagiarismChecker.py
Normal file
107
PlagiarismChecker.py
Normal file
@@ -0,0 +1,107 @@
|
||||
"""
|
||||
----------------------------------------
|
||||
Plagiarism Checker
|
||||
----------------------------------------
|
||||
With content creation and blogging one of
|
||||
the good businesses in the market everyone
|
||||
wants to try their hands on this but some
|
||||
lack sufficient funds to give their articles
|
||||
a free plagiarism check as mostly plagiarism
|
||||
checkers do not come for free. Building a
|
||||
Python plagiarism checker could be built here
|
||||
using a natural language processing library
|
||||
along with the search API to search the first
|
||||
few pages of Google and detect plagiarism if any.
|
||||
----------------------------------------
|
||||
"""
|
||||
import re
|
||||
import nltk; nltk.download('punkt')
|
||||
from nltk.util import ngrams, pad_sequence, everygrams
|
||||
from nltk.tokenize import word_tokenize
|
||||
from nltk.lm import MLE, WittenBellInterpolated
|
||||
import numpy as np
|
||||
import plotly.graph_objects as go
|
||||
from scipy.ndimage import gaussian_filter
|
||||
|
||||
# Training data file
|
||||
train_data_file = ""
|
||||
|
||||
# read training data
|
||||
with open(train_data_file) as f:
|
||||
train_text = f.read().lower()
|
||||
|
||||
# apply preprocessing (remove text inside square and curly brackets and rem punc)
|
||||
train_text = re.sub(r"\[.*\]|\{.*\}", "", train_text)
|
||||
train_text = re.sub(r'[^\w\s]', "", train_text)
|
||||
|
||||
# set ngram number
|
||||
n = 4
|
||||
|
||||
# pad the text and tokenize
|
||||
training_data = list(pad_sequence(word_tokenize(train_text), n,
|
||||
pad_left=True,
|
||||
left_pad_symbol="<s>"))
|
||||
|
||||
# generate ngrams
|
||||
ngrams = list(everygrams(training_data, max_len=n))
|
||||
print("Number of ngrams:", len(ngrams))
|
||||
|
||||
# build ngram language models
|
||||
model = WittenBellInterpolated(n)
|
||||
model.fit([ngrams], vocabulary_text=training_data)
|
||||
print(model.vocab)
|
||||
|
||||
# testing data file
|
||||
test_data_file = ""
|
||||
|
||||
# Read testing data
|
||||
with open(test_data_file) as f:
|
||||
test_text = f.read().lower()
|
||||
test_text = re.sub(r'[^\w\s]', "", test_text)
|
||||
|
||||
# Tokenize and pad the text
|
||||
testing_data = list(pad_sequence(word_tokenize(test_text), n,
|
||||
pad_left=True,
|
||||
left_pad_symbol="<s>"))
|
||||
print("Length of test data:", len(testing_data))
|
||||
|
||||
# assign scores
|
||||
scores = []
|
||||
for i, item in enumerate(testing_data[n-1:]):
|
||||
s = model.score(item, testing_data[i:i+n-1])
|
||||
scores.append(s)
|
||||
|
||||
scores_np = np.array(scores)
|
||||
|
||||
# set width and height
|
||||
width = 8
|
||||
height = np.ceil(len(testing_data)/width).astype("int32")
|
||||
print("Width, Height:", width, ",", height)
|
||||
|
||||
# copy scores to rectangular blank array
|
||||
a = np.zeros(width*height)
|
||||
a[:len(scores_np)] = scores_np
|
||||
diff = len(a) - len(scores_np)
|
||||
|
||||
# apply gaussian smoothing for aesthetics
|
||||
a = gaussian_filter(a, sigma=1.0)
|
||||
|
||||
# reshape to fit rectangle
|
||||
a = a.reshape(-1, width)
|
||||
|
||||
# format labels
|
||||
labels = [" ".join(testing_data[i:i+width]) for i in range(n-1, len(testing_data), width)]
|
||||
labels_individual = [x.split() for x in labels]
|
||||
labels_individual[-1] += [""]*diff
|
||||
labels = [f"{x:60.60}" for x in labels]
|
||||
|
||||
# create heatmap
|
||||
fig = go.Figure(data=go.Heatmap(
|
||||
z=a, x0=0, dx=1,
|
||||
y=labels, zmin=0, zmax=1,
|
||||
customdata=labels_individual,
|
||||
hovertemplate='%{customdata} <br><b>Score:%{z:.3f}<extra></extra>',
|
||||
colorscale="burg"))
|
||||
fig.update_layout({"height":height*28, "width":1000, "font":{"family":"Courier New"}})
|
||||
fig['layout']['yaxis']['autorange'] = "reversed"
|
||||
fig.show()
|
||||
@@ -1,5 +1,5 @@
|
||||
# Introduction:
|
||||
_`Last Updated: May 04' 2021`_
|
||||
_`Last Updated: May 13' 2021`_
|
||||
|
||||
Here are programs that every budding programmer who is learning to code in Python should start with. These programs are a compilation of many different types of programs and levels of programming you should try. You can use the table in "Order Of Programs" file to find the order in which it is best to program in.
|
||||
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
"""
|
||||
----------------------------------------
|
||||
Rock Paper Scissors
|
||||
----------------------------------------
|
||||
This program or a mini-game is designed when you don’t have anyone
|
||||
to play or you are under lockdown alone. There are a number of functions
|
||||
that this program requires so let us have an overview of each.
|
||||
|
||||
1. A random function: to generate rock, paper, or scissors.
|
||||
2. Valid function: to check the validity of the move.
|
||||
3. Result function: to declare the winner of the round.
|
||||
4. Scorekeeper: to keep track of the score.
|
||||
|
||||
The program requires the user to make the first move before it makes one
|
||||
the move. Once the move is validated the input is evaluated, the input entered
|
||||
could be a string or an alphabet. After evaluating the input string a winner
|
||||
is decided by the result function and the score of the round is updated by the
|
||||
scorekeeper function.
|
||||
----------------------------------------
|
||||
"""
|
||||
|
||||
import random
|
||||
import os
|
||||
import re
|
||||
|
||||
os.system('cls' if os.name=='nt' else 'clear')
|
||||
while (1 < 2):
|
||||
print ("\n")
|
||||
print ("Rock, Paper, Scissors - Shoot!")
|
||||
userChoice = input("Choose your weapon [R]ock, [P]aper, or [S]cissors: ")
|
||||
if not re.match("[SsRrPp]", userChoice):
|
||||
print ("Please choose a letter:")
|
||||
print ("[R]ock, [S]cissors or [P]aper.")
|
||||
continue
|
||||
# Echo the user's choice
|
||||
print ("You chose: " + userChoice)
|
||||
choices = ['R', 'P', 'S']
|
||||
opponenetChoice = random.choice(choices)
|
||||
print ("I chose: " + opponenetChoice)
|
||||
if opponenetChoice == str.upper(userChoice):
|
||||
print ("Tie! ")
|
||||
# if opponenetChoice == str("R") and str.upper(userChoice) == "P"
|
||||
elif opponenetChoice == 'R' and userChoice.upper() == 'S':
|
||||
print ("Scissors beats rock, I win! ")
|
||||
continue
|
||||
elif opponenetChoice == 'S' and userChoice.upper() == 'P':
|
||||
print ("Scissors beats paper! I win! ")
|
||||
continue
|
||||
elif opponenetChoice == 'P' and userChoice.upper() == 'R':
|
||||
print ("Paper beat rock, I win! ")
|
||||
continue
|
||||
else:
|
||||
print ("You win!")
|
||||
134
TikTacToe.py
134
TikTacToe.py
@@ -1,134 +0,0 @@
|
||||
"""
|
||||
----------------------------------------
|
||||
Tic Tac Toe
|
||||
----------------------------------------
|
||||
This game is very popular amongst all of us a
|
||||
nd even fun to build as a Python project. I am
|
||||
pretty sure most of us know how to play it but
|
||||
let me give a quick brush up.
|
||||
|
||||
It is a two-player game and consists of a nine-square
|
||||
grid. Each player chooses their move and with O or X
|
||||
and marks their square one at each chance. The player
|
||||
who succeeds in making their marks all in one line whether
|
||||
diagonally, horizontally, or vertically wins. The challenge
|
||||
for the other player is to block the game for their opponent
|
||||
and also to make their chain.
|
||||
|
||||
For building this project in Python who can use the Pygame
|
||||
Python library that is loaded with all computer graphics and sounds.
|
||||
----------------------------------------
|
||||
"""
|
||||
|
||||
import random
|
||||
import sys
|
||||
|
||||
board=[i for i in range(0,9)]
|
||||
player, computer = '',''
|
||||
|
||||
# Corners, Center and Others, respectively
|
||||
moves=((1,7,3,9),(5,),(2,4,6,8))
|
||||
|
||||
# Winner combinations
|
||||
winners=((0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6))
|
||||
|
||||
# Table
|
||||
tab=range(1,10)
|
||||
def print_board():
|
||||
x=1
|
||||
for i in board:
|
||||
end = ' | '
|
||||
if x%3 == 0:
|
||||
end = ' \n'
|
||||
if i != 1: end+='---------\n';
|
||||
char=' '
|
||||
if i in ('X','O'): char=i;
|
||||
x+=1
|
||||
print(char,end=end)
|
||||
|
||||
def select_char():
|
||||
chars=('X','O')
|
||||
if random.randint(0,1) == 0:
|
||||
return chars[::-1]
|
||||
return chars
|
||||
|
||||
def can_move(brd, player, move):
|
||||
if move in tab and brd[move-1] == move-1:
|
||||
return True
|
||||
return False
|
||||
|
||||
def can_win(brd, player, move):
|
||||
places=[]
|
||||
x=0
|
||||
for i in brd:
|
||||
if i == player: places.append(x);
|
||||
x+=1
|
||||
win=True
|
||||
for tup in winners:
|
||||
win=True
|
||||
for ix in tup:
|
||||
if brd[ix] != player:
|
||||
win=False
|
||||
break
|
||||
if win == True:
|
||||
break
|
||||
return win
|
||||
|
||||
def make_move(brd, player, move, undo=False):
|
||||
if can_move(brd, player, move):
|
||||
brd[move-1] = player
|
||||
win=can_win(brd, player, move)
|
||||
if undo:
|
||||
brd[move-1] = move-1
|
||||
return (True, win)
|
||||
return (False, False)
|
||||
|
||||
# AI goes here
|
||||
def computer_move():
|
||||
move=-1
|
||||
|
||||
# If I can win, others do not matter.
|
||||
for i in range(1,10):
|
||||
if make_move(board, computer, i, True)[1]:
|
||||
move=i
|
||||
break
|
||||
if move == -1:
|
||||
|
||||
# If player can win, block him.
|
||||
for i in range(1,10):
|
||||
if make_move(board, player, i, True)[1]:
|
||||
move=i
|
||||
break
|
||||
|
||||
if move == -1:
|
||||
# Otherwise, try to take one of desired places.
|
||||
for tup in moves:
|
||||
for mv in tup:
|
||||
if move == -1 and can_move(board, computer, mv):
|
||||
move=mv
|
||||
break
|
||||
return make_move(board, computer, move)
|
||||
|
||||
def space_exist():
|
||||
return board.count('X') + board.count('O') != 9
|
||||
player, computer = select_char()
|
||||
print('Player is [%s] and computer is [%s]' % (player, computer))
|
||||
result='%%% Deuce ! %%%'
|
||||
while space_exist():
|
||||
print_board()
|
||||
print('#Make your move ! [1-9] : ', end='')
|
||||
move = int(input())
|
||||
moved, won = make_move(board, player, move)
|
||||
if not moved:
|
||||
print(' >> Invalid number ! Try again !')
|
||||
continue
|
||||
|
||||
if won:
|
||||
result='*** Congratulations ! You won ! ***'
|
||||
break
|
||||
elif computer_move()[1]:
|
||||
result='=== You lose ! =='
|
||||
break;
|
||||
|
||||
print_board()
|
||||
print(result)
|
||||
@@ -1,43 +0,0 @@
|
||||
"""
|
||||
----------------------------------------
|
||||
Website Blocker
|
||||
----------------------------------------
|
||||
We all know while surfing through the net many unwanted sites
|
||||
popup to distract us. This project comes at help in such cases
|
||||
as it can be built up to block certain websites from opening.
|
||||
The program is beneficial for people who get easily distracted
|
||||
to switch to social media sites while into something serious.
|
||||
----------------------------------------
|
||||
"""
|
||||
|
||||
import time
|
||||
from datetime import datetime as dt
|
||||
|
||||
|
||||
hosts_path = r"/etc/hosts" # r is for raw string
|
||||
hosts_temp = "hosts"
|
||||
redirect = "127.0.0.1"
|
||||
web_sites_list = ["www.facebook.com", "facebook.com"] # users can modify the list of the websites they want to block
|
||||
|
||||
while True:
|
||||
if dt(dt.now().year, dt.now().month, dt.now().day, 9) < dt.now() < dt(dt.now().year, dt.now().month, dt.now().day,22):
|
||||
print("Working hours")
|
||||
with open(hosts_path, "r+") as file:
|
||||
content = file.read()
|
||||
for website in web_sites_list:
|
||||
if website in content:
|
||||
pass
|
||||
else:
|
||||
file.write(redirect+" "+website+"\n")
|
||||
else:
|
||||
print("Fun time")
|
||||
with open(hosts_path, "r+") as file:
|
||||
content = file.readlines()
|
||||
file.seek(0) # reset the pointer to the top of the text file
|
||||
for line in content:
|
||||
# here comes the tricky line, basically we overwrite the whole file
|
||||
if not any(website in line for website in web_sites_list):
|
||||
file.write(line)
|
||||
# do nothing otherwise
|
||||
file.truncate() # this line is used to delete the trailing lines (that contain DNS)
|
||||
time.sleep(5)
|
||||
@@ -1 +0,0 @@
|
||||
https://www.youtube.com/channel/UCz6SDxk2KQqJAD6Ra_YPm6A
|
||||
Reference in New Issue
Block a user