├── LICENSE.md ├── README.md ├── code ├── API │ └── Tweepy (Twitter) │ │ └── tweets.py ├── Algorithms │ ├── Searching │ │ ├── binary.py │ │ ├── jump.py │ │ └── linear.py │ └── Sorting │ │ ├── bubble.py │ │ ├── bucketsort.py │ │ ├── insertion.py │ │ ├── mergesort.py │ │ ├── quicksort.py │ │ ├── radixsort.py │ │ └── selection.py ├── Class Based │ └── Event Ticket Handler │ │ ├── event.txt │ │ ├── handler.py │ │ ├── readme.txt │ │ ├── start.py │ │ └── tickets.txt ├── Math │ ├── MathGame.py │ ├── Primes │ │ └── primes.py │ ├── calculator.py │ └── collatz.py ├── Python Modules │ ├── checknet.py │ ├── dice.py │ └── timymodule.py ├── Strings │ ├── charfreqcount.py │ └── txtbin.py └── Web Scraping and Automation │ ├── Selenium │ ├── Google Search │ │ ├── getsearchlinks.py │ │ ├── imfeelinglucky.py │ │ └── search.py │ └── Instagram Instant Follow │ │ └── instafollow.py │ ├── kickstarter.com scraper │ ├── README.md │ ├── kickstarter.py │ └── project.txt │ └── xkcd_comics.py └── requirements.txt /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Shreyas Daniel 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python Scripts 2 | 3 | All programs are written in ![Python 3.6](https://img.shields.io/badge/Python-3.5-yellow.svg) 4 | 5 | Contributor(s): [Shreyas Daniel](https://github.com/shreydan) 6 | 7 | _Please_ **star** if you found this repo helpful. 8 | 9 | _Contribute_ by **forking** this repo. 10 | 11 | **Watch** to get _updates_ about this repo. 12 | 13 | ## to install modules run: 14 | 15 | ` pip install -r requirements.txt ` 16 | 17 | ## FILES: 18 | 19 | 20 | - [API](https://github.com/shreydan/Python/tree/master/code/API) 21 | 22 | * [Tweepy (Twitter)](https://github.com/shreydan/Python/tree/master/code/API/Tweepy%20(Twitter)) 23 | - [tweets.py](https://github.com/shreydan/Python/blob/master/code/API/Tweepy%20(Twitter)/tweets.py) 24 | : This script allows the user to tweet text or an image directly from the terminal. 25 | 26 | 27 | - [Algorithms](https://github.com/shreydan/Python/tree/master/code/Algorithms) 28 | 29 | * [Searching](https://github.com/shreydan/Python/tree/master/code/Algorithms/Searching) 30 | 31 | - [binary.py](https://github.com/shreydan/Python/blob/master/code/Algorithms/Searching/binary.py) 32 | : Binary search algorithm. 33 | - [linear.py](https://github.com/shreydan/Python/blob/master/code/Algorithms/Searching/linear.py) 34 | : Linear search algorithm. 35 | 36 | * [Sorting](https://github.com/shreydan/Python/tree/master/code/Algorithms/Sorting) 37 | 38 | - [bubble.py](https://github.com/shreydan/Python/blob/master/code/Algorithms/Sorting/bubble.py) 39 | : Bubble sort algorithm. 40 | - [insertion.py](https://github.com/shreydan/Python/blob/master/code/Algorithms/Sorting/insertion.py) 41 | : Insertion sort algorithm. 42 | - [selection.py](https://github.com/shreydan/Python/blob/master/code/Algorithms/Sorting/selection.py) 43 | : Selection sort algorithm. 44 | 45 | 46 | - [Class Based](https://github.com/shreydan/Python/tree/master/code/Class%20Based) 47 | 48 | * [Event Ticket Handler](https://github.com/shreydan/Python/tree/master/code/Class%20Based/Event%20Ticket%20Handler) 49 | : Manages ticket sales in events with log. 50 | 51 | 52 | - [Math](https://github.com/shreydan/Python/tree/master/code/Math) 53 | 54 | * [Primes](https://github.com/shreydan/Python/tree/master/code/Math/Primes) 55 | - [primes.py](https://github.com/shreydan/Python/blob/master/code/Math/Primes/primes.py) 56 | : Generates prime numbers and writes them to a file. 57 | 58 | * [calculator.py](https://github.com/shreydan/Python/blob/master/code/Math/calculator.py) 59 | : Pythons eval() fuction to implement a calculator. 60 | * [collatz.py](https://github.com/shreydan/Python/blob/master/code/Math/collatz.py) 61 | : Collatz conjecture: Begin with a number and if it's even: divide by 2, if odd: multiply by 3 and add 1; continue with the resulting nos. and eventually it reaches 1. 62 | * [MathGame.py](https://github.com/shreydan/Python/blob/master/code/Math/MathGame.py) 63 | : A math game with 3 levels, 2 operands, 4 operators and grades accordingly. 64 | 65 | 66 | - [Python Modules](https://github.com/shreydan/Python/tree/master/code/Python%20Modules) 67 | 68 | * [checknet.py](https://github.com/shreydan/Python/blob/master/code/Python%20Modules/checknet.py) 69 | : Checks if internet is working or not. 70 | * [dice.py](https://github.com/shreydan/Python/blob/master/code/Python%20Modules/dice.py) 71 | : Rolls dice for you; can also change the no. of dice. 72 | * [timymodule.py](https://github.com/shreydan/Python/blob/master/code/Python%20Modules/timymodule.py) 73 | : A look at timy module - [timy module - GitHub](https://github.com/ramonsaraiva/timy) 74 | 75 | 76 | - [Strings](https://github.com/shreydan/Python/tree/master/code/Strings) 77 | 78 | * [charfreqcount.py](https://github.com/shreydan/Python/blob/master/code/Strings/charfreqcount.py) 79 | : Returns frequency of every character in a given sentence. 80 | * [txtbin.py](https://github.com/shreydan/Python/blob/master/code/Strings/txtbin.py) 81 | : Converts text to binary. 82 | 83 | 84 | - [Web Scraping and Automation](https://github.com/shreydan/Python/tree/master/code/Web%20Scraping%20and%20Automation) 85 | 86 | * [Selenium](https://github.com/shreydan/Python/tree/master/code/Web%20Scraping%20and%20Automation/Selenium) 87 | 88 | - [Google Search](https://github.com/shreydan/Python/tree/master/code/Web%20Scraping%20and%20Automation/Selenium/Google%20Search) 89 | 90 | + [imfeelinglucky.py](https://github.com/shreydan/Python/blob/master/code/Web%20Scraping%20and%20Automation/Selenium/Google%20Search/imfeelinglucky.py) 91 | : Opens the first link in a Google search result. 92 | + [search.py](https://github.com/shreydan/Python/blob/master/code/Web%20Scraping%20and%20Automation/Selenium/Google%20Search/search.py) 93 | : Google search from terminal. 94 | 95 | - [Instagram Instant Follow](https://github.com/shreydan/Python/tree/master/code/Web%20Scraping%20and%20Automation/Selenium/Instagram%20Instant%20Follow) 96 | + [instafollow.py](https://github.com/shreydan/Python/blob/master/code/Web%20Scraping%20and%20Automation/Selenium/Instagram%20Instant%20Follow/instafollow.py) 97 | : Logs in and follows people when usernames are provided. 98 | 99 | * [kickstarter.com scraper](https://github.com/shreydan/Python/tree/master/code/Web%20Scraping%20and%20Automation/kickstarter.com%20scraper) 100 | - [kickstarter.py](https://github.com/shreydan/Python/blob/master/code/Web%20Scraping%20and%20Automation/kickstarter.com%20scraper/kickstarter.py) 101 | : Gives project details of any kickstarter campaign. 102 | 103 | * [xkcd_comics.py](https://github.com/shreydan/Python/blob/master/code/Web%20Scraping%20and%20Automation/xkcd_comics.py) 104 | : Downloads the latest XKCD comic into a new folder (comics). 105 | 106 | 107 | -------------------------------------------------------------------------------- /code/API/Tweepy (Twitter)/tweets.py: -------------------------------------------------------------------------------- 1 | """ 2 | This program allows you to tweet directly from terminal. 3 | 4 | Prerequisites: 5 | install tweepy (python module) with "pip install tweepy" Ignore if installed from requirements.txt 6 | Also, grab your Twitter API from apps.twitter.com 7 | Get your comsumer key, consumer key secret, access token, access token secret. 8 | Replace them in initialize() method. 9 | 10 | Have fun, this code is all yours. 11 | NEVER SHARE YOUR CONSUMER KEY SECRET AND ACCESS TOKEN SECRET!!! 12 | """ 13 | 14 | import tweepy, os 15 | 16 | def tweetthis(type): 17 | if type == "text": 18 | print ("Enter your tweet "+user.name) 19 | tweet = input() 20 | api.update_status(tweet) 21 | elif type == "pic": 22 | print ("Enter pic path "+user.name) 23 | pic = os.path.abspath(input()) 24 | print ("Enter status "+user.name) 25 | title = input() 26 | api.update_with_media(pic, status=title) 27 | 28 | print ("\n\nDONE!!") 29 | 30 | def initialize(): 31 | global api, auth, user 32 | ck = "here" # consumer key 33 | cks = "here" # consumer key SECRET 34 | at = "here" # access token 35 | ats = "here" # access token SECRET 36 | 37 | auth = tweepy.OAuthHandler(ck,cks) 38 | auth.set_access_token(at,ats) 39 | 40 | api = tweepy.API(auth) 41 | user = api.me() 42 | 43 | def main(): 44 | doit = int(input("\n1. text\n2. picture\n")) 45 | initialize() 46 | if doit == 1: 47 | tweetthis("text") 48 | elif doit == 2: 49 | tweetthis("pic") 50 | else: 51 | print ("OK, Let's try again!") 52 | main() 53 | 54 | main() 55 | 56 | # written by shreydan. github.com/shreydan 57 | -------------------------------------------------------------------------------- /code/Algorithms/Searching/binary.py: -------------------------------------------------------------------------------- 1 | # binary search 2 | 3 | def binary(srchlist,srch): 4 | """list needs to be in ascending order to search for element""" 5 | 6 | first = 0 7 | last = len(srchlist)-1 8 | while first <= last: 9 | mid = (first + last)/2 10 | if srch > srchlist[mid]: 11 | first = mid+1 12 | elif srch < srchlist[mid]: 13 | last = mid-1 14 | else: 15 | return mid 16 | 17 | return -1 18 | 19 | -------------------------------------------------------------------------------- /code/Algorithms/Searching/jump.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | def jumpSearch( arr , x , n ): 4 | 5 | # Finding block size to be jumped 6 | step = math.sqrt(n) 7 | 8 | # Finding the block where element is 9 | # present (if it is present) 10 | prev = 0 11 | while arr[int(min(step, n)-1)] < x: 12 | prev = step 13 | step += math.sqrt(n) 14 | if prev >= n: 15 | return -1 16 | 17 | # Doing a linear search for x in 18 | # block beginning with prev. 19 | while arr[int(prev)] < x: 20 | prev += 1 21 | 22 | # If we reached next block or end 23 | # of array, element is not present. 24 | if prev == min(step, n): 25 | return -1 26 | 27 | # If element is found 28 | if arr[int(prev)] == x: 29 | return prev 30 | 31 | return -1 -------------------------------------------------------------------------------- /code/Algorithms/Searching/linear.py: -------------------------------------------------------------------------------- 1 | # linear search 2 | 3 | def linear(srchlist, srch): 4 | """check every element, kinda slow""" 5 | 6 | for element in srchlist: 7 | if element == srch: 8 | return srchlist.index(element) 9 | 10 | return -1 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /code/Algorithms/Sorting/bubble.py: -------------------------------------------------------------------------------- 1 | # bubble sort 2 | 3 | def bubble(sortlist): 4 | """checks for adjacent values and swaps them on the spot""" 5 | 6 | for i in range(0,len(sortlist)): 7 | for j in range(0,len(sortlist)-1): 8 | if sortlist[j] > sortlist[j+1]: 9 | sortlist[j],sortlist[j+1] = sortlist[j+1],sortlist[j] 10 | 11 | return sortlist 12 | -------------------------------------------------------------------------------- /code/Algorithms/Sorting/bucketsort.py: -------------------------------------------------------------------------------- 1 | def bucket_sort(alist): 2 | largest = max(alist) 3 | length = len(alist) 4 | size = largest/length 5 | 6 | buckets = [[] for _ in range(length)] 7 | for i in range(length): 8 | j = int(alist[i]/size) 9 | if j != length: 10 | buckets[j].append(alist[i]) 11 | else: 12 | buckets[length - 1].append(alist[i]) 13 | 14 | for i in range(length): 15 | insertion_sort(buckets[i]) 16 | 17 | result = [] 18 | for i in range(length): 19 | result = result + buckets[i] 20 | 21 | return result -------------------------------------------------------------------------------- /code/Algorithms/Sorting/insertion.py: -------------------------------------------------------------------------------- 1 | # insertion sort 2 | 3 | def insertion(sortlist): 4 | """starts from index 1, sorts everything behind and moves forward.""" 5 | 6 | for i in range(1,len(sortlist)): 7 | element = sortlist[i] 8 | j = i 9 | while j > 0 and sortlist[j-1] > element: 10 | sortlist[j] = sortlist[j-1] 11 | j = j - 1 12 | sortlist[j] = element 13 | 14 | return sortlist 15 | 16 | -------------------------------------------------------------------------------- /code/Algorithms/Sorting/mergesort.py: -------------------------------------------------------------------------------- 1 | def merge(arr,l,mid,r): 2 | L=[0]*(mid-l+1) 3 | R=[0]*(r-mid) 4 | for i in range(0,mid-l+1): 5 | L[i]=arr[l+i] 6 | for i in range(0,r-mid): 7 | R[i]=arr[mid+1+i] 8 | i=j=0 9 | k=l 10 | while i!=len(L) and j!=len(R): 11 | if L[i]<=R[j]: 12 | arr[k]=L[i] 13 | i+=1 14 | else: 15 | arr[k]=R[j] 16 | j+=1 17 | k+=1 18 | while i Array to be sorted, 25 | # low --> Starting index, 26 | # high --> Ending index 27 | 28 | # Function to do Quick sort 29 | def quickSort(arr,low,high): 30 | if low < high: 31 | 32 | # pi is partitioning index, arr[p] is now 33 | # at right place 34 | pi = partition(arr,low,high) 35 | 36 | # Separately sort elements before 37 | # partition and after partition 38 | quickSort(arr, low, pi-1) 39 | quickSort(arr, pi+1, high) -------------------------------------------------------------------------------- /code/Algorithms/Sorting/radixsort.py: -------------------------------------------------------------------------------- 1 | # Method to do Radix Sort 2 | def radixSort(arr): 3 | 4 | # Find the maximum number to know number of digits 5 | max1 = max(arr) 6 | 7 | # Do counting sort for every digit. Note that instead 8 | # of passing digit number, exp is passed. exp is 10^i 9 | # where i is current digit number 10 | exp = 1 11 | while max1/exp > 0: 12 | countingSort(arr,exp) 13 | exp *= 10 -------------------------------------------------------------------------------- /code/Algorithms/Sorting/selection.py: -------------------------------------------------------------------------------- 1 | # selection sort 2 | 3 | def selection(sortlist): 4 | """ checks for the largest and then replaces - ascending order only""" 5 | 6 | for i in range(0,len(sortlist)-1): 7 | small = sortlist[i] 8 | pos = i 9 | for j in range(i+1,len(sortlist)): 10 | if sortlist[j] < small: 11 | small = sortlist[j] 12 | pos = j 13 | 14 | sortlist[pos] = sortlist[i] 15 | sortlist[i] = small; 16 | 17 | return sortlist 18 | 19 | -------------------------------------------------------------------------------- /code/Class Based/Event Ticket Handler/event.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shreydan/Python/9576100b0fc81304340711cce6ad47ef078c1f38/code/Class Based/Event Ticket Handler/event.txt -------------------------------------------------------------------------------- /code/Class Based/Event Ticket Handler/handler.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | 3 | class ticket_handler(): 4 | 5 | def __init__(self): 6 | 7 | try: 8 | with open('event.txt','r') as f: 9 | event,tickets,unitprice = f.readline().rstrip().split(';') 10 | self.event = str(event) 11 | self.tickets = int(tickets) 12 | self.unitprice = int(unitprice) 13 | self.value = self.tickets * self.unitprice 14 | self.original_tickets = self.tickets 15 | 16 | except Exception: 17 | print ("ERROR: empty file OR wrong formatting OR missing values") 18 | exit() 19 | 20 | def sell(self): 21 | 22 | if self.tickets > 0: 23 | self.buyer = input("Enter buyer's name: ").strip() 24 | self.ticketsnum = int(input("Enter no. of tickets to purchase ").strip()) 25 | 26 | if self.ticketsnum > self.tickets: 27 | 28 | return False 29 | 30 | else: 31 | self.cost = self.ticketsnum * self.unitprice 32 | self.tickets = self.tickets - self.ticketsnum 33 | 34 | return True 35 | 36 | def register(self): 37 | 38 | with open('tickets.txt','a') as f: 39 | self.ticket_info = self.buyer + " PURCHASED " + str(self.ticketsnum) + " TICKETS OF COST " + str(self.cost) + " ON " + str(datetime.now()) + "\n" 40 | f.write(self.ticket_info) 41 | 42 | 43 | def update_details(self): 44 | 45 | with open ('event.txt','w') as f: 46 | self.update = self.event + ';' + str(self.tickets) + ';' + str(self.unitprice) 47 | f.write(self.update) 48 | 49 | def reset(self): 50 | 51 | with open ('event.txt','w') as f: 52 | self.resetvalue = self.event + ';' + str(self.original_tickets) + ';' + str(self.unitprice) 53 | f.write(self.resetvalue) 54 | 55 | with open ('tickets.txt','w') as f: 56 | f.write('') 57 | 58 | def print_details(self): 59 | print ("Please collect ${} from {}".format(self.cost,self.buyer)) 60 | 61 | -------------------------------------------------------------------------------- /code/Class Based/Event Ticket Handler/readme.txt: -------------------------------------------------------------------------------- 1 | Hello 2 | 3 | HOW TO USE THIS PROGRAM: 4 | 5 | -> open event.txt 6 | -> Type the eventname, tickets available and unit cost of a ticket in this format: 7 | 8 | EVENTNAME;TOTALTICKETS;UNITCOST 9 | 10 | Example: THE GREAT CIRCUS;2000;150 11 | 12 | -> launch start.py via terminal and follow the onscreen instructions 13 | 14 | -> To take a look at the log of tickets sold, open tickets.txt 15 | 16 | -> NOTE: 17 | RESET option in start.py resets the inventory and log 18 | to AVOID RESET simply choose END SESSION 19 | 20 | Written by: Shreyas Daniel - github.com/shreydan 21 | -------------------------------------------------------------------------------- /code/Class Based/Event Ticket Handler/start.py: -------------------------------------------------------------------------------- 1 | from handler import ticket_handler 2 | import os 3 | 4 | event = ticket_handler() 5 | 6 | def handle(): 7 | choice = int(input("1. SELL\n2. RESET\n3. END SESSION / GET A BREAK\n")) 8 | 9 | if choice == 1: 10 | 11 | os.system('clear') 12 | sale = event.sell() 13 | 14 | if sale is True: 15 | 16 | event.register() 17 | event.update_details() 18 | event.print_details() 19 | 20 | else: 21 | 22 | print ("We can't sell {} tickets. We only have {} tickets".format(event.ticketsnum,event.tickets)) 23 | 24 | elif choice == 2: 25 | 26 | os.system('clear') 27 | event.reset() 28 | 29 | elif choice == 3: 30 | 31 | os.system('clear') 32 | exit() 33 | 34 | else: 35 | 36 | os.system('clear') 37 | handle() 38 | 39 | 40 | while True: 41 | handle() 42 | -------------------------------------------------------------------------------- /code/Class Based/Event Ticket Handler/tickets.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shreydan/Python/9576100b0fc81304340711cce6ad47ef078c1f38/code/Class Based/Event Ticket Handler/tickets.txt -------------------------------------------------------------------------------- /code/Math/MathGame.py: -------------------------------------------------------------------------------- 1 | """ 2 | written in Python 3 by Shreyas Daniel - github.com/shreydan 3 | Game: 2 operators, 2 operands, 3 levels and grades accordingly. 4 | 5 | *********************************************** 6 | * READ THIS CAREFULLY TO UNDERSTAND THE LOGIC * 7 | *********************************************** 8 | 9 | """ 10 | 11 | import random 12 | 13 | correct = 0 14 | wrong = 0 15 | 16 | def result(correct, wrong, level): 17 | print ("You got %s correct and %s wrong!"%(correct,wrong)) 18 | if level == 1: 19 | if correct < 5: 20 | print ("Grade: C") 21 | elif correct >= 5 and correct <= 7: 22 | print ("Grade: B") 23 | else: 24 | print ("Grade: A") 25 | 26 | if level == 2: 27 | if correct <7: 28 | print "Grade: C") 29 | elif correct >= 7 and correct <= 15: 30 | print ("Grade: B") 31 | else: 32 | print ("Grade: A") 33 | 34 | if level == 3: 35 | if correct < 13: 36 | print ("Grade: C") 37 | elif correct >= 13 and correct <= 19 : 38 | print ("Grade: B") 39 | else: 40 | print ("Grade: A") 41 | 42 | def finalizer(level,questions,correct,wrong): 43 | if level == 1 and questions == 10: 44 | result(correct,wrong,level) 45 | elif level == 2 and questions == 15: 46 | result(correct,wrong,level) 47 | elif level == 3 and questions == 20: 48 | result(correct,wrong,level) 49 | 50 | def calculator(numbers, operator, level, questions): 51 | 52 | if operator == '+': 53 | answer = float(numbers[0] + numbers[1]) 54 | elif operator == '-': 55 | answer = float(numbers[0] - numbers[1]) 56 | elif operator == '*': 57 | answer = float(numbers[0] * numbers[1]) 58 | 59 | guess = float(input("\n\n" + str(numbers[0]) + " "+operator+" " + str(numbers[1]) + "\n")) 60 | global correct, wrong 61 | if guess == answer: 62 | correct += 1 63 | else: 64 | wrong += 1 65 | print ("\nCorrect answer: %s"%answer) 66 | 67 | finalizer(level,questions,correct,wrong) 68 | 69 | def levels(level,questions): 70 | operators = ['+','-','*'] 71 | op = random.randint(0,2) 72 | operator = operators[op] 73 | 74 | global numbers 75 | numbers=[] 76 | if level==1: 77 | while len(numbers) <= 1: 78 | numbers.append(float(random.randint(1,15))) 79 | elif level==2: 80 | while len(numbers) <= 1: 81 | numbers.append(float(random.randint(5,20))) 82 | elif level==3: 83 | while len(numbers) <= 1: 84 | numbers.append(float(random.randint(10,30))) 85 | 86 | calculator(numbers,operator,level,questions) 87 | 88 | def loop(level): 89 | questions = 1 90 | if level==1: 91 | while questions <= 10: 92 | levels(level,questions) 93 | questions+= 1 94 | elif level==2: 95 | while questions <= 15: 96 | levels(level,questions) 97 | questions+= 1 98 | elif level==3: 99 | while questions <= 20: 100 | levels(level,questions) 101 | questions+= 1 102 | 103 | def difficultyselector(): 104 | level = int(input("1. Easy\n2.Medium\n3. Hard\n\n")) 105 | if level==1: 106 | loop(level) 107 | elif level==2: 108 | loop(level) 109 | elif level==3: 110 | loop(level) 111 | 112 | def welcome(): 113 | print ("The Math Game\nCoded with <3 by Shreyas Daniel\n2016\n") 114 | difficultyselector() 115 | 116 | welcome() 117 | -------------------------------------------------------------------------------- /code/Math/Primes/primes.py: -------------------------------------------------------------------------------- 1 | """ 2 | Written in Python 3 3 | 4 | Description: writes "n" prime nos to a file. 5 | teaches while loop, defining function and calling it, file input. 6 | Written by: Shreyas Daniel github.com/shreydan 7 | 8 | Catch: This program is VERY slow when generating a lot of prime nos. 9 | It took around 6.5 seconds to generate 1000 primes 10 | This program is all yours now! 11 | """ 12 | 13 | def write_to_file(primes): 14 | f = open("primes.txt","w+") # creates file if it doesn't exist 15 | for pnos in primes: 16 | pnos = str(pnos)+"\n" 17 | f.write(pnos) 18 | 19 | print ("The primes are in the file primes.txt") 20 | 21 | 22 | def prime(): 23 | 24 | primes = [] 25 | i = 1 26 | num = 2 27 | n = int(input("Enter the no. of prime nos. you want\n>>> ")) 28 | print ("generating...") 29 | while len(primes) < n: # loop to generate n prime nos. 30 | count = 0 31 | i = 1 32 | while i <= num: # loop to generate factors of a no. 33 | if num%i==0: 34 | count += 1 35 | i+=1 36 | 37 | if count == 2: # checks if it's a prime no. 38 | primes.append(num) 39 | 40 | num += 1 41 | 42 | write_to_file(primes) 43 | 44 | prime() 45 | -------------------------------------------------------------------------------- /code/Math/calculator.py: -------------------------------------------------------------------------------- 1 | """ 2 | Written by : Shreyas Daniel - github.com/shreydan 3 | Description : Uses Pythons eval() function 4 | as a way to implement calculator. 5 | 6 | Functions available: 7 | -------------------------------------------- 8 | + : addition 9 | - : subtraction 10 | * : multiplication 11 | / : division 12 | % : percentage 13 | e : 2.718281... 14 | pi : 3.141592... 15 | sine : sin(rad) 16 | cosine : cos(rad) 17 | tangent : tan(rad) 18 | remainder : XmodY 19 | square root : sqrt(n) 20 | round to nearest integer : round(n) 21 | convert degrees to radians : rad(deg) 22 | """ 23 | 24 | import math 25 | import sys 26 | 27 | 28 | def calc(k): 29 | 30 | k = k.replace(' ', '') 31 | k = k.replace('^', '**') 32 | k = k.replace('=', '') 33 | k = k.replace('?', '') 34 | k = k.replace('%', '/100') 35 | k = k.replace('rad', 'radians') 36 | k = k.replace('mod', '%') 37 | 38 | functions = ['sin', 'cos', 'tan', 'sqrt', 'pi', 'radians', 'e'] 39 | 40 | for i in functions: 41 | if i in k.lower(): 42 | withmath = 'math.' + i 43 | k = k.replace(i, withmath) 44 | 45 | try: 46 | k = eval(k) 47 | except ZeroDivisionError: 48 | print("Can't divide by 0") 49 | exit() 50 | except NameError: 51 | print('Invalid input') 52 | exit() 53 | except AttributeError: 54 | print('Check usage method') 55 | exit() 56 | 57 | return k 58 | 59 | 60 | def result(k): 61 | print("\n" + str(calc(k))) 62 | 63 | 64 | def main(): 65 | 66 | print("\nScientific Calculator\nEg: sin(rad(90)) + 50% * (sqrt(16)) + round(1.42^2) - 12mod3\nEnter quit to exit") 67 | 68 | if sys.version_info.major >= 3: 69 | while True: 70 | k = input("\nWhat is ") 71 | if k == 'quit': 72 | break 73 | result(k) 74 | 75 | else: 76 | while True: 77 | k = raw_input("\nWhat is ") 78 | if k == 'quit': 79 | break 80 | result(k) 81 | 82 | 83 | if __name__ == '__main__': 84 | main() 85 | 86 | # made by me with contributions from github.com/geekcomputers/python 87 | -------------------------------------------------------------------------------- /code/Math/collatz.py: -------------------------------------------------------------------------------- 1 | """ 2 | Written in Python 3. 3 | 4 | This program is all yours now! Have fun experimenting!! 5 | 6 | Collatz conjecture: Count steps to reach 1 from n. If even: divide n by 2 7 | if odd: multiply n by 3 and add 1. 8 | 9 | teaches: creating functions, function calling, loops, loops with else (Python's cool!). 10 | """ 11 | 12 | def collatz(n): # collatz function with n as parameter. 13 | step = 0 14 | num = n 15 | while(True): 16 | if n % 2 == 0: 17 | n = n/2 18 | step += 1 19 | elif n % 2 != 0 and n != 1: 20 | n = n *3 + 1 21 | step += 1 22 | elif n == 1: 23 | step += 1 24 | break 25 | 26 | print ("It took %s steps to reach 1 with %s"%(step,num)) 27 | 28 | def input(): 29 | # takes input and rejects it to use it as an argument till it's neither 1 nor 0. 30 | n= int(input("Enter a no. ")) 31 | while n==1 or n == 0: 32 | print ("Nope, Another..") 33 | input() 34 | else: 35 | collatz(n) # call collatz function with n as argument 36 | 37 | input() #calls input function 38 | 39 | # written by @shreydan. github.com/shreydan 40 | -------------------------------------------------------------------------------- /code/Python Modules/checknet.py: -------------------------------------------------------------------------------- 1 | """ 2 | program to check internet connection 3 | written in: Python 3 4 | written by: Shreyas Daniel github.com/shreydan 5 | """ 6 | 7 | import urllib2 8 | 9 | try: 10 | urllib2.urlopen("https://www.google.com") 11 | print ("Internet is working...") 12 | except urllib2.URLError: 13 | print ("Internet is not working...") 14 | 15 | -------------------------------------------------------------------------------- /code/Python Modules/dice.py: -------------------------------------------------------------------------------- 1 | """ 2 | Written by: Shreyas Daniel - github.com/shreydan 3 | Description: Rolls dice with ability to select the number of dice. 4 | """ 5 | 6 | import random 7 | 8 | class dice(object): 9 | 10 | def __init__(self,dicenum): 11 | self.dicenum = dicenum 12 | 13 | 14 | def roll(self): 15 | roll_list = [] 16 | for i in range(self.dicenum): 17 | roll_list.append(random.randint(1,6)) 18 | 19 | return roll_list 20 | 21 | 22 | obj = dice(2) # change the number of dice here 23 | rolls = obj.roll() 24 | 25 | for r in rolls: 26 | print (r,end=' ') 27 | 28 | print() 29 | -------------------------------------------------------------------------------- /code/Python Modules/timymodule.py: -------------------------------------------------------------------------------- 1 | """ 2 | Written by: Shreyas Daniel - github.com/shreydan 3 | Description: an overview of 'timy' module - pip install timy 4 | 5 | A great alternative to Pythons 'timeit' module and easier to use. 6 | """ 7 | 8 | import timy # begin by importing timy 9 | 10 | @timy.timer(ident = 'listcomp', loops = 1) # timy decorator 11 | def listcomprehension(): # the function whose execution time is calculated. 12 | li = [x for x in range(0,100000,2)] 13 | 14 | listcomprehension() 15 | 16 | """ 17 | this is how the above works: 18 | timy property is created. 19 | any function underneath the timy decorator is the function whose execution time 20 | need to be calculated. 21 | after the function is called. The execution time is printed. 22 | in the timy decorator: 23 | ident: an identity for each timy property, handy when using a lot of them 24 | loops: no. of times this function has to be executed 25 | """ 26 | 27 | # this can also be accomplished by 'with' statement: 28 | # tracking points in between code can be added 29 | # to track specific instances in the program 30 | 31 | def listcreator(): 32 | with timy.Timer() as timer: 33 | li = [] 34 | for i in range(0,100000,2): 35 | li.append(i) 36 | if i == 50000: 37 | timer.track('reached 50000') 38 | 39 | listcreator() 40 | 41 | """ 42 | there are many more aspects to 'timy' module. 43 | check it out here: https://github.com/ramonsaraiva/timy 44 | """ 45 | -------------------------------------------------------------------------------- /code/Strings/charfreqcount.py: -------------------------------------------------------------------------------- 1 | """ 2 | Written in Python 3. 3 | 4 | This program is all yours now! Have fun experimenting!! 5 | 6 | This program accepts a sentence and prints the frequency of all the letters in the sentence. 7 | 8 | teaches: creating functions, function calling, loops, bubble sort algorithm, lists (arrays), dictionary. 9 | """ 10 | 11 | def main(): 12 | sentence = input("\n\nEnter a sentence\n") 13 | sentence = sentence.lower() 14 | string = sentence.replace(" ","") 15 | chars = [] 16 | for char in string: 17 | chars.append(char) 18 | alphad = {} 19 | for i in range(0,len(chars)): 20 | for j in range(0,len(chars)-1): 21 | if ord(chars[j]) > ord(chars[j+1]): 22 | chars[j+1] , chars[j]=chars[j],chars[j+1] 23 | 24 | 25 | for i in range(0,len(chars)-1): 26 | abet = chars[i] 27 | count = 0 28 | for j in chars: 29 | if j == abet: 30 | count += 1 31 | alphad.update({abet:count}) 32 | 33 | print ("\n\n") 34 | for ch in alphad: 35 | print (ch + " : "+str(alphad[ch])) 36 | print ("\n\n") 37 | 38 | 39 | main() 40 | 41 | # written by @shreydan. github.com/shreydan 42 | -------------------------------------------------------------------------------- /code/Strings/txtbin.py: -------------------------------------------------------------------------------- 1 | """ 2 | Written in Python 3 3 | Description: converts string to binary 4 | Written by: Shreyas Daniel github.com/shreydan 5 | """ 6 | 7 | def tobin(string): 8 | bstring = "" # new empty string 9 | for char in string: 10 | ochar = bin(ord(char)).replace("0b","0") # string[char] -> ord -> bin -> replace 11 | bstring += (str(ochar) + " ") # add space 12 | 13 | return bstring.strip(' ') #remove trailing white space 14 | 15 | string = input("Text to Binary\n>>> ") 16 | print (tobin(string)) 17 | -------------------------------------------------------------------------------- /code/Web Scraping and Automation/Selenium/Google Search/getsearchlinks.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Get search links using Beautiful Soup and requests libraries to find links from search terms: 4 | Beautiful Soup install: pip install beautifulsoup4 5 | Requests install: pip install requests 6 | 7 | """ 8 | 9 | import requests 10 | from bs4 import BeautifulSoup 11 | import re 12 | 13 | search = input("Enter your search:\n>>> ") 14 | search = search.replace(" ","+") 15 | url = "https://www.google.com/search?q=" + search #format search query 16 | 17 | page = requests.get(url) 18 | soup = BeautifulSoup(page.content, features='lxml') #get request and bring content into beautiful soup 19 | 20 | links = soup.findAll("a") #Find all tags 21 | 22 | print('\n\n') 23 | 24 | for link in soup.find_all("a",href=re.compile("(?<=/url\?q=)(htt.*://.*)")): #use regex to find links with correct format 25 | print(re.split(":(?=http)",link["href"].replace("/url?q=",""))[0]) 26 | 27 | -------------------------------------------------------------------------------- /code/Web Scraping and Automation/Selenium/Google Search/imfeelinglucky.py: -------------------------------------------------------------------------------- 1 | """ 2 | I'm Feeling Lucky using Selenium module: pip install selenium. Ignore if installed from requirements.txt 3 | written in Python 3 4 | 5 | Uses Firefox webdriver, feel free to change the browser variable with desired driver 6 | 7 | """ 8 | from selenium import webdriver 9 | 10 | search = input("Enter search:\n>>>") 11 | search = search.replace(" ","+") 12 | url = "https://www.google.com/search?q="+search 13 | 14 | browser = webdriver.Firefox() 15 | browser.maximize_window() 16 | browser.get(url) 17 | h3 = browser.find_element_by_class_name("r") 18 | link = h3.find_element_by_tag_name('a') 19 | link.click() 20 | -------------------------------------------------------------------------------- /code/Web Scraping and Automation/Selenium/Google Search/search.py: -------------------------------------------------------------------------------- 1 | """ 2 | Google search using Selenium module: pip install selenium. Ignore if installed from requirements.txt 3 | written in Python 3 4 | 5 | Uses Firefox webdriver, feel free to change the browser variable with desired driver 6 | 7 | """ 8 | 9 | from selenium import webdriver 10 | 11 | search = input("Enter your search:\n>>>") 12 | search = search.replace(" ","+") 13 | url = "https://www.google.com/search?q="+search 14 | 15 | browser = webdriver.Firefox() 16 | browser.get(url) 17 | -------------------------------------------------------------------------------- /code/Web Scraping and Automation/Selenium/Instagram Instant Follow/instafollow.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | written in Python 3 by Shreyas Daniel - github.com/shreydan 4 | 5 | follow people on Instagram by providing usernames to the program 6 | requirements: Selenium -> pip install selenium 7 | no exceptions are catched in this version yet. 8 | Instagram account can't have 2 factor verification. 9 | 10 | """ 11 | 12 | from selenium import webdriver 13 | from selenium.webdriver.common.keys import Keys 14 | import time 15 | 16 | def done(): 17 | print ("Followed all the users") 18 | time.sleep(2) 19 | browser.quit() 20 | 21 | def follow(userlist): 22 | for users in userlist: 23 | url = "https://www.instagram.com/"+users 24 | browser.get(url) 25 | follow_btn = browser.find_element_by_class_name("_ah57t") 26 | follow_btn.click() 27 | print ("Followed: "+users) 28 | time.sleep(2) 29 | 30 | done() 31 | 32 | 33 | def users(): 34 | time.sleep(3) 35 | userlist = [] 36 | n = int(input("Enter no. of users to follow ")) 37 | if n == 0: 38 | done() 39 | else: 40 | for i in range(0,n): 41 | follow_user = input("Enter correct username ") 42 | userlist.append(follow_user) 43 | follow(userlist) 44 | 45 | def login(): 46 | global usr 47 | usr = input("Enter your username ") 48 | psw = input("Enter your password ") 49 | username = browser.find_element_by_name("username") 50 | username.send_keys(usr) 51 | password = browser.find_element_by_name("password") 52 | password.send_keys(psw) 53 | password.send_keys(Keys.RETURN) 54 | 55 | 56 | browser = webdriver.Firefox() 57 | browser.maximize_window() 58 | browser.get("https://www.instagram.com/accounts/login/") 59 | login() 60 | users() 61 | 62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /code/Web Scraping and Automation/kickstarter.com scraper/README.md: -------------------------------------------------------------------------------- 1 | ## How to use kickstarter.com scraper: 2 | 3 | - Paste the project link in `project.txt` 4 | - Run `kickstarter.py` 5 | 6 | If `project.txt` is empty or link pasted is broken, errors are raised. 7 | -------------------------------------------------------------------------------- /code/Web Scraping and Automation/kickstarter.com scraper/kickstarter.py: -------------------------------------------------------------------------------- 1 | """ 2 | Written by: Shreyas Daniel - github.com/shreydan 3 | Written on: 29 April 2017 4 | 5 | Description: Prints project details of any kickstarter campaign. 6 | 7 | Before executing: 8 | Please copy the URL of the project to project.txt (ONLY 1 URL at a time) 9 | """ 10 | 11 | import requests 12 | from lxml import html 13 | import os 14 | 15 | def error_reason(issue): 16 | if issue == "empty file": 17 | print ("Please enter the correct URL of the kickstarter project in project.txt") 18 | else: 19 | print ("INVALID URL or NOT CONNECTED TO THE INTERNET.") 20 | 21 | with open("project.txt","r") as project: 22 | file_size = os.stat("project.txt").st_size 23 | if file_size > 0: 24 | url = project.readline().rstrip() 25 | else: 26 | error_reason("empty file") 27 | exit() 28 | 29 | try: 30 | project_page = requests.get(url) 31 | except requests.exceptions.RequestException as e: 32 | error_reason(e) 33 | exit() 34 | 35 | structure = html.fromstring(project_page.content) 36 | 37 | creator = str(structure.xpath(".//*[@id='content-wrap']/section/div/div[2]/div/div/div[2]/span[1]/a/text()")[0]).strip() 38 | title = str(structure.xpath(".//*[@id='content-wrap']/section/div/div[2]/div/div/div[3]/h2/text()")[0]).strip() 39 | description = str(structure.xpath(".//*[@id='content-wrap']/section/div/div[2]/div/div/div[3]/p/text()")[0]).strip() 40 | backers = str(structure.xpath(".//*[@id='backers_count']/text()")[0]).strip() 41 | backed_amount = str(structure.xpath(".//*[@id='content-wrap']/section/div/div[1]/div[2]/div[1]/div[3]/div[1]/span[1]/text()")[0]).strip() 42 | pledged_amount = str(structure.xpath(".//*[@id='content-wrap']/section/div/div[1]/div[2]/div[1]/div[3]/div[1]/span[3]/span[1]/text()")[0]).strip() 43 | 44 | print ("CREATOR: "+creator) 45 | print ("TITLE: "+title) 46 | print ("DESCRIPTION: "+description) 47 | print ("BACKED AMOUNT: "+backed_amount) 48 | print ("PLEDGED AMOUNT: "+pledged_amount) 49 | 50 | backed_amount = int(backed_amount[1:].replace(",","")) 51 | pledged_amount = int(pledged_amount[1:].replace(",","")) 52 | backed_percentage = str(int((backed_amount/pledged_amount)*100)) + "%" 53 | 54 | print (backed_percentage + " FUNDED") 55 | print ("BACKED BY: "+backers+" PEOPLE") 56 | -------------------------------------------------------------------------------- /code/Web Scraping and Automation/kickstarter.com scraper/project.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shreydan/Python/9576100b0fc81304340711cce6ad47ef078c1f38/code/Web Scraping and Automation/kickstarter.com scraper/project.txt -------------------------------------------------------------------------------- /code/Web Scraping and Automation/xkcd_comics.py: -------------------------------------------------------------------------------- 1 | """ 2 | Written by: Shreyas Daniel - github.com/shreydan 3 | Written on: 26 April 2017 4 | 5 | Description: Download latest XKCD Comic with this program. 6 | 7 | NOTE: 8 | if this script is launched from the cloned repo, a new folder is created. 9 | Please move the file to another directory to avoid messing with the folder structure. 10 | """ 11 | 12 | import requests 13 | from lxml import html 14 | import urllib.request 15 | import os 16 | 17 | def xkcd(): 18 | 19 | # opens xkcd.com 20 | try: 21 | page = requests.get("https://www.xkcd.com") 22 | except requests.exceptions.RequestException as e: 23 | print (e) 24 | exit() 25 | 26 | # parses xkcd.com page 27 | tree = html.fromstring(page.content) 28 | 29 | # finds image src url 30 | image_src = tree.xpath(".//*[@id='comic']/img/@src")[0] 31 | image_src = "https:" + str(image_src) 32 | 33 | # gets comic name from the image src url 34 | comic_name = image_src.split('/')[-1] 35 | comic_name = comic_name[:-4] 36 | 37 | # save location of comic 38 | comic_location = os.getcwd() + '/comics/' 39 | 40 | # checks if save location exists else creates 41 | if not os.path.exists(comic_location): 42 | os.makedirs(comic_location) 43 | 44 | # creates final comic location including name of the comic 45 | comic_location = comic_location + comic_name 46 | 47 | # downloads the comic 48 | urllib.request.urlretrieve(image_src, comic_location) 49 | 50 | if __name__ == "__main__": 51 | xkcd() 52 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | tweepy 2 | selenium 3 | timy 4 | requests 5 | lxml 6 | --------------------------------------------------------------------------------